Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Efficient way of dividing a querySet with a filter, while keeping all data?
I have a 'Parts' model, and these parts are either linked to a 'Device' model or not yet. The actual "link" is done via more than just one ForeignKey, i.e. I have to go through 3 or 4 Models all linked between each other with ForeignKeys to finally get the data I want. My question is: What is the most efficient way of getting both the linked and non-linked parts ? Right now, I am getting all parts and simply outputting that, but I would like a little separation: allParts = Parts.object.all() I know I could do something similar to this: allParts = Parts.object.all() linkedParts = allParts.objects.filter(...device_id=id) nonLinkedParts = allParts.objects.exclude(...device_id__in=[o.id for o in linkedParts]) But is that really the most efficient solution ? I feel like there would be a better way, but I have not yet found anything in the docs about it. Just to clarify, there are only linked, and non-linked parts. These are mutually exclusive and exhaustive. Thank you very much -
How to add custom button in django summernote?
I want to add new button in the summernote widget rendered by django-summernote. How can I do it here ? I did this but nothing happening in the widget. <script> var HelloButton = function (context) { var ui = $.summernote.ui; // create button var button = ui.button({ contents: '<i class="fa fa-child"/> Hello', tooltip: 'hello', click: function () { // invoke insertText method with 'hello' on editor module. context.invoke('editor.insertText', 'hello'); } }); return button.render(); // return button as jquery object } $('.summernote').summernote({ toolbar: [ ['mybutton', ['hello']] ], buttons: { hello: HelloButton } }); </script> how can I do this in django summernote ? -
Django Channels ORM Database Query
I don't know what I did wrong I can't get Database Data. class AsyncChatConsumer(AsyncWebsocketConsumer): async def receive(self, text_data): users = await self.get_users() for user in users: print(user.id) @database_sync_to_async def get_users(self): return User.objects.all() django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. The information I checked and the official documents are all written in this way. But why am I getting an error? -
Style and background-image is not working for pdf generator in Django
I am trying to generate an invoice with style and background image. I am using xhtml2pdf library to generate it. I have written all the style in body section. But unfortunately, the original view is not working. I follow this tutorial to generate pdf. Here is my original invoice.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> .backgroundImage { position: absolute; opacity: 20%; top: 15%; left: 10%; } img { height: 80vh; } .logo { height: 70px; width: 70px; object-fit: contain; } .header_text { font-weight: bold; } .text_bg { background-color: #13465cfb; color: white; padding-left: 10px; } .finish { font-weight: bold; font-size: 1.3rem; color: rgba(255, 168, 7, 0.87); } .com_name { font-size: 1.5rem; } .resize { font-size: 0.8rem; } .sign { height: 10px; width: 150px; border-bottom: 1px solid black; } .t_name { font-size: 1.1rem; font-weight: bolder; } /* bootsrap edit */ .container-fluid { width: 100%; padding-right: 15px; padding-left: 15px; margin-right: auto; margin-left: auto; } .p-5 { padding: 3rem !important; } .mb-5, .my-5 { margin-bottom: 3rem !important; } .mt-5, .my-5 { margin-top: 3rem !important; } .mt-4, .my-4 { margin-top: 1.5rem !important; } * { box-sizing: border-box; } body { margin: 0; … -
create django user based on existing model object
I'm working on Property Management django app where my base model is Tenant with all basic info like name, surname, email etc. Willing tenants will be able to create user account so they can log in and book Gym/Cinema, but not all Tenants will need to have user account. My problem is: How can I create new user accounts based on existing Tenant objects? Obviously user will have Tenant ForeignKey but how can I extract Tenant.name, Tenant.surname etc to more than 1 field in my user model? ForeignKey only gives me reference to object but can I somehow access certain fields of that object during creation of new user so I make sure that Tenant.email is the same as user.email? -
Django: Change fields and corresponding form based on a foreign key's field value
I'm writing an app for creating sales quotes. The quote consists of one or more lineitems. Each lineitem consists of a product and some product-specific properties. The user should be able to input the products they want to sell and the properties associated with it at runtime. For example, the user might decide they're selling cars (properties: colour, air conditioning) and tomatoes (properties: weight). When the user creates a lineitem, I want them to choose a product (a car or tomato or any other products they've added) and the properties for that lineitem. For example, they may want to include a red car with air-conditioning, a blue-car without air-conditioning, and a 0.25 kilogram tomato. I've found JSONFields allow one to add multiple properties on the fly. The challenge is accessing those properties from the lineitem. I've set up the models from django.db import models # Create your models here. class Product(models.Model): product_name = models.TextField() specs = models.JSONField() class LineItem(models.Model): product_type = models.ForeignKey(Product, on_delete=models.CASCADE) specs = models.JSONField() and the views to create products or lineitems: class CreateLineItemView(generic.CreateView): model = LineItem fields = ["product_type", "specs"] template_name_suffix = "_create_form" def get_success_url(self): return reverse('poc:index') class CreateProductView(generic.CreateView): model = Product fields = ["product_name", "specs"] template_name_suffix … -
Unable to show more than four complaints on screen at the moment. How do I change the html or css to fit more?
Right now when in my system the user can enter around four complaints or putting it simplay at the most only four complaints show up in a proper order. The fifth complaint shows up in the wrong place like this: What should i change in my css or html so that when someone enters the fifth complaint the middle cntainer increases and a card shows up below the others as well? right now I am using four different css for four cards so that is the problem. How do I change it to fit this functionality? html: <!-- Middle Container --> <div class="col-lg middle middle-complaint-con"> <i class="fas fa-folder-open fa-4x comp-folder-icon"></i> <h1 class="all-comp">My Complaints</h1> <p class="all-comp-txt">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p> {%for c in complaint %} <a href="{% url 'Complaint' c.pk %}" style="color:black;"> <div class="container comp-con-{{forloop.counter0}}"> <p style="color: #D37A19; margin-left: -130px; margin-top: -5px;">Report number:</p> <p class="history-level-1">{{c.reportnumber}}</p> <p class="comp-title-1">{{c.event_type}}</p> <p class="comp-sub-1">{{c.event_text|truncatechars:85}}</p> </div> </a> {%endfor%} </div> css: .middle-complaint-con { position: absolute; width: 1000px; height: 650px; left: 204px; top: 57px; background: #FDF8F4; box-shadow: 4px 4px 20px 1px rgb(0 0 0 / 25%); border-radius: 30px; } .comp-con-0 { display: flex; flex-direction: column; … -
Firebase Admin Send Multicast not getting called or working
I'm working on django project in which i need to send notifications to the users using firebase admin sdk. but when ever i tried to send notification i see no logs for messaging.send_multicast(message). can anyone help me on this? message = messaging.MulticastMessage( data={ 'data': str(self.data) }, tokens=registration_tokens, ) print('message', message) response = messaging.send_multicast(message) print('response', response.success_count, response.failure_count) -
when I post file data, it contains null value
models.py class Image(models.Model): image_file = models.ImageField(blank=True,upload_to=image_saving_product,null=False) product = models.ForeignKey(ProductInfo,on_delete=models.PROTECT,default=None, blank=False) def __str__(self): return f'image id is {self.id} & this image is for {self.product.id},s product' def __unicode__(self): return f'image id is {self.id} & this image is for {self.product.id},s product' serializers.py class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields = '__all__' views.py class ProductImageViewSet(viewsets.ModelViewSet): authentication_classes = [TokenAuthentication] permission_classes = [IsAdminUser] queryset = Image.objects.all() serializer_class = ImageSerializer this is my code, I can send post request when I wanna post Image but it's value is null.. I'll be thankfull if you answer my Question. -
django form is not picking data which is already in database
How do I update my form as the form.instance.users = request.user is not working however if I print request.user on terminal it prints the username of the user currently logged in. Also in this form I want to pick existing data from that user to display in the form to update it. models.py class BasicDetails(models.Model): GENDERS = ( ('M', 'Male'), ('F', 'Female'), ('O', 'Others'), ) users = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=50, null=True, blank=True) last_name = models.CharField(max_length=50, blank=True, null=True) father_name = models.CharField(max_length=50, blank=True, null=True) mother_name = models.CharField(max_length=50, blank=True, null=True) date_of_birth = models.DateField(blank=True, null=True) gender = models.CharField(max_length=1, choices=GENDERS) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(default=timezone.now) def __str__(self): return self.first_name+" "+ self.last_name class Education(BasicDetails): current_year = datetime.date.today().year YEAR_CHOICES = [(r, r) for r in range(2000, datetime.date.today().year+2)] course_name = models.CharField(max_length=100, blank=True, null=True) university_board_name = models.CharField( max_length=200, blank=True, null=True) passing_year = models.IntegerField( choices=YEAR_CHOICES, default=current_year, blank=True, null=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(default=timezone.now) forms.py class BasicDetailsForm(forms.ModelForm): class Meta: model = BasicDetails fields = '__all__' exclude = ['users'] class EducationForm(forms.ModelForm): class Meta: model = Education fields = '__all__' exclude = ['users'] views.py @login_required def View(request): education = EducationForm() education.instance.users = request.user if request.method =="POST": print(request.user.id) education = EducationForm(request.POST,instance=request.user) if education.is_valid(): education.save(commit=True) return HttpResponse("Saved Successfully") else: education = … -
Multiple login possible in Django?
After Hosting the Django website can i login with same user name and password in multiple systems (ex: two or there systems) for that do i need to write any code can any one help me -
Checking token value of request- Django
This is my django test code. I want to look at access_token of request if the proper Bearer token is sent ,but last line makes error. How can I revise the code?? apiClient.credentials(HTTP_AUTHORIZATION='Bearer ' + self.access_token) print(self.access_token) response =apiClient.post('/order/create/',{form_data}) print(response.json()) print(response.user()) -
What do I write in my views.py for it to register a user and redirect it to the new complaint page?
Right now, this is how my dashboard looks: I don't know how to do this but I need that if a user enters his report number in the enter report number field and clicks on register then the page gets redirected to the add new complaint field but the report number field should already be filled out. It should redirect to this: my models.py: class Complaint(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE, null = True, blank=True) id = models.AutoField(blank=False, primary_key=True) reportnumber = models.CharField(max_length=500 ,null = True, blank= False) eventdate = models.DateField(null=True, blank=False) event_type = models.CharField(max_length=300, null=True, blank=True) device_problem = models.CharField(max_length=300, null=True, blank=True) manufacturer = models.CharField(max_length=300, null=True, blank=True) product_code = models.CharField(max_length=300, null=True, blank=True) brand_name = models.CharField(max_length = 300, null=True, blank=True) exemption = models.CharField(max_length=300, null=True, blank=True) patient_problem = models.CharField(max_length=500, null=True, blank=True) event_text = models.TextField(null=True, blank= True) document = models.FileField(upload_to='static/documents', blank=True, null=True) def __str__(self): return self.reportnumber forms.py: class DateInput(forms.DateInput): input_type = 'date' class ComplaintForm(ModelForm): class Meta: model = Complaint fields = '__all__' widgets = { 'reportnumber': forms.TextInput(attrs={'placeholder': 'Report number'}), 'event_type': forms.TextInput(attrs={'placeholder': 'Event type'}), 'eventdate': DateInput(), 'device_problem': forms.TextInput(attrs={'placeholder': 'Device Problem'}), 'event_text': forms.Textarea(attrs={'style': 'height: 130px;width:760px'}), 'manufacturer': forms.TextInput(attrs={'placeholder': 'Enter Manufacturer Name'}), 'product_code': forms.TextInput(attrs={'placeholder': 'Enter Product Code'}), 'brand_name': forms.TextInput(attrs={'placeholder': 'Enter Brand Name'}), 'exemption': forms.TextInput(attrs={'placeholder': 'Enter Exemption'}), 'patient_problem': forms.TextInput(attrs={'placeholder': … -
Django Heroku how to go back to development server to make more changes
So I just deployed my Django app to Heroku, and everything is working fine. The current version of the app isn't perfect, so I want to edit it, but my current process is: 1. **make changes in files 2. git status (just to make sure changes are seen) 3. git add -A 4. git commit -m "message" 5. git push heroku master How can I get back the whole python manage.py runserver development part so I can be more thorough with my changes, and only commit when I know the changes meet my expectations? Since I'm new to Python/HTML/CSS, I'm always coding then testing to see what my code does, and it would involve a lot of git commit / git push currently. Any help is appreciated! -
How to create an admin mixin for common/abstract model in Django
I am creating a multi tenant app and have the following abstract class that all relevant tenant specific models inherit from: class TenantAwareModel(models.Model): tenant = models.ForeignKey(Tenant, on_delete=models.CASCADE) class Meta: abstract = True When registering models in the Django admin, I want to keep my code DRY and not have to add 'tenant' to every single search_fields, list_display, list_filter etc so I tried creating a super class to inherit from. class TenantAwareAdmin(admin.ModelAdmin): class Meta: abstract = True # change_form_template = "admin/professional_enquiry_change_form.html" search_fields = ('tenant__id', 'tenant__name', 'tenant__domain',) list_display = ('tenant',) list_filter = ('tenant',) And then trying to inherit that in the registration of the other models. E.g. class UserAdmin(TenantAwareAdmin, admin.ModelAdmin ): ... This approach matches the way the TenantAwareModel works. class TenantAwareModel(models.Model): tenant = models.ForeignKey(Tenant, on_delete=models.CASCADE) class Meta: abstract = True class User(AbstractUser, Uuidable, Timestampable, TenantAwareModel): ... and it is of course giving me: django.core.exceptions.ImproperlyConfigured: The model TenantAwareModel is abstract, so it cannot be registered with admin. Does anybody know the proper way to do this to avoid all the duplicated code? -
How to write a urls.py in django so that I can do something like */page
Here is the problem: I have an app with the following models: project, position, outreach A position is connected to a project and project only with a Foreign key An outreach is connected to a position and a position only with a Foreign key I can create a new project from almost anywhere in my app (same for the other objects). Currently I wrote that a new project is created from the url dashboard/newjobproject but I would to make it so that depending on the page that I am, the url simply becomes something like www.myapp.com/..../newproject What's a way to write the urls.py to achieve that? from django.urls import path from action import views app_name = 'action' urlpatterns = [ # ex: /action/ path('', views.login, name='login'), path('dashboard/', views.dashboard, name='dashboard'), path('contacts/', views.contacts, name='contacts'), path('projects/', views.project, name='project'), path('contacts/newcontact', views.new_contact, name='new_contact'), path('projects/newjobproject', views.new_outreach, name='new_outreach'), path('dashboard/newjobproject', views.new_jobproject, name='new_jobproject'), path('projects/<uuid>/newjobposition', views.new_jobposition, name='new_jobposition'), ] However, -
Could not import 'rest_framework_simplejwt.auth.JWTAuthentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'
I am trying to make REST APIs using Django. I have installed djangorestframework & djangorestframework-simplejwt using pip pip install djangorestframework pip install djangorestframework-simplejwt Whenever I import anything from rest_framework, It gives me this error ImportError: Could not import 'rest_framework_simplejwt.auth.JWTAuthentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'. ModuleNotFoundError: No module named 'rest_framework_simplejwt.auth' Requirement.txt file: djangorestframework==3.12.4 djangorestframework-simplejwt==4.7.2 Setting.py file: INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", 'rest_framework', 'rest_framework_simplejwt', 'rest_framework_simplejwt.token_blacklist', "config", "response", "utils", "authentication", ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.auth.JWTAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ] } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(days=1), 'REFRESH_TOKEN_LIFETIME': timedelta(days=5), } -
Django can't identify the user after registering an account *AnonymousUser*
So the goal is for a new user to register an account and then get redirected to the home page and recognized. So that the user does not have to register for their account then go through the process of logging in right after. I want a standard registration, like Instagram, Twitter, and other professional applications. So far, I'm where the user can register and redirect them to the homepage, but when I try to print their name on the screen, I get AnonymousUser. The user's information is written to the database after registering, but Django doesn't know who the user is. For Django to know who is logged in after registering, they have to log out and then log in right after registering their account. If anyone could help, I would be much appreciated it. Views.py from django.shortcuts import render, redirect from .forms import RegisterForm from django.contrib import messages def register(response): if response.method == "POST": form = RegisterForm(response.POST) if form.is_valid(): form.save() return redirect("/") else: form = RegisterForm() return render(response, "register/register.html", {"form": form}) -
how to get latest second row in django?
can anyone help me I'm new to django so I don't know how to make sql queries into django code. my sql table is : select * from mangazones.mangabank_comic_banks; sql table image (below image) then for second row query : WITH added_row_number AS (SELECT comic_chapter,comic_english_name_id, row_number() OVER(PARTITION BY comic_english_name_id ORDER BY comic_chapter DESC) AS row_num FROM mangazones.mangabank_comic_banks) SELECT * FROM added_row_number WHERE row_num = 2; I get table (below image) : seond row table I want second row table query in django also. Can anyone please help me? -
Images not showing in PDF generated by WeazyPrint in a Django Project
I have a question related to generating PDF in a Django Project using Weazy Print So the first thing I have done is that I made sure that the PDF is showing correctly as per the CSS file I have included in the function below in the views.py: def admin_order_pdf(request, info_id): info = get_object_or_404(Info, id=info_id) html = render_to_string('businessplan/pdf.html', {'info': info}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="order_{}.pdf"'.format( Info.id) weasyprint.HTML(string=html,base_url=request.build_absolute_uri()).write_pdf(response, stylesheets=[weasyprint.CSS(settings.STATICFILES_DIRS[0] + '\css\\report.css')], presentational_hints=True) return response Second I have included the {% load static %} in the report.css and I am trying to access the image file using the below: @page :first { background: url('{% static "img/report-cover.jpg" %}') no-repeat center; background-size: cover; margin: 0; } I have reviewed the following questions and their answers but they didn't help achieving my goal to show the image: PDF output using Weasyprint not showing images (Django) attach img file in pdf weasyprint My trials: I was able to get the image showing by adding @page :first in the html page between <style></style> but my issue is that there are other things that I need to link also like fonts and svgs so I wanted to know what I am doing wrong that doesn't allow the … -
Django Simple Captcha Can't change Validation Error?
I want change validation error for Captcha input after the wrong value is entered, default value error is 'Invalid CAPTCHA' how can I change it ? from django import forms from captcha.fields import CaptchaField from django.contrib.auth import get_user_model User = get_user_model() class LoginForm(forms.Form): username = forms.CharField( widget=forms.TextInput(attrs={"class": "form-control", "id": "input-email"}) ) password = forms.CharField( widget=forms.PasswordInput(attrs={"class": "form-control", "id": "input-password"}) ) captcha = CaptchaField(required=False, label='') Error text image -
Im getting a 500 Server error when i try submitting with Django app
I deployed my django app to my cpanel and it is live, but when i go to submit a post with the form I created it gives me a 500 server error. I think it has to do with my static files and the thumbnail. enter image description here can someone tell me how are the static urls supposed to be formatted since it is live now? -
How to store a value in database using user's input in Django?
class User(models.Model): GENDER = [ ('0', 'Male'), ('1', 'Female'), ] DEGREE = [ ('0', 'High School or below'), ('1', 'Associate or Bachelor'), ('2', 'Master or PhD'), ] name = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) gender = models.CharField(max_length = 1, choices = GENDER, null=True) age = model.IntegerField(null=True) degree = models.CharField(max_length = 1, choices = DEGREE, null=True) Assuming I have a formula that calculate credit scores based on this input, for example, 2.03884 * ln(age) + 12.8938 * ln(degree) + 9.9 * (ln(degree)^2). Now, I am just curious about where, how and what should I do so that whenever I look up at the User, I can obtain his/her/their score? Thank you very much for spending your time to help me since I am extremely new to Django. -
How to add, view, sort data from models or db on GMT week number basis
Please guide me im new to django i want to display and add data on week number basis For ex GMT week starts on Sunday and ends Saturday so only current week data should be shown but should be able to retrieve past weeks data as wel kind Select Week [2021-30] 30th week of year 2021 So how to write the login to display datas stored in db fetching creation date or updation date -
Django Rest Framework django_filters return empty list
I'm trying to filter my queryset on Datefield based on year and month. After searching a lot I found this answer and tried to use it. but when I use filter I got and empty list. model.py: class Sample(models.Model): name = models.CharField(max_length=50) date = models.DateField(auto_now=False, auto_now_add=False) serializer.py: class SampleSerializer(serializers.ModelSerializer): class Meta: model = Sample fields = '__all__' filter.py: import django_filters # only for showing I use django_fliter not drf defult filter from .models import Sample class SampleDateFilter(django_filters.FilterSet): month = django_filters.NumberFilter("date", lookup_expr='month') year = django_filters.NumberFilter('date',lookup_expr='year') class Meta: models=Sample fields = ['month','year'] views.py: class SampleListview(generics.ListAPIView): serializer_class = SampleSerializer queryset = Sample.objects.all() filter_backends = (DjangoFilterBackend,) filterset_class = SampleFilter I have an object in my database with this config: { "id": 1, "name": "test", "date": "2020-05-03", #date format %YYYY-%MM-%DD } without filter I got my list but I got nothing when I use queryparam: http://127.0.0.1:8000/sample/?year=2020 http://127.0.0.1:8000/sample/?month=05 or any combination of both filters. I'm using: django-filter==2.4.0 djangorestframework==3.12.4 Django==3.0.8 How can I fix this? Thanks