Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python, Django: Cross-Saving possible?
Good evening, I would like to know, if there's a "cross-saving"-possibility between to models inside my django-application? For example: models.py class Person(models.Model): first_name = models.CharField() last_name = models.CharfFeld() age = models.IntegerField() value_person= models.IntegerField() date_created = models.DateField class Account(): name = models.CharField() description = models.Textarea() person = models.ForeignKey(Person, null=False, blank=False, on_delete=models.CASCADE) value_a = models.IntegerField() value_b = models.IntegerField() date_created = models.DateField forms.py: class UpdateAccountForm(ModelForm): class Meta: model = Account exclude = [ 'name', 'date_created', ] views.py: [...] account_db = Account.objects.get(id=pk) form = UpdateAccountForm(instance=Account) if request.method == 'POST': form = CreateAccountForm(request.POST, instance=Account) if form.is_valid(): form.save() *** Do something here return("Somehwere") [...] Now I'm asking myself, if it's possible - while updating the "Account" - to update the "Person" and - let's say for example - add one of the two "values_..." into the "value_person"? The connection should be there via the "ForeignKey", right? I think I should also mention, that I'm talking about my default database! I'm aware that this might be a bad example, but it's just so that I can understand the system behind this - hopefully existing - function! Thanks to all of you! -
Name is not defined while trying to get request.user to use in a form
I know this question was asked many times but I keep getting the same error with the solutions posted in stackoverflow. I am probably making a simple mistake but as a beginner, I don't realy see where is my mistake. Here is my forms.py: from django import forms from .models import * class AddMark(forms.Form): def __init__(self, user, *args, **kwargs): self.user = user super(AddMark, self).__init__(*args, **kwargs) teacher = Teacher.objects.filter(user = self.user)[:1] modules = Module.objects.filter(enseignants__in = (teacher)) desc = forms.CharField(label='Description') coef = forms.FloatField(label='Coefficient') max_mark = forms.FloatField(label='Max Mark') module = forms.ChoiceField(label='Module',choices=modules) and it seems like error comes from teacher = Teacher.objects.filter(user = self.user)[:1] -
How to get all self foreign key data in Django?
how to retrieve all related parent field data in Django REST API class Category(models.Model): name = models.CharField(max_length=160) description = models.TextField() meta_title = models.CharField(max_length=160) meta_keywords = models.CharField(max_length=160) meta_description = models.TextField() level = models.IntegerField(default=0) parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True) icon = models.ImageField(upload_to='category/') def __str__ (self): return self.name -
django.db.utils.DataError: integer out of range(Websockets-Django Channels)
I am deploying a django chat application built using django Channels. I have create a daphne.service file to run the daphne command. Following are its contents: [Unit] Description=WebSocket Daphne Service After=network.target [Service] Type=simple User=root WorkingDirectory=/home/path/to/my/workingdirectory ExecStart=/home//path/to/my/virtualenv/python /home/django/path/to/virtualenv/bin/daphne -b 0.0.0.0 -p 8001 myapp.asgi:application Restart=on-failure [Install] WantedBy=multi-user.target The websocket connects when the page loads but as soon as I send a message, the socket closes. After checking the status of the daphne.service file I get the following: Nov 25 14:48:41 ip-172-31-34-249 daphne[1165]:return self._execute_with_wrappers(sql, params,many=False, executor=self._execute) Nov 25 14:48:41 ip-172-31-34-249 daphne[1165]: File "/home/ubuntu/django/virtualenv2/lib/python3.7/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers Nov 25 14:48:41 ip-172-31-34-249 daphne[1165]: return executor(sql, params, many, context) Nov 25 14:48:41 ip-172-31-34-249 daphne[1165]: File "/home/ubuntu/django/virtualenv2/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute Nov 25 14:48:41 ip-172-31-34-249 daphne[1165]: return self.cursor.execute(sql, params) Nov 25 14:48:41 ip-172-31-34-249 daphne[1165]: File "/home/ubuntu/django/virtualenv2/lib/python3.7/site-packages/django/db/utils.py", line 90, in __exit__ Nov 25 14:48:41 ip-172-31-34-249 daphne[1165]: raise dj_exc_value.with_traceback(traceback) from exc_value Nov 25 14:48:41 ip-172-31-34-249 daphne[1165]: File "/home/ubuntu/django/virtualenv2/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute Nov 25 14:48:41 ip-172-31-34-249 daphne[1165]: return self.cursor.execute(sql, params) Nov 25 14:48:41 ip-172-31-34-249 daphne[1165]: django.db.utils.DataError: integer out of range Any ideas What could be wrong here? Thanks -
Nested Serializer In List Serializer
I have a query_set like this: def get_queryset(self): return [ [Article(id=1), Article(id=2)], [Article(id=3)] ] that return list of list of objects(Article). How can I create a Serializer for this? -
DetailView Show Model With Boolean Property Set to True
I am creating a Django web app and am trying to set a page model to be the homepage (page at root directory). There can only be one homepage model, and homepages are set via setting the the homepage variable to true. Settings one true, will set the previous homepage to false. # models.py class Page(models.Model): title = models.CharField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() homepage = models.BooleanField(default=False) def save(self, *args, **kwargs): if not self.homepage: return super(Page, self).save(*args, **kwargs) with transaction.atomic(): Page.objects.filter( homepage=True).update(homepage=False) return super(Page, self).save(*args, **kwargs) def __str__(self): # return self.title + ' | ' + str(self.author) return self.title # views.py class HomePage(DetailView): model = Page.objects.filter(homepage=True) template_name = 'home.html' In my views.py script, I am trying to get the model which has homepage = True and displaying it as a DetailView. # urls.py urlpatterns = [ ... path('', HomePage.as_view(), name="home"), ... ] Unfortunately, I am getting an error: AttributeError at / 'QuerySet' object has no attribute '_default_manager' What am I doing wrong and how do I fix this? -
How do you set a password on a PDF using Python reportlab and buffer from BytesIO
I am trying to programmatically add a password to a generated PDF file that is created using Python's reportlab. The PDF is generated within a Django web application. The code to dynamically generate a PDF from Django is well documented on Django's help pages: import io from django.http import FileResponse from reportlab.pdfgen import canvas def some_view(request): # Create a file-like buffer to receive PDF data. buffer = io.BytesIO() # Create the PDF object, using the buffer as its "file." p = canvas.Canvas(buffer) # Draw things on the PDF. Here's where the PDF generation happens. # See the ReportLab documentation for the full list of functionality. p.drawString(100, 100, "Hello world.") # Close the PDF object cleanly, and we're done. p.showPage() p.save() # FileResponse sets the Content-Disposition header so that browsers # present the option to save the file. buffer.seek(0) return FileResponse(buffer, as_attachment=True, filename='hello.pdf') But as soon as I attempt to add a password to the PDF file, the resulting PDF file is blank. # This results in a blank PDF document p = canvas.Canvas(buffer, encrypt='password') Does anyone know how to use a BytesIO buffer with reportlab and set a password on the file? -
Booking management system (Restriction of booking times)
I am currently trying to add a restriction to what dates and times a client can book. Example.. My day starts at 8AM so I want only bookings from 8AM onwards. A client wants to book a slot from 7AM-8AM then they should receive an error saying something along the lines of "can only book 8AM-7PM". currently I have done this code: class AvailabilityForm(forms.Form): check_in = forms.DateTimeField(required=True, input_formats=['%m/%d/%Y %H:%M', ]) check_out = forms.DateTimeField(required=True, input_formats=['%m/%d/%Y %H:%M', ]) def validate_checkin_time(check_in_time): if check_in_time <= 5.59 or check_in_time >= 7.00: raise ValidationError("Check in times must be between 6:00AM and 7:00PM") def validate_checkout_time(check_out_time): if check_out_time <= 6.59 or check_out_time >= 8.00: raise ValidationError("Check in times must be between 7:00AM and 8:00PM") class Booking(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) check_in = models.DateTimeField(validators=[validate_checkin_time]) check_out = models.DateTimeField(validators=[validate_checkout_time]) My first question is.. am I on the right lines here using validation? So looking at it I don't think the if statements are correct but im not entirely sure how to correct them. Also do I have to somehow add the format of datetime into the validate funcs? I Also don't want to allow clients to book in the past. Is there a way to allow that in the functions at … -
How can I send notifications to subscribers of an entity according to the type of entity in a django app with REST framework?
I have to create a web app similar to ratemyproffesors.com (but login is required to create a review) but I dont know what would be the best way to design the database, especially the notifications system. I have the following desing in mind. My Database I have 3 entities that have some fields in common and can receive reviews from users. Every time a reviews is created for a professor, a deparment or a college, subscribers to that entity recieve a notification. How can I send notifications to subscribers of an entity according to the type of entity that receives a new review (professor, deparment, college)? Example: Professor NAME LASTNAME recieve a new review URL. NAME deparment of COLLEGENAME recieve a new review URL. NAME college recieve a new review URL. -
Django, Permissions other than the 'view' permission are not authenticated
First of all, I can't speak English well. test1 account permissions.py from rest_framework import permissions import copy class ViewPermissions(permissions.DjangoObjectPermissions): def __init__(self): self.perms_map = copy.deepcopy(self.perms_map) self.perms_map['GET'] = ['%(app_label)s.view_%(model_name)s'] class AddPermissions(permissions.DjangoObjectPermissions): def __init__(self): self.perms_map = copy.deepcopy(self.perms_map) self.perms_map['POST'] = ['%(app_label)s.add_%(model_name)s'] class UpdatePermissions(permissions.DjangoObjectPermissions): def __init__(self): self.perms_map = copy.deepcopy(self.perms_map) self.perms_map['PATCH'] = ['%(app_label)s.change_%(model_name)s'] view.py from rest_framework import viewsets, permissions, generics from .serializers import PlayerListSerializer from .models import PlayerList from .permission import ViewPermissions, AddPermissions, UpdatePermissions class ListPlayer(generics.ListCreateAPIView): permission_classes = [ViewPermissions, ] queryset = PlayerList.objects.all().filter(del_yn='no').order_by('-key') serializer_class = PlayerListSerializer class AddListPlayer(generics.ListCreateAPIView): permission_classes = [AddPermissions, ] queryset = PlayerList.objects.all().filter(del_yn='no').order_by('-key') serializer_class = PlayerListSerializer class DetailPlayer(generics.RetrieveUpdateDestroyAPIView): permission_classes = [UpdatePermissions, ] queryset = PlayerList.objects.all() serializer_class = PlayerListSerializer With a simple test, I found that I can't see the list without'view' permission. But for the rest of the permissions I get a '401 (Unauthorized)' error and it doesn't work. The'view' permission is authenticated, but the rest of the permission is not and I get a 401 error. I want to know the reason. No matter how much I searched the internet, I couldn't find the answer I wanted. No answer posted, so I ask again. -
To JSON serialize objects that contain a file?
I want to retrieve Story together with the associated story_media from my DRF backend. Story_Media contains both data and files and comes as a list. This means a single Story can have multiple Story_Media objects (Story is FK in story_media). However, when I want to return the litst of Story_Media objects, it seems that they are not serializable. So my question is, how do I JSON serialize objects that contain a file? TypeError: Object of type Story_Media is not JSON serializable class StoryRetrieveSerializer (serializers.ModelSerializer): story_media = serializers.SerializerMethodField('get_story_media') class Meta: model = Story fields = ('title', 'story_media') def get_story_media(self, story): return Story_Media.objects.filter(story=story.id) -
Streaming generated word file with python-docx
I have to generate very large word document using python-docx library, so is it possible to stream this file while generating it? -
Rendering not working even through command is visible in CMD log
I am new to django, trying to use AJAX to move data from html to views.py via AJAX, something weird is happening, data is moving but the page is not changing, new page is not getting rendered. HTML CODE <div class="bodyclass"> {% csrf_token %} {% for account in accounts %} <div class=""> <div class="accountname"> <button onclick="submitform('{{ account}}')" class="btn btn-info accbtn " id="{{ account }}">{{account}}</button> </div> </div> {% endfor %} </div JS Code <script> function submitform(accname){ alert(accname); var csrf = document.getElementsByName('csrfmiddlewaretoken'); $.ajax({ type : 'POST', url : 'accounts', data:{ csrfmiddlewaretoken : csrf[0].value, 'accname': accname, }, }); alert('bye'); } </script> views.py def accounts(request): if request.user.is_authenticated: if request.method == 'GET': if request.user.is_superuser: account = AccountDescription.objects.all() else: account = UserAccount.objects.filter(user=request.user) return render(request, 'accounts.html',{'accounts':account}) elif request.method == "POST": print(request.POST) print(request.POST.get('accname')) return HttpResponseRedirect('/clientinfo') else: return HttpResponseRedirect('/login') also the cmd screenshot Kindly let me what wrong I am doing. also let me know if any more input is required. Thanks in advance. -
Django - What is better, creating a ImageField on DB or a string path?
i started programming on Django and needed to make an Image Upload, saving the imagepath. I have 2 options, save the image on the BD as an ImageField or Save the path where the image is saved. Which one is better? -
How do I allow the authenticated user to retrieve their API credential from the database automatically?
I am relatively new to Django and I am struggling how to go about a feature that I want to implement. For the feature, I need to get a set of secondary credentials (used to authenticate against third-party software API), hashing the credentials, and then storing it in the database. These creds can then be called by the authenticated user associated with those secondary credentials, unhashed, and then used to make the API connection. My question is, how do I allow the authenticated user to retrieve their API credential from the database automatically? Currently, I have a custom user model set up under a new app called users and in the models.py as: import uuid from django.db import models from django.contrib.auth.models import AbstractUser, BaseUserManager class UserManager(BaseUserManager): def create_user(self, email, username, unique_id, first_name, last_name, password, **other_fields): email = self.normalize_email(email) user = self.model( email = email, username = username, unique_id = unique_id, first_name = first_name, last_name = last_name ) user.set_password(password) user.save(user=self._db) return user def create_superuser(self, email, username, unique_id, first_name, last_name, password, **other_fields): email = self.normalize_email(email) user = self.model( email = email, username = username, unique_id = unique_id, first_name = first_name, last_name = last_name, password = password ) user.is_admin = True user.is_staff = … -
django site adminstration asking for CSRF Validation
I have been developing a django page and deployed the same on IIS. everything was working fine. there was no issue with CSRF validations. I then integrated the page in Sharepoint iframe and now I am facing an CSRF error. it is working fine via url but in iframe the site is not able to validate CSRF. I don't know what screenshots are required. let me know i will share accordingly. let know if someone faced the same issue and know how to resolve it. Thanks in advance. -
KeyError: 'Unable to find stateless DjangoApp called app'
Why the DjangoApp app can't be found? Given result After executing manage.py runserver in the console Django is starting properly but in case I'm calling http://127.0.0.1:8000/dash_simple/app1/ a KeyError was thrown: Django Version: 3.1.3 Exception Type: KeyError Exception Value: 'Unable to find stateless DjangoApp called app' Expected result After executing manage.py runserver in the console Django is starting properly and the related page is shown for http://127.0.0.1:8000/dash_simple/app1/ dash_simple/urls.py urlpatterns = [ path('', views.home, name='home'), path('app1/', views.app, name='app') ] dash_simple/views.py def home(request): return render(request, template_name='dash_simple/home.html') def app(request): return render(request, template_name='dash_simple/app1.html') dash_simple/templates/dash_simple/app1.html {% load plotly_dash %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>App 1</title> </head> <body> <H1>I'm App 1</H1> <p> {% plotly_app name="app" %} </p> </body> </html> -
Data loss in an inline formset
I am developing an application which allows an administrator to create several projects and within those projects different tasks can go, the idea is that when the administrator creates a project within that form he can also assign multiple tasks, for this I am using inline formset because I feel That meets my needs, but I have a problem and it is that when I click the button to add more tasks, the select where are the types of tasks is lost. This is my template: This is my view: class ProjectCreateView(LoginRequiredMixin, CreateView): login_url = 'users:login' template_name = 'projects/add_project.html' form_class = ProjectForm success_url = reverse_lazy('projects:project') def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) if self.request.POST: data['formset'] = ProjectFormSet(self.request.POST) else: data['formset'] = ProjectFormSet() return data def form_valid(self, form): context = self.get_context_data() formset = context['formset'] with transaction.atomic(): self.object = form.save() if formset.is_valid(): formset.instance = self.object formset.save() return super().form_valid(form) This is my template: {% extends "base.html" %} {% load materializecss %} {% load static %} {% block content %} <div class="container"> <div class="card"> <div class="card-content"> <h2>Agregar Proyecto</h2> <div class="col-md-4"> <form id="form-container" method="post"> {% csrf_token %} {{ form|materializecss }} <h2>Tareas</h2> <table> {{ formset.management_form }} {% for form in formset %} {% if forloop.first %} <thead> <tr> … -
Django Test with setting up DB extensions
For my project i'm using PostgreSQL with pg_trm and unaccented extensions that I enable by executing a script into the DB. Running tests results in error because the test database doesn't have those extensions, of course. How can I add those scripts into the test database before the migrations are applied? -
How to apply css classes to the TimeDurationWidget in Django
I am trying to apply css styling to my modelform. from durationwidget.widgets import TimeDurationWidget class WeightDistanceTimeModelForm(forms.ModelForm): weight = forms.DecimalField(widget=forms.NumberInput(attrs={'placeholder': 'Weight', 'class': 'form-control', 'step': 2.5})) distance = forms.IntegerField(widget=forms.NumberInput(attrs={'placeholder': 'Distance', 'class': 'form-control'})) time = forms.DurationField(widget=TimeDurationWidget(show_days=False, show_hours=True, show_minutes=True, show_seconds=True), required=False) My weight and distance fields are showing up how I'd like but does anyone know how I can apply a placeholder and class of form-control to each of hours, minutes and seconds. I can't seem to find any documentation that explains this anywhere. Alternatively, is there a better way to display this information? I have also tried adding the class directly into my template: <div class="form-control"> {{ form.time }} </div> But this didn't work either -
How to check certain headers exist in each request in Django Rest Framework?
I want to test api_key and secret against all requests of different models. Both fields exist in a table. I am using DefaultRouter which itself creates all CRUD based requests URLs. Will I need to create custom functions to check headers or there is some better way to do it? -
How to customize the selection form?
I have a model class Car(models.Model): class ModelChoise(models.IntegerChoices): Model_1 = 0 Model_2 = 1 Model_3 = 2 Model_4 = 3 name = models.TextField('Name') model_id = models.IntegerField('model id', choices=ModelChoise.choices, default=1) def __str__(self): return self.name And I created a form for it class CarForm(ModelForm): class Meta: model = ExtraUser fields = ['model_id'] I need to deduce both key and value from it {% for mykey,myvalue in form.model_id %} {{ mykey }} : {{ myvalue }} {% endfor %} <!-- Model_1 : 0 Model_2 : 1 Model_3 : 2 Model_4 : 3 --> How should I do it? I can only get the key. -
How would I be able to set an usb barcode scanner to compare the scanned id to the id in the database table in Django?
First of all, I'm pretty new to programming in general. I've been trying to learn Django/python. I've had an app in mind that i started building. The app would be used to track users coming in and exiting the building. The data that would be stored in the database is the User, date and time at the exact moment of entering/leaving the building, temperature, location of the building. Ok so I have my database set up with the tables. Now the User has an id which is represented in a barcode. The problem I have now is that I want to create a homepage that is empty with just a few words like: Please scan your barcode. And when the barcode is scanned I want the page to redirect to the form for adding a new database entry but is populated with the user data. I don't know how to do that, that's my problem here. -
Retrieve access_token subsequent to login with mozilla_oidc_connect
After I have logged in and authenticated a user with mozilla_django_oidc I need to subsequently use the access token to call an API. mozilla_django_oidc offers to store the access token in the session variable but this is insecure so I'd like to run a second call against the OIDC provider. I need to pull out the logic from OIDCAuthenticationBackend that will retrieve the access token in order to do the API call. I could re-authenticate but that sounds like it will be a pain. -
how to use django 3 with django-otp to send token sms using SMS service provider for user verification and redirecting to password reset form?
I have only been able to make the following changes in django code: settings.py: added along with other apps added in INSTALLED_APPS = [ ..... 'django_otp', 'django_otp.plugins.otp_totp', ] In additions to other middleware configurations, added: MIDDLEWARE = [ 'django_otp.middleware.OTPMiddleware', ] urls.py: from django_otp.admin import OTPAdminSite from django_otp.plugins.otp_totp.models import TOTPDevice admin_site = OTPAdmin(name='OTPAdmin') admin_site.register(User) admin_site.register(TOTPDevice) urlpatterns = [ path('admin/', admin_site.urls), #otp app path('dadmin/', admin.site.urls), ] Then I ran: $ python3 manage.py migrate otp_totp --fake and runserver. Created a user and totp device. Scanned the qr code in google authenticator. Then tried logging in using the admin url to login for this new user. It asks for the token generated which I input, it says invalid token though user is authenticated. Seen other posts where the secret code needs to be converted to 32basecode etc, but don't know exactly and where to implement. What more code needs to be added to get this working? I will require detailed code and steps for my use case where i need to change the time for generating the code and send via sms using my service provider api and redirect to password reset form. Using django 3.1, django-otp 1.0.2