Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Social account link validation in django
In my django form ..I am asking the person who is login to enter a social account link like for example :- https://www.facebook.com/firstname.lastname.31 I am new to Django.I don't know how to verify if this link exists or not after the person submits the form and if not then give appropriate error. -
Custom user models in Django: `no such table: auth_user`
According to the answer to my previous question, I edited the django-registration module with the following modifications: in myapp/models.py: from django.contrib.auth.models import UserManager from django.contrib.auth.models import AbstractUser class AccountManager(UserManager): def create_user(self, email, password=None, **kwargs): if not email: raise ValueError('Users must have a valid email address.') if not kwargs.get('username'): raise ValueError('Users must have a valid username.') account = self.model( email=self.normalize_email(email), username=kwargs.get('username'), #year_of_birth = kwargs.get('year_of_birth'), #MODEL = kwargs.get('MODEL_NAME'), ) account.set_password(password) account.save() return account def create_superuser(self, email, password, **kwargs): account = self.create_user(email, password, **kwargs) account.is_staff = True account.is_superuser = True account.save() return account class Account(AbstractUser): #email = models.EmailField(unique=True) points = models.FloatField(default = 100.0) #ADD YOUR MODELS HERE objects = AccountManager() def __str__(self): return "Account: "+self.username and in myproject/settings.py: AUTH_USER_MODEL = 'myapp.Account' now the rest of the application works (i.e. refers to Account which also has base fields from the User model). However, the django-registration module itself is not working now. When I send a new registration form (with username, email and password), I get the error: OperationalError at /accounts/register/ no such table: auth_user I tried a lot of combinations of makemigrations and migrate (also with --fake and --fake-initial arguments) but (I guess) the auth table is not initializing with the new settings. How … -
Parsing the JSON returned by a Django REST Framework API call
In my Javascript app I make an API call to my Django server's /rest-auth/registration code. If the registration attempt fails the API call returns the following JOSN which I am having problems parsing: { "_body":"{\"email\":[\"Enter a valid email address.\"],\"username\":[\"A user with that username already exists.\"]}", "status":400, "ok":false, "statusText":"Bad Request", "headers":{ "Server":[ "Apache/2.4.23 (Amazon) mod_wsgi/3.5 Python/3.4.3" ], "Transfer-Encoding":[ "Identity" ], "Content-Type":[ "application/json" ], "Date":[ "Thu", " 20 Oct 2016 13:10:04 GMT" ], "Connection":[ "close" ], "X-Frame-Options":[ "SAMEORIGIN" ], "Access-Control-Allow-Origin":[ "*" ], "Allow":[ "POST", " OPTIONS" ] }, "type":2, "url":"http://www.worldimagearchive.com/rest-auth/registration/" } I can see how to pull out the 'status' and 'ok' values but can't work out how to parse the "_body" section which may or may not contain errors for email, username, etc. I can use err.status to get at the status value, and err.ok to get at the ok value. What do I need to do to get the value of the \"email\" section (and test if that section exists?)? -
Refer to User (a Foreign Key) to fill in keyword's default value
I have a structure similar to grocery shopping baskets. The user can have many baskets, and inside each basket, there are several bags holding fruits or other types of items. I categorize each bag by item and color, that is, each bag only holds the same type of item with the same color. I keep track of how many of that item are there. So a bag may be: "3 Red Apples", another "60 Red Cherries" Each user may choose a favorite color, and this is stored as a UserOption entry. I chose not to modify the built-in User model. I want to simplify a function for computing the total number (quantity) of items of a given color in the desired basket. When no color is given, the favorite color is picked. I have a working function, called get_total_default_none, that pulls the favorite color inside the function, but my question is: Is it possible to retrieve the user's favorite color directly as the keyword default, instead of running the query inside the function? I think this (working) approach is ugly, needing to use the None as default, and then checking the UserOption. When I try referring to user (as shown … -
ProgrammingError: permission denied for relation postgres and django
This is what i have done I have configured django website on a linux server recently with a root user unfortunately Now i have created a normal user on linux server and moved the entire website to new user(adam) I expect i have configured the postgres database when i am in root But after moving to new user, i can't access some of my database tables and keep on getting the below error ProgrammingError: permission denied for relation geoapp_zipcodes_us Below are my django database settings DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'USER': 'adam', 'NAME': 'client', 'PASSWORD': 'client', 'HOST': 'localhost', 'PORT': '5432', } } Note: The database id geo django spatial and very huge in gb's, so can'delete or recreate in this stage I googled some posts and tried the below steps but din't worked out client=> GRANT SELECT ON ALL TABLES IN SCHEMA public TO adam; ERROR: role "adam" does not exist Can anyone please let me know how to remove the above permission denied for relation error ? -
geoJson : Json.load() ValueError: Expecting property name: line 2 column 9
I have troube loading my json file using the json.load(). My format is a geojson with the following example format: { "type" : "Feature Collection", {"features" : [ { "type" : "Feature", "id" : FORT_1, "geometry" : { "type" : "Point", "coordinates" : ["121.046859", "14.54544278"]}, "properties" : { "name" : "City"} }, { "type" : "Feature", "id" : FORT_2, "geometry" : { "type" : "Point", "coordinates" : ["121.0500991", "14.54973692"]}, "properties" : { "name" : "One"} }, I wanted to test it out using the following code, knowing that this will create a dict: with open(geojsonFilePath) as file: jsonFile = json.load(file) for feature in jsonFile['features']: print (['id']) print (['geometry'],['type']) print (['geometry'],['coordinates']) print (['properties'],['name']) However the error occurs at the line jsonFile = json.load(file) -
Using Django management.call_command and dumpdata gives empty output
I really don't understand what's going on. I'd like to export JSON data of a module called authentication in Python with Django 1.10.2. Here is what I'm doing: >>> from django.core import management >>> management.call_command('dumpdata', 'authentication') [] >>> authentication.User.objects.count() 9 If I run from the command line: ./manage.py dumpdata authentication The data is correctly exported. If I use management.call_command with another command it works, I get the output. Any idea? -
Django - Save a TextField and FileField of a user together
I'm making a basic blog with a title, text and an image field for a post. But I keep on getting the following error when trying to save a TextField and FileField of a model together in one view. The Error. AttributeError at /new/ 'Post' object has no attribute '_committed' Request Method: POST Request URL: http://127.0.0.1:8000/new/ Django Version: 1.9.8 Exception Type: AttributeError Exception Value: 'Post' object has no attribute '_committed' Exception Location: /usr/local/lib/python3.5/dist-packages/django/db/models/fields/files.py in pre_save, line 309 Python Executable: /usr/bin/python3 Python Version: 3.5.2 Python Path: ['/home/appu/Django/Colesk', '/usr/lib/python35.zip', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-x86_64-linux-gnu', '/usr/lib/python3.5/lib-dynload', '/home/appu/.local/lib/python3.5/site-packages', '/usr/local/lib/python3.5/dist-packages', '/usr/lib/python3/dist-packages'] The class for a Post. class Post(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length = 200) text = models.TextField() docfile = models.FileField(upload_to='documents/%Y/%m/%d') created_date = models.DateTimeField(default = timezone.now) published_date = models.DateTimeField(blank = True, null = True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title Form for the Post. class PostForm(forms.ModelForm): class Meta: model = Post fields = ('title' ,'text','docfile') View for getting the Post def new_post(request): if request.method == 'POST': form = PostForm(request.POST, request.FILES) if form.is_valid(): post = form.save(commit = False) post.docfile = Post(docfile = request.FILES['docfile']) post.author = request.user post.published_date = timezone.now() post.save() return redirect('post_detail', pk = post.pk) else: form = PostForm() return render(request, 'core/post_edit.html', {'form' : … -
Initialize two values with an if in template-django
I have a condition where I need to display values depending on an if condition. Below is my template code. Template: <td><label>Review Title/Purpose*</label></td></br> <td><input type="text" class="col-md-10" maxlength="256" ng-show="title1" ng-model="arform.revtitle" > <required/></td> <td><input type="text" class="col-md-10" maxlength="256" ng-show="!title1" ng-init="'{{reviewtit}}'" ng-model="arform.revtitle" > <required/></td> The value in ng-init="'{{reviewtit}}'" is the value I get from Views. Where as the value in ng-show="title1" is the value I get from controller. I just wanted to know is it right to use ng-show in the different ways I mentioned. Can anyone here clarify? Thanks. -
Url for Remember me Option in Django
In my django project i want to use remember me option.Now if user hit localhost/home it redirect to home page of that user.If user hit only localhost/ it is not. Localhost/ is the url of my project home page where user can find login and registration. If already logged in user exist and user hit localhost/ urlit should take user to localhost/home -
Django 1.8+ extending the User model
I know this question has been asked hundreds of times, but most of them contain -accepted- answers that are not valid anymore. Some of them are for Django 1.5, some of them are even older. So I'm looking for an up-to-date answer. The question that most resembles my problem is this one. I'm using the django-registration module and I want users to have additional fields (like integer user.points). I'm OK with implementing my own MyUser model and changing the rest of my program accordingly. However I doubt this will work in compliance with the registration module. So I guess the ideal way would be keep using the User model, and somehow tie them so that whenever a User object is created, a corresponding MyUser object is created with the default values for additional fields. -How- can I do this with Django 1.8+? Thanks for any help, -
Django change admin inline delete checkbox
I am trying to change the Delete-Checkbox for a inlinemodle on the Django-Admin-Page. Unitl now, one can check the box and after pression save it will be deleted. But I want some Button (or this "X" like when you klick "Add another...") that when it is pressed deletes immediately. I would prefere not editing the admintemplates and including a ton of javascript. Thx for your Help -
Django admin Tabular Inline 'Add More' not showing
I am using Tabular Inline in my site admin. It was working as expected, but since my upgrade from Django 1.9 to Django 1.10, it is not showing up in the screen. However, when I click on the add foreign key and the pop up appears, the add more button is showing up. Please see the screenshots. I have tried downgrading back to Django 1.9 and 1.8, but it is still same. I have also done collectstatic with clear, still same results. Please help. In the site On the pop up 2: -
How to create a "relationship" of class properties in Django models?
class Question(models.Model): whom = models.ForeignKey('UserProfile', related_name='whom_Question') who_liked = models.ForeignKey('UserProfile', related_name='who_liked_QUESTION') class Notification(models.Model) who_liked = models.ForeignKey('UserProfile', related_name='who_liked_Notification') whom = models.ForeignKey('UserProfile', related_name='whom_Notification') Is it possible to create a sort of relationship between properties of those classes, or is it inevitable to save the same information in different classes? As far as I am into documentation the only way is to create one more class and then use OneToOne relationships, right? -
Dreamhost Shared server Web application could not be started Django
I'm trying to deploy a Django app (for this question just to get to the successful default page) on a Dreamhost shared server. Dreamhost recommends deployment of Django apps using a Passenger module for Apache2 - this is the way I'm going. I'm using Python 3.5 and Django 1.9 both of which are not default on the shared server, so I've decided deploy in a virtual machine. My folder structure is as following: Home/user --| .virtualenvs ----| project-env (inside of which I use Python3 and have django installed) --| domain.com ----| public ----|--| project-pr (my Django project) ----|--| tmp ----| passenger_wsgi.py The Traceback, when trying to connect to the server is: Traceback (most recent call last): File "/dh/passenger/helper-scripts/wsgi-loader.py", line 320, in <module> app_module = load_app() File "/dh/passenger/helper-scripts/wsgi-loader.py", line 61, in load_app return imp.load_source('passenger_wsgi', startup_file) File "/home/user/.virtualenvs/project-env/lib/python3.5/imp.py", line 172, in load_source module = _load(spec) File "<frozen importlib._bootstrap>", line 693, in _load File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "passenger_wsgi.py", line 17, in <module> application = get_wsgi_application() File "/home/user/.virtualenvs/project-env/lib/python3.5/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application django.setup() File "/home/user/.virtualenvs/project-env/lib/python3.5/site-packages/django/__init__.py", line 17, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/home/user/.virtualenvs/project-env/lib/python3.5/site-packages/django/conf/__init__.py", line 55, in … -
Problems with nginx try_files setup
I'm trying to set up a project using django, gunicorn and nginx and I'm having trouble with the nginx configuration. More precisely when I use "try_files". If I use "if (!-f $ request_filename) {...}" everything works fine but if use "try_files ..." Django generates the exception: "Invalid HTTP_HOST header: 'myproject_server'. The domain name provided is not valid according to RFC 1034/1035.". Once everything works using the "if ..." I assume that the other settings (gunicorn etc) are correct. The configuration files I'm using are: /home/myproject/myproject/settings.py (django) ... ALLOWED_HOSTS = [192.168.200.100, ] ... /etc/nginx/sites-available/myproject (this one WORKS) upstream myproject_server { unix server:/home/myproject/run/gunicorn.sock fail_timeout = 0; } server { listen 80; server_name 192.168.200.100; root /home/myproject; location /media/ {} location /static/ {} location / { proxy_set_header Host $ HTTP_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-Proto $ scheme; if (!-f $request_filename) { proxy_pass http://myproject_server; break; } } } /etc/nginx/sites-available/myproject (this one DOES NOT WORK) upstream myproject_server { unix server: /home/myproject/run/gunicorn.sock fail_timeout = 0; } server { listen 80; server_name 192.168.200.100; root /home/myproject; location /media/ {} location /static/ {} location / { proxy_set_header Host $ HTTP_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-Proto $ scheme; try_files $uri @myproject_backend; … -
Django Select Related
i want to filter the database like this . qs = profile.objects.filter().select_related('profile_detail').select_related('location') But here location is a foreignkey in profile_detail model. So how can i do that query class Location(models.Model): place = models.CharField(max_length=128) class ProfileDetail(models.Model): location = models.ForiegnKey(Location) class Profile(models.Model): detail = models.ForeignKey(ProfileDetail) -
How to customize celery job to work at a specific time given by user?
I have to create an application with user interface using django , So now I will have a user interface where user will select certain mp3.file from drop down and he will select some date and time .At that time my server has to schedule that particular job and it has to do it on time. In order to do this in python I have tried schedule, apschedule now but i was unable to run a job at given time (there can be many jobs to run) Then I got a suggestion like using celery-- I have got few doubts here : Is celery used only for scheduling n number of jobs only at predefined time? 2.Can I run a job after filtering datatime and filename from database using celery ? Is this the only way to schedule a job in celery or can we customize it by filtering data from database? CELERYBEAT_SCHEDULE = { # Executes every Monday morning at 7:30 A.M 'add-every-monday-morning': { 'task': 'tasks.add', 'schedule': crontab(hour=7, minute=30, day_of_week=1), 'args': (16, 16), }, } -
How to use socket objects inside Celery tasks using Django?
I am stuck with an issue regarding serializing socket objects for a long time and need help. Before I state my problem, here is the technology stack of the application I am building. Django-1.8.7 Redis Celery MySQL gevent-socketio greenlet Here is the background of the problem : I want to send notifications asynchronously in my application without making the request wait for the notifications to be sent to the subscribers. I am using Celery to run the tasks for sending notifications via sockets which are created when a user logs in into the application. The problem is Celery doesnt recognize the sockets created inside the django application. My attempts : I tried multiple ways to serialize the sockets object and pass it to Celery task but I keep getting this error. "Socket Object cannot be serialized" I also tried storing the sockets in cache so that I can retrieve from the cache during the Celery task. But then I get this error while inserting into cache - "cannot serialize 'Hub' object" or ""cannot serialize 'Greenlet' object" Also took help of the below answer, but no luck. http://stackoverflow.com/a/26164781/6876786 Can someone help me fix this problem? Thanks in Advance! -
What is Wrong here in the code?
What is wrong in the code? I have email registered! what is happening here and showing that email does not exist? I have email registered! what is happening here and showing that email does not exist? views.py from django.contrib.auth import( authenticate, get_user_model, login, logout, ) from django.shortcuts import render from .forms import UserLoginForm # Create your views here. def login_view(request): form = UserLoginForm(request.POST or None) if form.is_valid(): email = form.cleaned_data.get("email") password = form.cleaned_data.get("password") return render(request, "accounts/form.html",{"form":form}) def register_view(request): return render(request, "form.html",{}) def logout_view(request): return render(request, "form.html",{}) I have email registered! what is happening here and showing that email does not exist? forms.py from django import forms from django.contrib.auth import( authenticate, get_user_model, #email, login, logout, ) User = get_user_model() class UserLoginForm(forms.Form): email = forms.EmailField() password = forms.CharField(widget=forms.PasswordInput) def clean(self, *args, **kwargs): email = self.cleaned_data.get("email") password = self.cleaned_data.get("password") user = authenticate(email=email, password=password) if not user: raise forms.ValidationError("This Email Is not Registered") if not user.check_password(password): raise forms.ValidationError("Incorrect Password") if not user.is_active: raise forms.ValidationError("Account Not Active") return super(UserLoginForm, self).clean(*args,**kwargs) what is wrong here? I have email registered! what is happening here and showing that email does not exist? -
dockerize does not delay the conatiner initialization
I am now preparing the images for my project. I use dockerize to control my initialization. I am not sure that hardcode the IP address given by docker is way to go or not? Problem: 1. backend does not wait until the database finish initialization first Terminal says backend_1 | django.db.utils.OperationalError: could not connect to server: Connection refused backend_1 | Is the server running on host "sakahama_db" (172.21.0.2) and accepting backend_1 | TCP/IP connections on port 5432? Here are my files: devdb.dockerfile FROM postgres:9.5 # Install hstore extension COPY ./Dockerfiles/hstore.sql /docker-entrypoint-initdb.d RUN mkdir -p /var/lib/postgresql-static/data ENV PGDATA /var/lib/postgresql-static/data hstore.sql create extension hstore; backend.dockerfile FROM python:2 RUN apt-get update && apt-get install -y wget ENV DOCKERIZE_VERSION v0.2.0 RUN wget https://github.com/jwilder/dockerize/releases/download/$DOCKERIZE_VERSION/dockerize-linux-amd64-$DOCKERIZE_VERSION.tar.gz \ && tar -C /usr/local/bin -xzvf dockerize-linux-amd64-$DOCKERIZE_VERSION.tar.gz RUN mkdir /usr/src/app WORKDIR /usr/src/app COPY requirements ./requirements RUN pip install -r requirements/local.txt COPY . . EXPOSE 8000 CMD echo "dockerize" CMD ["dockerize", "-wait", "tcp://sakahama_db:5432"] CMD echo "migrate" CMD ["python", "sakahama/manage.py", "migrate"] CMD echo "runserver" CMD ["python", "sakahama/manage.py", "runserver", "0.0.0.0:8000"] docker-compose.yml version: "2" services: backend: build: context: . dockerfile: Dockerfiles/backend.dockerfile restart: "always" environment: DATABASE_URL: postgres://username:password@sakahama_db:5432/sakahama REDISCLOUD_URL: redis://redis:6379/0 links: - sakahama_db ports: - "9000:8000" sakahama_db: build: context: . dockerfile: Dockerfiles/devdb.dockerfile environment: POSTGRES_USER: username POSTGRES_PASSWORD: password … -
Does PHP have to go along with SQL?
I have been researching Sql, Django, PhP, I saw this one tutorial on creating a social network website and they were using SQL in conjunction with PHP. Is this always required? What does the PHP do for the SQL? I know it is a server side, but isn't Django as well? So I can use Django/SQL instead of PHP/SQL? -
django get files from different directories
I have a django app (installed on a Debian server) where there is file upload. Traditionaly, it ulpload in a folder in site_media. For some reason,(please don't ask why,take it for granted) I have to save the files in a different disk. The path to the other disk is /disk/site_media The saving do the other disk is donw succesfully! When I try to open the file by clicking on it , I get File not Found. I am open to ideas!!! Here's my code when uploading the file: obj = form.save(commit=False) obj.user_id = self.request.user.pk obj.save() initial_path = obj.file.path print(initial_path) new = settings.MEDIA_ROOT_NEW + obj.file.name print(new) #os.rename(initial_path,new) shutil.move(initial_path, new) I upload the files in my EmployeeDoc class: class EmployeeDoc(models.Model): file = models.FileField('DocFile', upload_to='edocs/') employee = models.ForeignKey(Employee , related_name='documents') user = models.ForeignKey(User , related_name='employeedocs') created_at = models.DateTimeField(auto_now_add=True,default=timezone.now) update_at = models.DateTimeField(auto_now=True,default=timezone.now) I get the files in my template with a function written under my Employee class: class Employee(models.Model): name ... last ... def getDocuments(self): return EmployeeDoc.objects.filter(employee_id=self.pk,del_f=0) Here are my paths in settings.py: MEDIA_ROOT = os.path.join(PROJECT_PATH, 'site_media/') MEDIA_ROOT_NEW = '/disk/site_media/' MEDIA_URL = '/site_media/' In my urls.py despite all the othe urls I have: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
How to work with Front End developer when you use Django web framework?
I am new for web programming. so I am very confused with concepts. I understood that Front-End developer and Back-End developer have different duty simply like below. Front-End developer : html css js Back-End developer : Django Web framework in Server Back-End developer(Server -> Data) Front-End Developer(Data->html with css,js(JQuery,Angular..)) I understood that Django framework is coupled with Front-End side. So I would like to send data by django rest framework to spearate duty more clearly(uncoupled way) for front-end and back-end developers. I thought that if Front-end developer knows information of data**(like below)** which they will get for page(template) or send, They can build up page with html, css, js without any coupled works. { "id": { "type": "integer", "required": false, "read_only": true, "label": "ID"} "title": { "type": "string", "required": true, "read_only": false, "label": "Title", "max_length": 200} ... } but I am very confused. for example you can get list of users by Get Method example.com/home.(JSON type) you need to show this lists on template(with html,css,js or JQuery or something). if you hit example.com, urls config find right view with regex and then render template like below example.com/home -> Server -> url config -> views -> template(render) urls.py url(r'^home$'), something_view.as_view() views.py … -
Changing Django's Admin Create/Change Form Layout
I have a simple model of a Student which is registered to the admin through a admin.ModelAdmin. The admin change form of this model looks like this: I'd like to change the layout of this form a little so that a few fields could be in the same line, like so (edited in Paint): Is there something I could do without overriding the default templates? And if there isn't, what's the best way? Thanks in advance.