Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ValueError, even if doesn't have any active mentions
I'm writing a forum application written entirely in Django, but whenever I try to visit a topic of an user without avatar (I don't want to make it necessary), it throws ValueError. I've tried to comment every mention of avatars on template, but it still doesn't work. topic.html (template) {% for post in posts %} <div class="row mb-3"> <div class="col-sm-10"> <div class="d-flex col mt-0 text-white" style="background-image: linear-gradient(to right, darkblue , blue);"> {{ topic.titleName }} </div> <div class="d-flex col bg-secondary"> <div class="row"> <div class="col-sm-3 border-right border-light"> <!--img src="{{post.author.avatar.url|default:"user_avatars/None/placeholder.jpg"}}" alt=" " class="avatar-forum rounded-circle"--> <br> {{ post.author }} </div> <div class="col-sm-9"> <div class="d-flex col"> Przez:{{post.author}} >> {{ post.created_date }} </div> <div class="d-flex col"> {{ post.postData }} </div> </div> </div> </div> </div> <div class="col-sm-2"> </div> </div> {% endfor %} models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(upload_to='user_avatars/', default = 'user_avatars/None/placeholder.jpg') is_blocked = models.BooleanField(default=False) @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() def __str__(self): return self.user.username Traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/retrobaza/topic/x Django Version: 2.1.7 Python Version: 3.7.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'retrobaza'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template D:\ZPW\mysite\retrobaza\templates\base.html, error at line 11 The 'avatar' attribute … -
Android Rest Authentication not returning the status code or network response
I have a android consuming a django REST API backend which includes token based authentication. The problem is that whenever a user provides a wrong email or password, i expect a 403 error from the code below but the volley library does not get the response code. This is the backed service in django rest. def api_authenticate_user(request): try: email = request.data['email'] password = request.data['password'] user = authenticate(email=email, password=password) if user is not None: try: payload = jwt_payload_handler(user) token = jwt.encode(payload, settings.SECRET_KEY) user_logged_in.send(sender=user.__class__, request=request, user=user) user = User.objects.get(email=email) user_details = {'token': token, 'names': user.get_name(), 'id': user.id} return JsonResponse(user_details, status=status.HTTP_200_OK) except Exception as e: raise e else: return JsonResponse({'error': 'Invalid email address or password', 'status': status.HTTP_403_FORBIDDEN}) except KeyError: return JsonResponse({'error': 'Provide email and password', 'status': status.HTTP_403_FORBIDDEN}) In my android app, this is how am trying to get the response code so that i can alert the user to enter the right credentials. private void UserLoginTask(final String email, final String password) { StringRequest request = new StringRequest(Request.Method.POST, loginUrl , new Response.Listener<String>() { @Override public void onResponse(String response) { try { JSONObject userObj = new JSONObject(response); userSession.initializeSession(userObj.getString("names"), email, userObj.getString("token")); Intent intent = new Intent(Login.this, MainActivity.class); startActivity(intent); finish(); } catch (JSONException e) { e.printStackTrace(); errorText.setText("Could … -
django throws error: Invalid column name 'id' (SQL SERVER)
I try to create a web app using django and connecting to a SQL Server Database. The table that I use to display the data in a django form consists of 2 columns. Both of them being a foreign key and both of them together building the primary key of the table CREATE TABLE [dbo].[MyTable]( [ID_Field1] [int] NOT NULL, [ID_Field2] [int] NOT NULL, CONSTRAINT [PK_Movies2Genres] PRIMARY KEY CLUSTERED ( [ID_Field1] ASC, [ID_Field2] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] ALTER TABLE [dbo].[MyTable] WITH CHECK ADD CONSTRAINT [FK_Field2] FOREIGN KEY([ID_Field2]) REFERENCES [dbo].[Table2] ([ID_Field2]) ALTER TABLE [dbo].[MyTable] CHECK CONSTRAINT [FK_Field2] ALTER TABLE [dbo].[MyTable] WITH CHECK ADD CONSTRAINT [FK_Field1] FOREIGN KEY([ID_Field1]) REFERENCES [dbo].[Table1] ([ID_Movie]) ALTER TABLE [dbo].[MyTable] CHECK CONSTRAINT [FK_Field1] Now, django appernatly cannot create a model corresonding to this kind of sql table structure, i.e. it cannot create a primary key consisting of more than one field. Instead, it sets the primary key on one of the 2 columns and in the meta section of the model class it sets unique_together = (('id_field1', 'id_field2'),) The complete model: class MyTable(models.Model): id_field1 = models.ForeignKey(Table1, on_delete=models.DO_NOTHING, db_column='ID_Field1') id_field2 = models.ForeignKey(Table2, … -
While submitting the form - Validation Error : Value Error
I have created a User Login Form. I want to save answer to a Question Submitted by the User. While submitting the form for answer Django is throwing value error Model class Day11(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,null=True) ans = models.CharField(max_length=100, default=0) time = models.TimeField(auto_now=True) Form class Ans1(forms.ModelForm): ans = forms.FileField(required=True) def save(self, commit=False): answer = super(Ans1, self).save(commit=False) answer.ans = self.cleaned_data['ans'] if commit: answer.save() return answer class Meta: model = Day11 fields = ('ans',) exclude = ('user',) View def email(request): print("test1") if request.method == "POST": form = Answer(request.POST) if form.is_valid(): post = form.save() post.author = request.user form.save() return redirect('/') else: print("error") else: form = Answer() return render(request, 'day1/email_q1.html', {'ans1_1': form}) -
How do I catch IntegrityError in Django when using UniqueConstraint across multiple fields?
I have a model with user as 1 field (Foreign Key) and one other field skill_group. I need to make sure the user does not add duplicate skill groups so I added a UniqueConstraint. This is working as the system errors out with IntegrityError at /skillgroup/create/ duplicate key value violates unique constraint "unique_skillgroup" - How do I catch this exception and notify user if duplicate; otherwise save it? New to Django/Python/Postgres and I thought I could handle it by overriding the save() function, but there is no access to user which is part of the check and I have read this should not be handled here. Is there a try/save catch/message I should be employing? I have tried a few things with no luck. I have seen similar questions on here, but they have not helped. Any help is appreciated. models.py class SkillGroup(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) skill_group = models.CharField(max_length=35) sequence = models.IntegerField(default=999) class Meta: constraints = [ models.UniqueConstraint(fields=['user', 'skill_group'], name='unique_skillgroup'), ] def __str__(self): return self.skill_group def get_absolute_url(self): return reverse('skillgroup-list') views.py class SkillGroupCreateView(LoginRequiredMixin, CreateView): model = SkillGroup fields = ['skill_group'] def form_valid(self, form): form.instance.user = self.request.user form.instance.sequence = SkillGroup.objects.filter(user=self.request.user).order_by('sequence').last().sequence + 1 return super().form_valid(form) skillgroup_form.html {% extends "recruiter/baseskills.html" %} {% load … -
How to debug web requests with Django and pdb?
I would like to use pdb to debug a view in Django but so far i've been unsuccessful, getting a BdbQuit error: The view i've tried this on is a simple get request: def get_file_names(request): pdb.set_trace() my_files = Files.objects.filter(user_id=request.user)) name_list += list(map(lambda x: (x.id, x.name, x.description), my_files)) return JsonResponse({'rows': name_list}) A couple notes: I prefer not to use Django pdb since this forces me to modify the client's request parameters. I also do not want to call my code from pdb (since this code is being called from the client). Django Version 1.10.6 Does anyone have a solution which works? Im finding that debugging complex web requests in python can be very tedious and it would be really amazing if pdb worked. Note this is not a subprocess, just a simple get request (eventually i would like it to work on a more complex request but i've posted a simple example since this already fails). Any suggestions? Suggestions here dont seem to work. -
An Android app should be able retrieve data from a sqlite database where django page will act as an admin on the same db
I am trying to create an android app on sqlite db , and I want to add data to the db using a django web page. How am I supposed to achieve that ? Is it possible that two of platforms (Android and web page) are connected to the same database? The web page will be used to write to the database and the android app will only be used to retrieve data from the db . -
send images with ajax and django
I try to send images from <input type="file" id="file" name="file" accept="image/*" multiple> without sending al the form. I found many post which explain this so I do this urls.py url(r'^images/', 'app.views.images', name='images'), view.py def images(request): if request.method == 'POST': print('hello') jquery $("#file").change(function (){ try{ var formdata = new FormData(); var files = $('#file')[0].files; formdata.append('file',files); jQuery.ajax({ url: "images/", type: "POST", data: formdata, processData: false, contentType: false, success: function (result) { // if all is well // play the audio file } }); } catch(err){ alert(err.message); } }); But this gives me "POST /images/ HTTP/1.1" 403 error I did diferent test and I think the error is the data: formdata part -
gunicorn static files not found
I'm building a REST Api in Django. I'm launching it with Gunicorn, but I have the following when I go to the admin page : Not Found: /static/admin/css/dashboard.css Not Found: /static/admin/css/fonts.css Not Found: /static/admin/css/base.css Not Found: /static/admin/css/responsive.css Not Found: /static/admin/css/base.css Not Found: /static/admin/css/dashboard.css Not Found: /static/admin/css/responsive.css Not Found: /favicon.ico Not Found: /static/admin/css/base.css Not Found: /static/admin/css/login.css Not Found: /static/admin/css/responsive.css Not Found: /favicon.ico And the same for Rest Framework CSS files. I tried to run "python3 manage.py collectstatic", I effectively have a "static" folder , but I have the same problem. In my settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") Is there any way to have CSS served by Gunicorn ? -
When I call models from other app it doesn't show. In shell work
I'm trying to call app models from a project views. In the app work but not in project. Project location - SSS - gallery - models.py - views.py - apps.py - admin.py - sss - settings.py - views.py - urls.py - __init__.py from gallery.models import Gallery def homepage(request) galleries = Gallery.objects.all() return render(request, 'index.html', {'galleries': galleries}) How I call in HTML {% for galleries in gallery %} <li class="diamond"> <img src="{{ MEDIA_URL }}{{ gallery.images.url }}" alt=""> </li> {% endfor %} But nothing Shown up. Please Help. Sorry for my English. I'm not good at describe. -
Django form can't see any data from fileupload
I searched a lot in google. I found that I need to add enctype="multipart/form-data" to form, but it still doesn't work. Everywhere, whenever i want to get this file it is just null. Everything else works as I excepted. Here's my code: home.html {% extends 'base_template.html' %} {% block content %} <h1> Welcome to the home jd! </h1> <form action = "{% url 'home' %}" method = "post" enctype="multipart/form-data"> {% csrf_token %} {{form}} <input type = "submit" value = "add new track"> </form> {{message}} {% endblock %} view: class home(View): template_src = "home.html" def get(self, request): form = forms.AddTrack() return render(request, self.template_src, {'form': form}) def post(self, request): form = forms.AddTrack(request.POST) print(request.POST) # Here fileupload field is also blank if form.is_valid(): record = form.save(commit=False) record.author = request.user record.save() form.clean() return render(request, self.template_src, {'message': 'Added new track!', 'form': form}) else: return render(request, self.template_src, {'message': 'Incorrect input!', 'form': form}) model: class Track(models.Model): title = models.CharField(max_length=40, null=True) description = models.CharField(max_length=500, null=True) author = models.ForeignKey(User, default=None, on_delete=models.CASCADE) audio_or_video = models.FileField(upload_to='audio_and_video/', default="file_not_found", validators=[validate_file_extension]) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) validators.py def validate_file_extension(value): import os from django.core.exceptions import ValidationError ext = os.path.splitext(value.name)[1] valid_extensions = ['.mp4', '.wav', '.webm', '.mp3'] print(os.path.splitext(value.name)) #it prints('file_not_found') models.py default value) if not ext.lower() … -
Django ORM left join with nested condition?
I am trying to build an ORM query in django. First please look at the database schema. Meeting Table ( meeting_meeting ) +----+------+------+ | id | host | name | +----+------+------+ | 1 | 1 | M1 | | 2 | 8 | M2 | | 3 | 1 | M3 | | 4 | 1 | M4 | +----+------+------+ Participans Table ( meeting_participants ) +----+------------+---------+ | id | meeting_id | user_id | +----+------------+---------+ | 1 | 1 | 8 | | 1 | 3 | 8 | +----+------------+---------+ All I am trying to do is to generate a list of meeting that someone either created or joined. For example user 8 created only one meeting (M2) but joined on two meetings ( M1 & M3 ). So the query will return M1,M2 and M3 as Meeting QueryDict. I have already done the query with pure sql. SELECT DISTINCT meeting_meeting.id, meeting_meeting.* FROM meeting_meeting LEFT JOIN meeting_participants on meeting_participants.meeting_id = meeting_meeting.id and ( meeting_meeting.host_id = 8 OR meeting_participants.user_id = 8 ) I am just not sure how to do that with ORM in Django. I did find some reference about prefetch_related and select related but I can't seem to put the … -
what could be the reason _set is not created on FK relation creation in Django?
I have the following data structure class A(models.Model): a number of fields here class AbstractParent(models.Model): some fields here class Meta: abstract = True class B(AbstractParent): a = ForeignKey(A, null=True,default=None, blank=True, on_delete=models.SET_NULL) I would expect to access the object of B class that fk to an instance of A a via a.b_set or a.bs_set however I only get the error that attribute b_set does not exist for a. Any ideas why this is possible and how to access b that references a via a itself? -
Can I use django tags in ckeditor?
I want to ask you: Can I use django-template tags in ckeditor? click here to see ckeditor and tags result: click here to see results P.S.: I use {{ post.body|safe }} in my html template -
Django: How to deploy static files on an apache server in production
Static files are not loading in production of my Django project. I am using mod-wsgi to serve the static files. Static files were serving fine in development (when DEBUG=True), but now I get 404 errors when the static files are trying to be called. My file structure is: https://imgur.com/a/FuFZSSh /etc/apache2/sites-available/mysite.conf <VirtualHost *:80> ServerName <ip address> ErrorLog ${APACHE_LOG_DIR}/mysite-error.log CustomLog ${APACHE_LOG_DIR}/mysite-access.log combined WSGIDaemonProcess mysite processes=2 threads=25 python-path=/var/www/mysite WSGIProcessGroup mysite WSGIScriptAlias / /var/www/mysite/mysite/wsgi.py Alias /robots.txt /var/www/mysite/static/robots.txt Alias /favicon.ico /var/www/mysite/static/favicon.ico Alias /static/ /var/www/mysite/static/ Alias /media/ /var/www/mysite/media/ <Directory /var/www/mysite/mysite> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /var/www/mysite/static> Require all granted </Directory> <Directory /var/www/mysite/media> Require all granted </Directory> </VirtualHost> settings.py STATIC_ROOT = '/var/www/mysite/static_root/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) STATIC_URL = '/static/' MEDIA_ROOT = '/var/www/mysite/media/' MEDIA_URL = '/media/' Any help would be greatly appreciated :) -
Use pydub with AWS-stored files
I want to concatenate two files I'm storing in AWS, save them as .wav and pass them to IBM's Speech-to-Text API. This is how a normal call to IBM looks like. with open(join(dirname(__file__), './.', 'audio-file.wav'), 'rb') as audio_file: recognition_job = speech_to_text.create_job( audio_file, content_type='audio/wav', timestamps=True ).get_result() Can pydub export directly to AWS, as online I cannot have it stored locally? Thank you in advance! -
Where should I put `requirements` folder for django login template?
According to documentation: It’s your responsibility to provide the html for the login template , called registration/login.html by default. Where should I put registration folder? I tried putting it in top folder (same place as manage.py). When that didn't work, I added registration to the INSTALLED_APPS list in settings.py. That didn't help either. I tried putting registration in the project folder (next to settings.py), and that didn't work either. My project's urls.py: from django.contrib import admin from django.urls import include, path from django.conf import settings from django.conf.urls.static import static from django.contrib.auth import views as auth_views urlpatterns = [ path('myapp', include('myapp.urls')), path('login', auth_views.LoginView.as_view(), name='my_login'), path('admin/', admin.site.urls), ] -
How to increase import processing speed in django?
I am using the django import-export module to import xlsx files. When the number of rows is less (say about 2000) the file is getting imported quickly. But this is not the case when I upload a file about 50k rows. It is showing some error like "Transaction support timed out." How can I upload a large xlsx file through django import - export? Thanks -
Collect static error while deploying app on Heroku
I had a problem with a Django app uploaded on Heroku, so I deleted the app and I'm trying to re-upload it. But now an error occurs while collectstatic is running. The error This what I have in settings.py for the statics files: STATICFILES_DIRS = [os.path.join(BASE_DIR, "static"),] STATIC_URL = '/static/' if os.environ.get('DJANGO_DEBUG') == 'PRODUCTION': # Static files settings PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles') # Extra places for collectstatic to find static files. STATICFILES_DIRS = (os.path.join(PROJECT_ROOT, 'static')) STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) I don't understand why it's occurring as the only things I changed compared to the previous version is the name of the project. Also, I'm on Window, so it's normal that I don't have Linux files. How can I fix this error ? Or how can I install the file ? (I tested with git bash, but the commands are not recognized). -
The Django template
{% extends "base.html" %} {% block head_title %}About Us{% endblock %} {% block content %} <p>about {{ title }}</p> {% endblock %} I don't understand why this isn't working. <title>{% block head_title %}{% endblock %} Title</title> <body>{% block content %} {% endblock %}</body> These {%block%} are not having effect. I'm not getting any error but instead of displaying 'About us' and 'about' it's displaying blank. Thanks -
Framework auto migrations
In Django (and some other frameworks) there is auto migration generation functionality: For example I create a class: class User(models.Model): group = models.ForeignKey(Group, on_delete=models.CASCADE) date_joined = models.DateField() And with some command you can create migrations: So if you delete the row date_joined for example and run the command it will drop the column. I want to ask if it is possible to rename the column without manually creating migration. If I want to rename "date_joined" to "date_registered". Yes, the framework doesn't know whether it should rename the column or drop and add a new one. So my question is is there solution clever solution that would not need to create manually creating the migrations or it can be done automatically with minimum coding. I need only an idea or pseude code, not code. Thanks -
Nginx+Django error: ERR_TOO_MANY_REDIRECTS or 502 Bad Gateway
I'm trying to deploy a django app with NGINX reverse-proxy server. My /etc/nginx/conf.f/app.conf looks like this: server { listen 80; listen 443 ssl; server_name myhost.com; ssl_certificate /etc/letsencrypt/live/myhost.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/myhost.com/privkey.pem; location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } When I open myhost.com, I get browser's ERR_TOO_MANY_REDIRECTS error. I don't know how to fix it, but if I rewrite http://127.0.0.1:8000 as https://127.0.0.1:8000, I get 502 Bad Gateway error. Django is listening at: http://127.0.0.1:8000. -
current path didnt match in django
i want get my album.object.all() coding running in my web site. i have included data but after putting it in urls.py file it doesnt find the path to response. please help me. this is django 1.11.2 my urls.py file ''' from django.conf.urls import url from django.contrib import admin from myapp import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.home, name='home'), url(r'^album/?$', views.music, name='music'), url(r'^album/(?P<album_id>\d+)/$', views.detail, name='detail'), url(r'^Database/?$', views.Database, name='Database'), ]''' my views.py file from django.shortcuts import render from django.http import HttpResponse from myapp.models import Album # Create your views here. '''def home(request): return render(request, 'index.html') def music(request): all_albums = Album.objects.all() context ={'all_albums': all_albums,} return render(request, 'album.html', context) def detail(request, album_id): return HttpResponse("<h2>Details for album id: " + str(album_id) + "</h2>") def Database(request): return render(request, 'data.html')'' ' my model.py page ' ''from django.db import models class Album(models.Model): artist = models.CharField(max_length=250) album_title = models.CharField(max_length=500) genre = models.CharField(max_length=100) album_logo = models.CharField(max_length=1000) def __str__(self): return self.album_title+ ' - ' +self.artist class Song(models.Model): Album = models.ForeignKey(Album, on_delete=models.CASCADE) #any songs of the related to the deleted album will be deleted file_type = models.CharField(max_length=10) song_title = models.CharField(max_length=200)''' want to use it get the whole directory by =album_id -
Django and Image recognition
I have a table in Django which stores images. I would like to make an Django Rest API that receives an image , use an image recognition to identify the image and return the fields associated to the image. Using sift from opencv i have made a python image recognition file that works but I dont know how I can integrate it into Django. I to receive and send info as json How can I integrate this? -
Mathematics Calculation using Python
Suppose there are 12 students in a class in school. The minimum number of student required in a section( Let's say Section A) is 5.How do I divide the class into three sections(Let's say A, B, C) so that Section A has 5 students, Section B has 5 students, and Section C has 2 students using python code