Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
auto_add with FactoryBoy
This issue: https://github.com/FactoryBoy/factory_boy/issues/102 describes how you should go about testing a 'created' field in django. How should this be implemented for auto_add (rather than auto_add_now)? I have an "updated" field, but whether I use models.DateTimeField(auto_now=True) or override the django model .save() method def save(self, *args, **kwargs): """On save, update updated timestamp""" self.updated = timezone.now return super(Task, self).save(*args, **kwargs) I can't seem to get FactoryBoy to return the value of updated that I want - it always returns timezone.now() LazyAttribute(lambda o: o.created + timedelta(hours=1)) # ignored by auto_add or using the _create() method as suggested in the GitHub issue: @classmethod def _create(cls, target_class, *args, **kwargs) updated = kwargs.pop('updated', None) obj = super(TaskFactory, cls)._create(target_class, *args, **kwargs) if updated is not None: obj.updated = updated obj.save() # <-- calls .save() method overriding with timezone.now() return obj What's the best way to go here? -
where to start my project when im on learning stage
I am a student of Computer science .i have decided to do my final year project in Django which is the most popular framework of python out there and I am also on learning stage of it.so the problem is I am little bit confused where to start .i have grip in HTML CSS and JS BOOtstrap .. just need a suggestion from where to start my project. if anyone can suggest me the steps i have to follow. -
Is django and django-rest-framwork badly designed?
I am (still) newbie to django and rest-framework. And when going through documentation, many times, I felt like both frameworks are violating the zen of python and MVC pattern. there are multiple ways to same things and sadly nothing seems obvious. (aginst zen of python) it overdid DRY principal, creating so many apis considering different scenarios and not well documented. (ok web is complicated but better to write base apis with proper docs instead writing many considering tons of patterns) even though it is following MVC/MVT pattern, in some places it gest violated. e.g. In django-rest-framework, you can configure routers in view. More and more tags are being added to put logic in templates. Only thing I like is ORM. I don't want to sound rude as being noob to django and still opinionated, but feel free to enlighten me with your opinions and/or any better alternative, hoping question will not be closed soon. -
How do I catch all exception in a common class like a mixin
I have class based views in python django application. Most of them handling same type of exception like: class A{ try: func1() except type1 as e: handle1() except type2 as e: handle() } class B{ try: func2() func3() except type1 as e: handle1() except type2 as e: handle() } I would like to keep this exception handling in a common class(may be a mixin). Which class need the exception handling will inherit the common class. Keep the repeated exception handling in a common class.I am using python3 and django1.11 - class based views -
Trouble with command line while working with python
I am trying to follow a tutorial for django, but I can't even get it installed. I am running windows 10, and when I open the command line and try: python --version I get: 'python' is not recognized as an internal or external command, operable program or batch file. I also cannot use the pip function at all. -
Django rest framework including "X-CSRFTOKEN" header, receiving "CSRF Failed: CSRF token missing or incorrect"
I am currenty creating a react native ios application where I am interacting with a django rest framework backend. I authenticate with the backend and store the csrftoken, sessionid, and messages cookies in asyncStorage. The backend view I have is class ItemList(generics.ListCreateAPIView): queryset = Item.objects.all() serializer_class = ItemSerializer permission_classes = (IsAuthenticated,) A GET request example is: axios({ url:'https://myapi.com/api/items/', method: "GET", withCredentials: true, headers: { Cookie: mycookies, }),... A POST request example is: axios({ url:'https://myapi.com/api/items/', method: "POST", withCredentials: true, headers: { Cookie: mycookies, 'X-CSRFTOKEN': cookies.csrftoken.value }),... NOTE: mycookies is the full string of cookies while cookies is the javascript object. This is not a typo. Shortly after I authenticate, both the GET and POST requests work. I can retrieve and create items from the api. However, If I close out of the Ios application and reopen the POST request stops working. The GET request will return a 200 response but the POST request returns a 403 authentication error with the message "CSRF Failed: CSRF token missing or incorrect". When I send the POST request I am certain the csrftoken, sessionid, and messages cookies are still correct, and I've checked that the X-CSRFTOKEN header matches the csrftoken cookie. I am thinking the … -
Azure Web App for Containers :: Multicontainer
I have a compose with multiple containers. It is a web app with Django using Nginx and hosted by Gunicorn. The build is successful but when i browse the site, I got a bad request 400. It works in localhost though. Any advise? Thanks. -
The view app_name.views.signup didn't return an HttpResponse object. It returned None instead. for a existing username
the signup view is working for new users but when i try to signup an existing user, my view returns nothing. views.py def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): userObj = form.cleaned_data name = userObj['username'] email = userObj['email'] if not (User.objects.filter(username=name).exists() or User.objects.filter(email=email).exists()): user = form.save() login(request, user) return redirect('app_name:home') else: raise forms.ValidationError('Looks like a username with that email or password already exists') else: form = SignUpForm() return render(request, 'app_name/signup.html', {'form':form}) form.py class SignUpForm(UserCreationForm): email = forms.EmailField(required='True') first_name = forms.CharField(required='True') last_name = forms.CharField(required='True') class meta: model = User fields = ( 'first_name', 'last_name', 'email', 'username', 'password1', 'password2', ) def save(self, commit='True'): user = super(SignUpForm, self).save(commit='False') user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] if commit: user.save() return user i want the form to return a message stating that the user already exist. can't see where the problem is. it sends None. -
Several issues when using PermisssionRequiredMixin
I have a class to delete notes, and this worked perfectly until i added the PermissionRequiredMixin. Previously, if the user was not a staff member, the user was sent to the ADMIN/login page ..he then logged in and on success was taken to main staff page, from where the user could then delete the note successfully. The note was deleted, and then the user was taken back to the ListNotes screen. @method_decorator(staff_member_required(login_url='/admin/login/?next={}'.format('/staff/')), name='dispatch') class DeleteNoteView(PermissionRequiredMixin, DeleteView): model = CandidateNote permission_required = 'CandidateNote.delete_CandidateNote' def get_success_url(self): return reverse('candidates:list_notes', kwargs={'pk': self.object.candidate.pk}) After adding the PermissionRequiredMixin, if the user does not have permission to delete the post, the user is taken to the ACCOUNTS/login page..which is not the page i wanted the user taken to ...the accounts login page is as you can see not defined in the staff_member_required decorator.. that is the first issue. The second issue is that even when the staff_member logs in with a member id that has permission to delete the note. i get an error of candidates/candidatenote_confirm_delete.html template does not exist. this template does not exist, but i thin the PermissionRequiredMixin is somehow changing the POST request to a GET request, which from the documentation will force the … -
Send and receive data from local client machine to a flask server on an Ubuntu server
On my local machine, I have a server and client implemented in Python. The JSON data is sent from client to server, the server parses the required data out of it and sends the result as JSON file back to the client. This is running fine on my local machine. I now want to implement this flask server on an Ubuntu server and then want to send and receive data. I am trying to use mod_wsgi as explained in https://www.digitalocean.com/community/tutorials/how-to-deploy-a-flask-application-on-an-ubuntu-vps I am still not able to get the data back to my local machine. Here is my code: client.py import sys import json import requests import time import os import glob data_location = 'C:\\Users\\cathy\\Desktop\\data' # folder containing all the data for root, directories, files in os.walk(data_location): for directory in directories: loc = (data_location + '/' + directory + '/*') all_files = glob.glob(loc) for filename in all_files: f=open(filename) f=f.read().splitlines() payload = {'input': f} s = json.dumps(payload) #res = requests.post("http://127.0.0.1:5000/my_data/", json=s).json() res = requests.post("http://12.345.678.890/my_data/", json=s).json() #time.sleep(10) if res['employee_id']: print(res['employee_id']) if res['name']: print(res['name']) server.py from flask import Flask from flask import request import json import re import sys import os import time from parsers import id_parser, name_parser import spacy import re from datetime … -
How to update page in django with foreignKey subject
I'm new to django, I'm trying to update a page with foreignkey to subject. Here is my code models.py class Subject(models.Model): title = models.CharField(max_length = 200) slug = models.SlugField(blank = False) visible = models.BooleanField(default = True) position = models.IntegerField() date_published = models.DateTimeField(auto_now_add = True) date_updated = models.DateTimeField(auto_now_add=False) def __str__(self): return self.title class Page(models.Model): subject = models.ForeignKey(Subject, on_delete= models.CASCADE) title = models.CharField(max_length = 200) slug = models.SlugField(blank = False) description = models.TextField() thumbs = models.ImageField(blank = True) visible = models.BooleanField(default = True) position = models.IntegerField() date_published = models.DateTimeField(auto_now_add = True, auto_now=False) date_updated = models.DateTimeField(auto_now_add=False, auto_now=True) def __str__(self): return self.title urls.py urlpatterns = [ path('dashboard/', views.dashboard, name='dashboard'), re_path(r'^dashboard/edit/(?P<subject_slug>[\w-]+)/(?P<slug>[\w-]+)', views.edit_article, name='edit_page'), ] views.py def edit_article(request, subject_slug, slug): subject = Subject.objects.get(slug = subject_slug) article = subject.page_set.get(slug = slug) form = ArticleForm(request.POST or None, instance = article) if request == request.POST: form = ArticleForm(request.POST, instance = article) if form.is_valid(): c = form.save( commit = False) c = subject c.save() return HttpResponseRedirect('/dashboard/') context = { 'title' : article.title, 'article' : article, 'form':form } return render(request, 'dashboard/editarticle.html', context) article.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Edit article</title> <link rel="stylesheet" href=""> </head> <body> <h1>{{ title }}</h1> <form method="POST" accept-charset="utf-8">{% csrf_token %} {{ form.as_p }} <input … -
Managing inheritance in Django
So, in our database we had a Car model, but there could be different kinds of cars, with different fields and different processes associated to them, so I made some model classes that inherit from that Car, it's something like this: class Car(models.Model): field = models.CharField(max_length=300) class CarA(Car): field_a = models.CharField(max_length=300) class CarA1(CarA): field_a1 = models.CharField(max_length=300) class CarA2(CarA): field_a2 = models.CharField(max_length=300) class CarB(Car): field_b = models.CharField(max_length=300) Also, there are trips, and each trip has a car associated to them: class Trip(BaseModel): car = models.ForeignKey(Car) If I have a CarA1 instance, car_a1, I can save it in a Trip with car_a1.car_ptr, but it would be saved as a Car, and from there I don't think there's a way to get the CarA1 instance again except searching by the Car id in all the subclasses. So, if I want to know which kind of car the trip has, or get a specific subclass field, it would be really complicated. What do you suggest to do? I can just keep only the Car class with the specific fields nullable (field_a, field_b, etc), and a field to specify the kind of car, but that doesn't seem right, I would have to check on the … -
Django Rest Framework error 'django.core.urlsolvers'
I am trying to implement Django REST Framework to my application, but facing this issue during the runtime. Any suggestion? I am using Django 2.0.2 File "/Users/../project1/blogs/models.py", line 7, in from rest_framework.reverse import reverse as api_reverse File "//anaconda/lib/python3.5/site-packages/rest_framework/reverse.py", line 6, in from django.core.urlresolvers import reverse as django_reverse ImportError: No module named 'django.core.urlresolvers' -
set_lanuguage is not changing the language of the enitre webpage and miss the redirections by views
My form with language selection buttons and an update button. Customer update form is implemented through django forms and views however language selections are directly implemented in html file using below code: {% load i18n %} <form action="{% url 'set_language' %}" method="post">{% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}" /> <select name="language"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected{% endif %}> {{ language.name_local }} ({{ language.code }}) </option> {% endfor %} </select> <input type="submit" value="Go" /> </form> 1:image of webpage rendered form Whenever I select any language same page with default english is rendered again. I'm the relevant context processors and locale middleware is placed where it should be in settings file. My root urlConf is given below: urlpatterns = [ url(r'^', include('custupdate.urls')), url(r'^i18n/', include('django.conf.urls.i18n')), ] urlpatterns += i18n_patterns( url(r'^', include('custupdate.urls')), My application url conf is given: urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^personBasic', views.person_detail, name='person_detail'), url(r'^licenseeBasic', views.licensee_detail, name='licensee_detail'), url(r'^address', views.address, name='address'), url(r'^contact', views.contact, name='contact'), url(r'^email', views.email, name='email'), ] My each url e.g personBasic is hooked its relevant view and view is hooked … -
How to make a topic public to all users in django?
There is problem I am creating a project, where you can make topics, that can be private or public to unauthenticated users. In every topic, you can then make several entries, applying to that topic. Now I'm trying to make a checkbox in my new_topic.html, where if you check it, it evaluates to True, if not, to False But I can't see the topic without logging in What I want I would like to show public subjects to users who have not logged in by changing the public property to True in the view, but I do not know how to implement them What I've tried I played with the query set topic.public == True but I don't know how to use that The Code My /learning_logs/modles.py looks like this: from django.db import models from django.contrib.auth.models import User class Topic(models.Model): """topic은 사용자가 공부하고 있는 주제이다.""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User, on_delete = models.CASCADE) public = models.BooleanField(default=False) def __str__(self): """모델에 관한 정보를 문자열 형태로 변환한다.""" return self.text class Entry(models.Model): """주제에 관해 공부한 내용""" topic = models.ForeignKey(Topic, on_delete = models.CASCADE) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'entries' def __str__(self): """모델에 관한 정보를 문자열 형태로 … -
Django 2.0.7 how URL app_name works
I'm working on a project built with python 3.4.3 and django 2.0.7 and I'm stuck with URLs files logic. I still haven't figured this error out: "ImportError: No module named 'fields'. Here's what I have: urls.py from django.urls import include, path from django.contrib import admin from bridge.core import views as core_views urlpatterns = [ path('', core_views.home), path('backoffice/fields/', include('fields.urls', namespace='backoffice')), path('admin/', admin.site.urls), ] fields/urls.py from django.urls import path from . import views app_name = 'fields' urlpatterns = [ path('', views.list_fields, name='list_fields'), ] What does "app_name" is supposed to be filled with? How "app_name" works? According to there files, when I submit "/backoffice/fields/" in the browser django should invoke "views.list_fields", shouldn't? If any other information is required to help me with this issue, just let me know and I'll provide it as quickly as possible. Thanks in advance -
Django File Field in model
I'm trying to display an HTML file that I upload in a model. At present, using the {{ object.file.url }} syntax simply displays the path to the file. I would like to display the file itself. The only additional pieces are that I have addressed my MEDIA_ROOT and I have added to my urls: if settings.DEBUG: urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Right now, the url displays literally as folder/file.html. Want to use the file as part of both a list and detail view with the larger model. -
Assigning html attributes to django LoginView form fields
Looking for some guidance on customising the default django LoginView. I have the HTML template set up and am now trying to replace the <input> tags with the ones supplied by the LoginView: template.html before: <html> ... <form> <div class="form-group pt-5"> <input type="email" class="form-control" placeholder="Email"> <input type="password" class="form-control" placeholder="Password"> </div> <button type="submit" class="btn btn-login">Login</button> </form> </html> template.html now: <html> ... <form> {% csrf_token %} <div class="form-group pt-5"> {{ form.username }} {{ form.password }} </div> <button type="submit" class="btn btn-login">Login</button> </form> </html> This works fine, however when it renders it is obviously missing the class and placeholder attributes. I know that I can apply these attributes within a ModelForm by using: some_form_variable = forms.CharField(widget=forms.TextInput( attrs = { 'class': 'form-control', 'placeholder':'place holder text' } )) My problem is - how do I get these onto the form that the LoginView uses? I presume I need to extend the LoginView with a custom one, but do I also need to extend the form used by the LoginView and if so, what form is this and where is it located? -
How do I setup django for automated testing with postgresql
What are the steps I need to take to configure my django app to do automated testing when I'm using a postgresql database? I've attempted to follow the very thin instructions in the docs but it doesn't work. I get the message: Django was unable to create a connection to the 'postgres' database and will use the default database instead. I tried creating a user with the name in USER in settings.py and I made it a superuser with connection privileges to postgresql but it still doesn't work. What commands do I type? Is there a tutorial I can refer to? What am I missing? Also the main database is a heroku database. -
django urls() invalid literal for int() with base 10:
I have looked at this post with no success. I have a review website and I am trying to post all reviews by a specific username. i.e. ".../reviews/user/username". urls.py: urlpatterns = [ ... url(r'^reviews/user/(?P<username>\w+)$', views.user_review_list, name='user_review_list'), ] views.py (User_Name is the name of the column in the database): def user_review_list(request, username): latest_review_list = Review.objects.filter(User_Name=username).order_by('-Pub_Date') context = {'latest_review_list': latest_review_list, 'User_Name': username} return render(request, 'bourbons/user_review_list.html', context) And the html file where I call it: <h5>Rated {{ review.Rating }} of 5 by <u><a href="{% url 'app:user_review_list' review.User_Name %}" style="color:#ffffff"> {{ review.User_Name }} </a></u></h5> I have found a couple of other posts with different methods and I still keep getting the error: "ValueError: invalid literal for int() with base 10: 'user/username'". I am using Django version 1.11.6. Thanks -
Web / App Server Configuration (Nginx / uWSGI / Django)
This is probably a silly question, but for me it's not easy to find an answer. I want to develop a web site that serves python application on aws ec2 instance. So I think it's probably the best to use Nginx and Django with uWSGI My question is What is the best architecture for this system considering Scalability? and How can I do that? At first, I thought using one Nginx server and multiple Django Application Servers, so that I can manage the resources (distribute requests to multiple application servers, since it's job can be quite heavy - recommendation based on collaborative filtering) Now I'm developing using only one ec2 instance (tiny server) Using architecture Nginx -> uWSGI -> Django project So, what is the best way to split servers for load balancing? and How can I do that using Nginx? Please let me know if this question is too ambiguous! If you know any blot posts or books related to this question, please feel free to recommend! Thanks! -
Sending plot image/object in addition to model query result and other variables to Django template
Please keep in mind that I am new to Django and web programming in general. I am trying to do something that seems like it should be simple but I can't figure it out: I have an 'object viewer' template that I am using to display information about a single selected object from the database and I want to include a graph on the page. models.py: class MaxExtent(models.Model): id = models.IntegerField(primary_key=True) geoName = models.CharField('Geounit name (territories are unique geounits)', max_length=40, null=True) sovereignty = models.CharField('Sovereign country name', max_length=32, null=True) lakeName = models.CharField('GLWD Lake name', max_length=50) areaMax = models.FloatField('Max Extent area (km^2)') area2000 = models.FloatField('2000 area (km^2)') area2001 = models.FloatField('2001 area (km^2)') area2002 = models.FloatField('2002 area (km^2)') area2003 = models.FloatField('2003 area (km^2)') area2004 = models.FloatField('2004 area (km^2)') area2005 = models.FloatField('2005 area (km^2)') area2006 = models.FloatField('2006 area (km^2)') centerLat = models.FloatField('Latitude of centroid') centerLon = models.FloatField('Longitude of centroid') poly = models.MultiPolygonField() def __str__(self): # default field for string representation if self.lakeName: return "ID {}: {} ({}, {})".format(self.id, self.lakeName, self.centerLon, self.centerLat) else: return "ID {}: Not named ({}, {})".format(self.id, self.centerLon, self.centerLat) views.py: from django.shortcuts import get_object_or_404, render from django.forms import ModelForm from .models import MaxExtent # Object viewer def objectViewer(request, req_id): waterBody = get_object_or_404(MaxExtent, … -
Countdown timer in Django
I would need a general idea for the following problem. I am creating a sports application on Django Framework. In this application there would be a link which shows what exercise has to be done for the given day. On clicking the link the following things will happen. 1) The link leads to a page which has detailed information about exercise(instruction and image). 2) Once the exercise page is loaded a countdown timer for 30 min should start. Any idea on how to implement this functionality? -
Django, delete permissions
All my users and staff users are now sorted into WHAT they can access on the site. The thing is .. the staff users all have access to templates that have some delete functionality . Most of the stuff, i want all staff to be able to delete, but some of the stuff i only want superuser to have the power to delete on the pages where i only want super user to have the power to delete i have a few options. 1.should i just set up permissions in admin panel for typical staff, and create a group, and then this will automatically restrict the staff that should not be able to delete certain things 2.should i show the delete trash can to all staff, but in the delete view, check if the staff memeber is super user and if not , somehow prevent the delete 3.or should i on raising the template use jinja to check if request.user is_superuser ...ps not sure this is possible in template and if super user display trash can if not super user do not display trash can. i want to implement the most professional and SAFE option. thanks in advance. -
Django returns 404 when HTTPS with NGINX
I'm deploying a django app on aws and it worked fine when http so I used let's encrypt to enable https. It works fine and I can see my index page but when I try to log in (post request), it returns a 404 error. I have no clue about it. This is my nginx configuration file: upstream sample_project_server { server unix:/home/ubuntu/django_env/run/gunicorn.sock fail_timeout=0; } server { listen 443 ssl; server_name mydomain.es www.mydomain.es; ssl_certificate /etc/letsencrypt/live/mydomain.es/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/mydomain.es/privkey.pem; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_prefer_server_ciphers on; ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH'; root /var/www/html; index index.html index.htm; server_name localhost; client_max_body_size 4G; access_log /home/ubuntu/logs/nginx-access.log; error_log /home/ubuntu/logs/nginx-error.log; location ~* \.(eot|otf|ttf|woff|woff2)$ { add_header Access-Control-Allow-Origin *; } location /static/ { alias /home/ubuntu/static/; } location /media/ { alias /home/ubuntu/media/; } location / { proxy_pass http://localhost:3000/; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header X-Real-IP $remote_addr;; proxy_set_header X-Forward-Proto http; proxy_set_header X-Nginx-Proxy true; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://sample_project_server; break; } if ($request_method = 'OPTIONS') { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range'; add_header 'Access-Control-Max-Age' 1728000; add_header 'Content-Type' 'text/plain; charset=utf-8'; add_header 'Content-Length' 0; return 204; } if ($request_method = 'POST') { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range'; …