Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Read one side of the association
Let's say we have two models in our Django app: class Member(models.Model): name = models.CharField() class Project(models.Model): name = models.CharField() Normally, for a many to many field I would make an intermediary table and just query that: class ProjectMember(models.Model): project = models.ForeignKey(Project) member = models.ForeignKey(Member) Is there a way to retrieve a queryset to list only the projects for a member? I tried ProjectMember.objects.filter(member=member).only('project') but I still get the ProjectMember object list with only the project field populated. I was wishing to retrieve a list of Project objects. -
Unable to create a sqllite test database in django
I am building a laboratory management software right now as a passion project, and I am getting stuck trying to test the Django backend of my application. I am trying to create a test database to use with pytest. I am using MySQL on PlanetScale as the default database, but if I were to create a second database for testing, I would have to upgrade from the free version. If possible, I want to avoid this, so I'm trying to use a SQLite database for testing. I need to figure out how to run my pytests using a second sqlite database. To begin, I run pytest using my dockerfile FROM python:3.11-alpine ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt /code/ RUN apk update \ && apk add --virtual build-deps gcc python3-dev musl-dev \ && apk add --no-cache mariadb-dev RUN pip install -r requirements.txt RUN apk del build-deps COPY . /code/ RUN pytest -v Once it starts running the pytests I receive an error, and all errors I receive from any test are the same. An example test would be @pytest.mark.django_db def test_create_user_serializer_save(valid_user_data): serializer = CreateUserSerializer(data=valid_user_data) assert serializer.is_valid() == True user = serializer.save() assert User.objects.filter(email=valid_user_data['email']).exists() == True assert user.name == valid_user_data['name'] … -
Using Django-simple-history with postgresql
So i was django simple history on my local server and using sqlite to test it out to see how I liked it. I decided to keep it for production, but I'm wondering if there is anything special needed to use simple history with postgress as that is what I am using for production. I migrated my changes with simple history over but it doesnt seem to want to show any kind of history for changes made. Is there something I need to do like save it? Reading documents online but I am not seeing much -
RegisterUserView creates user but doesn't log in user
I am trying to make a class-based registration view equivalent of my old function based registration view. When I register as a new user, a user is created but is not logged in after registration, and this bug only happens when I use class-based registration view. Form doesn't return any errors also. So views.py class-based (doesn't log in after registration) from django.contrib import messages from django.contrib.auth import login from django.urls import reverse_lazy from django.views.generic import CreateView from .forms import NewUserForm class RegisterUserView(CreateView): form_class = NewUserForm success_url = reverse_lazy('home') template_name = 'users/register.html' def form_valid(self, form): user = form.save() login(self.request, user) return super().form_valid(form) def form_invalid(self, form): messages.error(self.request, form.errors) return super().form_invalid(form) views.py function-based (does log in after registration) from django.contrib import messages from django.contrib.auth import login from django.shortcuts import redirect, render from .forms import NewUserForm def register_user(request): if request.method == "POST": form = NewUserForm(request.POST) if form.is_valid(): user = form.save() login(request, user) return redirect('home') messages.error(request, form.errors) form = NewUserForm(request.POST) context = { "form": form } return render(request, "users/register.html", context) models.py from django.db import models from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): email = models.EmailField(unique=True) forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from .models import CustomUser class NewUserForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model … -
Paginating Django query results in a table
I am having issues with paginating my query results. When I use the query without pagination it works as intended, but once I add the pagination to the query I am seeing results on the last page that do not match what was defined in the search. For example, if I search a date like april 5th, 2023 I get 53 as my last page, after clicking on 53 to view the page 54 appears in the pagination as the last page. If you navigate to 54 it has items from later dates. Also I noticed if you navigate to a page in the query then try to navigate back to the first page the table then shows results from earlier dates. I have tried researching and fixing this but I am at a loss, any help would be greatly appreciated. models.py: class Package(models.Model): barcode = models.AutoField(primary_key=True) barcode_img = models.ImageField(upload_to='images/', null=True) origin = models.CharField('Origin Location', max_length=50, choices=[(location.locations, location.locations) for location in Location.objects.all()]) destination = models.CharField('Destination Location', max_length=50, choices=[(location.locations, location.locations) for location in Location.objects.all()]) description = models.CharField('Description', max_length=50) date_created = models.DateTimeField('Date Created', default=timezone.now) employee = models.ForeignKey(Employee, on_delete = models.CASCADE, default=320557) status = models.CharField('Status', default='Created', max_length=50) views.py: def search(request): form = SearchForm() … -
Django, Integrity error with PK, but new objects are still working fine
So here's my view def add_tutorial(request): if request.method == 'POST': User = request.POST.get('user') # other properties lang = request.POST.get('lang') new_tutorial = Tutorial.objects.create( User=User, ..., lang=lang) context = { 'page_title': 'create tutorial', } return render(request, "add-tutorial.html") I do create a tutorial with forms, it all works well, I can see the tutorial where it needs to be, but for some reason I get integrity error regarding the pk IntegrityError at /add_tutorial. UNIQUE constraint failed: main_tutorial.id The Id in the db is correct (i use sqlight). Before I used to specify the id in the create function, but now it shouldn't be any problem since I've dropped that db and (properly) undone all migrations; nothing changed [the only meaningful traceback that i get is to the Tutorial.objects.create(...) line] -
Return response not downloading through pandas Django
I want to export the query data if the form is valid after submitting two dates from a modal form. I don't understand why the return response is not working here. Any help would be appreciated. def load_date_range_ajax(request): data = dict() template_name ='date_range_modal.html' if request.method == 'POST' and request.is_ajax(): form = DateRangeForm(request.POST) if form.is_valid(): data['form_is_valid'] = True start_date = form.cleaned_data['start_date'] end_date = form.cleaned_data['end_date'] with connection.cursor() as cursor: cursor.execute('''qry_string;''') rows = cursor.fetchall() response = HttpResponse(content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename="Location Date.xlsx"' df = pd.DataFrame(rows, columns=[col[0] for col in cursor.description]) df.to_excel(response, index=False, header=True) return response else: data['form_is_valid'] = False else: form = DateRangeForm() data['html_form'] = render_to_string(template_name, context={'form': form}, request=request) return JsonResponse(data) -
Django "This field is required." error every time I fill out my video post form
As the title says, I'm getting this error and I'm not really sure why am I getting it. Here's my models.py for the video upload form: class Video(models.Model): title = models.CharField(max_length=100) thumbnail = models.ImageField(upload_to='videos/thumbnails/', null=True) video = models.FileField(upload_to='videos/video/', validators=[FileExtensionValidator(allowed_extensions=["mp4", "mov"])]) date = models.DateTimeField(auto_now=True) slug = models.SlugField(unique=True) user = models.OneToOneField(User, related_name='user',on_delete=models.PROTECT) description=models.TextField(validators=[MinLengthValidator(10)], blank=True) category= models.ForeignKey(Category, on_delete=models.CASCADE, blank=True) game = models.ForeignKey(Igdb, on_delete=models.PROTECT, null=True,blank=True) def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Video, self).save(*args, **kwargs) def __str__(self): return self.title Here's my forms.py: class videoupload(forms.ModelForm): title = forms.CharField(max_length=100, widget= forms.TextInput (attrs={'placeholder':'Title'})) thumbnail = forms.ImageField() video = forms.FileField(widget= forms.FileInput (attrs={'class':'videobox'})) description = forms.Textarea() category = forms.Select() game = forms.Select() class Meta: model = Video fields = ['title', 'description', 'thumbnail', 'video','category', 'game'] exclude = ("date","user", "slug") And here's my views.py: def uploadpage(request): if request.method == "POST": form = videoupload(request.POST,request.FILES or None) if form.is_valid(): video = form.save(commit=False) video.user = request.user video.save() return redirect("home") else: form = videoupload() return render(request, "glavna/upload.html", {"form": form}) I'm trying to have it post a video, username would be automatically filled out. -
How to give AbstractUser permissions to a users' group?
I have user model inherited from AbstractUser called CustomAbstractUser. When I try to assign the permissions of this model to a user group, nothing is done. No trace of the assignment in the database. When I go through the administration interface, it works without problem. But programmatically not. content_type = ContentType.objects.get_for_model(CustomAbstractUser) add_user = Permission.objects.get( codename="add_customabstractuser", content_type=content_type ) change_user = Permission.objects.get( codename="change_customabstractuser", content_type=content_type ) ... admin, _ = Group.objects.get_or_create(name="AdminUser") ... admin.permissions.set([add_user, change_user, view_user]) By following this procedure with other models, it works without any problem. Also note that CustomAbstractUser is in a different application than the other models. -
What is the difference between save() and clean() method in django? Who is the first to be called when instantiating a model? [closed]
I want to make a blog in Django I have an Article table and a Blogger table I would like the number of blogger articles to be incremented with each record. However, it should not be incremented if it is an update. I tried to overload the clean() method but with each update the number of blogger articles also increases. I tell myself that if I understand how these two work I would know how to use them better that'is what i have tried from django.utils.text import slugify from django.conf import settings from django.db import models import uuid import datetime from django.shortcuts import reverse from user_cust.models import Blogger class Articles(models.Model): """Attributes list of my articles""" blogger = models.ForeignKey( Blogger, on_delete=models.CASCADE, primary_key=False, default="", verbose_name="Auteur:", editable=True, ) id = models.UUIDField( unique=True, primary_key=True, default=uuid.uuid4, ) title = models.CharField(max_length=200, verbose_name="Titre") slug = models.SlugField(default="", max_length=200, blank=True) body = models.TextField(blank=False, null=False, default="") created_at = models.DateTimeField(auto_now_add=True, verbose_name="Cree le:") update_at = models.DateTimeField(auto_now=True, verbose_name="Mis a jour le: ") image = models.ImageField(upload_to="article_images", blank=True) def __str__(self): return f"{self.title}" def save(self, *args, **kwargs): value = self.title self.slug = slugify(value=value, allow_unicode=True) if self.blogger.nb_articles == 0: self.blogger.nb_articles += 1 self.blogger.save() super().save(*args, **kwargs) def clean(self): """Try to avoid that an update action add a number … -
import all sections of the connected user's profile on LinkedIn using the LinkedIn API
I want to import all sections of the connected user's profile on LinkedIn using the LinkedIn API in Python. I used the REST API to retrieve profile information by sending a GET request to the URL: https://api.linkedin.com/v2/me, using the obtained access_token. However, I want to import the education and experience sections, and I am unsure of what to add to the URL to achieve this. What parameters do I need to add to the URL to retrieve the education and experience sections of the connected user's profile using the LinkedIn API in Python?" i tried this url " api_url = 'https://api.linkedin.com/v2/me?projection=(id,firstName,lastName,headline,profilePicture(displayImage~:playableStreams),educations,experience)' " but when i execute this url form : response = oauth.get(api_url) profile_data = response.json() the profile_data contain only the name , image profil and emailAdress . -
how we can connect two table in django model
**I am new to django i am working on a project where I have 4 usertype 1- super admin 2- sub admin 3 - clinic 4 - patient Now I want to make the login for all the 4 usertype** right now I have create a model like this import django from django.db import models from django.contrib.auth.models import AbstractUser class Registered_user(AbstractUser): is_clinic = models.BooleanField(default=False) is_patient = models.BooleanField(default=False) token = models.CharField(max_length=120, default=None, null= True) forgot_token = models.CharField(default=None, max_length=120, null=True), email = models.EmailField(unique = True, max_length=254, verbose_name='email address') updated = models.DateTimeField(auto_now=True) published = models.DateTimeField(default=django.utils.timezone.now) #clinic clnc_name = models.CharField(max_length=255) clnc_phone = models.BigIntegerField(null= True) clnc_contact_name = models.CharField(max_length=255) clnc_Job_Title = models.CharField(max_length=255) clnc_address_line1 = models.CharField(max_length=255) clnc_address_line2 = models.CharField(max_length=255) clnc_county = models.CharField(max_length=255) clnc_postcode = models.CharField(max_length=255) clnc_town_city = models.CharField(max_length=255) clnc_created_at = models.DateTimeField(auto_now_add=True) clnc_status = models.BooleanField(default=False) #Patient punique_number = models.CharField(max_length=20) pname= models.CharField(max_length=255) patient_adddress = models.TextField(max_length=500) pphone_number = models.IntegerField(null=True) phome_number = models.IntegerField(null=True) pwork_number = models.IntegerField(null=True) pdob = models.CharField(max_length=255,null=True) relative_name = models.CharField(max_length=255,null=True) relative_phone = models.CharField(max_length=255,null=True) relation = models.CharField(max_length=255,null=True) pgender = models.CharField(max_length=20) pcreated_at = models.DateTimeField(auto_now_add=True) ptnt_status = models.BooleanField(default=False) **I want them to be seperated I know this is not the right way to do this I also tried to use the foreign key but i got null value error Please let me … -
dj-rest-auth/registration return http 204 no content
I were following the book Django for APIs by William.S.Vincent. In Chapter 8: User Authentication, I make Implementing token authentication and use dj-rest-auth and django-allauth to make registration. In the book after register the http return 201 created, it created new account and return API auth key token, save that in db. With my it return http 204 no content( not return API auth key token ), it still created a new account but don't create key token for account. My url.py urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/', include("posts.urls")), # v1 for api version 1. (Name for each api route) path('api-auth/', include('rest_framework.urls')), # build-in log in/out rest path("api/v1/dj-rest-auth/", include("dj_rest_auth.urls")), #url for dj_rest_auth path("api/v1/dj-rest-auth/registration/", include("dj_rest_auth.registration.urls")), ] My settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', #3party "rest_framework", "corsheaders", "rest_framework.authtoken", "allauth", "allauth.account", "allauth.socialaccount", "dj_rest_auth", "dj_rest_auth.registration", #local 'accounts.apps.AccountsConfig', 'posts.apps.PostsConfig',] REST_FRAMEWORK = { # new "DEFAULT_PERMISSION_CLASSES": [ "rest_framework.permissions.IsAuthenticated", ], "DEFAULT_AUTHENTICATION_CLASSES": [ "rest_framework.authentication.SessionAuthentication", "rest_framework.authentication.TokenAuthentication", ],} I compared with github files both author and found no difference. github:https://github.com/wsvincent/restapiswithdjango/tree/master/ch8-blog-user-auth Has there been any change to the version? Thank for you time. -
WeasyPrint server error 500 on render.com
im having a 'server error 500' in my project when i tried to use Weasyprint (im not having any error when i use local host), I deploy my project on render.com it's a django app with postrgres. here is the code: html_template = get_template('printinfo.html') html_string = html_template.render({'person': passanger}) html_string = html_template.render(context) pdf_file = HTML(string=html_string).write_pdf() response = HttpResponse(pdf_file, content_type='application/pdf') response['Content-Disposition'] = f'filename="{passanger.passanger.name} Reservation.pdf"' return response Im thinking its an enviroment error but i installed my requirements.txt in render.com which has weasyprint on it. I tried to find a way to install gtk or pango in render.com but i couldnt find the way... -
Django not identifying User custom model
Error: django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'users.User' that has not been installed settings.py INSTALLED_APPS = [ ... 'apps.users', ... ] AUTH_USER_MODEL='users.User' Resolver o erro. Sem mudar o nome do app no INSTALLED_APPS -
How to annotate a Django queryset with a boolean value for "is older than n days"?
Given the toy example of a model: class Article(models.Model): title = models.CharField(max_length=64) published = models.DateTimeField() How might you get a queryset such that you can tell whether the article was published over 2 years ago? I was thinking something like this, but it didn't pan out: Article.objects.all().annotate( is_relevant=ExpressionWrapper( timezone.now() - F("start") > timedelta(days=365 * 2), output_field=BooleanField(), ) ) Basically, I want to be able to iterate over the list of articles and access article.is_relevant in the template to decide how I might render it. -
How to save another user in your contacts django-rest-framework
I have model of IndividualUser which has OneToOneField to user like its his profile I'm looking for way to save another user in this model like contacts in your mobile phone Or maybe i shouldnt save contacts in model but so where i can save that info? I want to do this with django-rest-framework and i'm wondering how can i do that? I think we can use m2m field there but i dont think that this is good practice for that models.py class IndividualUser(models.Model): individual_user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) first_name = models.CharField(_("first name"), max_length=150) last_name = models.CharField(_("last name"), max_length=150) -
Is there a way to publish a page in the past in Wagtail CMS?
In Wagtail CMS you can publish pages and even set schedules. It seems that you can't publish pages in the past. When I set a schedule in the past (e.g. 01/01/2022) and publish the page, I don't get the expected behaviour. When now accessing the pages property (first_published_at & last_published_at), I don't get 01/01/2022, but the date and time I published the date. Is there a way to achieve that? -
Disable one input in a dynamically generated <tr> with two inputs, one of them a dropdown
I have a recipe app in DJango with an inline-formset-factory. I use this to dynamically add ingredients to my recipe. The ingredient table has three inputs: A rum, an item and an amount. I now want to disable either rum or item depending on which one has a value enterd. If rum has a value, items should be disabled an the other way around. How can I get this done? I've been experimenting with an each loop but I really struggle get get anything useful out of it. Any help and pointers on learning to get better with jquery loops for things like this would be much appreciated. See my HTML code below: <tbody id="item-ingredients"> <!-- id="item-inlineformsetname" --> <!-- formset non forms errors --> <tr id="ingredients-0" class="hide_all"> <!-- id="inlineformsetname-counter" --> <input type="hidden" name="ingredients-0-id" id="id_ingredients-0-id"> <td> <select name="ingredients-0-ingredient_rhum" class="rhum ingredient-input" id="id_ingredients-0-ingredient_rhum"> <option value="" selected="">---------</option> <option value="1">Original - 50.0</option> <option value="2">Se Mettre Au Vert - 44.0</option> <option value="5">Se Mettre Au Vert - 68.0</option> </select> </td> <td> <input type="text" name="ingredients-0-ingredient_name" class="items ingredient-input" maxlength="255" id="id_ingredients-0-ingredient_name"> </td> <td> <input type="number" name="ingredients-0-ingredient_amount" step="0.1" id="id_ingredients-0-ingredient_amount"> </td> <td> <input type="checkbox" name="ingredients-0-DELETE" id="id_ingredients-0-DELETE"> </td> </tr> </tbody> -
Problem with file uploader on Django after deploy
I have a site with file uploader developed on django. But after deployment when I upload a file from one device, the same file becomes visible to all other devices on which the site is opened. But I need each user can upload his file and work with it independently. For example, on this site https://pixmiller.com/en/remove-background/ if I upload pictures from different devices, they will not interfere with each other. And I would like that my site works in this way. How can this problem be solved? Thank for any ideas. For your information: for deployment I have used Docker and Google Cloud. I don't want to create authentication system at this stage. -
How to integrate a Next.js frontend into an existing Django/Vue.js app?
I have an existing Django/Vue.js app, and the Vue.js app is using a hash character (#) before the actual URL (via vue-router). I'm planning to develop a new frontend using Next.js. Is it possible to integrate the Next.js frontend into the existing Django/Vue.js app? I would like to allow users to try out the new frontend while the existing one still works. I assume that Next.js will use v2 in the URLs. Example: https://myapp.ltd/#/profile -> Vue.js https://myapp.ltd/v2/profile -> Next.js Does anyone have any suggestions for how to approach this situation? -
Log format not recognized
I'm using pycharm on windows when i was using that on Linux everything was fine I'm parsing info from my loggers into my model db but for some reason i guess bcs log format for somehow not recognized in pycharm i got this in my model Персональный компьютер UTF-8 in my log files works good I mean i have russian letters and thats what i need but when i parse them with this: with open('loggers/log_user_activity/user_activity.log', 'r') as filelog: for i_line in filelog.readlines(): if i_line.startswith('INFO') and len(i_line.split()) == 9: I got this in console: INFO 2023-04-24 16:20:19,672 k.nefedov 127.0.0.1 Персональный_компьютер Зашёл_на_сайт - - Log settings in pycharm: -
How to store encode file data into database with django ORM which has TextField
i have a java api which store byets stream as encoded data but i don't find anything in django to do that here is Java code :` File f1=new File(publicKeyFile); File f2=new File(privateKeyFile); if(f1!=null || f2!=null) { keys=new Keys(); keys.setPublicKeyFile(f1); keys.setPrivateKeyFile(f2); } and here is how it store like that in db ÂÊLñ¢êl¹ jóEyº_ÿäFþ2ß[o‡V?óI©è4ÔågôJþ¨{A Ae`§GŽjÿ&ømnÏ' Šž‘Üè÷g¥åÿ |ß-멃¨Æ%°m”(åè}þY[S but i can't save this as in django. basically i want something like that which java code is doing please help -
Configuration for Celery during deployment
I am trying to deploy a django app on railway where I am using celery for sending email and redis as celery_broker but When I deploy it then celery don't send emails. I also use Redis Cloud and use the url of it as celery_broker_url. I want to know how to run celery on Redis Cloud. I want to send emails and it doesn't not happen -
How to add a a slug to the URL for the Django admin change page?
I want the url to the admin change pages of single objects to be /admin/app/object/object_pk/slug/change/ instead of /admin/app/object/object_pk/change/. I'd like to avoid writing custom views since in my case the built-in admin interface is used as the frontend for the app. Some users will receive only the link to a change page for read-only purposes and I'd like to increase security by adding the slug to the url. Is this in any way possible or is the Django admin not suitable for such a case? Could I alternatively write a custom view that uses the admin change form as a template? How would I be able to access the built-in template for the custom view? I already tried subclassing ChangeList to change the url_for_result: class ReportAdmin(admin.ModelAdmin): def get_changelist(self, request, **kwargs): class ReportChangeList(ChangeList): def url_for_result(self, obj): return reverse('app_report_change', args=[obj.pk, obj.slug]) return ReportChangeList This made the links for the results on the change list page disappear completely. Maybe I'm missing how to hook in the url at a different place?