Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Digitalocean django one-click second site
I am a noobie when it comes to deploying django on a webserver. I always used digitalocean one-click instalation. Now I wanted to add a second website on the server but it is more difficult than I thought.Since you have generate a new gunicorn.socket?? I searched duckduckgo and google to find the awnser. So before I start reading in on how to use gunicorn and wsgi to create a gunicorn.socket file. Or maybe some other ways to do it with gunicorn without the socket file. My question is: How can I add a second website to the digitalocean one-click server? -
django formset unique_together integrity error
I am using Django and jquery.formset.js. I am trying to update multiple objects with a formset. My model looks like this: class Item(models.Model): class Meta: unique_together = ('index', 'parent') ordering = ['index'] index = models.PositiveIntegerField() parent = models.ForeignKey('playlist', related_name='items', on_delete=models.CASCADE) Every time the order gets changed on update it creates IntegrityError on unique_together. How do I update multiple objects with unique_together on required fields? Any help would be much appreciated. -
Declaring objects for globals() using a nested for loop
Firstly, I know I shouldn't be using globals(). I know I shouldn't. But I'm using a custom Django API which doesn't allow me to use collections (as far as I can tell), so I'm pretty much stuck with using globals(). I'm trying to design a game where a player will have 1 choice in the first round, 2 choices in the second round, 4 choices in the third round (so the formula for calculating choices per round is num_choices = 2^num_rounds). Of course, the first round has only 1 choice, so I am declaring that statically. However, for subsequent rounds I am trying to use the following code: for i in range(2, NUM_ROUNDS): dec_num = math.pow(2, i) for j in range(1, int(dec_num)): globals()['dec_r{}_{}'.format(i).format(j)] = models.CharField( choices=list_of_choices, widget=widgets.RadioSelect(), blank=False, initial='blank' ) However, when I attempt to run my Django app, I receive the following error: IndexError: tuple index out of range I figure it has something to do with the way that I am declaring the variable name. Is there an alternative I can use? Thanks! -
Django/Python and Raw SQL Querying with PostgreSQL
I'm practicing my raw SQL querying in a Django project using cursor.execute. Here's my Django models.py database schema: class Client(models.Model): date_incorporated = models.DateTimeField(default=timezone.now) And here's the psql description of the table: # \d+ client Column | Type | Modifiers | Storage | -------------------+--------------------------+--------------------+----------+ date_incorporated | timestamp with time zone | not null | plain | Here's where I get confused: If I use psql to query the data from the table, I get: # SELECT date_incorporated FROM client; date_incorporated ------------------------ 2017-06-14 19:42:15-04 2017-11-02 19:42:33-04 (2 rows) This makes sense to me. In the PostgreSQL docs, it shows that this is (I believe) just a string that is correctly formatted and stored as a UTC timestamp. When I go through Django using this query: cursor.execute('SELECT date_incorporated FROM client;') data = [dict(zip(columns,row)) for row in cursor.fetchall()] (using the dictfetchall method from the Django docs) ...my date_incorporated field gets turned into a python datetime object. {'date_incorporated': datetime.datetime(2017, 11, 2, 23, 42, 33, tzinfo=<UTC>)} In this app I'm building, I wanted a user to be able to input raw SQL, and put that inputted string into the cursor.execute(rawSQL) function to be executed. I expected the output to be the same as the psql version. … -
Is django's EmailMessage filtering out certain HTML attributes and properties?
I'm having an issue... I'm trying to properly setup Google's schema for event reservations I'm printing out the rendered template before the email is sent and it outputs properly, however after sending the email and opening it up,the HTML attributes and properties I set are not there. The only tag that is shown properly is the one. Shown below is the case for when I'm using HTML. I tried the same thing using the script version shown in the linked URL and I'm having an issue where it just disappears... anyone know what's going on? Template code: ... <body style="margin:0; padding:0; -webkit-text-size-adjust:100%; -ms-text-size-adjust:100%;" bgcolor="#f3f3f3"> <div itemscope itemtype="http://schema.org/EventReservation"> <meta itemprop="reservationNumber" content="{{rsvp.id}}"/> <div itemprop="underName" itemscope itemtype="http://schema.org/Person"> <meta itemprop="name" content="{{rsvp.candidate.first_name}} {{rsvp.candidate.last_name}}"/> </div> <div itemprop="reservationFor" itemscope itemtype="http://schema.org/Event"> <meta itemprop="name" content="{{rsvp.event.title}}"/> <time itemprop="startDate" datetime="{{rsvp.event.start_date_iso}}"/> <div itemprop="location" itemscope itemtype="http://schema.org/Place"> <meta itemprop="name" content="{{rsvp.event.event_location.name}}"/> <div itemprop="address" itemscope itemtype="http://schema.org/PostalAddress"> <meta itemprop="streetAddress" content="{{rsvp.event.event_location.address1}}"/> <meta itemprop="addressLocality" content="{{rsvp.event.event_location.city}}"/> <meta itemprop="addressRegion" content="{{rsvp.event.event_location.state}}"/> <meta itemprop="postalCode" content="{{rsvp.event.event_location.zipcode}}"/> <meta itemprop="addressCountry" content="US"/> </div> </div> </div> </div> ... </body> This is what's in the email when I inspect it... -
Method in Django to give privileges to users based on the Group?
Is there a way in Django 1.11 to give privileges to users based on the Group they belong to? Please can someone direct me to a good resource to look into. -
Strange publish date in django
I have a publish date for blog posts in my model like this: published=models.DateTimeField(verbose_name="date published") Then somewhere in my templates, I have this: {{ post.published }} {{ post.published.day }} And the output becomes this: November 29, 2017 28 So why the second line shows one day earlier??? PS: It wasn't like this last week, but I don't know what I have changed since then. I don't use version control! -
How to turn off rounding numbers in FloatField model
Hello I have got problem I am saving latitude and longitude data from google maps to my database in FloatField model and when there are numbers which have a lot of integers after comma the FloatField form django is automatically rounding them. For example from google maps I get coordinates: latitude': 49.82895324990301, 'longitude': 21.160517976135225 And in my database the saved values are: latitude': 49.828953249903, 'longitude': 21.1605179761352 So the saved numbers are rounded and I dont know how to disable it. I will be very thankful for every help. Field in my models.py looks like: class MuseumLocation(models.Model): owner = models.ForeignKey(User) name = models.CharField(max_length=150) location = models.CharField(max_length=150, null=True, blank=True) latitude = models.FloatField(null=True, blank=True) longitude = models.FloatField(null=True, blank=True) -
Django how to add a pk to a request object?
I am struggling in my TDD to add a pk inside a request object in Django. Here is my trial : request = HttpRequest() request.method = "GET" request.GET = request.GET.copy() request.GET["pk"] = 1 response = info_station(request) knowing that the info_Station take a pk as parameter : def info_station(request, pk): And my url file : url(r'^info_station/(?P<pk>[0-9]+)$', views.info_station) The error is : info_station() missing 1 required positional argument: 'pk' How can I add this 'pk' parameter into my request ? -
Django: Wrong permissions for created SOCK file using mod_wsgi
I have a Django app running on my server using Apache2 and mod_wsgi. I also having WSGI running in daemon mode. Due to this, I have a small issue that occurs every time I restart my apache2 service. A new sock file is created in /var/run/ which isn't the issue itself, but due to this, the new file is being created by root and therefore, my user who is serving the files is not the owner. My Question: How do I make it so that the new sock file being created is created with user as the owner and www-data as the group? -
Can't add new rows to Postgres database at Heroku via Django admin
After provisioning my Postgres database on Heroku, I restored the structure and data from a local backup created using pg_dump. I am unable to add new data to any table via Django admin. I get: null value in column "id" violates not-null constraint when adding data for any model. What's going on with this database? -
Display dynamic data from database in Django
I am using Django and Postgresql as database. I have a HTML page with two fields name and item. I can save the data in the database by clicking on submit. But, I want to show the saved data from database in the HTML page. It means, whenever we load the page, it should show the existing saved data and after submitting new data, the list should be updated. Below is my python code. models.py from django.contrib.auth.models import User from django.db import models class AllocationPlan(models.Model): name = models.CharField(max_length=50) item = models.CharField(max_length=4096) views.py class HomePageView(TemplateView): template_name = "index.html" def post(self, request, **kwargs): if request.method == 'POST': form = AllocationPlanForm(request.POST) if form.is_valid(): form.save() return render(request, 'index.html', { 'form': AllocationPlanForm() }) forms.py from django import forms from django.forms import ModelForm from homeapp.models import AllocationPlan class AllocationPlanForm(ModelForm): class Meta: model = AllocationPlan fields = "__all__" index.html <html> <form method="post">{% csrf_token %} Name:<br> <input type="text" name="name" > <br> Item:<br> <input type="text" name="item" > <br><br> <input type="submit" value="Submit"/> </form> {% for i in form %} {{ i.name }} {{ i.item }} {% endfor %} </html> It is returning NONE -
Filter Django queryset for a dict value
I have a queryset of Products with JSONField attributes containing dict class Product(models.Model): attributes = JSONField( pgettext_lazy('Product field', 'attributes'), encoder=DjangoJSONEncoder, default={}) I want to filter Products where attributes['12'] == '31' Following one works: qs.filter(attributes__contains={'12': '31'}) Following one does not: qs.filter(attributes__12='31') Unfortunately I cannot use first solution, as this dict may contain more keys. Is this something I can achieve with PostgreSQL or should I move it to ES? -
Django - An existing connection was forcibly closed by the remote host
I am creating a function to logout from my website.(my admin account is currently logged in) And an error An existing connection was forcibly closed by the remote host triggers when I tried to logout. Here is the code: def logout_view(request): logout(request) return render(request, 'index/index.html', {}) There are two other exceptions: 'NoneType' object is not subscriptable and 'NoneType' object has no attribute 'split' Tracebacks are too long, if it is really necessary to see them, i can paste them here. Thanks your any help! -
How to set up 2 sites on 1 VPS?
I have 1 site on my VPS server with such NGINX config. It's /etc/nginx/sites-available/default server { listen 80 default_server; listen [::]:80 default_server; root /var/www/Era; # Add index.php to the list if you are using PHP index index.html index.htm index.nginx-debian.html; server_name eraart.ru; location / { try_files $uri $uri/ =404; } error_page 404 /404.html; location = /404.html { root /var/www/Era; internal; } } I want to deploy the second site on with django. I created /etc/nginx/sites-available/blog with upstream app_server { server unix:/home/split/Blog-Boards/run/gunicorn.sock fail_timeout=0; } server { listen 81; server_name www.progxother.stream; # here can also be the IP address of the server keepalive_timeout 5; client_max_body_size 4G; access_log /home/split/Blog-Boards/logs/nginx-access.log; error_log /home/split/Blog-Boards/logs/nginx-error.log; location /static/ { alias /home/split/Blog-Boards/static_root/; } # checks for static file, if not found proxy to app location / { try_files $uri @proxy_to_app; } location @proxy_to_app { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://app_server; } } created symbolic link to the sites-enabled folder and refresh nginx. Trying to open an ip adress with 81 port and get nothing. -
Tilde (~) symbol on Django regex url (Cookiecutter Django)
After installing Cookiecutter Django i saw the tilde (~) symbol in regex and don't know the meaning for url purposes. It's related to a regular expression or only a way to declare paths? ./users/urls.py: urlpatterns = [ ... url( regex=r'^~redirect/$', ... url( regex=r'^~update/$', ... ] -
can I register the same app twice under two different names in Django?
I know that sounds a bit weird task, but if I have one app, called App1 in my project folder, can I add it twice under two different names (let say App1_1, and App1_2? I know that it is theoretically possible using AppConfig but when I try to do it the error `Application names aren't unique, duplicates: foo” is raised. -
Django project: track migrations
While developing a Django project tracking it with git and GitHub, how should I manage migrations? Sometimes when I deploy a release to production some migrations crash due to files that I delete after this migration. How can I avoid this? Thanks. -
Django group permissions like linux file system permissions
Basically I would like to have a permission system like Linux file system. I want to classify the permissions whether the user is in the same group as the owner (creator) of the object. Example scenario: User can change objects created by someone in the same group as them. Group Admins can change and delete any object created by users in their group. Is it possible to do this with default django permission system? If not, is there a package you could recommend? I hope I am not missing anything basic in django docs but I couldn't find a way to accomplish this. -
Copy model object to another model
I want to copy recipes from my Recipe model to my Shoplist model so that certain combinations of recipes can be summarized in a shoplist. The user should be able to choose recipes which get added to a shoplist which the user can use to go to the store. The next time the user comes to the site he should be able to make another shoplist with other recipes. I imagine that the user should be able to trigger a function. But I do not know what the function should look like. If I need to provide to more details please tell me! recipe/models.py class Recipe(models.Model): """ A model describing a cookbook recipe. """ # Selection menu for the category of the product CATEGORY_1 = 'Vegetarisch' CATEGORY_2 = 'Pasta' CATEGORY_3 = 'Oosters' CATEGORY_4 = 'Vlees' CATEGORY_5 = 'Vis' CATEGORY_6 = 'Dessert' CATEGORY_7 = 'Simpel' CATEGORY_8 = 'Sauzen' CATEGORY = ( (CATEGORY_1, u'Vegetarisch'), (CATEGORY_2, u'Pasta'), (CATEGORY_3, u'Oosters'), (CATEGORY_4, u'Vlees'), (CATEGORY_5, u'Vis'), (CATEGORY_6, u'Dessert'), (CATEGORY_7, u'Simpel'), (CATEGORY_8, u'Sauzen'), ) title = models.CharField(u'Titel', max_length=255) slug = models.SlugField(unique=True) image = StdImageField(upload_to=UploadToAutoSlug(populate_from='title'), variations={'thumbnail':{'width': 300, 'height': 300, 'crop': True}}, verbose_name=u'recipe image') ingredients = models.ManyToManyField(Ingredient, verbose_name=u'ingredients') neccesities = models.TextField(u'Benodigdheden') preparation = models.TextField(u'Bereiding') number_of_portions = models.PositiveIntegerField(u'Aantal personen') category … -
Signal Call to Auto populate a User Field if it exists in another Model
I simplified my previous post to provide clarity. I'm attempting to auto populate a field in my custom user model with a 1 or a 0 if the formattedusername exists in another model using the following signal, but it will not work: @isthisflag def is_this(self, is_this): if cfo.ntname is user.formattedusername: return 1 else: return 0 I have a custom User model like the following: class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=7, unique=True) formattedusername = models.CharField(max_length=11, unique=True, primary_key = True) is_this = models.BooleanField(default=False) USERNAME_FIELD = 'username' I then have another model we'll call cfo that has a list of formattedusernames the ntname field is a FK to formattedusernames. class cfo(models.Model): ntname = models.CharField(db_column='CFO_NTName',primary_key=True, serialize=False, max_length=11) class Meta: managed = False db_table = 'cfo' If ntname exists as the User who logs with their LDAP authentication I want to place a 1 in the User.is_this field. -
Django - __str__ method not working, says name is not defined
I have the following model defined. class Response(models.Model): question = models.ForeignKey(Question, on_delete = models.CASCADE) STATEMENT_CHOICES = ( (-1, "Strongly Disagree"), (-0.5, "Somewhat Disagree"), (0, "Uncertain"), (0.5, "Somewhat Agree"), (1, "Strongly Agree"), ) statement = models.DecimalField( max_digits=2, decimal_places=1, choices = STATEMENT_CHOICES ) def __str__(self): return self.statement when I run the django shell, I create a question q that says you like pizza and response r which is 1 for strongly agree. then when I run the __str__ method on r I get an error saying name 'statement' is not defined. Here is the exact console output... >>> q <Question: You like pizza.> >>> r = Response(question=q, statement=1) >>> r.question <Question: You like pizza.> >>> r.statement 1 >>> r Traceback (most recent call last): File "<console>", line 1, in <module> File "/Users/TN/Documents/Programming/Django/Practice/myve /lib/python3.5/site-packages/django/db/models/base.py", line 572, in __repr__ u = six.text_type(self) File "/Users/TN/Documents/Programming/Django/Practice/mysite/personalityQuiz/models.py", line 48, in __str__ return self.statement NameError: name 'statement' is not defined -
Django: passing variable from view.py to html with render
I am new to Django and I have the following problem With views.py I render a page called 'results_links.html' located in application templates directory which has an 'include' statement toward another page 'MAPE_history.csv.html' located in 'upload' directory (which is also defined in settings.py as template directory). I want to dynamically pass the file to be used in 'included' statement from views.py. For the test I use same file: MAPE_history.csv.html The problem I have is that I receive a 'template not existing'error from include statement. If I remove the statement of I replace the 'content' variable with the file name, I do not receive a problem. Here is the code: ### views.py from django.shortcuts import render from django.http import HttpResponse import os from formupload import Best_model_forecast_v11 # Create your views here. def home(request): return render(request, 'index.html', {'what':'Django File Upload'}) def upload(request): if request.method == 'POST': handle_uploaded_file(request.FILES['file'], str(request.FILES['file'])) MAPE_file = 'MAPE_'+str(request.FILES['file'])+'.html' return render(request,'result_links.html',{'content':MAPE_file}) elif request.method == 'GET': return render(request,'result_links.html',{'content':'MAPE_history.csv.html'}) response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'upload/MAPE_history.csv; filename="MAPE_history.csv"' return response return HttpResponse("Failed") def handle_uploaded_file(file, filename): if not os.path.exists('upload/'): os.mkdir('upload/') if not os.path.exists('forecast/'): os.mkdir('forecast/') with open('upload/' + filename, 'wb+') as destination: for chunk in file.chunks(): destination.write(chunk) #print(Best_model_forecast_v11.main('upload/' + filename)) return Best_model_forecast_v11.main('upload/' + filename) ### result_links.html … -
Django model fields mapping: Modelform vs ModelSerializer
I have a model.The required property of the fields is not same for the Modelform and Modelserializer. Please see the below example class Test(models.Model): name = models.CharField(max_length=200,null=False) streetname = models.CharField(max_length=200) Checking the fields mapping with ModelForm class Testform(forms.ModelForm): class Meta: model=Test fields=['name','streetname'] Properties of the fields are: name -> required=true (may be because of null=false or its the default value) streetname -> required=true (since default value is true) Checking the fields mapping with ModelSerializer: class TestSerializer(ModelSerializer): class Meta: model = Test fields=['name','streetname'] the field properties are serialized as: name -> required=true (may be because of null=false) streetname -> required=false (although the default is True, its showing false) How to understand the Modelserialize's streetname required property. -
Django database model design - linking 3 models
My project is written in Django. I have one model for academic articles. class Article(models.Model): title = models.CharField(max_length=300) abstract = models.TextField(blank=True) ... I have another model for questions that articles may be responsive to: class Question(models.Model): question = models.CharField(max_length=300) article = models.ManyToManyField(Article) An article can respond to a question in one of three ways: 'yes', 'no', and 'insufficient evidence'. But the same article may respond differently depending on the question. So for example, article1 may respond 'yes' to question1, 'no' to question2 and 'insufficient evidence' to question3. I'm struggling with how to design these responses into my model. I could create a separate model for responses like below: class Response(models.Model): response = models.CharField(max_length=25) then populate that model with my three responses ('yes', 'no', 'insufficient evidence') and then add a field in my Article model for responses like so: response = models.ManyToManyField(Response) But then how would I link an article's response to a question? How do I tell the database that article1's response to question1 is 'yes', its response to question2 is 'no' and its response to question3 is 'insufficient evidence'? Thank you.