How can I capitalize first word of “lorem” template tag output in Django 2.2?

Django provides a useful “lorem” template tag that will output some “lorem ipsum” text, but the text is all lowercase. How can the first word be capitalized, to get “Lorem ipsum … “? I know that if I had a string I could run it through a filter, but I don’t know how to filter the output of a tag.

too many values to unpack (expected 2) no Django

Estou com este trecho de código no Django, a intenção é inserir, se já existir o ds_user_id então ele atualiza o usuário com esse ds_user_id ao invés de criar um novo

ds_user_id = int(post_login['ds_user_id']) csrftoken = post_login['csrftoken'] cookies = json.dumps(str(post_login['cookies']))  defaults = {   'username': username,   'password': password,   'ds_user_id': ds_user_id,   'csrftoken': csrftoken,   'cookies': cookies,   'status': 0 }  try:   obj = User.objects.get(ds_user_id=ds_user_id)    for key, value in defaults.keys():     setattr(obj, key, value)   obj.save() except User.DoesNotExist:   new_values = {     'username': username,     'password': password,     'ds_user_id': ds_user_id,     'csrftoken': csrftoken,     'cookies': cookies,     'status': 0   }    new_values.update(defaults)    obj = User(**new_values)   obj.save() 

O insert funcionou porém, ao tentar logar novamente, recebo:

too many values to unpack (expected 2)

Eu não estou entendendo muito bem, mas eu acho que é esta linha que está buguizando meu código:

for key, value in defaults.keys(): 

After installing ssl certificate for django application on apache server with debian, I am getting Default test page only

Following are my configuration files

<VirtualHost *:80> Redirect permanent / https://www.piping.pro/ ServerName localhost ServerAdmin admin@piping.pro  ErrorLog $  {APACHE_LOG_DIR}/error.log CustomLog $  {APACHE_LOG_DIR}/access.log combined </VirtualHost>  <VirtualHost *:443> ServerName localhost ServerAdmin admin@piping.pro  Alias /static /var/www/static-root <Directory /var/www/static-root>    Require all granted  </Directory>  Alias /media /var/www/media-root <Directory /var/www/media-root>    Require all granted </Directory>  <Directory /var/www/venv/src/mysite>     <Files wsgi.py>         Require all granted     </Files> </Directory>   ErrorLog $  {APACHE_LOG_DIR}/error.log CustomLog $  {APACHE_LOG_DIR}/access.log combined  SSLEngine on SSLCertificateFile /etc/ssl/piping_pro.crt SSLCertificateKeyFile /etc/ssl/private/PrivateKey.key SSLCertificateChainFile /etc/ssl/piping_pro.ca-bundle  </VirtualHost> 

Verificar se cookie existe no Django

Já pesquisei aqui no StackOverflow, porem nenhuma resposta me ajudou.

Tenho esse código, que cria os cookies:

def home(request):   if not 'username' in request.COOKIES and not 'password' in request.COOKIES and not 'challenge' in request.COOKIES:     response = render(request, 'home/home.html')      # Aqui ele cria os cookies     response.set_cookie('username', 'user', max_age=86400)     response.set_cookie('password', '123456', max_age=86400)     response.set_cookie('ds_user_id', '9132831900', max_age=86400)      return response   else:     # Aqui ele verifica: se existir o cookie username, password e NÃO existir o challenge ele renderiza a home_session.html     if 'username' in request.COOKIES and 'password' in request.COOKIES and 'challenge' not in request.COOKIES:       try:         getAllData = User.objects.get(ds_user_id=request.COOKIES['ds_user_id'])          if getAllData.gender == 0:           return redirect('gender')          return render(request, 'home/home_session.html')       #Se algo der errado ao procurar na db, ele limpa os cookies e redireciona pra home sem session       except User.DoesNotExist:         response = redirect('home')          response.delete_cookie('username')         response.delete_cookie('password')         response.delete_cookie('ds_user_id')          return response 

Conforme comentado no código, quero verificar se o cookie existe, se existir renderiza home_session.html caso contrario ele cria os cookies.

Verificar se cookie existe no Django

Já pesquisei aqui no StackOverflow, porem nenhuma resposta me ajudou.

Tenho esse código, que cria os cookies:

def home(request):   if not 'username' in request.COOKIES and not 'password' in request.COOKIES and not 'challenge' in request.COOKIES:     response = render(request, 'home/home.html')      # Aqui ele cria os cookies     response.set_cookie('username', 'user', max_age=86400)     response.set_cookie('password', '123456', max_age=86400)     response.set_cookie('ds_user_id', '9132831900', max_age=86400)      return response   else:     # Aqui ele verifica: se existir o cookie username, password e NÃO existir o challenge ele renderiza a home_session.html     if 'username' in request.COOKIES and 'password' in request.COOKIES and 'challenge' not in request.COOKIES:       try:         getAllData = User.objects.get(ds_user_id=request.COOKIES['ds_user_id'])          if getAllData.gender == 0:           return redirect('gender')          return render(request, 'home/home_session.html')       #Se algo der errado ao procurar na db, ele limpa os cookies e redireciona pra home sem session       except User.DoesNotExist:         response = redirect('home')          response.delete_cookie('username')         response.delete_cookie('password')         response.delete_cookie('ds_user_id')          return response 

Conforme comentado no código, quero verificar se o cookie existe, se existir renderiza home_session.html caso contrario ele cria os cookies.

DJango API with JavaScript Frontend

Friends:

I am building a DJango Web Application (My first in DJango) where the backend is REST API and the front end is HTML/JS.

Basically, I have 2 questions.

  1. Can I keep both front end programs (in www folder) and the DJango API programs in the same server?

  2. I’m making the API calls from JS files through http: requests. Is this the correct approach?

Appreciate the help here.

Thanks Amsa

Language dialects Django model

I’m creating the Dictionary app, where you can search for words, click on a word, and show the same word in other dialects of the language. I have now created the following Django model:

from django.db import models  from .base_models import BaseModel   class WordCoreModel(models.Model, BaseModel):     word_core = models.CharField(max_length=255, default="")     word_russian_typed = models.CharField(max_length=255, default="", blank=True)     word_english_typed = models.CharField(max_length=255, default="", blank=True)      homonyms = models.ManyToManyField('self', null=True, blank=True)     synonyms = models.ManyToManyField('self', null=True, blank=True)     antonyms = models.ManyToManyField('self', null=True, blank=True)      class Meta:         indexes = [models.Index(fields=['word_core'])]         verbose_name = 'Core Word'         verbose_name_plural = 'Core Words'      def __str__(self):         return self.word_core   class FirstDialectVariant(models.Model):     word = models.ForeignKey(WordCoreModel, on_delete=models.CASCADE)     dialect = models.CharField(max_length=255, default="")   class SecondDialectVariant(models.Model):     word = models.ForeignKey(WordCoreModel, on_delete=models.CASCADE)     dialect = models.CharField(max_length=255, default="")   class ThirdDialectVariant(models.Model):     word = models.ForeignKey(WordCoreModel, on_delete=models.CASCADE)     dialect = models.CharField(max_length=255, default="")   class FourthDialectVariant(models.Model):     word = models.ForeignKey(WordCoreModel, on_delete=models.CASCADE)     dialect = models.CharField(max_length=255, default="")   class FifthDialectVariant(models.Model):     word = models.ForeignKey(WordCoreModel, on_delete=models.CASCADE)     dialect = models.CharField(max_length=255, default="")   class SixthDialectVariant(models.Model):     word = models.ForeignKey(WordCoreModel, on_delete=models.CASCADE)     dialect = models.CharField(max_length=255, default="") 

But I’m not sure if I’m doing it right. Could you advise me how best to do that?

Authenticating Users In Django With SSH Keys

I would like to users of my REST API written in Django to be able to authenticate using SSH keys.

What I am doing is I have created an API to allow me to release software to my website via the command line. I want to authenticate using my ssh key when accessing that API.

So I have in my user interface that I can add public ssh keys associated with my user account.

Now how do I validate the keys in order to authenticate? What is it that I have to do?

I have my API client that will make a post call to:

https://examlple.com/api/release/

How can validate keys!? I have found a couple of python libraries but they are incomplete or unclear. Any step in the right direction would be helpfl.

Pegar dados do banco por sessão com Django

Inicio minha sessão

request.session['username'] = 'usuario' request.session['password'] = 'senha' 

Aqui é o seguinte, se existir a sessão username, password e não existir a sessão challenge, eu gostaria que pegasse os dados do banco pelo nome de usuário que está com a sessão aberta. (meu caso o nome da sessão é usuário mesmo)

def gender(request):   if request.session.get('username') and request.session.get('password') and not request.session.get('challenge'):     a = User.objects.all()     return render(request, 'gender/gender.html', {'a': a})   return redirect('home') 

Resumindo o código acima, se o gender for igual a = 1 redireciona pra home se for 0 escolha.

Mas está pegando os dados de todos do banco de dados, gostaria só da minha sessão

Django авторизация по email (вместо username)

Сделал вход сайт почти по мануалу, но теперь надо переделать поле username на email, а еще лучше на оба сразу в зависимости о того, что вводит пользователь. Итак, по views.py:

def do_login(request):     if request.method == 'POST':         form = AuthenticationForm(request=request, data=request.POST)         if form.is_valid():             username = form.get('username')             password = form.cleaned_data.get('password')             try:                 user=authenticate(username=User.objects.get(email=username), password=password)             except:                 user=authenticate(username=username, password=password)             if user is not None:                 login(request, user)                 messages.info(request, f"You are now logged in as {username}")                 return redirect('form/')             else:                 messages.error(request, "Invalid username or password.")         else:             messages.error(request, "Invalid username or password.")     form = AuthenticationForm()     return render(request = request, template_name = "dologin.html", context={"form":form}) 

Функция она принимает только username, а на емэил дает ошибку ввода. Не понимаю, может я совсем не в том направлении пишу.