Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Image does not upload using createview from template django
CompanyCreateView is a generic view. The file uploads from django administration but does not upload from template. company_logo is stored in mysql database class CompanyCreateView(CreateView): model = Company fields = ['company_name', 'company_description', 'company_email', 'company_website', 'company_address', 'company_phone', 'company_status', 'company_monthly_payment', 'company_logo'] company_form.html {% extends "super_admin/base.html" %} {% load crispy_forms_tags %} {% block content %} {{ form | crispy}} {% endblock content %} -
problems with sending email using foreign key email
I need to send an email when I pay in the Mensalista table, but with this code I can not get the email that appears through the foreign key in the Veiculo field and even when he was sending before, in the body of the email the code "def total_mes_pagar" appeared like this: models.py class Veiculo(models.Model): marca = models.ForeignKey(Marca, on_delete=models.CASCADE, blank=False) modelo = models.CharField(max_length=20, blank=False) ano = models.CharField(max_length=7, default="2018") placa = models.CharField(max_length=7) proprietario = models.ForeignKey( Pessoa, on_delete=models.CASCADE, blank=False, ) cor = models.CharField(max_length=15, blank=False) def __str__(self): return str(self.modelo) + ' - ' + str(self.placa) class Mensalista(models.Model): veiculo = models.ForeignKey(Veiculo, on_delete=models.CASCADE, blank=False) inicio = models.DateField(("Início"), default=datetime.date.today) validade = models.DateField(("Validade"), blank=False, ) valor_mes = models.DecimalField( max_digits=6, decimal_places=2, blank=False) pago = models.CharField(max_length=15, choices=PAGO_CHOICES) @property def email(self): return self.pessoa.email def mensal(self): return math.ceil((self.validade - self.inicio).total_seconds() / 86400) def total_mes(self): return math.ceil(self.mensal() // 30) def total_mes_pagar(self): return self.valor_mes * self.total_mes() def __str__(self): return str(self.veiculo) + ' - ' + str(self.inicio) def send_email(self): if self.pago == 'Sim': assunto = 'Comprovante pagamento Estacione Aqui 24 Horas' mensagem = 'Obrigado por utilizar o Estacione Aqui 24 horas. Ativação do estacionamento dia : ' + str(self.inicio) + 'Com validade até o dia ' + str( self.validade) + ' Confirmamos o … -
Filtering the data displayed in Django Templates
I have a Django application that shows all the users registered. However, I would like to filter the users displayed dynamically. For example, if I select Male from a dropdown list, I want the application to display only Males. Could someone point me in the right direction? I did not include any code because it is just a scenario. Thank you! -
In a ModelForm/Form collect the information for another Model connected thru a ManyToMany Relationship
I have 3 models Account, Email and Item. An Account can have multiple Email and and Item can multiple Email and an Email can have multiple Item. class Account(models.Model): name = models.CharField(max_length=255) class AccountEmail(models.Model): account = models.ForeignKey(Account, on_delete=models.CASCADE) email = models.EmailField(max_length=255, unique=True) class Item(models.Model): emails = models.ManyToManyField(AccountEmail, related_name='account_emails_products') name = models.CharField(max_length=255) The emails can be added at the Item level, none or multiple(dynamic no fixed number). <input type="email" id="email" size="30" > <input type="email" id="email" size="30" > <input type="email" id="email" size="30" > The form: class ItemModelForm(forms.ModelForm) class Meta: model = Product My issues is how do I add this to form and save it. I need visually to appear as input forms, gather the values, validate and check for all inputs, save them in AccountEmails and after create relations. Being M2M (dynamic) I can represent them in the ModelForm, but use a collector field, or not. How do I gather the info to the cleaning/validation if the fields don't exist in reality ? -
Check form errors in Django testing
I want to test field errors using assertFormError. How can I test it? In forms.py password = forms.RegexField(max_length=254, error_messages={'required': _('This is required.') 'invalid': _('It is invalid)} ) In tests.py form = UserForm(data=data) self.assertContains(form['password'].errors, 'It is invalid') -
Document request and response without serializers in django-rest-swagger
I don't use serializers for response, because it is too custom. How can I manually document response fields? I browsed internet, but found no solutions. I use django rest framework and django rest swagger. Possibly, there are other libraries for documenting api (request and response). -
Access pk from related model using prefetch and to_attr
I have the following model relationship: class CustomEmail(models.Model): template = models.ForeignKey(SystemEmail, on_delete=models.CASCADE) In a ListView, I am displaying SystemEmail objects, obtained by: def get_queryset(self): prefetch = Prefetch('customemail_set', queryset=CustomEmail.objects.filter(client=self.request.user.client), to_attr='custom_email') return (SystemEmail.objects.filter(user_editable=True) .order_by('template_name').prefetch_related(prefetch)) Now, in my template, I am attempting to access the pk from the related CustomEmail through the to_att like so: {% if email.custom_email %} <li><a href="{% url 'settings:edit_custom_email' email.custom_email.pk %}">Edit</a></li> {% endif %} The part where I call email.custom_email.pk doesn't retrun anything. How can I (if at all possible) get the pk using the to_attr from the related CustomEmail? -
Django : Define DateTimeField default value as None or blank field
I would like to define a new field in my models.py file. Case 1 : download_date = models.DateTimeField(verbose_name=_('download date'), null=True, default=None) This field should be None or Blank field when an object is saved into my database. If I write my field like above, it gives : null value in column "download_date" violates not-null constraint Case 2 : If I add blank = True, I get the same issue null value in column "download_date" violates not-null constraint What I have to write in order to get a blank/empty field ? Thank you -
how to do validations when javascript is disabled in a browser in django
i am using html forms (not using djangoforms). i am managing validations using jquery. But when javascript is disabled i am getting errors in views.py because the values posting from html forms are empty.how can i manage these validations when javascript is disabled. i have tried like this in views.py if time =="" or header=="" or communicationid=="" : messages.success(request,'Enter all values') return redirect('/samepage/') can i manage them using model validators.if possible please explain -
Django get records from polymorphic model with custom manager
models.py # My Model class MyModel(BaseModel): somefield1 = models.CharField(max_length=100) somefield1 = models.CharField(max_length=100) my_records = MyModelManager() class Meta: db_table = 'my_table' # My Polymorphic Model class PolModel(BaseModel): source_id = models.IntegerField() source_type = models.CharField() class Meta: db_table = 'pol_model' managers.py # Display Actives QuerySet class MyModelManager(models.Manager): def __init__(self, *args, **kwargs): super(MyModelManager, self).__init__(*args, **kwargs) def get_queryset(self): my_queryset = super(MyModelManager, self).get_queryset() return my_queryset.filter(deleted_at=None).extra( select={"inner join pol_model on my_table.id = pol_model.source_id" "WHERE pol_model.type = 'MyExample'"} ) Every Time I select MyModel instances i want to get associated records with instances from polymorphic model. I tried this solution added extra inner join to queryset but id does nothing -
How to redirect from html page to view and post data in Django
First I post some data from my view to an html page: view.py def export(request): primary_key = request.GET.get('primary_key') selected_peer = Peer.objects.get(pk=int(primary_key)) template= loader.get_template('delete-peer.html') content= { 'selected_peer':selected_peer, } return HttpResponse(template.render(content,request)) the selected_peer will be sent to the html page I have a HTML page as below: {% block content %} <div class="submit-row"> <p> {{ selected_peer.address }}</p> <input type="submit" value="Delete Peer" name="_delete-confirm"> </div> {% endblock %} I can use the data (content) in my Html page. Now I have a button (Delete Peer) and I want to redirect to another view and post the data (content)!!(if I click this button) Any Idea -
bootstrap's container-fluid'c class is not working in django
<div class="container-fluid"> <div class="row"> <img class="graph" src="{% static 'images/graph.png' %}"/> </div> </div> Hi. I need to resize the graph.png static image to full width of the screen. But it leaves a blank white space to the left and right margins of the screen. I have used the following CSS for it. The image is resizing to the width of the screen if used in a raw HTML but not in Django. In short, the container-fluid is not doing its job. But other bootstrap classes like grid, buttons and other classes are working very perfectly. .graph{ padding: 0; display: block; margin: 0 auto; max-height: 100%; max-width: 100%; } -
Update M2M relation for a Model instance in Django
I have 3 models as follows: class Service(models.Model): name = models.CharField(max_length=50, unique=True) class ServiceGroup(models.Model): name = models.CharField(max_length=50, unique=True) services = models.ManyToManyField(Service, through=ServiceToServiceGroup) class ServiceToServiceGroup(models.Model): service = models.ForeignKey(Service) service_group = models.ForeignKey(ServiceGroup) I have a list of services that I need to make as M2M association for an instance of the ServiceGroup. I tried the following: In [145]: instance = ServiceGroup.objects.get(pk=1) In [146]: instance.services.all() Out[146]: <QuerySet [<Service: service-1>]> In [147]: new = ['service-2'] In [148]: service_objects = Service.objects.filter(name__in=new) In [149]: service_objects Out[149]: <QuerySet [<Service: service-2>]> In [150]: instance.service_set = service_objects In [151]: instance.save() In [152]: instance.services.all() Out[152]: <QuerySet [<Service: service-1>]> However, as is evident, this did not work. What is the correct way of doing this ? -
Error 500 deployement Django on IIS Server
I try to deploy a django app to a IIS Server. During this step, I find this error: HTTP Error 500.0 - Internal Server Error scriptProcessor could not be found in application configuration My directory folder are: C:\inetpub\wwwroot\MyApp (where i Found manage.py) in wwwroot\MyApp\web.config I have: <?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <directoryBrowse enabled="true" /> </system.webServer> </configuration> I have into my IIS Manager, into my handlermapping of my Sites\MyApp this datas: Request path: * Module: FastCgiModule Executable (optional): C:\Users\ybe\Envs\MyApp\Scripts\python.exe|C:\Users\ybe\Envs\MyApp\Lib\site-packages\wfastcgi.py If I try to go to C:\Users\ybe\Envs\MyApp\Scripts|Lib I find the files need. Directory browsing are checked for Time, Size Extension and Date (but not long date) The MyApp ApplicationPool are Started. Have you any idea of this error ? Thanks per advance, -
How to upload a file using winium with python?
Below is the code that I have been working on since 3 days but could not find any solution. file=driver.find_element_by_name("File name:") file.send_keys("C:\chandra.pdf") I am trying to automate a desktop application using winium with python. All the code is running perfect. But when it reach here, its failing and winium desktop driver stopped working. Traceback (most recent call last): File "C:\Users\amanulla.s\AppData\Local\Programs\Python\Python37\lib\site-packages\urllib3\connectionpool.py", line 600, in urlopen chunked=chunked) File "C:\Users\amanulla.s\AppData\Local\Programs\Python\Python37\lib\site-packages\urllib3\connectionpool.py", line 384, in _make_request six.raise_from(e, None) File "", line 2, in raise_from File "C:\Users\amanulla.s\AppData\Local\Programs\Python\Python37\lib\site-packages\urllib3\connectionpool.py", line 380, in _make_request httplib_response = conn.getresponse() File "C:\Users\amanulla.s\AppData\Local\Programs\Python\Python37\lib\http\client.py", line 1321, in getresponse response.begin() File "C:\Users\amanulla.s\AppData\Local\Programs\Python\Python37\lib\http\client.py", line 296, in begin version, status, reason = self._read_status() File "C:\Users\amanulla.s\AppData\Local\Programs\Python\Python37\lib\http\client.py", line 257, in _read_status line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1") File "C:\Users\amanulla.s\AppData\Local\Programs\Python\Python37\lib\socket.py", line 589, in readinto return self._sock.recv_into(b) ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\amanulla.s\Downloads\CMR\src\CMR_python.py", line 72, in file.send_keys("C:\chandra.pdf") File "C:\Users\amanulla.s\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webelement.py", line 475, in send_keys value = self._upload(local_file) File "C:\Users\amanulla.s\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webelement.py", line 699, in _upload return self._execute(Command.UPLOAD_FILE, {'file': content})['value'] File "C:\Users\amanulla.s\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webelement.py", line 633, in _execute return self._parent.execute(command, params) File "C:\Users\amanulla.s\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 319, in execute response = self.command_executor.execute(driver_command, params) File "C:\Users\amanulla.s\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\remote_connection.py", line … -
Django cross-application auth
I have two Django-apps: the first is a complete backend application with registration and token auth (JWT); the second is an app with more simplier API without auth. They are running on different machines but have the same domain (using nginx reverse proxy): 1: http://foo.com/api, 2: http://foo.com/another_api I was thinking about propagation of auth to the second app. So that users having active account in 1st app could have access to 2nd with token given by 1st app's auth. What is the common way to implement such a feature? Can it be resolved by nginx? -
How to put session data in SetUp() - Django testing
I am setting session data in SetUp() in Django testing but it raises an error not found. What's missing here? def setUp(self): session = self.client.session session['email'] = 'hi@test.com' session.save() def test_valid_data(self): form = CreationForm(data=self.valid_data) u1 = form.save(email=session['email']) -
CORS headers working from Wifi but not from 3G
An IT company set up a server at our business to host our website/portal (mostly for employees - so very few people) locally. Now I have been creating the website for the last few months and we have been using it on our intranet for more than 2 months. The weird thing is when my cellphone is connected to our website via the company wifi, I can go to the website and use it without any problem. All the CORS are fine. But when I am at home, or I switch of my wifi and try to connect via 3G, then suddenly I get CORS heading errors: Access to XMLHttpRequest at 'http://192.168.2.24:8000/api/rest-auth/login/' from origin <website IP> has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Now I would like our employees to use the portal from home as well (it contains a message board) but as soon as the leave wifi range, no one can lock in anymore. I have an angular front end that the domain goes to the opens up fine anywhere, but as soon as you try to log in and access … -
Django auditlog get actor from rest
I have a django project and I use auditlog app.Rest changes saved without actor. But rest users have token. Is there anyway automatically get actor from token? -
Any library for cross framework internationalization?
am looking for cross framework internationalization/localization in particularly Django/Python and Angular6. is anyone aware of any such libraries? Thanks -
About subdomain of django
Any link about how to use a subdomain as the main domain. Let 's say I have www.example.com. But as the main domain, I would like to use subdomain www.movie.exmple.com. if anytime I use example.com or www.example.com it should transfer me to the www.movie.example.com. Any link, a tutorial would be helpful. I really appreciate. -
Puppet: file_line evaluates os.path.join
I'm trying to replace the Django-Settings line 'NAME': os.path.join(BASE_DIR , 'db.sqlite3'), by 'NAME': os.path.join(BASE_DIR , 'db.mysql'), but it doesn't find it. The other line with the ENGINE parameter works fine. The problem must be the "os.path.join"-part. # replace sqlite3 db with mysql file { '/var/www/mysite/mysite/settings.py': ensure => present, } file_line { 'replace db engine': path => '/var/www/mysite/mysite/settings.py', replace => true, line => "'ENGINE': 'django.db.backends.mysql',", match => "'ENGINE': 'django.db.backends.sqlite3',", append_on_no_match => false, } file_line { 'replace db name': path => '/var/www/mysite/mysite/settings.py', replace => true, line => "\'NAME\': os.path.join(BASE_DIR , \'db.mysql\'),", match => "\'NAME\': os.path.join(BASE_DIR , \'db.sqlite3\'),", append_on_no_match => false, } I tried it with \' and without \ . Can somebody please help? -
How to view elements horizontaly in python-django
How to align the elements in an horizontal manner using list view in python-django. By using List view the default action of vertical alignment takes place the below code gets the data from the DB and displays in a vertical aligned form python:- class HomePageView(generic.ListView): template_name = 'Home/index.html' context_object_name = 'Events_List' def get_queryset(self): return Event.objects.order_by('id') HTML:- <div id="Events"> <h2>Events</h2> {% if Events_List %} {% for Events in Events_List %} <div id="Events-list"> <p>{{Events.Event_title}}</p> </div> <p></p> {% endfor %} {% else %} <p>No polls are available.</p> {% endif %} </div> Screenshot:- I need to align these divs horizontally -
Django and angular6 with multitenancy
there is any possibility to connect the frontend angular 6 with Django multitenant rest api? -
Server running with daphne starts to response with code 504 on any http request after passing uncertain time
I'm using django-channels2+daphne in production. After uncertain time passed I got this error twice (after 2 and after 6 hours correspondingly), which involved 504 answer on any HTTP request. I have no idea how should I debug the problem. Using nginx, django-channels2, daphne. Application instance <Task pending coro=<AsgiHandler.__call__() running at /usr/local/lib/python3.7/site-packages/channels/http.py:202> wait_for=<Future pending cb=[_chain_future.<locals>._call_check_cancel() at /usr/local/lib/python3.7/asyncio/futures.py:348, <TaskWakeupMethWrapper object at 0x7ff116ef9708>()]>> for connection <WebRequest at 0x7ff116a86d30 method=GET uri=/api/v1/feed/?page_size=10&distance=-1000&not_reviewed=1 clientproto=HTTP/1.1> took too long to shut down and was killed Here is my nginx config: server { server_name www.example.com example.com; return 301 https://example.com$request_uri; } server { server_name www.lvh.me lvh.me; return 301 https://lvh.me$request_uri; } server { listen 443 ssl; ssl_certificate /etc/ssl/certs/server.crt; ssl_certificate_key /etc/ssl/private/server.key; server_name www.example.com; return 301 https://example.com$request_uri; } server { listen 443 ssl; ssl_certificate /etc/ssl/certs/server.crt; ssl_certificate_key /etc/ssl/private/server.key; server_name www.lvh.me; return 301 https://lvh.me$request_uri; } server { server_name example.com lvh.me; charset UTF-8; listen 443 ssl; ssl_certificate /etc/ssl/certs/server.crt; ssl_certificate_key /etc/ssl/private/server.key; access_log /var/log/nginx/mini.access.log; error_log /var/log/nginx/mini.error.log; location /static/ { autoindex on; root /data/django; } location /media/ { autoindex on; root /data/django; } location / { proxy_pass http://django:8000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Forwarded-Proto $scheme; } } Starting daphne.com with: daphne …