I have a python syntax error in the Django project

since django.shortcuts import render
from django.contrib.auth.models import User
django.contrib import auth

def inscription (request):
if request.method == "POST":
if request.POST["password1"] == request.POST["password2"] :
user = User.objects.create_user {
user name = request.POST["username"], password = request.POST["password"]
                if the user is not None:
auth.login (request, user)
return the redirection['home']
                other:
return the rendering (request, login.html, error: username or password is incorrect)
other:
returns the rendering (request, login.html & # 39;)
}

Problems with CreateView – Django

I have the following model:

Reserva class (models.Model):
client = models.CharField (max_length = 200)
employee_of_turne = models.ForeignKey (user, on_delete = models.CASCADE)

I want to create an instance of the model Booking at sight CreateView, which will create a form to create this instance, but in the form, I do not want the field to be displayed user I only want the field shown customer and that by default the field user to be the user who started the session at that moment.

Well to fix this problem, try to modify the data sent by the POST method, in the method get_form_kwargs:

ReservaCreateView class (CreateView):
model = reserve
template_name = & # 39; testapp1 / example.html & # 39;
fields = ['cliente']
    success_url = reverse_lazy (& # 39; home & # 39;)

def get_form_kwargs (auto):
form_kwargs = super (). get_form_kwargs ()
if form_kwargs.get ('data'):
user = User.objects.get (user name = self.request.user)
post = self.request.POST.copy ()
to post['empleado_de_turno'] = str (user.pk)
form_kwargs['data'] = post

return form_kwargs

The fact is that it does not work for me, I always get this error:

django.db.utils.IntegrityError: NOT NULL constraint failure: testapp1_reserva.empleado_de_turno_id

I started trying to find out exactly where the error occurred because the solution of the method get_form_kwargs that I have already shown, you should solve the error, and the error occurs in the method form_valid, especially in the form.save (), here is the source code of the method form_valid:

ModelFormMixin:

    def form_valid (self, form):
"" "If the form is valid, save the associated template." ""
self.object = form.save ()
returns super (). form_valid (form)

FormMixin:

def form_valid (self, form):
"" "If the form is valid, redirect it to the provided URL." ""
returns HttpResponseRedirect (self.get_success_url ())

In the method form_valid, I've printed formulaire.data when in the attribute fields I had the courage to ['cliente'] and when he had the courage to ['cliente', 'empleado_de_turno'] and compare the results and they are exactly the same, so why does it give an error?

So, the solution I found for the problem was:

ReservaCreateView class (CreateView):
model = reserve
template_name = & # 39; testapp1 / example.html & # 39;
fields = ['cliente']
    success_url = reverse_lazy (& # 39; home & # 39;)

def form_valid (self, form):
user = User.objects.get (user name = self.request.user)
Reserva.objects.create (client = self.request.POST['cliente'], employee_of_turno = user)
return the redirection (self.success_url)

But I do not finish convincing this solution, I do not know if this solution is a bad practice or such, because it seems a little "hacker".

To get back to the subject, then why am I getting this error? (this error does not make sense)

Django Templates – Error 500 Internal Server Error (Nginx) When I Try to Generate a PDF File from Weasyprint

Hello everyone.

I have a problem with my application and have tried everything and I could not solve it.

I decided to generate a dynamic PDF in my application and for that I used the Weasyprint library. The function is called by Django Admin and renders an HTML template to generate the PDF. On my development machine, the application is well behaved and everything went well. However, when I downloaded the Web server, the PDF Generator displays an error. Internal server error. After breaking my head a lot, I realized that, strangely, this error only occurs when the client's name is accented. The other variables, even if they are highlighted, are displayed without any problem.

I use Django 2.2.3 and my application is hosted on Digital Ocean. I use Gunicorn and Ngnix.

Here is my function to generate the PDF:

def generate_pdf_procuration (self, request, obj):
# Before rendering the model, take the variables forenkey and go to the address of the variable
address = f # {obj.client.endereco_set.first () .address, {obj.client.endereco_set.first () .number}, {obj.client.endereco_set.first (). neighborhood} - {obj.client () {}} - {obj.client.endereco_set.first (). cep} & # 39;
get_email = & # 39; # Set a default value for the email in case the client does not have it
for the email in obj.cliente.contato_set.all ():
if email.type_contact == & # 39; 4 & # 39 ;:
get_email = email.contact
context = {
& Obj = obj,
& # 39; address: address,
& # 39; get_email & # 39 ;: get_email
}
if obj.iterabetizado:
template = reports / pdf_procuration_template-1.html & # 39;
if not:
template = reports / pdf_procuration_template-2.html & # 39;
html_string = render_to_string (template, context)

html = HTML (string = html_string)
html.write_pdf (target = # /; / tmp / {}. pdf & # 39; .format (obj));

fs = FileSystemStorage (& # 39; / tmp & # 39;)
with fs.open (& # 39; {}. pdf & # 39; .format (obj)) as pdf:
response = HttpResponse (pdf, content_type = & # 39; application / pdf & # 39;)
reply['Content-Disposition'] = & # 39; attachment; filename = "Procurement _-_ {} .pdf" format (obj)
back answer

back answer

generate_pdf_procuracao.label = Generate a PDF & # 39;
generate_pdf_procuracao.short_description = & # 39; Click to generate the PDF of this proxy. Make sure the recording has already been saved & # 39;

change_actions = (& # 39; generate_pdf_procuration & # 39 ;,)

Ngnix access.log log

100.00.000.000 - - [07/Jul/2019:06:16:53 +0000] "GET / admin / ged / hyposufficiency / 3 / actions / generate_pdf_procuration / HTTP / 1.1" 500 141 "http://www.hostname.adv.br/admin/ged/hipossufficiency/3/change/" "Mozilla / 5.0 ( Linux x86_64) AppleWebKit / 537.36 (KHTML, like Gecko) Chrome / 75.0.3770.100 Safari / 537.36 "

In my render template, I've already placed tags:





But even if the customer's name is accurate, this triggers the error Internal server error. What's more interesting is that this error only appears if the client's name is accented because all the other names can accentuate the fact that it does not generate the error .

Even in the admin.py of my app I put # coding: utf-8but none of this resolves.

This is the model line that loads the name of the variable:

By the present and in the best law, {{customer_object | upper}}, Brazilian {{obj.client.get_estado_civil_display | lower}}, {{customer.profissual | lower}}, RG: {{obj.cliente.rg}}, CPF holder: {{obj. client.cpf}}, {{address}}, email address: & nbsp;{{}} Get_email, & nbsp; & nbsp; for the specific purpose of the benefit sought & nbsp; in paragraph LXXIV of Article 5 & of the Federal Constitution, c / c Law no. 1 060/50, point 1 of the law n ° ordm; 7.115 / 83 and in accordance with Article 98 et seq. Of Law 13.105 / 2015 (Code of Civil Procedure), & nbsp;DECLARED, under the law, have no financial condition to bear the costs and expenses of the proceedings, without prejudice to their means of subsistence and family, reason for which it is necessary to grant the benefits of FREE JUSTICE. & nbsp; I further require that the benefit covers all procedures.

Has anyone ever had this problem and knows how to solve it?

Thank you in advance.

django – AttributeError in / posts / add / The object PostForm & # 39; does not have attribute 'cleaner_data & # 39;

Display the PostForm class on the metodo which is valid for work formulas, but which is not restored or for the one that is cleaned, but which is already updated:

AttributeError to / posts / add /
The object & # 39; PostForm & # 39; does not have attribute 'cleaner_data & # 39;

postform

PostForm class (forms.Form):
image = forms.ImageField (required = False)
content = forms.CharField (widget = forms.Textarea, required = False)

def is_valid (self):
valid = true
image = self.cleaned_data.get ('image')
content = self.cleaned_data.get ('content')

if the picture is None and the content is None:
self.add_error (& # 39; Only texting precisions / or uma imagem & # 39;)
valid = false

valid return

def add_error (self, message):
errors = self._errors.setdefault (forms.forms.NON_FIELD_ERRORS, forms.utils.ErrorList ())
errors.append (message)

View

@Connection required
def add_post (request):
if request.method == & # 39; POST & # 39 ;:
form = PostForm (request.POST, request.FILES)

if form.is_valid ():
data_form = form.cleaned_data
Post.objects.create (image = data_form['image'], content = data_form['content'], user = request.user)

return the redirection (& # 39; index & # 39;)

other:
return the redirection (& # 39; index & # 39;)

django – Installing the Python mysql client on Mac

I'm trying to install mysqlclient in a virtual environment. The Python version is 3.0 So here's what I did

Creating a virtual environment, activated from a terminal
Installed the below,

pip install django
pip install mysqlclient

Both installed without any errors.

I've therefore enabled the virtual environment in the terminal using this,

cd users / myenv / bin /

so what

source ./activate

Then I navigated to my project folder using

cd users / pyworkspace / project

I then started the server using this and

python manage.py server

so I had this error below,

Monitor file changes with StatReloader
Exception in the django-main-thread:
Traceback (last most recent call):
"/Users/user/Desktop/python/myenv/lib/python3.6/site-packages/django/db/backends/mysql/base.py" file, line 15, in 
    import MySQLdb as a database
File "/Users/user/Desktop/python/myenv/lib/python3.6/site-packages/MySQLdb/__init__.py", line 18, in 
    of. import _mysql
ImportError: dlopen (/Users/user/Desktop/python/myenv/lib/python3.6/site-packages/MySQLdb/_mysql.cpython-36m-darwin.so, 2): Unloaded Library: @ rpath / libmysqlclient.21 .dylib
Referenced from: /Users/user/Desktop/python/myenv/lib/python3.6/site-packages/MySQLdb/_mysql.cpython-36m-darwin.so
Reason: image not found

The exception above was the direct cause of the following exception:

Traceback (last most recent call):
"/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py" file, line 916, in _bootstrap_inner
self.run ()
"/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py" file, line 864, in progress
self._target (* self._args, ** self._kwargs)
"/Users/user/Desktop/python/myenv/lib/python3.6/site-packages/django/utils/autoreload.py" file, line 54, in the package
fn (* args, ** kwargs)
"/Users/user/Desktop/python/myenv/lib/python3.6/site-packages/django/core/management/commands/runserver.py" file, line 109, in inner_run
autoreload.raise_last_exception ()
"/Users/user/Desktop/python/myenv/lib/python3.6/site-packages/django/utils/autoreload.py" file, line 77, in raise_last_exception
lift _exception[1]
  "/Users/user/Desktop/python/myenv/lib/python3.6/site-packages/django/core/management/__init__.py" file, line 337, in progress
autoreload.check_errors (django.setup) ()
"/Users/user/Desktop/python/myenv/lib/python3.6/site-packages/django/utils/autoreload.py" file, line 54, in the package
fn (* args, ** kwargs)
"/Users/user/Desktop/python/myenv/lib/python3.6/site-packages/django/__init__.py" file, line 24, in the configuration
apps.populate (settings.INSTALLED_APPS)
File "/Users/user/Desktop/python/myenv/lib/python3.6/site-packages/django/apps/registry.py", line 114, to be completed
app_config.import_models ()
"/Users/user/Desktop/python/myenv/lib/python3.6/site-packages/django/apps/config.py" file, line 211, in import_models
self.models_module = import_module (model_module_name)
"/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py" file, line 126, in import_module
returns _bootstrap._gcd_import (name[level:], package, level)
File ""line 994, in _gcd_import
File ""line 971, in _find_and_load
File ""line 955, in _find_and_load_unlocked
File ""line 665 in _load_unlocked
File ""line 678 in exec_module
File ""line 219 in _call_with_frames_removed
"/Users/user/Desktop/python/myenv/lib/python3.6/site-packages/django/contrib/auth/models.py" file, line 2, in 
    since django.contrib.auth.base_user, import AbstractBaseUser, BaseUserManager
File "/Users/user/Desktop/python/myenv/lib/python3.6/site-packages/django/contrib/auth/base_user.py", line 47, in 
    AbstractBaseUser class (models.Model):
"/Users/user/Desktop/python/myenv/lib/python3.6/site-packages/django/db/models/base.py" file, line 117, in __new__
new_class.add_to_class (_ meta, Options (meta, app_label))
"/Users/user/Desktop/python/myenv/lib/python3.6/site-packages/django/db/models/base.py" file, line 321, in add_to_class
value.contribute_to_class (cls, name)
"/Users/user/Desktop/python/myenv/lib/python3.6/site-packages/django/db/models/options.py" file, line 204, in contrib_to_class
self.db_table = function_name (self.db_table, connection.ops.max_name_length ())
"/Users/user/Desktop/python/myenv/lib/python3.6/site-packages/django/db/__init__.py" file, line 28, in __getattr__
return getattr (connections[DEFAULT_DB_ALIAS], article)
"/Users/user/Desktop/python/myenv/lib/python3.6/site-packages/django/db/utils.py" file, line 201, in __getitem__
backend = load_backend (db['ENGINE'])
"/Users/user/Desktop/python/myenv/lib/python3.6/site-packages/django/db/utils.py" file, line 110, in load_backend
return import_module (% s.base% backend_name)
"/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py" file, line 126, in import_module
returns _bootstrap._gcd_import (name[level:], package, level)
"/Users/user/Desktop/python/myenv/lib/python3.6/site-packages/django/db/backends/mysql/base.py" file, line 20, in 
    ) of err
django.core.exceptions.ImproperlyConfigured: Error while loading the MySQLdb module.
Did you install mysqlclient?

I then googled and tried various solutions like,

Error loading MySQLdb module – did you install mysqlclient or mysql-python? & # 39;

But none worked, I continued to have the same mistake. Please tell me how can I solve this problem?

OS: Mac OS
Version: Python Version 3.6

python – Django with SQL Server in production

I need to implement Django in a production application developed with c # desktop with SQL Server 2014

I created a project and managed to connect Django to SQL Server during the migration. The auth_gruop, auth_group_permissions, and so on tables were created for me (image).

enter the description of the image here

Of course, I will not create models because they already exist and have production data. My idea is to use Django to perform web queries with information from the SqlServer database in production.

how can i use these templates, why when i open the admin
I have nothing but groups and users ..

Or what I'm trying to do is not possible.

enter the description of the image here

python 3.x – I can not display my ManytoMany template field in the Django template

I would like to know how to display my ManyToMany field in my chart, follow the code below.

My model:

Instructor class (models.Model):
id = models.AutoField (primary_key = True)
record_instructor = models.IntegerField (verbose_name = & nbsp; Instructor registration & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp;)
teacher_name = models.CharField (max_length = 50, verbose_name = & # 39; InstructorName & # 39;)
training_enabled = models.ManyToManyField (Training, empty = True, bulk_name = "Activated Training")
photo_instructor = models.ImageField (upload_to = "Photos_Instructor", null = True, empty = True, verbose_name = "Photo of the instructor")

def __str __ (auto):
return self.instruction_name

My views:

    @login_required
def instructor_list (request):
teacher_name = request.GET.get ("teacher_name", None)
record_instructor = request.GET.get ('record_instructor', None)


if teacher_name:
Instructor = Instructor.objects.all ()
Instructor = Instructor.filter (InstructorName__icontains = InstructorName)

elif registration_instructor:
Instructor = Instructor.objects.all ()
instructor = instructor.filter (
record_instructor__icontains = record_instructor)

elif instructor_name and instructor_record:
instructor = Instructor.objects.filter (teacher_name__icontains = teacher_name) | Instructor.objects.filter (
record_instructor__icontains = record_instructor)

if not:
Instructor = Instructor.objects.all ()

make render
request, "instructor.html", {"instructor": instructor})

# My model:
  
{% endfor%}
Instructor registration Name of the instructor Training activated Photo of the instructor
{% for the instructor in the instructor%} {% endfor%} {% for the instructor in the instructor%}
{{}} Instructor.insecutor {{}} Instructor.instructorName {{instructor.training} enabled}} {{}} Instructor.instructor

Django join multiple tables via select_related ()

I have three tables users, blocks, cars

User class (models.Model):
user_id = models.BigIntegerField (primary_key = True)
is_out = models.CharField (default = 'N')
birthday = templates.DateTimeField ()

Cars class (models.Model):
user_id = models.ForeignKey (User, on_delete = models.CASCADE, db_column = & # 39; user_id & # 39 ;, related_name = & # 39; cars & # 39;)
title = templates.CharField ()
sold_out = models.CharField (default = "N")

Class Blocks (Models.Model):
user_id = models.BigIntegerField ()
target_user_id = models.ForeignKey (User, on_delete = models.CASCADE, db_column = & # 39; target_user_id & # 39 ;, related_name = & # 39; blocks & # 39;)

I want to extract the cars that are satisfied below the condition.

  1. Cars that a user who is not is_out = & # 39; N & # 39;
  2. Cars that are not sold. (sold_out = & # 39; N & # 39;)
  3. Cars of users that do not exist in the target_user_id column of the block table

To get the cars that fit the condition above, I wrote the query like this.

blocks = Blocks.objects.filter (user_id = 10000) .values_list (& # 39; target_user_id & # 39; flat = True)
Cars.objects.filter (sold_out = "N"). Select_related (& # 39; user_id & # 39;). Filter (user_id__is_out = & # 39; N). Exclude (user_id__in = block)

But as you know, if the number of blocks increases, there may be performance issues.

Question

  1. Is it possible to join blocks?
  2. The above query is the best case?
  3. A defect on my schema?

Thank you.

python – Register the user Django Admin

Hello everyone.

I have a small application created entirely in Django Admin and I have to make sure that the logged-in user performs a specific SEO query for the registered clients and other models of that user / this company to separate the application by group of users.

How can I do this with Django Admin? Because of what I read request and the example only works in the views and as I just use Django Admin as CRUD, I do not use views.

I've tried to place the application in the interior modèles.Manager and I receive an exception:

ClientManager class (models.Manager):
def get_queryset (auto, request):
return super (ClientManager, self) .get_queryset () .filter (client = True) .filter (desktop = request.user.username)

TypeError to / admin / register / client /
get_queryset () missing 1 positional argument required: & # 39; request & # 39;

Did not return HttpResponse object. He returned None instead. (Django)

I must URLPATTERN: re_path (r ajax / login & # 39 ;, ajax.login, name = & # 39; login & # 39;)

I have the record ajax.py

since django.http import JsonResponse

def login (request):
if request.method == & # 39; POST & # 39 ;:
username = request.POST.get ('username')
password = request.POST.get (& # 39; password)

if none in (username, password):
returns JsonResponse ({
& # 39; status & # 39 ;: False,
'Message: Enter the user name and password & # 39;
})

And my javascript that asks for the URL domain / ajax / login

But he returns to me:

The projectoname.ajax.login view did not return an HttpResponse object. He returned None instead.

NOTE: This is not a view, but a file to make validations of forms to send pro ajax in js