Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
How to do MYSQL table partitioning in Django?
I need to do partitioning on the region field of my Street model.I want to have a table for each region (there are 10 different regions). I am using architect but it returns an error. Here is my model using architect : @architect.install('partition', type = 'range', subtype = 'integer', constraint = '1', column ='region') class Street(models.Model): region = models.PositiveSmallIntegerField(null=1) name = models.IntegerField() Here is the error : architect partition: error: unsupported partition range subtype "integer" in "Meter" model, supported range subtypes for "mysql" database are: date But what exactly I need is partitioning the table based on region field (streets in region 1, streets in region 2,... streets in region 10). Thanks a lot. -
Django Createview and redirect url to detailview
I'm looking to add a push buttom in my detailview for add some new documents or other stuff. I'm using a modal in ma detailview html which is vorking well. but when i click to submit form i'am not able to go back to my detailview ... my view.py class MissionsList(FilterView): pagination =22 model = Missions context_object_name = 'missions_list' template_name = 'missions/index.html' filterset_class = MissionsFilters # ADD YOUR filterset class ''' class MissionDetails(DetailView): model = Missions template_name = "missions/mission_detail.html" def get_context_data(self, **kwargs): context = super(MissionDetails, self).get_context_data(**kwargs) mission_pk = self.kwargs['pk'] documents = DocMission.objects.filter(mission = mission_pk) details= Missions.objects.filter(id=mission_pk) reservations = Reservation.objects.filter(mission = mission_pk) context['documents']=documents context['reservations'] = reservations return context class DocMissionsCreate(CreateView): template_name = 'missions/create_doc.html' form_class = DocMissionForm succes_url = reverse_lazy('mission_detail') ''' here my models.py ''' class Projets(models.Model): id = models.AutoField( primary_key=True) # Field name made lowercase. name = models.CharField(max_length=45, blank=True, null=True) commentaire = models.TextField() pi = models.CharField(max_length=45, blank=True, null=True) class Meta: managed = False db_table = 'projets' ordering = ["name"] def __str__(self): return str(self.name) class Missions(models.Model): id = models.AutoField( primary_key=True) # Field name made lowercase. name = models.CharField(max_length=45, blank=True, null=True) debut = models.DateField(blank=True, null=True) fin = models.DateField(blank=True, null=True) lieu = models.CharField(max_length=45, blank=True, null=True) navire = models.CharField(max_length=45, blank=True, null=True) nombre_participant = models.IntegerField(db_column='nombre participant') … -
Send email to user after password reset in django
I am using the Django native password reset functionality to reset account passwords. urls.py path('reset/', auth_views.PasswordResetView.as_view(template_name='account/password_reset.html', form_class=PasswordResetform), name='reset'), path('reset_done/', auth_views.PasswordResetDoneView.as_view(template_name='account/reset_done.html'), name='password_reset_done'), path("reset/<uidb64>/<token>/", auth_views.PasswordResetConfirmView.as_view(template_name='account/reset_confirm.html', form_class=PasswordResetConfirm), name='password_reset_confirm'), path("reset/complete", auth_views.PasswordResetCompleteView.as_view(template_name='account/reset_complete.html'), name='password_reset_complete'), now everything works fine, I get the password reset link in my email and when I open it I am able to reset my password, but after the user resets the password, I want to send them an email saying their password has been reset I tried to write an ajax function that is triggered when it goes to the 'password_reset_complete' template, but there I am unable to access the user's email or username. how do i retrieve the user's email or username in the 3rd or the 4th template of the password reset steps? -
Can't Upload Img Using concrete view django rest framework
Hope You Are Fine! How Can i Upload Img Using concrete view Django rest framework? i have a model class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) headline = models.CharField(max_length=100, blank=True, null=True) maiden_name = models.CharField(max_length=100, blank=True, null=True) profile_picture = models.ImageField(upload_to='avatar/', blank=True, null=True) company_name = models.CharField(max_length=124, blank=True, null=True) proposal_comments = models.TextField(blank=True, null=True) associations = models.TextField(blank=True, null=True) interests = models.TextField(blank=True, null=True) website = models.URLField(blank=True, null=True) location = models.CharField(max_length=124, blank=True, null=True) bio = models.TextField(blank=True, null=True) state = models.CharField(max_length=124, blank=True, null=True) country = CountryField(blank=True, null=True) date_of_birth = models.DateField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.user.username which had image field named profile_picture i have also registered this model to admin and when i upload img using django administration it automatically upload/added to media folder. but when i upload img using django rest framework it is not showing me any error. what django rest framework do just update the url of img. django rest framework is not uploading/adding img to my media folder. i'm uploading img by hand. settings.py .... MEDIA_ROOT = os.path.join(BASE_DIR.parent, "media") MEDIA_URL = "/api/media/" urls.py ..... if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ("username", "email", "first_name", "last_name",) read_only_fields = ("username",) def validate_email(self, …