Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Pagination on object, in view with multiple items in context-list
I use below code in my view to generate a page, based on a default "layout.html", and include "items.html" which has the object list in it to iterate through and print the items. However, I want to apply Django's pagination functionality, on the item object. How do I go about this? Sorry if this is an easy question; just got into Django from a PHP background. def Items(request): context = { "item": Items.objects.all(), "page": "items.html", } return render(request, 'layout.html', context) -
Django AttributeError: 'Model' object has no attribute 'field'
I'm new to Django and I'm trying to create a simple test project with one Customer model. models.py: from django.db import models class Customer(models.Model): first_name = models.CharField(name='First name', max_length=20) last_name = models.CharField(name='Last name', max_length=20) def __str__(self) -> str: return self.first_name However, when I try to enter this table in the admin console, it throws an error AttributeError: 'Customer' object has no attribute 'first_name'. I've tried to rerun the server, but it doesn't help. If I change the method to something else, then the problem disappears: def __str__(self) -> str: return "1" But I need to have first_name as a basic presentation of my Customer objects. So what did I miss? -
Drag and Drop parts of an image as separate images
I am trying to develop a front-end feature where the user can drag and drop parts of an image (texts detected via Google Vision API for OCR) to different <div>s to categorize detected texts on the image. For example, in the picture below, I want 'Moreno', 'Kaffeepads', '40 pads' etc. to enable dragging and dropping these texts on the original image as separate images to other divs. However, I'm not completely sure how to implement such feature. I am implementing the backend with Django. Any suggestion would be appreciated. -
how to retrieve data from django backend using react
Is there a ReactJS library that allows me to get the data sent by django rest framework backend? views.py @api_view(["GET"]) def some_view_url(request): if request.method == "GET": context = {"token": "someBase64Code"} return Response(context) From the front end, i want to access context and get the value of token I don't like the route of modifying the script tag manually... and i am trying to find something else that what is mentioned in django documentation with the getCookie function or using js-cookie in the front end. -
"local variable 'shipment_booking' referenced before assignment" How can i solved this
**shipment_booking is my table name. ***i want to check my table filed "ord" value is "yes" or not ****if my "ord"field value "yes" then return "pre-budget" page. def bkp1(request): orderv="yes" allorder=shipment_booking.objects.all() return render(request, 'bkp1.html') if request.method=='POST'and 'pbd' in request.POST: for shipment_booking in allorder: o=shipment_booking.ords if orderv==o: return render(request, 'Pre-Budget.html') else: return render(request, 'bkp1.html',{'msg':'Please Add Order Details'}) else: return render(request, 'bkp1.html') -
Why am I getting a 'django.db.utils.ProgrammingError: relation "auth_user" does not exist' when running tests?
Recently I've migrated a Django project from version 1.9.1 to 3.2.7. Now I'm trying to write some new tests, and I'm getting this error: # python manage.py test Creating test database for alias 'default'... Got an error creating the test database: database "test_django" already exists Type 'yes' if you would like to try deleting the test database 'test_django', or 'no' to cancel: yes Destroying old test database for alias 'default'... Traceback (most recent call last): File "/opt/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "auth_user" does not exist I understand this is because currently I don't have any 'migrations' directory, as I cloned the git repo and the DB already existed when the Django project was running in version 1.9.1. I've read: This question. Also this one. Also this. All of them recommend running migrations, but: # python manage.py makemigrations No changes detected # python manage.py makemigrations auth No changes detected in app 'auth' Again, I think this is because the DB schema already existed before upgrading to 3.2. I cannot seem to solve the issue running the migrations approach. Is there another way to solve this issue, or force to generate the migrations even if the DB … -
How to post prepopulated disabled ModelMultipleChoiceField?
I need my ModelMultipleChoiceField to be prepopulated with query parameters from GET-request (/?extending=1&extending2). I know from this question that I can define get_initial() method for my view, returning my request. And everything works fine until I disable the ModelMultipleChoiceField, since I don't need it to be mutable. This is my ModelForm class deduced from this answer: class ExtensionForm(forms.ModelForm): class Meta: model = Record fields = ['extending', 'name', 'description', 'picture', 'content', 'files'] extending = forms.ModelMultipleChoiceField(queryset=Record.objects.all()) def __init__(self, *args, **kwargs): if kwargs.get('instance'): initial = kwargs.setdefault('initial', {}) initial['extending'] = [el.pk for el in kwargs['instance'].extending.all()] forms.ModelForm.__init__(self, *args, **kwargs) self.fields['extending'].disabled = True def save(self, commit=True): instance = forms.ModelForm.save(self, False) old_save_m2m = self.save_m2m def save_m2m(): old_save_m2m() instance.extending.clear() instance.extending.add(*self.cleaned_data['extending']) self.save_m2m = save_m2m if commit: instance.save() self.save_m2m() return instance How do I update this class in order for my request to get there? -
Save progress or actions of user in django?
I have a serious of task which needs to be completed by users when they signup ! How to keep track on this ? For now am checking if data exsist in more than 5 tables (like address, education etc). I think this is not a good way of doing this ! As when ever user logins, i need to check if they have finished all the basic tasks and then allow them to do other things.. On doing research, i have few options: Option1: Create a new model and store all progress on each row and then fetch all the rows to check if required is completed. Option2: Create a new model and store the finished actions in a array, for instace: Class Actions: owner = models.ForeignKey(User, on_delete=models.CASCADE) actions = ArrayField(models.CharField(max_length=128)) And with these, i can append all the finished task one by one, like {emailverification, personal_details,education_details} etc And then use the above to work on the conditions I think the second option is more effective, as it just fetches on row from the table instead of fetching multiple rows ! Or please suggest any new option to track this ! -
Show django filter options according to the logged-in user
I’m new to Django and am trying to show filter options that are only relevant to the user - for example, my app has Message and Automation classes with a many:many relationship, but my filter shows a select option with automations created by other users rather than only those created by the logged-in user. How can I get it to only show those created by the current user? The view: @login_required(login_url='login') @allowed_users(allowed_roles=['admin', 'customer'], own_account_only=True) def message_list(request, pk): account = Account.objects.get(id=pk) messages = account.message_set.all() filter = MessageFilter(request.GET, queryset=messages) messages = filter.qs context = {'account': account, 'messages': messages, 'filter': filter} return render(request, 'messages/message_list.html', context) The filter: class MessageFilter(django_filters.FilterSet): class Meta: model = Message # model we’re building filter for fields = '__all__' exclude = ['account', 'date_created', 'text', 'subject'] The classes: class Message(models.Model): name = models.CharField(max_length=100) subject = models.CharField(max_length=128) text = models.TextField() account = models.ForeignKey(Account, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True, null=True) automations = models.ManyToManyField('automations.Automation', blank=True) def __str__(self): return self.name class Automation(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=200) account = models.ForeignKey(Account, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True, null=True) messages = models.ManyToManyField(Message, blank=True) def __str__(self): return self.name And the HTML: <form method="get" class="filter-form with-ps hide"> {{filter.form.as_p}} <button class="button" type="submit">Search</button> </form> I’m assuming I need to edit the messages … -
Django User reset password, MongoDB to store user information
I am working on Django to reset user password. But all my user information are stored in MongoDB and not the default User table provided. All examples given in StackOverflow and elsewhere use the default User authentication mechanism which is not helping me. I need to generate an email link when user needs to reset password. Forms.py class EmailForPasswdChange(UserCreationForm): username = forms.CharField(max_length = 20, widget=forms.TextInput(attrs={'placeholder': 'Enter your username'}), required=True) password1 = forms.CharField(max_length = 20, widget=forms.TextInput(attrs={'placeholder': 'Enter your username'}), required=False) password2 = forms.CharField(max_length = 20, widget=forms.TextInput(attrs={'placeholder': 'Enter your username'}), required=False) class Meta: model = User fields = [ 'username', ] Views.py def sendEmail(request): if request.method == 'POST': form = EmailForPasswdChange(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.is_active =False current_site = get_current_site(request) username = request.POST.get('username') print(username) subject = 'Your Request for Password Reset' message = "Your Password will be reset" message = render_to_string('email_activation_link.html', { 'username':username, 'domain':current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(username)), 'token': token, }) from_email = settings.EMAIL_HOST_USER recipient_list = (email,) print (recipient_list) send_mail(subject, message, from_email, recipient_list) return render (request, 'user/forgotpasswd.html', {'inform': "EMail sent for resetting Password"}) else: print (form.errors) return render (request, 'user/forgotpasswd.html', {'inform': "EMail Not sent"}) Since I have customized UserCreationForm, on the template rendered, if I enter a username whose password is to be … -
Authenticating requests in Django test client
My API works when I test it using Postman (with the server running). For example: When I test using Django test client, I am able to log in, but not to authenticate a request. For example: headers = {'Authorization': 'Token ' + token} response = client.get('/api/v1/users/auth/user/', **headers) The response object contains: '_container': [b'{"detail":"Authentication credentials were not provided."}'] For some reason, the token ends up in the request, not in headers: 'request': {'Authorization': 'Token 665c371b1b894abba102cdbae8b35b613321791d', What am I missing? -
Reuse context in multiple views
I'm very new to Django and in my application I have a dynamic navbar on top. The context are passed in as context. Imagine it looks like this: <ul> {% for link in links %} <li><a href="{{ link }}"></a></li> {% endif %} </ul> The views may look like this: def nav_links(): # Display links to first 5 MyModel objects objects = MyModel.objects.all()[:5] return [o.get_absolute_url() for o in objects] def index(request): return render("request", "app/index.html", context={"links": nav_links()}) def page1(request) some_data = ... return render("request", "app/page1.html", context={"links": nav_links(), "data": some_data}) def page2(request) return render("request", "app/page2.html", context={"links": nav_links()}) ... Currently, I need to pass in links as context in each of the views. This is obviously bad design. Is there a way to pass in the same context for all views? -
Convert sql code to django orm self table and no foreignkey used
This is a part of sql query which i need to convert to django query using orm. Now the thing is that i don't need to use raw sql django way instead only django orm. As you all can see in the sql query it is left joining self table twice. Their is no foreignkey on self for columns. Model class PurchaseOrders(models.Model): id = models.AutoField(primary_key=True, unique=True) po_no = models.CharField(max_length=255) type = models.CharField(choices=TYPE_CHOICES, max_length=17) franchise = models.ForeignKey( 'franchise.Franchise', on_delete=models.DO_NOTHING, db_column='franchise_id' ) status = models.CharField(choices=STATUS_CHOICES, max_length=15) parent_po_id = models.IntegerField() ref_po_no = models.CharField(max_length=255, blank=True, null=True) is_deleted = models.BooleanField(default=False) class Meta: db_table = 'purchase_orders' Raw Sql Query: SELECT po.`po_no`, po.`type`, f.`gst_no`, po2.`po_no` as 'parent_po_no', po2.`type` as 'parent_po_type', refPo.`type` as 'ref_po_type', refPo.`po_amount` as 'ref_po_amt' INNER JOIN `franchise` f ON f.`franchise_id` = po.`franchise_id` LEFT JOIN `purchase_orders` po2 ON po2.`id` = po.`parent_po_id` LEFT JOIN `purchase_orders` refPo ON refPo.`po_no` = po.`ref_po_no` WHERE po.`id` = ? AND po.`is_deleted`=0 AND po.`status` <> 'rejected' "; -
Session handling with django-rest-framework
I'm building a django-rest-framework application in which a user should only be logged in 1 system at a time, I want the user to be able to login from another device as soon as he closes the site from the 1st device , what approach and Auth type will be appropriate for this task? -
Django allow only a one time form submission and create and save variable
I've various probem with my code: I'd like my user to be able to complete ony one time my form and then when they try to access again the page to receive the success message alert and not the form anymore. How can I achieve this? When the form is submitted I get two successufull alert msg and I'd like to have just one test_date field doesn't appear in my database at all. I'd like to calculate the age and not making the person input that and also to create and save in my databese a code based on the input user, but I'm keeing getting an error so I # that part of the code. Is it possible? Thank you alll! model class UserBio(models.Model): name = models.CharField(max_length=120) birthdate = models.DateField() age = models.CharField(max_length=2) phone = models.CharField(max_length=10) test_date = models.DateField(auto_now_add=True) height = models.CharField(max_length=3) weight = models.CharField(max_length=3) id = models.CharField(max_length=120) form class UserBio(forms.ModelForm): class Meta: model = UserBio fields = (name', 'phone', 'height', 'weight') views def add_bio(request): if request.method == "POST": form = UserBio(request.POST) if form.is_valid(): #age = datetime.now().year - self.birthdate.year #id = self.name + '_' self.height + '/' + self.weight + '_' self.phone form.save() messages.success(request, 'Form submission successful') else: form … -
Accessing host data modified by docker container
I am trying to use docker on my local system for development purposes. I am using Django Framework and with docker, I added some apps. docker exec -it CONTAINER_ID python3 manage.py startapp myapp This adds an app to my host as well. But it is readonly. How can I change the permission to make it executable and writable from my host as well? -
Django: ¿Is it better to load choices field dynamically or to create a Foreign Key model?
I have the case where I want a model to have a lot of choices and right now I dont have that information persisted in my database. This information is the link between the urls and the views related to them in my application. I was trying to override the ModelAdmin to show all of this choices loaded dynamically but surprisingly, for me, I couldn't do that because the model field choices are evaluated just once. That kept me wondering about if it's a good idea to load this choices right in the model dynamically. After that, I read from the django docs that choices are meant to be unvariable data. And this choices, because of it's conceptualization (url and view linked to it) are necessarily going to increase. So, my question is: ¿is there a good way to load the choices of a field in Django or should I just create a ForeignKey for this choices? -
Django unit testing authentication token not accepted
I've checked the DRF official documentation, have read the below posts and copy-pasted code from some answers to avoid any typo, but I still can't authenticate in my unit tests. I always get a 401 response code. I have a custom User model that just has a couple of none required fields so far. Can anyone see any logic issue, or error in the code? Could the issue originate from having a proper local DB and a testing DB and the authentication mixing both up somehow? Checked posts that did not solve the problem: DRF documentation SO post 1 SO post 2 SO post 3 So here's my code. Unit test from django.test.testcases import SimpleTestCase from django.urls import reverse, resolve from rest_framework import status from rest_framework.test import APITestCase from rest_framework.authtoken.models import Token from test_project.models.user import * from test_project.views import UserViewSet # from django.contrib.auth.models import User from test_project.models import * class UserAPIViewTests(APITestCase): def setUp(self) -> None: self.users_list_url = reverse('user-list') self.users_detail_url = reverse('user-detail', args=[1]) self.user =User.objects.create( username="admin", password="admin", email="test@necktie.com", first_name="test first name", last_name="test last name", is_superuser=True, is_staff=True, is_active=True ) self.token = Token.objects.create(user=user) self.client.credentials(HTTP_AUTHORIZATION='Bearer ' + self.token.key) # The testing DB is automatically torn down, no implementation required for those tests def tearDown(self) … -
How to leave Django mode in VS Code
Have been following a Django tutorial and now I would like to 'quit' Django mode in VS Code. Any thoughts on how I could achieve that? See attached for clarification. Thanks! -
Django Admin ModelMultipleChoiceField Form Updation not working
Models.py class CustomUser(models.Model): username = models.CharField(max_length=20) ...<fields>.... firm = models.ForeignKey( 'Firm', null = True, blank = True, on_delete = models.Set_NULL, related_name = 'users' ) class Firm(models.Model): firm_name = models.CharField(max_length=20) .....<fields>..... Forms.py class FirmAdminForm(forms.ModelForm): users = forms.ModelMultipleChoiceField( widget = FilteredSelectMultiple('username', is_stacked=False), queryset=User.objects.exclude(is_staff=True).filter(firm=None), required=False, ) class Meta: model = Firm, fields = [...<other fields>, 'users'] def save(self, commit=True): # Save the provided password in hashed format firm = super().save(commit=False) users = self.cleaned_data['users'] firm.users.set(users) return firm admin.py class FirmAdmin(admin.ModelAdmin): form = FirmAdminform ...other codes ..... def render_change_form(self, request, context, add, change, form_url, obj): users = SalesToolUser.objects.exclude(is_staff=True).filter(partner_firm=None) if obj: partner_agents = obj.users.all() users = User.objects.exclude(is_staff=True).filter(Q(firm=None)|Q(firm=obj)) context['adminform'].form.fields['users'].initial = partner_agents context['adminform'].form.fields['users'].queryset = users return super().render_change_form(request, context, add=add, change=change, form_url=form_url, obj=obj) While I Crete a new firm, where I can add users without any error. But while I'm trying to update the firm, I selected default the users already infirm using initial with field(I am not sure it is a good method), I'm getting this error Select a valid choice. 3 is not one of the available choices . I think that my default selecting method is not good. Answer me if anyone knows working with this. -
How to Add/remove the event source of Full Calendar on checkboxes?
I am trying to add/remove the event sources of full Calendar depending on which checkbox This is my checkbox and calendar. <div class="x_content"> <div class="row"> {% for key,val in mydict.items %} <label class="checkbox-inline" style="margin: 5px;"> <input class="email_id" type="checkbox" id="{{key}}" value = "{{key}}">{{key}} </label> {% endfor %} </div> <div class="clearfix"></div> <br> <div id="calendar"></div> </div> This is my javascript added in html. <script> var eventSourceName = new Array(); var eventSourceData = new Array(); var i = 0; {% for key,val in mydict.items %} eventSourceName[i] = "{{key}}"; eventSourceData[i] = [ {% for dt in val %} { "title": "{{dt.title}}", "start": "{{dt.start}}", "end": "{{dt.end}}", "id": "{{dt.id}}", "color": "{{dt.color}}", }, {% endfor %} ]; i = i+1; {% endfor %} document.addEventListener('DOMContentLoaded', function () { var calendarEl = document.getElementById('calendar'); var currentDate = new Date(); var day = currentDate.getDate(); var month = currentDate.getMonth() + 1; var year = currentDate.getFullYear(); current_date = year + "-" + month + "-" + day; var calendar = new FullCalendar.Calendar(calendarEl, { initialView: 'dayGridMonth', initialDate: currentDate, headerToolbar: { left: 'prev,next today', center: 'title', right: 'dayGridMonth,timeGridWeek,timeGridDay' }, editable: true, slotMinTime: "07:00:00", slotMaxTime: "20:00:00", eventSources:[ ] }); calendar.render(); }); jQuery(function(){ $("input.email_id").click(function(){ $("input.email_id:checked").each(function(){ var temp = $(this).val(); for(let i = 0;i<eventSourceName.length;i++){ if(eventSourceName[i] === temp){ $('#calender').fullCalendar('addEventSource',eventSourceData[i]); } … -
request.data changes in every variable
I have this code: initial_data = dict(request.data.copy()) reserve_data = dict(request.data.copy()) print(initial_data) for key in initial_data.keys(): merchant_data = initial_data.get(key) for sub_key in merchant_data.keys(): if sub_key in keys_to_change: reserve_data[key].pop(sub_key) reserve_data[key][values_to_change.get(sub_key)] = merchant_data.get(sub_key) print(initial_data) As you can see, I am not changing initial_data, but it changes anyway #before {'22': {'domain': 'cashier.random.io', 'salt': 'ewrwerwe', 'active': 1, 'separate_cashier': '', 'additional_hosts': {}, 'tradingroom_url': '', 'crm': {'login': '', 'secret': '', 'url': ''}, 'currencies': ['USD', 'EUR'], 'payment_methods': {'12': {}}, 'processors': {}}} #after {'22': {'salt': 'ewrwerwe', 'separate_cashier': '', 'additional_hosts': {}, 'tradingroom_url': '', 'crm': {'login': '', 'secret': '', 'url': ''}, 'currencies': ['USD', 'EUR'], 'payment_methods': {'12': {}}, 'processors': {}, 'host': None, 'is_active': None}} Is there a way to avoid this? Thanks everybody -
Why celery task can not create record in django postgres database?
I use Django to run a web server and I installed celery and rabbitmq to deal with async tasks. Everything works fine however, celery tasks seem not to be able to create record in database. api/tasks.py from celery import shared_task from .models.event import Event @shared_task def test(): Event.objects.create(name='test') return '' api/views/test.py from api.tasks import test @api_view(['GET']) @authentication_classes([]) @permission_classes([]) def test(request): test.delay(); return Response(status=status.HTTP_200_OK, data='ok') api/celery.py import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.settings') app = Celery('api') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() api/settings.py CELERY_BROKER_URL = 'amqp://localhost' Could you please help me out? Thank you! -
Django forms.select
I'm new with Django. I am creating a form with multiple Select fields. I would like my select to be able to display several fields, for example: ID - Group Name - Description This is my code forms.py `class EssenceForm(forms.ModelForm): readonly_fields = ('created', 'updated', 'created_by', 'updated_by') class Meta: model = essences fields = ['Essence','Classe','IdGroupe'] widgets = { 'Essence': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Saisissez une Essence'}), 'Classe': forms.Select(attrs={'class':'form-select', 'placeholder':'Saisissez une Classe'}), 'IdGroupe': forms.Select(attrs={'class':'form-select', 'placeholder':'Saisissez un Groupe'}), }` In the model.py I have declared the field like this: IdGroupe = models.ForeignKey('essence_groupe', on_delete=models.DO_NOTHING, blank=True, null=True, db_column='IdGroupe',verbose_name='Groupe') The problem is that in my Dropdown List only the "Group" appears. The "ID" and "Description" do not appear. What I'm doing wrong? Thanks -
How to download pdf from huge data in efficient way in django?
How can we download or generate pdf from huge data in Django in an efficient way? I'm having huge records like in millions and I want to generate pdf from data,As of now pdf is generating but it takes time to download, does an one know the efficient way or any alternative way to download pdf in more faster