Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Creating a new field to an extended user model every time a post is made by that user
I want my extended user model to look like what it does below, where I can upload an Image as many times as I want to that extended user model. With everything being in one model without having two separate models. Is there a way I can manipulate my extended user model to do that, without using a stacked inline model? -
Scrollspy not working at all - menu items not being highlighted
I'll preface by saying that I am a complete beginner with HTML, Bootstrap and CSS - I only started a few days ago. For the life of me I cannot seem to get Scrollspy to work. I know this question has been asked many times, and I've spent hours going through the solutions, but I have not found one that works for me. Below is my the start of my HTML, up to my nav: {% load static %} <!doctype html> <html lang="en" class="h-100"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Steven Cunden | Home</title> <link rel="canonical" href="https://getbootstrap.com/docs/5.1/examples/cover/"> <!-- Bootstrap core CSS --> <link href="/docs/5.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static '/css/main.css' %}"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link href="/docs/5.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.5.0/font/bootstrap-icons.css"> <style type="text/css"> body{ position: relative; overflow-y: scroll; } </style> <!-- Custom styles for this template --> <!-- <link href="cover.css" rel="stylesheet"> --> </head> <section class="cover-thing first text-center"> <nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark" id='nb'> <div class="container-fluid"> <a class="navbar-brand" href="#">Steven Cunden</a> <div class="collapse navbar-collapse justify-content-end"> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link" href="#test">TEST</a> </li> <li class="nav-item"> <a class="nav-link" href="#about-me">ABOUT ME</a> </li> <li class="nav-item"> <a class="nav-link" href="#aoi">INTERESTS</a> </li> <li class="nav-item"> <a class="nav-link" href="#skills">SKILLS</a> </li> </ul> </div> … -
Django model function implementation to auto initialize a particular field's value
I need to write a Django model function to calculate the value of an existing field. my models.py: class questionNumeric(models.Model): question = models.TextField() marks = models.IntegerField() correctAns = models.FloatField() class questionTureFalse(models.Model): question = models.TextField() marks = models.IntegerField() correctAns = models.BooleanField() class questionSet(models.Model): examName = models.CharField(max_length=200) questionNumeric = models.ManyToManyField(questionNumeric) questionTureFalse = models.ManyToManyField(questionTureFalse) totalMarks = models.IntegerField(default=0) As you can see here, each questionNumeric or questionTureFalse object has specific marks. Now I want to set my questionSet object's totalMarks field with- the summation of marks carried by all questionNumeric or questionTureFalse under this questionSet object. How can I write a Django Model function under questionSet to auto initialize totalMarks? -
Desing patterns in Django
I'm learning Desing Patterns and appling it into Python. I've work with Django, but I don't know how to apply a Factory method (for instance), into Django or I shouldn't use it in it. Thanks for your answers =) -
Django: Querying a stacked inline object (photo) that is connected to extended user model
I am trying to make an Instagram Clone. So what I'm trying to do here is query the user's photos that were uploaded and display them on the frontend. When I query into the stacked inline Uploads model I can get the photos to display on the frontend, but not the photos that belong to the user (all the photos in database display on the frontend). I tried to figure out a way to get all the photo's to go to the extended user model, but I couldn't figure a way to do that. Basically I'm trying to get the images that the user uploaded and if anyone could help that would be much appreciated. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, null = False, blank = True) first_name = models.CharField(max_length = 50, null = True, blank = True) last_name = models.CharField(max_length = 50, null = True, blank = True) phone = models.CharField(max_length = 50, null = True, blank = True) email = models.EmailField(max_length = 50, null = True, blank = True) bio = models.TextField(max_length = 300, null = True, blank = True) profile_picture = models.ImageField(default = 'default.png', upload_to = "img/%y", null = True, blank = True) #uploads … -
django form field error_messages not working with IntegerField
This is my model : class Bid(models.Model): id = models.AutoField(primary_key=True) bid = models.IntegerField(verbose_name='Prix demandé', null=False, blank=False) note = models.TextField(verbose_name='Description', null=False, blank=False) date = models.DateField(auto_now_add=True) This is my form class BidForm(forms.ModelForm): class Meta: model = Bid fields = ['bid', 'note'] bid = forms.IntegerField(error_messages={'invalid': 'Please enter a valid bid'}) When the bid is invalid, I always get the default error message not the one I specificed Ensure this value is greater than or equal to 1 However it works if I add another field of another type, like CharField class BidForm(forms.ModelForm): .... bid = forms.IntegerField(error_messages={'invalid': 'Please enter a valid bid'}) text = forms.CharField(error_messages={'required': 'Please enter a valid text'}) Ensure this value is greater than or equal to 1. Please enter a valid text -
I deployed my app on digital ocean and every one can access the URL and the app except me I get error as shown in screenshot
it is a Django app on a ubuntu 20.04 server using nginx and gunicorn error i get -
Can Anyone Please solve this test Project (Django and Django Rest Framework)
Please solve this Test project. The instruction is available at the following link. https://bitbucket.org/staykeepersdev/bookingengine/src/master/ -
Disadvantages of launching multiple identical tasks in Celery (python)
could you please point this out... I have a task to generate a document (~5-6 seconds to generate a full doc) and also I have a platform with a user who can click on some choices (checkboxes) at the page (frontend part) and send a PATCH request with a new data. This action will change a model in database and also will launch described above task. So if user will click checkboxes multiple times (for fun or something like that) -> it will send multiple PATCH requests to update table in database and at the same time it will launch same tasks to generate document. But these tasks are useless except of the last one, because the last task will generate a document with the right data (final click of user by choice "checkbox" in choices) So my question is as follows: Do I need to worry about all other useless almost identical tasks if I need only the last one? Should I use cron at this case and to launch a generate document task (every 1 minute) if the table in database changed or should I leave the above described functionality with multiple tasks? Will it affect my application … -
this iç ã têstto sẽ a slũg in actón
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -
Comment doesn't submit to the database
I am having a hard time to get the comment object work, anytime i comment and submit it shows the the JsonResponse but wont submit to the database. Here is my view to create comments def blog_detail(request,post_id): user = request.user post = get_object_or_404(Post, pk=post_id) if request.method == 'POST': post_id = request.GET.get('post_id') body = request.POST['body'] user_obj = Account.objects.get(username=request.user.username) create_comment = Comment.objects.create(post=post_id, name=user_obj, body=body) create_comment.save() return JsonResponse({'body':body}) return render(request,'blog/blog_detail.html', {'post':post}) Here is my comment model class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='commentts') name = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="commentts") body = models.CharField(max_length=200) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) This is my HTML code for the comment form! <form for="id_body" action="." method="POST"> {% csrf_token %} <div class="bg-gray-100 rounded-full relative dark:bg-gray-800 border-t" for="id_body" > <input placeholder="Add your Comment.." name="body" id="id_body" class="bg-transparent max-h-10 shadow-none px-5"> <div class="-m-0.5 absolute bottom-0 flex items-center right-3 text-xl"> <a href="#"> <ion-icon name="happy-outline" class="hover:bg-gray-200 p-1.5 rounded-full"></ion-icon> </a> <a href="#"> <ion-icon name="image-outline" class="hover:bg-gray-200 p-1.5 rounded-full"></ion-icon> </a> <a href="#"> <ion-icon name="link-outline" class="hover:bg-gray-200 p-1.5 rounded-full"></ion-icon> </a> </div> </div> <input class="btn btn-outline-success my-3" id="send_btn" type="submit" value="Comment"> </form> This is the URL as well. path('post/<int:post_id>/',views.blog_detail, name='detail'), -
How to pass encrypted string in URL
I am encrypting user invite information and adding it to the URL so that when a user receives a registration link certain information will already be filled in. The way I am encrypting it is by using the django.core.signing package as such: def encrypt_object(self): """ Encrypts the Private Key. The cryptographic key is appended to the URL of the invite. """ return signing.dumps({"pk": f'{self.pk}'}) def decrypt_object(self, signed_obj): """ Decrypts the Private Key which is passed as an argument on the invite URL. """ return signing.loads(signed_obj) I would like to pass the encrypted pk in the URL like this: path('register/<str:encrypted_pk>/', views.register, name='register'), but I get a 404 error. How can I accomplish this? -
Django user-uploaded media files in production with Dokku
I would like to serve user uploaded media files using nginx on the same host as the Django application rather than a CDN or S3 or similar. The django-private-storage library can be used to protect media files behind a login: https://github.com/edoburu/django-private-storage I am deploying my Django application with Dokku. Dokku says that dokku persistant storage plugin should be used to allow for user uploads to be persisted on the host. https://dokku.com/docs~v0.9.2/advanced-usage/persistent-storage/ My confusion is that django-private-storage requires you to edit the config for nginx. Specifically, it requires you to set the location of the private media being served to be internal. So that the URL cannot be accessed from the outside by a user who isn't logged in. The dokku docs don't explain how to use persistant storage behind an application login. Do I actually need django-persistant-storage to be able to write user uploaded media? How can I combine these solutions so that my application, which is inside a container, can read and write media files, which media files are served by nginx, and served at an internal location that can only be accessed by a user who is logged into the application? -
Why am I getting an integer precision error when I run: heroku run python manage.py migrate
I have deployed a Django app on Heroku, but I want to migrate to PostgreSQL, so I am following a video tutorial on YouTube on how to do that. In the tutorial, we have to run Heroku run python manage.py migrate to migrate my current SQLite database to the PostgreSQL one on Heroku. I keep getting this error: psycopg2.errors.CannotCoerce: cannot cast type date to double precision LINE 1: ...cted" TYPE double precision USING "lastInteracted"::double p... Here is my models.py file. I am pretty sure that the problem is in the Conversation model with the lastInteracted variable, but I do not know why it is happening. from django.contrib.auth.models import AbstractUser from django.db import models from django.db.models.fields import CharField from django.db.models.fields.files import FileField, ImageField, ImageFieldFile from django.utils.timezone import localtime, now from datetime import datetime import time import os import sys from django.core.files.base import File from django.core.files.uploadedfile import InMemoryUploadedFile class User(AbstractUser): userType = models.CharField(max_length=20, default="student") profile_pic = models.ImageField( null=True, blank=True, default="blankUserIcon.svg") class Classroom(models.Model): name = models.CharField(max_length=100, default="Classroom") students = models.ManyToManyField(User, blank=True) teacher = models.ForeignKey( User, on_delete=models.CASCADE, related_name="teacher") code = models.CharField(max_length=20) subject = models.CharField(max_length=50, default="") theme = models.CharField(max_length=20, default="cardBlue") class Comment(models.Model): date = models.DateTimeField(default=datetime.now()) text = CharField(max_length=5000, default="") commenter = models.ForeignKey( User, on_delete=models.CASCADE, related_name="commenter", … -
close div with js event listener in django
i want to add a js eventlistner so i could close an alert pop up after display, below is the current code...i have the script in separate file as well. Thank you Hello all, i want to add a js eventlistner so i could close an alert pop up after display, below is the current code...i have the script in separate file as well. Thank you JS Code: // Invoke Functions Call on Document Loaded document.addEventListener("DOMContentLoaded", function () { hljs.highlightAll(); }); let alertWrapper = document.querySelector(".alert"); let alertClose = document.querySelector(".alert__close"); if (alertWrapper) { alertClose.addEventListener( "click", () => (alertWrapper.style.display = "none") );`enter code here` } Template Code: <!DOCTYPE html> {% load static %} <html> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <!-- Favicon --> <link rel="shortcut icon" href="images/favicon.ico" type="image/x-icon" /> <!-- Icon - IconMonster --> <link rel="stylesheet" href="https://cdn.iconmonstr.com/1.3.0/css/iconmonstr-iconic-font.min.css" /> <!-- Mumble UI --> <link rel="stylesheet" href="{% static 'uikit/styles/uikit.css' %}" /> <!-- Dev Search UI --> <link rel="stylesheet" href="{% static 'styles/app.css' %}" /> <title>DevSearch - Connect with Developers!</title> </head> <body> {% include 'navbar.html' %} {% if messages %} {% for message in messages %} <div class="alert alert--{{message.tags}}"> <p class="alert__message">{{message}}</p> <button class="alert__close">x</button> </div> {% endfor %} {% endif … -
Django - Admin Area width
My admin area on my Django application is a little bit off since a few days. I don't know what I did wrong... At the moment, the width is not fully used by the tables and the forms. The buttons instead are using the full width. Where can I change the width to full for the forms and tables? Is this a problem in Django or just visualization? In the second screenshot you can see, that the area should be on the full width. PS: It's not a browser problem, I tried. Cheers guys :) Screenshot Django Admin Area Screenshot Django Admin Area with selected width -
I am new to Django Rest Framework and practicing this question but i am not able to understand it can anyone help me solve it
Summary: Extend Django Project with Django REST Framework for a simple prebuild booking app that have: - Listing object with two types - booking_engine.models : - Apartment(single_unit) have booking information (price) directly connected to it. - Hotels(multi-unit) have booking information (price) connected to each of their HotelRoomTypes. - filtering through Listings and returning JSON response with available units based on search criterias. - should handle large dataset of Listings. There is a pre-build structure for Hotels/Apartments (could be changed or extended). Database is prefilled with information - db.sqlite3. superuser username: admin password: admin We should be able to block days ( make reservations ) for each Apartment or HotelRoom. A new Model for blocked (reserved) days must be created NEW endpoint where we will get available Apartments and Hotels based on: available days (date range ex.: "from 2021-12-09 to 2021-12-12") - Apartment should not have any blocked day inside the range - Hotel should have at least 1 Hotel Room available from any of the HotelRoomTypes max_price (100): Apartment price must be lower than max_price. Hotel should have at least 1 Hotel Room without any blocked days in the range with price lower than max_price. returned objects should be sorted … -
Finding Largest Value of an Integer Field - Django
I have a Django website and one of my models has an integer field. Does anyone know of a way to retrieve the largest value currently in that field into the view? Thanks! -
Django: How to automatically generate the USERNAME_FIELD of a custom user model?
This is a learning project and I've been trying to create a custom user model with the possibility of having multiple accounts with the same nickname. The USERNAME_FIELD would be username = f"{nickname}#{random_number}" (just like the Blizzard and Discord format), but I can't figure out at which step I should include the function that would automatically create the username. I tried generating the username in the CustomAccountManager.create_user() method but it doesn't seem to be called while filling the RegistrationForm from the view and it fails to create the superuser with manage.py createsuperuser (TypeError: create_superuser() got an unexpected keyword argument 'username'). I'd be glad if someone could explain how to procede in this case or link a resource, I couldn't find one with this kind of example. Any additional insight on the code will be appreciated. I have registered the model in admin.py with admin.site.register(Account), included the accounts app in the settings and set AUTH_USER_MODEL = 'account.Account' account/models.py from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from random import randint from django.contrib.auth import get_user_model ### ACCOUNT class CustomAccountManager(BaseUserManager): def create_user(self, email, nick, password = None): if not email: raise ValueError("Email was not provided during user creation. (account/models.py/CustomAccountManager.create_user)") if not nick: raise ValueError("Username was not … -
Django how to raise validation error if foreignkey objects id change in hidden input
I have an hidden foreigkey filed in my forms. I want to raise validation error or stop submitting forms if user try to change the value. here is my code: html: {%for i in user_profile%} <input type="hidden" name='userprofile' value="{{i.id}}"> {%endfor%} models.py: class BlogComment(MPTTModel): userprofile= models.ForeignKey(UserProfile,on_delete=models.CASCADE,null=True,blank=True) #my others model fields... views.py: user_profile = UserProfile.objects.filter(user=request.user) I want to raise validation error if current id change in hidden input. how to do that? -
url template tag in django from parent project
i was trying to use the url tag in my template: <div><a href="{% url 'download_file' filename='rilasci_progetto_scuole.xlsx' %}">Esporta file Excel</a></div> the template path is: \FastFM\Scuole\templates the 'download_file' function is declared inside the views.py (\FastFM\FastFM\views.py) of the parent project (the name is FastFM) but the html in wich i want to use it is in the app named scuole Scuole: the parent urls.py (\FastFM\FastFM\urls.py) is: urlpatterns = [ path('admin/', admin.site.urls), path('', views.FastFMHome.as_view(), name='FastFM') , path('Scuole', include('Scuole.urls')), path('RilasciSettimanali', include('RilasciSettimanali.urls')), path('accounts/', include('django.contrib.auth.urls')), path('downloadxls', views.download_file, name='download_file'), the intention was to put the downloadxls path in the main project to use it in the others apps. By the way, i get the NoReverseMatch exception. -
Where to store files for admin to download in Django?
I have some example files that I want to serve in a download link to all admins. They are not model dependant or user dependant (other than requiring admin). They're txt files and the same files must be available to all admins. I cannot find anything about this in the docs, or maybe I don't know what to look for. As far as I understand only css, js and images are static files, so should txt files be in /media/? Where can I put these files so only admins can download them? Right now I have a hard coded link in my custom admin template to /media/admin/examples/data_template.txt, but anyone can get to this link. I have these configs in settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'assets') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') -
Django Rest Framework | TypeError: Field 'id' expected a number but got OrderedDict([('name', 'string')])
I'm trying to update a ManyToManyField in a UserProfile, which is part of my custom User model in my Django REST API. However, I get this error: TypeError: Field 'id' expected a number but got OrderedDict([('name', 'string')]) Since I'm doing this in my update() method in my UserSerializer, I already have an instance created. account/serializers.py class UserSerializer(serializers.ModelSerializer): password = serializers.CharField( max_length=68, min_length=6, write_only=True) userprofile = UserProfileSerializer(write_only=True) class Meta: model = User fields = ['email', 'username', 'password', 'tokens', 'userprofile'] # Read-only b/c doesn't need any validating parameters read_only_fields = ['tokens'] def update(self, instance, validated_data): """Perform an update on User""" # Remove password field b/c we don't want to iterate over it in the # validated_data dictionary. Django will salt/hash it. validated_data.pop('password', None) profile_data = validated_data.pop('userprofile', {}) skills = profile_data.pop('skills', []) for (key, value) in validated_data.items(): # Set remaining keys in the user setattr(instance, key, value) instance.save() for (key, value) in profile_data.items(): setattr(instance.userprofile, key, value) for skill in skills: instance.userprofile.skills.add(skill) instance.userprofile.save() return instance The error occurs when I call add() for updating the user's skills. The model and serializer for Skill are defined below: user_profile/models.py class Skill(models.Model): name = models.CharField(max_length=120) def __str__(self): return self.name user_profile/serializers.py class SkillSerializer(serializers.ModelSerializer): class Meta: model = Skill … -
Creating a Blogpost Like/Dislike Button within Django/Wagtail
I'm new to Django and Wagtail and have looked for a way to implement a "simple" like/dislike button on a blog entry page using Wagtail. I included a total_likes IntegerField in my model for the page and would like to increment or reduce this int within the database when the user clicks a button on the html template. The user is not supposed to be logged in. Most tutorials I've found deal with this only for registred users which is not something I want. I would be glad if somebody could point me in the right direction. The models.py code is below. I do not understand how to call a function from within a template. class BlogEntry(Page): date = models.DateField("Post date") intro = models.CharField(max_length=250, blank=False) body = RichTextField(blank=True) tags = ClusterTaggableManager(through=BlogEntryTag, blank=True) categories = ParentalManyToManyField('blog.BlogCategory', blank=False) total_likes = models.IntegerField(blank=False, default=0) image = models.ForeignKey( "wagtailimages.Image", null=True, blank=True, on_delete=models.SET_NULL, related_name="+" ) streamBody = StreamField([ ("text", blocks.StaticContentBlock()), ("quotes", blocks.QuoteBlock()), ("image_and_text", blocks.ImageTextBlock()), ("related_articles", blocks.RelatedArticlesBlock()), ], null=True, blank=True) sidebarBody = StreamField([ ("text", blocks.StaticContentBlock()), ("quotes", blocks.QuoteBlock()), ("image_and_text", blocks.ImageTextBlock()), ("related_articles", blocks.RelatedArticlesBlock()), ], null=True, blank=True) search_fields = Page.search_fields + [ index.SearchField('intro'), index.SearchField('body'), ] content_panels = Page.content_panels + [ MultiFieldPanel([ ImageChooserPanel("image"), FieldPanel('date'), FieldPanel('tags'), FieldPanel('categories', widget=forms.CheckboxSelectMultiple), ], heading="Blog information"), FieldPanel('intro'), … -
Django for...empty with different container when empty
I have a common pattern in which I have a container in HTML (e.g., ul, table ...) with elements from a queryset. However, when the list is empty, I don't want to display the container itself. I seek to get the equivalent of {% if query.exists %} <ul class="list-of-stuff"> {% for x in query %} <li>{{ x }}</li> {% endfor %} </ul> {% else %} <p class="information"> The list is empty. </p> {% endif %} but without extra query (query.exists), much like for...empty does. However, one large drawback of for...empty is that I cannot remove or change the container when the list is empty. How can I get an equivalent of the above with only one execution of my query in a clean way (i.e., without displaying the container tag if forloop.first and such)? I'm open for implementing new tags or filters.