Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
the best way to insert three related models in django rest api in one request for user roles
I have three models for defining user roles. Each User can have multiple roles. What is the best way to inserts roles as a list in one request that also it will create a user account for them? my models: class Account(AbstractBaseUser): # django's own fields email = models.EmailField(blank=True, null=True, max_length=60, unique=True, verbose_name='آدرس ا .... class Role(models.Model): name = models.CharField(max_length=20, verbose_name='اسم رول') def __str__(self): return self.name class Meta: verbose_name = 'رول' verbose_name_plural = 'رول ها' class UserRole(models.Model): account = models.OneToOneField(Account, on_delete=models.CASCADE, verbose_name='اکانت', related_name='user_roles') roles = models.ManyToManyField(Role, verbose_name='رول') is_active = models.BooleanField(verbose_name='فعال') def __str__(self): return f"{self.account}" class Meta: verbose_name = 'رول کاربر' verbose_name_plural = 'رول های کاربر' my serializers: class RoleSerializer(serializers.ModelSerializer): class Meta: model = Role fields = ['id', 'name'] class UserRoleSerializer(serializers.ModelSerializer): roles = RoleSerializer(many=True, read_only=True) class Meta: model = UserRole fields = ['roles', 'is_active'] extra_kwargs = {'roles': {'required': False}} class NewAccountSerializer(serializers.ModelSerializer): user_roles = UserRoleSerializer(many=False, read_only=False) class Meta: model = get_user_model() fields = ['phone_number', 'user_roles',] -
What are the differences between APIView and Django generic views in terms of usage?
I am trying to build a Django backend API that will be accessible both by a mobile app and a website. I am setting up the user authentication functionality using the rest-framework module. Can anyone explain the difference in functionality and usage between the two types of views (APIView and Django display/editing generic views) and which ones would be more suitable for my goals? -
Python Django - multipule update form in a loop
So I'm trying to make a template which will show tests from different students and I would like to make it possible to grade (with a choice field) those tests on one view. I have a loop which shows all of ungraded tests and next to them an update possibility. So I tried this views.py class TestUpdate(UpdateView): model = Tests fields = ['grade'] template_name = "tests_update.html" success_url = reverse_lazy('home') class ClassDetails(WhichUserMixin, DetailView): model = Classes template_name = "class_test_details.html" def get_context_data(self,**kwargs): context = super().get_context_data(**kwargs) tests = Tests.objects.all().filter(grade = None, teacher = self.current_teacher) context['ungraded_tests'] = tests return context models.py class Tests(models.Model): teacher = models.ForeignKey(Teacher,on_delete=models.CASCADE, null = True) desc = models.CharField(max_length = 50, null = True) student = models.ForeignKey(Student, on_delete = models.CASCADE, null = True) subject = models.CharField(max_length=10, choices=SUBJECTS, null = True) classes = models.ForeignKey(Classes, on_delete = models.CASCADE, null = True) class Grades(models.IntegerChoices): F = 1 E = 2 D = 3 C = 4 B = 5 A = 6 grade = models.IntegerField(choices = Grades.choices, null = True) def __str__(self): return self.desc template: <h2> Class</h2> {% for test in ungraded_tests %} <p>{{test.student.user.first_name}} {{test.student.user.last_name}} - Class: {{test.classes}} - {{test.desc}}</p> <form method="post"> {% csrf_token %} {% bootstrap_form form %} <input type="submit" class = 'btn … -
Django: Import legacy database data keeping primary keys having an autokey
I am using Django to develop new software to replace a legacy one, and all my new models have auto-increment primary keys. I want to import records from the legacy database keeping their original primary keys (users know them all), but I don't know how to do it with auto-increment primary keys. Is it possible to create my models with integer primary keys and change them to auto-increment ones without losing their data? -
How to compare DateTimeField with timezone.now()
I'm new to python/django and I have an Events app where users can see upcoming events of an organization but I don't know how to show only future events and disregard events from the past. models.py class Event(models.Model): title = models.CharField(max_length=500) description = RichTextField() start_date = models.DateTimeField() end_date = models.DateTimeField() created_date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(NewUser, on_delete=models.CASCADE) views.py class ShowEventsListPageView(ListView): model = Event template_name = 'registration/user_events.html' def get_queryset(self, *args, **kwargs): user = self.kwargs['pk'] return Event.objects.filter(author=user).annotate(Event.end_date > timezone.now()).order_by('-start_date') This code is returning '>' not supported between instances of 'DeferredAttribute' and 'datetime.datetime' -
Mapping access token to client IP
My Setup I am using React and Django as frontend & backend. For authorization purposes I chose Django-rest-knox, which works via tokens stored in a database. My Problem Now if an attacker gets a hold of the token (stored in local storage on the client side after a login), he can do anything that the user is able to. There is some expiration on the token and the ability to destroy all tokens of the user by the user himself. But I'd like to be on the safer side. My Solution My idea is to map all tokens to the IP address (of the user) that was used to login. That way the token would only be usable on the machine that was used to login. That token-to-IP-address relation would be checked on the backend. My Questions Is the idea feasible at all or is there anything in the nature of those IP addresses that breaks my intent? What is the best way to get the client IP-address? Do you think that is a secure approach? Thanks for the help! -
jquery save get response as csv file
I have this view that returns csv data def get_newsletters_email(request): if request.user.is_staff: df = pd.DataFrame(list(NewsletterSubscription.objects.all().values('name', 'email'))) file_path = settings.MEDIA_ROOT + '/newsletter_emails/emails.csv' df.to_csv(file_path) with open(file_path, 'rb') as fh: response = HttpResponse(fh.read(), content_type="application/csv") response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path) return response else: response = {} return HttpResponse( json.dumps(response), content_type="application/json" ) from a get request $('.download-newsletters').click(function(e){ e.preventDefault(); $.get("/newsletter_emails/", function( data ) { //Save file }); }); since it's a link click that prevents any redirect I need to tell the browser to use the response and opt to save the data. -
Can't login to Django Admin with custom User Model
I create a custom model for User, By this I can create superuser from command line, and its create successfully. But when I trying to login to Django admin with created Super user its show me This error @property def is_staff(self): return self.staff @property def is_superuser(self): return self.superuser @property def is_active(self): return self.active These property also set True models.py from django.db import models from django.contrib.auth.models import (BaseUserManager, AbstractBaseUser) class UserManager(BaseUserManager): def create_user(self, email, password=None): """ creates a user with given email and password """ if not email: raise ValueError('user must have a email address') user = self.model( email=self.normalize_email(email), ) user.set_password(password) user.save(self._db) return user def create_staffuser(self, email, password): """ creates a user with staff permissions """ user = self.create_user( email=email, password=password ) user.staff = True user.save(using=self._db) return user def create_superuser(self, email, password): """ creates a superuser with email and password """ user = self.create_user( email=email, password=password ) user.staff = True user.superuser = True user.save(using=self._db) return user class User(AbstractBaseUser): email = models.EmailField( verbose_name='Email address', max_length=255, unique=True ) active = models.BooleanField(default=False) staff = models.BooleanField(default=False) # <- admin user, not super user superuser = models.BooleanField(default=False) # <- super user USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] # <- email and password are required by default … -
Replace bearer token to Token
I am trying to implement google authorization in django rest. I am using django-rest-framework-social-oauth2. I get a response with a Bearer token. Is it possible to change Bearer to Token? And remove everything in the response, leaving only access and refresh token "access_token": "xX7KPdrMeINhO7yT0g5jhqHoR3oipI", "expires_in": 36000, "token_type": "Bearer", "scope": "read write", "refresh_token": "cwlZsSDL15NVbcE1VeUd5YEihQfR0E" -
How to delete a logger in the logger hierarchy using python3 logging?
I have created a logger hierarchy using the python3 logging module. Since I'm using multiprocessing (fork-based), I need re-create my loggers in the child processes, which are otherwise inherited. How can I delete loggers in the logging logger hierarchy (or reset the logging module in child processes)? I've looked at logging.Logger.removeHandler(), but I'd rather not have to loop through all loggers and call that method for each handler. Furthermore, I've experienced weird behaviour when attempting this. -
Total marks is not getting calculated properly here. Its always showing 0. How can i solve this?
1.This is my html code. <form class="form" autocomplete="off" onsubmit="return saveAns()" action="/calculate_marks_view" method="POST"> {% csrf_token %} <h1 style="text-align: center;">{{test.course_id.course_name}}</h1> {% for q in questions%} <h3 class="text-info">{{ forloop.counter }}. {{q.question}}</h3><h4 style="text-align: right;">[Marks {{q.marks}}]</h4> <input type="hidden" name="csrfmiddlewaretoken" value="{{csrf_token}}"> <div class="form-check mx-4"> <input class="form-check-input" type="radio" name="{{ forloop.counter }}" id="{{q.option1}}" value="Option1"> <label class="form-check-label" for="option1"> {{q.option1}} </label> </div> <div class="form-check mx-4"> <input class="form-check-input" type="radio" name="{{ forloop.counter }}" id="{{q.option2}}" value="Option2"> <label class="form-check-label" for="option2"> {{q.option2}} </label> </div> <div class="form-check mx-4"> <input class="form-check-input" type="radio" name="{{ forloop.counter }}" id="{{q.option3}}" value="Option3"> <label class="form-check-label" for="option3"> {{q.option3}} </label> </div> <div class="form-check mx-4"> <input class="form-check-input" type="radio" name="{{ forloop.counter }}" id="{{q.option4}}" value="Option4"> <label class="form-check-label" for="option4"> {{q.option4}} </label> </div> {% endfor %} <input class="btn btn-info btn-lg" type="submit" value="Submit"> </form> 2.This is my javascript code to save answer through cookies. But i guess that something is wrong here, but i couldn't put my eye on it. <script> function saveAns(){ var answer = document.getElementsByTagName('input'); for(i = 0; i < answer.length; i++) { if(answer[i].type="radio") { if(answer[i].checked){ setCookie(answer[i].name,answer[i].value,3) } } } } function setCookie(cname, cvalue, exdays) { var d = new Date(); d.setTime(d.getTime() + (exdays*24*60*60*1000)); var expires = "expires="+ d.toUTCString(); document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/"; } This is my calculate_marks_view. Here I … -
How can I pass string variable in JavaScript using Django URL?
This is my script: var id = $('#filename').val(); location.href = "{% url 'officelyapp:finalTemplate' privateId=id %}" This is my url: path('signature/template/merge/private/access/<str:privateId>/', views.finalTemplate, name='finalTemplate') I get the following error attached below whenever I tried to load my page. Error Shown In Image I find this link: https://stackoverflow.com/.../get-javascript-variables... that passes JavaScript value like this: window.location = "{% url 'your_view_name' 1234 %}".replace(/1234/, tmp.toString()); But this only works when one specifically writes a specific integer value in it like 1234 in the above line of code. -
Hotel Management System using Django and PostgreSQL
I'm a Front-End Developer and Graphics Designer. I need to build web-based application and i'm doing backend for first time using Django for my final yaer project. So, the idea of my project is that there will be waiter, stockstaff, chef, cashier and manager and each user will have their own pages after login on webite and it will go like this: Waiter book tables and take order when customer’s arrives to the restaurant using his page. StockStaff then get notify for the food item, they have to check in stock. Then at same time staff will notify both waiter, if there is stock or not and manger, if there is no stock. If waiter get notify that there is stock available then waiter will notify chef to cook meal otherwise he will go to customer and say no food available. At the same time manager will get notify too that there is no stock, he will notify staff that stock will be updated soon only. After meal is cooked, chef will notify waiter to take the meal at particular table number. Overall details are then transferred to cashier so that they can generate payment. Server process the request and … -
Why aren't my custom routes in django recognized?
I'm trying this Django tutorial https://www.javatpoint.com/django-crud-application Here is how my view is defined: def show(request): employees = Employee.objects.all() return render(request, "show.html", {'employees': employees}) Here is how my url file in the django_crud project (my project name) is defined: from django.contrib import admin from django.urls import path, include from employee import views urlpatterns = [ path('admin/', admin.site.urls), path('emp', views.emp), path('show', views.show), path('edit/<int:id>', views.edit), path('update/<int:id>', views.update), path('delete/<int:id>', views.destroy), ] My templates are in employee/templates My app is obviously registered: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'employee' ] I run the server with python manage.py runserver with no errors. Migrations are done with no error. The database is empty, but this should not matter. The problem is that only the admin route work. The show route (or any other) doesn't work. I hate when a tutorial doesn't work and I'm triying to figure out the problem, but I don't see any issue. Maybe the turorial is about an old version of Django and I have something missing? Any insight? -
Python Application for mobile
Hy everyone, I want to create python base earthquake mobile application for android. You anyone have idea about it guide me how can I create it and what are the prerequisites for application. -
How to set up URL aliases for dynamically created URLs in DJANGO?
In my site, I have pages that are created on the fly using primary keys (for privacy/security reasons using uuid.uuid4()) as the URLs. I end up with .../reports/e657334b-75e2-48ce-8571-211251f1b341/ Is there a way to make aliases for all of these dynamically created sites to something like .../reports/report/. Right now my urls.py includes the following: path("reports/<str:pk>/", views.report_detail, name="report") I tried changing it to: re_path('reports/<str:pk>/', RedirectView.as_view(url='/reports/report/'), name="report"), path("reports/report/", views.report_detail), But I go to the site that has the links to the long URLs, I get the following error: NoReverseMatch at /reports/Reverse for 'report' with arguments '('e657334b-75e2-48ce-8571-211251f1b341',)' not found. 1 pattern(s) tried: ['reports/str:pk/'] The template for that site includes: <a class="card-title" href="{% url 'report' report.pk%}"> Without trying to make an alias, the site works fine. -
how to disable a specific button out of many button after click?
I have list of many users. i have table to dispalay user name and then one input field for email id and then submit button, when i enter email id of a specific user and click submit then user get userid and password in their mailbox. i want when i submit the submit button of that particular user get disabled. i am using django for loop in html so its disables submit button of all users. i want only that users button get disables. <a id="elementId" href="{% url 'urlabc' %}" onclick="" onclick="setTimeout(function(){document.getElementById('elementId').this.removeAttribute('href');}, 1);">Click -
Django Restframework serializing matrix of objects
I have a model which holds matrix data as JSON. class SomeModel(models.Model): matrix_data = models.TextField(...) @property def matrix(self): return json.loads(self.matrix_data) @matrix.setter def matrix(self, value: list): self.matrix_data = json.dumps(value) Form data is transferred as application/x-www-form-urlencoded: matrix[0][0][x]: 0 matrix[0][0][y]: 1 ... matrix of objects with properties x, y. Serializer looks like: class Cell(serializers.Serializer): x = serializer.IntegerField() y = serializer.IntegerField() class Row(serializers.ListSerializer): child = Cell(many=True) many = True class SomeSer(serializer.ModelSerializer): matrix = Row() class Meta: model = ... ... self.data at Serializer.save() has all data needed. I dont understand what I'm doing wrong. -
DJango form Select a valid choice. This is not one of the available choices
Here is my models.py class ProductEntry(models.Model): product=models.ForeignKey(Product, on_delete=models.CASCADE) size=models.CharField(max_length=50) # ...more fields This is my admin.py class ProductEntryForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ProductEntryForm, self).__init__(*args, **kwargs) self.fields['size'] = forms.ChoiceField( widget=forms.Select ) I am overriding the CharField with a Select widget and want to fetch the options of the select widget using javascript. But the problem is when I am going to save the model, I am getting the following error: DJango form Select a valid choice. This is not one of the available choices. Any form of work round will be appreciated. Yes I am aware that I can pass a choices arguments to the CharField but I don't want to do so because I want the choices to load dynamically based on the value of other fields. -
How to get uploaded absolute s3 image path in Django
How to get uploaded s3 image absolute path. I tried model_instance.image.file.path but it throws an error django backend doesn't support absolute paths I have multiple models with image (FileField) and wanted to get absolute path of it to be served to FE. Locally things won't get messed up but when I deploy it on production couldn't get absolute path. I was thinking to define a method get_image_path() in each model and concatenate related path something like f"https://{domain}/{static_location}/{self.image.file.url}" Please suggest if this is an ideal way to do this or is there any better approach. Thanks. -
TabError: inconsistent use of tabs and spaces in indentation while reading last object from model
TabError: inconsistent use of tabs and spaces in indentation strong text class DownloadPDF(View): def get(self, request, *args, **kwargs): patientInfo.objects.all() # data.update({'Pregencies':pInfo.Pregencies,'Glucose':Glucose,'BloodPressure':BloodPressure,'SkinThickness':SkinThickness,'Insulin':Insulin,'BMI':BMI,'DiabetesPedigreeFunction':DiabetesPedigreeFunction,'Age':Age,'username':request.user,'result':predict}) pdf = render_to_pdf('accounts/pdf_template.html', data) response = HttpResponse(pdf, content_type='application/pdf') filename = "Invoice_%s.pdf" %("12341231") content = "attachment; filename='%s'" %(filename) response['Content-Disposition'] = content return response -
Run a function in parellel in Django
This is my views.py from django.shortcuts import render, redirect from . import x def index(request): return render(request,'a.html', {}) This is x.py def y() while(True): print("X") y() Currently the while loop takes all resources and blocks Django from serving a.html I need to run Django and x.py simultaneously.They are unrelated.How should do I that? I am stuck on this for 3 days.Plz help -
Handling inclusion tags though a View
So I have this index.html page that renders a sidebar though an inclusion tag, like so: {% extends "dash_base.html" %} {% load core_tags %} {% block title %} Dashboard {% endblock %} {% block links %}{% endblock %} {% block body %} <body id="page-top"> <div id="wrapper"> {% my_sidebar %} [... ... ] </body> /templatetags/core_tags.py. It doesn't make use the context for now, but eventually the sidebar.html template will: import django.template register = django.template.Library() @register.inclusion_tag('projectlibs/sidebar.html', takes_context=True) def my_sidebar(context): return {} So that works well, but ultimately I want to have different sidebars for different user profiles. My thinking is that my_sidebar should be rendered through a view, so that this view can leverage the User model to check permission & other details stored in the profile & display things accordingly. However I don't understand how I am supposed to process the included tag template (e.g. my_sidebar) through a view, since by the time I arrive at the place in the index.html template where I call my_sidebar, I'm already in the render() shortcut: views.py: from django.shortcuts import render from django.views.generic import View class IndexView(View): template_name = 'myapp/index.html' def get(self, request): return render(request, self.template_name) I know I could include that logic within the … -
trying to manipulate data for bar chart in python for test scores
trying to manipulate data for bar chart in python for test scores for the x-axis we have 0--100 % steps of 9 so if a user scores 4 it will be in the step 0 --9 , if another scores 3 it will be counted as 2 persons scored within the step. any help in implementing this will be appreciated. thanks -
sys.path don't locate local dir
thanks for your time. i've been trying to import a models file inside a seeder command. i've tried from ...models import Player, from winners.models import Player added init.py every thing that could be possible right. and keep getting or ModuleNotFoundError: No module named 'winners' or ImportError: attempted relative import with no known parent package although when i print the sys.path the local project ain't there. I've just started working on kali VirtualBox, could it be something wrong with the configuration? Please i'm 2 days stuck in a stupid problem.