Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Nginx not serving static files in production with whitenoise
Everything looks like it should work, but I get a 404 error in console for all static files including css, js and images. What am I doing wrong? Everything else seems to work just fine. nginx.conf server { listen 443 ssl; server_name www.${NGINX_HOST}; ssl_certificate /etc/letsencrypt/live/${NGINX_HOST}/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/${NGINX_HOST}/privkey.pem; ssl_trusted_certificate /etc/letsencrypt/live/${NGINX_HOST}/chain.pem; location / { proxy_pass http://api; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static { autoindex on; alias /myapp/collectedstatic/; } location /media/ { autoindex on; alias /myapp/media/; } } settings.py STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' ... MIDDLEWARE = [ ... 'whitenoise.middleware.WhiteNoiseMiddleware', ... ] STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'collectedstatic') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') -
Is it possible to cycle through django model object fields?
I have a user & user_profile model and I've allowed signup with nullable fields so user can fill profile later but I want the app to check if any profile fields are null after every login. Is it possible to cycle through django model object fields? I tried the below code and got 'uProfile is not iterable' def profile_Populated(usr): for x in usr: if x == 'null': return False return True if profile_Populated(request.user.uProfile) == True: pass else: return redirect("account:profile_edit") -
How to redirecting to a page after registering a user in - Django
After a user successfully registers an account, the webpage redirected to some other locations... I want it to redirect to a specific path, 'products/index' (products is myapp) after successful registration the user logged in automatically. I am here using function based view.. -
Authenticate user if present in the group
I want to authenticate user only if the user in present in a specific group. Can someone tell me how can I do it please ! I am doing this to add user to a group when user signs up but this is also not working def stusignup(request): if request.method == "POST": name = request.POST['name'] email = request.POST['email'] pass1 = request.POST['password1'] pass2 = request.POST['password2'] if not pass1 == pass2: messages.error(request,"Please enter same password!") else: myuser = User.objects.create_user(username=name,password=pass1,email=email) myuser.name = name myuser.email = email myuser.password = pass1 myuser.save() group = Group.objects.get(name='Student') myuser.groups.add(group) return redirect('studentloginpage') return render(request,'stusignup.html') views.py def stuloginpage(request): if request.method == 'POST': user_email = request.POST['email'] pass1 = request.POST['password'] user = User.objects.get(email=user_email,password=pass1) if user.groups.filter(name = 'Student').exists(): if user is not None: login(request,user) return redirect('homepage') #messages.success(request,'Login Succcessful') else: messages.info(request, "Username OR Password is INCORRECT") else: return HttpResponse("You aren't a Student !") I also tried this def is_student(user): return user.groups.filter(name='Student') @user_passes_test(is_student) I need help in adding the user to a group at the time of sign up and then before login checking if the user is in a particular group ! -
How to transfer file from one model to another model?
I have a model in my django app which stores a file. I have made another model in the same app to store the files using foreign key from the 1st model. When a new file arrives in model 1 push the existing file to the model 2, and keep the new file in the model 1 and all the old files in model 2. Does any one have any idea that how can I implement it. -
How can I load media file from js to django's template?
video.js file code here is my js file that has a media file that I want to load in django template. also in the template there is no code for that specific file...the template execute the js file and tries to show the media. After running the server but as I can guess without the {% load static %} tagging django won't show the media and also this {% load static %} tagging is unavailable in django. -
Django: Render text and link from a textfield in database
I am new to web development and currently building a blog. I am trying to render some text that I wrote in a textfield inside the database. The problem is that this text includes a link that redirects to another blog article. This is the textfield from database Some text I want to render in blog with a link <a href="{{ STATIC_URL }}/articles/8-Photogenic-Spiral-Staircases" class="link-within">8 Photogenic Spiral Staircases</a> html <p class="article-redirect">{{ article.redirect|safe|escape }}</p> The HTML is successfully rendered using |safe filter but when I click on the link it displays a 404 error, the requested URL in the error message is Request URL: http://localhost:8000/articles/7-Photogenic-Spiral-Staircases%7B%7B%20STATIC_URL%20%7D%7D/articles/8-Photogenic-Spiral-Staircases In the above requested URL that caused the error, "7-Photogenic-Spiral-Staircases" is the current blog post and "8-Photogenic-Spiral-Staircases" is the blog post that I want to jump to. Can someone help me understand why this is not working and what could be the possible solution? models.py class Articles(models.Model): title = models.CharField(max_length=155) slug = models.SlugField(unique=True, max_length=155) summary = models.TextField(blank=True, null=True) redirect = models.TextField(blank=True, null=True) views.py def article(request, slug): article = get_object_or_404(Articles, slug=slug) context = { 'article': article, } return render(request, 'articletemplate.html', context) urls.py urlpatterns = [ path("articles/<str:slug>/", views.article, name="articles") ] -
How do we make a htmx response trigger a form reset?
I am creating a very basic Django messaging application, and would like to use htmx to send and render messages. I am able to post, save the message, and render the partial message without issue. However, I am running into a weird problem where my form textarea is not being reset. So, I would send a message, and after the swap is inserted, my old message would still be in the textarea. This isn't very ideal! I tried to manually clear the textarea by adding an onclick event like so: Html <div id="new-message-div"></div> <form id="message-form" class="chat-form rounded-pill bg-dark" data-emoji-form="" hx-post="{% url "chat:create-message" object.pk %}" hx-target="#new-message-div"> ... {{ message_form }} ... <button class="btn btn-icon btn-primary rounded-circle ms-5" type="submit" onclick="submitForm()"> </button> </form> Script (https://stackoverflow.com/a/14589251/12758446) <script> function submitForm() { var message_form = document.getElementById('message-form'); message_form.submit(); // Submit the form message_form.reset(); // Reset all form data return false; // Prevent page refresh } </script> Despite having the message_form.submit() in the submitForm(), my form is not being submitted, but the textarea is getting reset. Question: How would I go about getting my textarea reset after successfully sending and rendering a message? Django view, based off of https://github.com/legionscript/socialnetwork/blob/84375841429887e394a2a31e1b67919f81a3cb06/social/views.py#L428 def create_message(request, pk): message = None if request.htmx: thread … -
Django login + pasword
[enter image description here][1] [1]: https://i.stack.imgur.com/ECii0.jpg Всем привет уважаемые коллеги! Сразу хочу сказать что, я недавно в IT и только учусь, прошу не употреблять профессиональные выражения, в решении данного вопроса, благодарен заранее! Я развернул проект Django, создал свой проект, хочу свой проект видоизменить, понимаю что основные файлы django лучше не изменять, по этому в корень своего проекта скинул копии файлов: login.html, base.html, base_site.html а так же в папку проекта скопировал файлы стилей: login.css и base.css. Связываю HTML файлы с CSS стилями, но при запуске своего проекта, все равно загружаются CSS файлы django. Подскажите где я ошибся и что делаю не так? Моя задача изменить стандартное отображение ввода окна login + password под свое представление ! -
How to add break to page between parts in django?
I'm creating a page, but for some reason content is not going down but it's going to right. I have tried to use tag br but it's now working. Why is this happening? and... how do I fix it? {% extends "base.html" %} {% load static %} {% block content %} {% include "parts/text_story1.html" %} <br> {% include "parts/text_story2.html" %} <br> <p> <form action="{% url "upload_story" %}" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ message }} <p>{{ form.non_field_errors }}</p> <p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p> <p> {{ form.docfile.errors }} {{ form.docfile }} </p> <p><input type="submit" value="Upload Story!"/></p> </form> </p> {% endblock content %} This is how it looks, now it's not important to styling a details but this is a bigger problem. -
Can't see tree when using $tree in django mac terminal
Whenever I try to see my files using $tree, nothing happens. Here is a picture of the code im trying to run. And here is what it is supposed to return. -
Serving Static Files in Heroku
I have a Django and React app hosted on Heroku, the issue is that it does not see my files but everything is completely working in my localhost. It was built successfully on Heroku. Debugging process: Project built successfully Opens App Returns a blank page meaning it is not serving my CSS and js files. Checked Developer tools The Django app requires the CSS and js files to show the template Checked Heroku logs Heroku returns err 404 for those files Check my Deployed files in Heroku I checked to see my files that are deployed in Heroku in my terminal, and they are there. Now, I'm confused, why is it not serving the files, it's not a code problem cos everything is working well in my localhost. Any solutions pls? Thanks. -
How to load part of html page in django?
Before I used to load just part of page in django. Usually it used to be a text that I did not want change often, but I forgot how to do it, now I cannot find it. I have two html docs, in one I want to load other, can you tell me where I made a mistake? Text to load text_story.html <p>Some text!</p> Page where is loaded text about.html {% extends "base.html" %} {% load static %} {% load "parts/text_story.html" %} {% block content %} {% endblock content %} Thanks in advance! -
Django NoReverseMatch error - urls.py path appears to match
In a Django application I am building as a project for an online course, I am expecting a link in one template (entry.html) to direct to a path ("edit") in urls.py with a variable in the url. This should initiate a function called edit in views.py and render the template edit.html. I am getting a NoReverseMatch error ("Reverse for 'edit' with no arguments not found. 1 pattern(s) tried: ['(?P<entry>[^/]+)/edit$']") after clicking the link in entry.html. If I view page source while on entry.html in the development server, I can see the url matches that in urls.py but I still get this error. In the example below, "maggie" is the value for entryTitle I'm trying to pass. entry.html: {% block title %} {{ entryTitle }} {% endblock %} {% block body %} {{ entry|safe }} <button> <a href="{% url 'edit' entry=entryTitle %}">Edit Entry</a> </button> {% endblock %} urls.py (last path listed is edit) from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("wiki/<str:entry>", views.entry, name="entry"), path("search", views.search, name="search"), path("new", views.new_page, name="new"), path("wiki/<str:entry>/edit", views.edit, name="edit") ] edit function in views.py from django.http import HttpResponseRedirect from django.urls import reverse class EditPageForm(forms.Form): content = forms.CharField( widget=forms.Textarea(), label="Edit Content:") def … -
how to pass a function in python mock side effect
I want to achieve the following: mocked.side_effect = somefunction and when mocked() gets called I want somefunction() to get executed however, right now when mocked() gets called only the name of the function is returned and not the callable. Note: I don't want to just do mocked.side_effect = somefunction() because that will call the function first and then result in a value. I would like the function to be called when mocked is called -
How do I render {{ STATIC.URL }} from textfield in database django
I am new to web development and currently building a blog. I want to render HTML that I am pulling in from the database. The HTML is successfully rendered by using |safe but I cant seem to render django template tags {{ STATIC_URL }} within the href. Can someone help me understand why this is not working and what could be the possible solution? html <p class="article-redirect">{{ article.redirect|safe|escape }}</p> models.py class Articles(models.Model): redirect = models.TextField(blank=True, null=True) database "redirect" textfield (the string I want to render) <a href="{{ STATIC_URL }}/articles/8-Photogenic-Spiral-Staircases" class="link-within">8 Photogenic Spiral Staircases</a> -
How do I resolve database migration error due to changed migration filename?
I'm still pretty new to Python as well as Django so I have a situation I'm not sure how to resolve. Main issue is that on deploy of my code to dev, deployment fails, to stage or prod, it passes. I worked on an issue where I had to drop some columns in a table in our app. After making the changes, I deployed to dev and asked for a code review. In code review, it was suggested I change the name of the migration file to something more descriptive rather than just leaving it 0018_auto_. I made that change and deployed to dev and stage. Dev failed (when I expected it to succeed) because the new name was seen and django tried to drop columns that no longer exist. In stage, the name was never changed and the columns were dropped for the first time using that new name of the file. So stage deploys just fine. How do I resolve this error on dev so it recognizes this migration already took place? Thanks! -
My Django REST admin page shows locally but in production I get a 404. What am I missing?
The actual API is working fine. My only issue is that the '/admin' route 404's in production. from django.contrib import admin from django.urls import path from appname import views urlpatterns = [ path('admin/', admin.site.urls), path('people/', views.people_list) ] -
Scheduled Tasks django-rest-framework
I built an api that scrapes data from a web. It needs to scraping every hour. How can I manage to program scraping in the background, and doesn't break the requests of the clients? I apologize for any error gramatical. -
Django - manager on ManyToMany relationship
I have 3 models class Person(models.Model): name = models.CharField(max_length=128) class Company(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField (Person, through = 'Membership', related_name = 'companies') class Membership(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) company = models.ForeignKey(Company, on_delete=models.CASCADE) is_admin = models.BooleanField() I can then call person.companies.all() to get the list of companies associated with person. How do I create a manager to have the list of companies associated with person, but whose person is admin (is_admin = True)? -
Django - Show Timeslots by Availability
I'm new to django & python. I've spend ~2-3 weeks on this and have tried many, many solutions. I have a vehicle scheduling service. Customers can login and see their vehicles and schedule service. They can select a service center ("branch"), a date, time, their vehicle, and the service they want. I want to be able to show available slots by date AND branch. Here is what I have so far. Models.py class NewAppt(models.Model): created = models.DateTimeField(auto_now_add=True) start_time = models.DateTimeField(blank=False) end_time = models.DateTimeField(blank=False) branch = models.ForeignKey(Branch, on_delete=models.SET_NULL, null=True) unit = models.ForeignKey(Vehicle, on_delete=models.SET_NULL, null=True) vin = models.CharField(max_length=17) sold_to = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) servicelevel = models.ForeignKey(ServiceLevel, on_delete=models.SET_NULL, null=True) servicetype = models.ForeignKey(ServiceType, on_delete=models.SET_NULL, null=True) def __str__(self): return f'{self.branch} | StartTime = {self.start_time} | EndTime = {self.end_time} | SoldTo = {self.sold_to} | Service = {self.servicetype} | Level = {self.servicelevel}' class Meta: ordering = ['branch', 'start_time'] unique_together = ('branch', 'start_time') @property def duration(self): return self.end_time - self.start_time class BranchSchedule(models.Model): """Creates one schedule for each branch""" branch = models.OneToOneField(Branch, on_delete=models.CASCADE, primary_key=True) holidays = models.CharField(max_length=1000, validators=[int_list_validator], blank=True, null=True) # list of comma separated days [2021-01-01, 2022-12-31] monday_first_appt = models.TimeField(blank=False, null=True) monday_last_appt = models.TimeField(blank=False, null=True) tuesday_first_appt = models.TimeField(blank=False, null=True) tuesday_last_appt = models.TimeField(blank=False, null=True) wednesday_first_appt = models.TimeField(blank=False, null=True) wednesday_last_appt … -
How to convert back mysql data in original format?
How to get back the data in original format. Screenshot database screenshot -
How to POST an entity specifiying an integer foreign key in django rest framework
I am building a chat application with django rest framework and I m currently working on messages. This are my models: from django.db import models from django.contrib.auth.models import User class Message(models.Model): text = models.CharField(max_length=500) datetime = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, on_delete=models.CASCADE); I am using the Django auth User model. This is my ModelViewSet for the messages: class MessageViewSet(ModelViewSet): queryset = Message.objects.all() serializer_class = MessageSerializer And these are my serializers: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username'] class MessageSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) class Meta: model = Message fields = '__all__' And this is my API: The code I've written so far works really well for the GET functionally I want. I want for each message to get the username of the user it belongs to. But now I want the following thing: when I POST a new message, I want to me able to specify with user it belongs to by specifying the user's id. Right now I have only the "text" field in the POST section. I need to add a "user" field which takes in an integer (the user primary key) to specify which user the message belongs to. How should I refactor my code in … -
Override Djange ImageField extension validation
Understand I can add a validator to Django's ImageField validators to restrict file extension types like below. But in terms of the error messages which are displayed via upload on Admin -- I'm still seeing the standard file type list (via PIL allowed types), if I upload a non-image type. If I upload an image type which is not in my custom allowed_extensions below, I see my custom message. How can I override Django's default ImageField handling, and show my custom error message no matter what type of file is uploaded (e.g. when any file other than .png is uploaded per below example)? class MM(models.Model): file_extension_validator = FileExtensionValidator( allowed_extensions=['png'], message='File extension not allowed. Allowed extensions include .png' ) image = models.ImageField( help_text='Upload images only (.png).', validators=[file_extension_validator], max_length=255, blank=False, null=False ) -
Using Python, how can I add attributes to Say in a Gather?
I am saying some text in a Gather. I would like to change the speech rate and I see that I can do this with Prosody, but I don't know how to implement this in Python (Django). Here is something I tried that didn't work: resp = VoiceResponse() with resp.gather(input='DTMF Speech', action=my_url, method='GET', num_digits=1) as g: g.say('Hello', voice='Polly.Amy-Neural') g.say.prosody(rate='50%') return HttpResponse(str(resp), content_type='text/xml')