Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Remove duplicate from the API end point
I have designed a microservices where I'm getting the JSON from the end point and I'm able to display it in the API but I'm getting the repeated data again and again for each id. im getting json data from localhost:8000 and i want to display it with current localhost:7000.I have done some wrong but couldn't able to find where Im going wrong.I'm stuck here views.py class filterlistView(APIView): def get(self, request): filter_list = Userbase.objects.all() # serializer = UserSerializer(filter_list, many=True) # return Response(serializer.data) return Response([self.formatfilter(filter) for filter in filter_list]) def formatfilter(self, post): table_data= requests.get('http://127.0.0.1:1500/api/').json() # return render(request, 'home.html',{'table_data':table_data}) return { 'id':post.id, 'Payment_Term':post.Payment_Term, 'Netdue_Date':post.Netdue_Date, 'Predicted_Paid_days':post.Predicted_Paid_days, 'PBK_Desc':post.PBK_Desc, 'Vendor_Name':post.Vendor_Name, 'Reference':post.Reference, 'company_code':post.company_code, 'Area':post.Area, 'country':post.country, 'table_data':table_data, } output: { "id": 1, "Payment_Term": "demo2", "Netdue_Date": "2021-10-20", "Predicted_Paid_days": "2021-10-20", "PBK_Desc": "sf", "Vendor_Name": "AB", "Reference": "AB", "company_code": "1074", "Area": "GCR", "country": "CEE", "table_data": [ { "id": 1, "stage": "Stage3 Train/Stage4 Test", "region": "NORTH AMERICA", "area": "US", "country": "US", "VendorName": "FOXLINK INTERNATIONAL INC", "PBK_Desc": "Free for payment" }, { "id": 2, "stage": "Stage3 Train/Stage4 Test", "region": "NORTH AMERICA", "area": "US", "country": "US", "VendorName": "FOXLINK INTERNATIONAL INC", "PBK_Desc": "Free for payment" }, ] }, { "id": 2, "Payment_Term": "3434", "Netdue_Date": "2021-10-20", "Predicted_Paid_days": "34", "PBK_Desc": "sfsd", "Vendor_Name": "fdsdf", "Reference": "sdfsd", "company_code": "1154", … -
Deloying Django app Apach2: 403 Forbidden error. Permission denied: mod_wsgi
I am trying to deploy my Django app with my Digital Ocean droplet. There was a very useful YouTube tutorial that I followed; when he adjusted settings in Apache2, and then refreshes, he sees his Django app, whereas when I do the same, I get the following error: Forbidden You don't have permission to access this resource. Apache/2.4.46 (Ubuntu) Server at 159.223.6.157 Port 80 Here you see the setup of my /etc/apache2/sites-available/hbm_project.conf file: <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName www.example.com ServerAdmin webmaster@localhost DocumentRoot /var/www/html # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. #LogLevel info ssl:warn … -
will my postgresql trigger execute even if I set the value from django model at save?
I have created a trigger on each row INSERT/UPDATE to set the created_at and updated_at respectively. Trigger: CREATE OR REPLACE FUNCTION insert_update_function() RETURNS trigger AS $BODY$ BEGIN -- CHECKING OPERATION TYPE AND DECIDE COLUMN IF TG_OP = 'INSERT' THEN NEW.created_at := current_timestamp; ELSE NEW.updated_at := current_timestamp; END IF; RETURN NEW; END; $BODY$ LANGUAGE plpgsql VOLATILE; Apply Trigger only those table where updated_at column exists DO $$ DECLARE t text; BEGIN FOR t IN SELECT table_name FROM information_schema.columns WHERE column_name = 'updated_at' LOOP EXECUTE format('CREATE TRIGGER insert_update_trigger BEFORE INSERT OR UPDATE ON %I FOR EACH ROW EXECUTE PROCEDURE insert_update_function()', t,t); END loop; END; $$ language plpgsql; So when I do INSERT/UPDATE from raw SQL I don't provide these two columns i.e created_at and updated_at, it is automatically trigged and added on my table which is expected and fine but now my query is when I try to INSERT/UPDATE row's of the table through the Django BaseModel where I am setting created_at and updated_at, the trigger will be again called? Django BaseModel with custom save() class AutoCreatedField(models.DateTimeField): """ A DateTimeField that automatically populates itself at object creation. By default, sets editable=False, default=datetime.now. """ def __init__(self, *args, **kwargs): kwargs.setdefault('editable', False) kwargs.setdefault('default', now) super().__init__(*args, … -
Nested annotation in Django View and serializers
I have a use case where I wanted to have data in the below format. { "total_discount_amount": 0, "total_paid": 0, "total_billed": 0, "visits": "string" "users_summary": [ { "id": "string", "date": "string", "total_discount_amount": 0, "total_paid": 0, "total_billed": 0, "visits": "string" } ] } The outer part of the data is the sum of users_summary list data. class Test(generics.ListAPIView): queryset = Model.objects.all() serializer_class = SummarySerializer def list(self, request, *args, **kwargs): data =Model.objects.values('user').annotate(visits=Count('user'),total_discount_amount=Sum('model__amount', total_paid = Sum('model__paid_amnt',total_billed = Sum('model__bill_amnt').filter() return data Here I am not getting the outer values. I tried to implement the serializer in a way that I can get users_summary aggregated data however couldn't achieve it. Any solution to it? -
'NoneType' object has no attribute 'add' (Django nested serializer)
I'm trying to update object but if main_photos_data.get('id', None): MainPhoto.objects.filter(id=main_photos_data.get( 'id')).update(**main_photos_data) else: id = instance.id project = Project.objects.get(id=id) new_main_photo = MainPhoto.objects.create(**main_photos_data) *project.main_photo.add(new_main_photo)* error in this line getting this error: File "/home/askar/work/tasnif-backend/portfolio/serializers.py", line 143, in update project.main_photo.add(new_main_photo) AttributeError: 'NoneType' object has no attribute 'add' I've tried: project.main_photo = new_main_photo But got this error: TypeError at /portfolio/edit-project/1/ Direct assignment to the forward side of a many-to-many set is prohibited. Use photo.set() instead. -
get the user email after deletation django
I was working with the settings.AUTH_USER_MODEL and I want the email of the user to remain( after the user deleted). the user is a foreign key in my model. here is the code class Text(models.Model): title = models.CharField(max_length=45) text = models.TextField() user= models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET(??) ) # TODO : should change( remain email from the deleted user) thanks for your help -
While working with django I am seeing warnings [duplicate]
This is the warning I get when I run and Django commands in the console. WARNING: Ignoring invalid distribution -ip (c:\python310\lib\site-packages) WARNING: Ignoring invalid distribution -ip (c:\python310\lib\site-packages) WARNING: Ignoring invalid distribution -ip (c:\python310\lib\site-packages) WARNING: Ignoring invalid distribution -ip (c:\python310\lib\site-packages) WARNING: Ignoring invalid distribution -ip (c:\python310\lib\site-packages) -
how to remove instruction labels in django-registration-redux registration form
I followed Django-registration-redux start guide and everything works fine but the registration form shows instruction label for username and password which is like in the picture below. I don't want it so how can I remove it? -
Django Search functionality: form returns None
i am trying to build a django search functionality for my app but the input form keeps returning a none views.py def search(request): if request.method == 'POST': query = request.POST.get('text') houses = Product.objects.filter(name__contains='query') context = { 'houses':houses, } return render (request, 'searchresult.html',context ) search.html <form> <input type='text' placeholder='search houses> <button type='submit'>Search</button> </form> -
how to write testcase of not adding a same number in 2 factor auth in django
how to write this testcase in correct way i have tried a lot times but it is failedmany times def test_same_number_add(self): device = self.user.totpdevice_set.create(name='default', key=random_hex()) response = self._post({'phone_setup-current_step': 'setup', 'setup-number': '+918362758326', 'setup-method': 'sms'}) print(response.content) self.assertContains(response, 'Token:',status_code=200) p = PhoneDevice(number="+918770109512", user=self.user) p.save() response = self._post({'token-otp_token': totp(device.bin_key), 'phone_setup-current_step': 'token'}) response = self._post({'phone_setup-current_step': 'setup', 'setup-number': '+918274610917', 'setup-method': 'sms'}) #print(response.status_code) print(response.content) self.assertContains(response, 'Same number cannot be added twice',status_code=200) -
How do you prefill a value in a model form field using __init__ in django?
So basically I want to be able to prefill a Charfield form field with a certain value in the init method. Here is my form: class UpdateForm(forms.ModelForm): #_____________________________________________________________ def __init__(self, *args, **kwargs): super(UpdateForm, self).__init__(*args, **kwargs) self.fields['form_field'].initial = "How are you doing?" self.fields['form_field'].widget = self.fields['form_field'].hidden_widget() #_____________________________________________________________ class Meta: model = form_model fields = ( 'form_field', ) However, I cannot seem to set the value of my form_field with How are you doing?. Morever, I need to be able to change the value in the init method. Does anyone know how I can do this? Thank you, and please send me any questions you have. -
unable to load photos in Django after deploying to heroku
I have made a portfolio + blog website using Django. it works perfectly when running it locally but after I deployed it to Heroku, accessing the portfolio redirected me to a 500 server error. I turned on debug mode and when I did the same, it didn't throw a 500 server error, however, the pictures won't load. this is very confusing and help will be very appreciated... settings.py from pathlib import Path import os from dotenv import load_dotenv load_dotenv() # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.getenv('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'projects', 'blog', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] ROOT_URLCONF = 'personal_portofolio.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ["personal_portofolio/templates/"], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'personal_portofolio.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': … -
Is exact querying of ArrayField possible?
Documentation on ArrayField only has contains. I know you can use __n__iexact on the ArrayField to get an exact match of n position... Apart from chaining a bunch of __n__iexact, is there a better way? More specifically to my use case, I'm using django-filters and I want to be able to exactly search for an object by its slug ArrayField. -
Can i use email verification function and Login With google in one project. (in django)
I try to make a website that have email verification and login with google function, so first i make email verification function, and it work and then i try to make login with google function but when I see in the tutorial, there can only be 1 function, namely choosing a verification email or logging in with google, because the verification email section I made with a custom auth system, while logging in with google in the tutorial uses the default auth system from a package. If you can use both, how? -
Is it possible to add a data to nested just using UUID of it?
I'm quite new to DRF and I trying to build a system with Document and Category. These are models.py for it class TimeStampedModel(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: abstract = True class Document(TimeStampedModel): unique_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) title = models.CharField(max_length=50, blank=True, default="") description = models.TextField(blank=True, default="") image = models.ImageField(blank=True, null=True) category = models.ForeignKey( 'Category', on_delete=models.SET_NULL, related_name='documents', blank=True, null=True, ) class Meta: ordering = ("-created_at",) class Category(TimeStampedModel): unique_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) name = models.CharField(max_length=50, blank=True, default="") description = models.TextField(blank=True, default="") class Meta: ordering = ("-created_at",) def __str__(self): return self.name And Serializes.py class DocumentViewSet(ModelViewSet): serializer_class = DocumentSerializer queryset = Document.objects.all() lookup_field = "unique_id" @action(detail=True, methods=['delete']) def delete_document(self, request, unique_id): """Delete document""" docs = Document.objects.get(unique_id=unique_id) try: docs.delete() return Response(status=status.HTTP_204_NO_CONTENT, data={'message': f'Delete successfully with {docs.unique_id}'}) except: return Response(data={'message': f'Delete failed with {docs.unique_id}'}) class CategoryViewSet(ModelViewSet): serializer_class = CategorySerializer queryset = Category.objects.all() lookup_field = "unique_id" filterset_fields = "__all__" @action(detail=True, methods=['delete']) def delete_category(self, request, unique_id): """Delete category""" cats = Category.objects.get(unique_id=unique_id) try: cats.delete() return Response(status=status.HTTP_204_NO_CONTENT, data={'message': f'Delete successfully with {cats.name}'}) except cats.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND, data={'message': f'Delete failed with {cats.name}'}) What I'm trying to do is update the Category name, description and add the Document to Category using UUID of Document with these JSON … -
How to return a list of available time slots via a forms ValidationError
models.py from django.db import models from django.utils import timezone from django.urls import reverse from django.contrib.auth.models import User class Customer(models.Model): username = models.ForeignKey(User,on_delete=models.CASCADE) name = models.CharField(max_length=20,null=True) def __str__(self): return self.name # Create your models here. class Booking(models.Model): customer_name = models.ForeignKey(Customer,on_delete=models.CASCADE,null=True) username = models.ForeignKey(User,on_delete=models.CASCADE) qty_plts = models.PositiveSmallIntegerField(default=1) cbm = models.PositiveSmallIntegerField(default=1) created_date = models.DateTimeField(default=timezone.now()) delivery_date = models.DateField(null=True) delivery_time = models.TimeField(null=True) booking_number = models.CharField(max_length=50,unique=True) def __str__(self): return self.booking_number def save(self, **kwargs): if not self.booking_number: self.booking_number = f"{self.delivery_date:%Y%m%d}{self.delivery_time:%H%M}" super().save(**kwargs) def get_absolute_url(self): return reverse('bookmyslot:detail',kwargs={'pk':self.pk}) forms.py from django import forms from bookmyslot.models import Booking,Customer from bootstrap_datepicker_plus import DatePickerInput import datetime as dt from django.utils import timezone HOUR_CHOICES = [(dt.time(hour=x), '{:02d}:00'.format(x)) for x in range(7, 13)] class BookingForm(forms.ModelForm): def __init__(self,*args,**kwargs): user = kwargs.pop('username',None) super(BookingForm,self).__init__(*args,**kwargs) self.fields['qty_plts'].label = "Quantity Of Pallets" self.fields['cbm'].label = "Shipment CBM" self.fields['delivery_date'].label = "Delivery Date" self.fields['delivery_time'].label = "Delivery Time" self.fields['customer_name'].label = "Customer Name" self.fields['customer_name'].queryset = Customer.objects.filter(username=user) def clean(self): cleaned_data = super(BookingForm,self).clean() booking_number = f"{cleaned_data.get('delivery_date'):%Y%m%d}{cleaned_data.get('delivery_time'):%H%M}" if Booking.objects.filter(booking_number=booking_number).exists(): raise forms.ValidationError("Requested slot is already booked, please choose another time") class Meta: model = Booking fields = ('customer_name','qty_plts','cbm','delivery_date','delivery_time') widgets = {'delivery_date':DatePickerInput(options={"daysOfWeekDisabled":[0,6],"minDate":timezone.now().date().strftime('%Y-%m-%d')}), 'delivery_time':forms.Select(choices=HOUR_CHOICES)} views.py from django.shortcuts import render # Create your views here. from .models import Booking,Customer from .forms import BookingForm from django.urls import reverse,reverse_lazy from django.contrib import messages from django.contrib.auth.mixins … -
how to create update link in home page...?
views.py class UpdateEvents(UpdateView): model = Event fields = ['event_name','event_date','venue','description'] template_name = 'events/events_update.html' success_url = '/' url.py path('update_events/<pk>/',UpdateEvents.as_view(), name='update-events'), home.html : when i go this "update" link than show me 'The current path, {% url 'update-events' id=events.id % }, didn’t match any of these.' how to i create upadate link in home.py file??? <a class="btn btn-primary" href="{% url 'update-events' id=events.id %}">update</a> [this is error page][1] [1]: https://i.stack.imgur.com/BIhqX.png -
How to block page access to other logged in user in django?
I am trying to block logged in user to access other user update profile page. My situation: Suppose Person A is logged in to his profile and he know other user update profile URl. In this situation he can simple getting access of the update profile url of other user. So , here i want to limit this restriction only to the same logged in user to update their profile only. this is my code for updating profiles: @login_required def UpdateProfile(request, slug): user = Profile.objects.get(slug=slug) if request.method == "POST": form = UpdateProfileForm(request.POST, request.FILES, instance=user) if form.is_valid(): profile_pic = form.cleaned_data['profile_pic'] form.profile_pic = profile_pic form.save() messages.success(request,"Data Updated successfully") return HttpResponseRedirect(reverse('updateaddress', args=(request.user.profile.slug,))) else: messages.error(request, "Please check all fields are valid") return HttpResponseRedirect(request.META.get('HTTP_REFERER')) else: form = UpdateProfileForm(instance=user) context = { 'user':user, 'form':form, } return render(request, "authentication/register/update/profile.html",context) urls.py path("<slug:slug>/update-profile/", UpdateProfile, name="updateprofile"), -
Can django prefetch related work with 3 lookups?
I want to prefetch 3 tables plus the initial table. Here are model examples of the project i am working on class ExampleOne(models.Model): name = models.Charfield() option = models.BooleanField() money = IntegerField() class ExampleTwo(models.Model): word = models.Charfield() example_one = models.ManyToManyField(ExampleOne) number = IntegerField() class ExampleThree(models.Model): number = models.IntegerField() example_two = models.ForeignKey(ExampleTwo) def get_calculation_one(self): Calculate using data from Example_2 and Example_1 class ExampleFour(models.Model): date = models.DateField() example_three = models.ManyToManyField(ExampleThree) def get_calculation_two(self): Calculate using data from method on Example_3 Now I want to know if it is possible to retrieve data from all these models with as little hits to the database as possible because when I try to retrieve data it takes over one minute to retrieve the data and send it to the frontend The calculation might be making many database hits in order to get the data and calculate and i think that is why it is taking more than a minute to retrieve the data my view looks like this qs = ExampleFour.objects.prefetch_related( Prefetch('example_three__example_two__example_one') ).filter(...) Is there a way to use prefetch to make the retrieval faster or is there another suggestion on I can rewrite my code in order to avoid this long retrieval time? Note I … -
How to relate a Django form template to the id of an input html tag
newbie here, this is my problem, i used to have a form looking like this in my website where the ID's of each input helped my to apply a JavaScript code to let users check their password's strength, so as the checkbox to watch or hide the password etc... <input id="psw_1" type="password"> <input id="psw_2" type="password"> Now with Django i just need these two lines: {{ form.password1 }} {{ form.password2 }} If i use those templates inside an input or div tag or whatever, to assign the ID's i i need, it shows some weird outputs in the sign form, is there a way to use those ID's or tell the js script those Django templates are what I'm pointing to? -
How ro redirect user to correct page in django-oscar checkout?
I am trying to follow this implementation of django-oscar cash on delivery but after updating and changing things my checkout flow is getting redirected back and forth to two pages only. I am not sure where i am going wrong. ] -
How to proxy binary files in django
I have a Django service that needs to be a proxy for binary files. For example, the binary files FileA.pdf and FileB.xslx are in http://some-server.con/binaryfiles/. My service have to access this data, and then return that data in a Response. Currently, it works fine if I have a binary file on my own server, for example: file_name = './example.pdf' with open(file_name, mode='rb') as file: return Response( file.read(), headers={'Content-Disposition': 'attachment; filename="{filename}"'.format(filename=file_name)}, content_type=self.get_type(file_name)) But I'm not sure of how get the data from the other server. Can I open an external uri resources as it was a simple file? I will greatly appreciate any help -
Django Rest Framework fails to return a response if response it too large. http code 0
We are building an API on Django and using the Django Rest Framework. This API sits between two servers, so it receives requests from server A, makes requests to server B, formats the response from server B and responds back to server A with the formatted data. The view handler extends the ApiView class from DRF, and the response is a Response object from DRF as well. Here is pseudo code from views.py to put things into perspective: class dummy(APIView) # define auth here def get(request): # handle the request from server A # get the content here, from server B # content is a list of up to 1028 elements response = Response({'status':'success','content':content}, status=200) return response <--- fails here if content length > 200 elements The content is a list of dicts, each dicts contain 4 - 5 key/value pairs, if this list is less than 200 elements long, the response goes through just fine, but anything above 200 elements will result in a response code 0 and no error message explaining what happened, other than a broken pipeerror from server A. We increased the timeout on the request from server A to 30 seconds, just to be sure … -
?: (corsheaders.E014) Origin 'https://domain_name.com/' in CORS_ALLOWED_ORIGINS should not have path
MIDDLEWARE = [ ... "corsheaders.middleware.CorsMiddleware", "django.middleware.common.CommonMiddleware", ] CORS_ALLOWED_ORIGINS = [ "https://domain_name.com", "http://127.0.0.1:8000", ] django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: ?: (corsheaders.E014) Origin 'https://api.krafttopia.com/' in CORS_ALLOWED_ORIGINS should not have path -
Getting Typerror in django but fields appear to be defined correctly
I'm brand new to django and I can't figure out why this is happening. Here is my model which I have added to my settings "Installed Apps" config and I have migrated: class User(models.Model): name = models.CharField(max_length = 200), state = models.CharField In the shell I import the model like so: from homepage.models import User then I try to create a new user like so: a = User(name='Alex', state='Alberta') and it throws this error which makes no sense to me because I've defined the fields of the User schema above: I know I'm missing something like maybe I'm supposed to add something to my views.py file before starting the shell but I just don't know. Any direction appreciated! Thanks! TypeError Traceback (most recent call last) <ipython-input-3-88cc332f436e> in <module> ----> 1 a = User(name='Alex Honing', state='Alberta') /usr/local/anaconda3/envs/pyfinance/lib/python3.9/site-packages/django/db/models/base.py in __init__(self, *args, **kwargs) 501 pass 502 for kwarg in kwargs: --> 503 raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.__name__, kwarg)) 504 super().__init__() 505 post_init.send(sender=cls, instance=self) TypeError: User() got an unexpected keyword argument 'name' In [4]: a = User(name = 'Alex', state ='Alberta')