Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create interface for web application? [closed]
The question is strange, but can you explain to a beginner how to make a web application in Django correctly? I created a Django project, figured out about where which files to configure, and how to actually make the page? In all video tutorials, people manually write html code and insert css styles from different bootstrap templates. And how to do it humanly? When you write a desktop application for example in PyQt or WPF (Windows Forms) you have an interface editor where you can drag and drop buttons, tables, forms, etc. and then link them to the code on the backend. How do you do this in Django? Is there any adequate web interface editor. I apologize if the question is completely stupid, but I only understand this topic. P.S. I want to make a one-page web application where there will be two TextInput, one button and a google map, where you enter a city, another python script is triggered, which gives the coordinates of the city and it is displayed on the map. What is the best way to do this? -
Can a server process data without client request?
I recently got into Flask web programming and built a shopping website fro scratch as an engineering school project, however I got lost when it came to product ranking etc. I had this idea for a dating website as an exercise but as I see it the server will have to run its own calculations to rank different possible couples in terms of compatibility, which is really the interesting part of the project. I don't really see these ranking calculations only being processed upon request as thay may take some time, but maybe I am highly underestimating SQL processing speed. I believe the data processing and calculations need to be run continuously on the server. If this is in fact continuous server data processing, how would I go about doing that? I hope the question makes sense, my English tends to be a bit dodgy as I don't live in an English-speaking country. Regards -
Using Django-RQ, a model query only works on second run
Using Django-RQ (v2.3.0) querying the (PostgreSQL) database only works when done twice. This is the setup: models.py: class AnalysisResult(models.Model): user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) public_id = models.UUIDField(unique=True, default=uuid.uuid4, editable=False) tasks.py: @job(os.getenv("REDIS_QUEUE_NAME", "default")) def update_progress_in_db(result_id: UUID): # FIXME This query only works on the second try when we run this here inside the rqworker?! try: tmp_record = AnalysisResult.objects.get(public_id=result_id) except (AnalysisResult.DoesNotExist, AnalysisResult.MultipleObjectsReturned) as e: # Always getting the exception here! logger.error("Error retrieving tmp_record with id={}: {}.".format(result_id, e)) except Exception as ex: logger.error("General error while retrieving tmp_record: {}".format(ex)) try: record = AnalysisResult.objects.get(public_id=result_id) logger.debug("result record: {}".format(record)) # Working fine. except (AnalysisResult.DoesNotExist, AnalysisResult.MultipleObjectsReturned) as e: # Never getting this exception. logger.error("Error updating progress status with id={}: {}.".format(result_id, e)) except Exception as ex: logger.error("General error while updating progress status: {}".format(ex)) Running AnalysisResult.objects.get(public_id=result_id) in a django-admin shell always works fine on the first try. And I would very much like to not use the above workaround of trying to query the record twice. It just feels too dirty. Pointers on what might be missing here are appreciated. -
Get value for each model field with _meta
In my model, I have a method for getting verbose_name for each field with _meta. How can I get value for each field similar way with _meta? class Description(models.Model): name = models.OneToOneField(Breeds, on_delete=models.CASCADE, primary_key=True) description = models.TextField() history = models.TextField() nature = models.TextField() care = models.TextField() feed = models.TextField() health = models.TextField() some_facts = models.TextField() def __str__(self): return self.name.breed def get_verbose_name(self): return [field.verbose_name for field in Description._meta.fields] I want to get values similar to the get_verbose_name method. -
Django URL Is One Step Behind
so I am working on a Django project. I have implemented a successful logic in the view and everything is working fine from the frontend to the backend database however the only problem is the URL is one step behind the actual page. For instance this URL http://127.0.0.1:8000/demo/2640066/1 is popping up whereas the page loading is this URL http://127.0.0.1:8000/demo/2640066/2 How can I fix this, please. -
AWS RDS master password resets every 2 days
I am very new at aws services. I recently deployed a django application on elasticbeanstalk with aws rds (postgresql). But the master password resets in every 2 days and I can't seem to find a solution for it. This is the error I receive after 2 days of resetting manually. FATAL: password authentication failed for user "postgres" Any help would be appreciated. -
Task model with EndUser model
I'm trying to create a task with the current user(EndUser), its title and date_created, but I can create the task with only fields=['title'] specification. I'd like to have the user field automatically filled with an EndUser(current user) and a creation date. models.py class EndUser(models.Model): user = models.OneToOneField(User, null=True, blank = True, on_delete=models.CASCADE) name = models.CharField(max_length = 200, null=True) email = models.CharField(max_length = 200, null=True) date_created = models.DateField(auto_now_add = True) def __str__(self): return self.name class Tag(models.Model): CATEGORY = (('My Day', 'My Day'), ('Important', 'Important'), ('Planned', 'Planned'),) name = models.CharField(max_length=200, null=True, choices=CATEGORY) def __str__(self): return self.name class Task(models.Model): user = models.ForeignKey(EndUser, null= True, on_delete = models.SET_NULL) title = models.CharField(max_length = 200) date_created= DateField(auto_now = True) tags = models.ManyToManyField(Tag, blank = True) def __str__(self): return self.title views.py @authenticated_user def mainPage(request): tasks = Task.objects.all() form = TaskForm() if request.method == 'POST': form = TaskForm(request.POST) if form.is_valid(): form.save() return redirect('/') context = {'tasks': tasks[::-1], 'form':form} return render(request, 'tasks/todoList.html', context) forms.py class TaskForm(ModelForm): title = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Add a task' , 'size': '5'})) class Meta: model = Task fields = ['title'] #fields = "__all__" class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username','email','password1','password2'] Tried the code below but this gives error ValueError: Cannot assign "<SimpleLazyObject: <User: … -
Schedule file download in Django
How can I order Django App to check for a file (in the link) every day and download it if some conditions are met. Let' say, in a pseudo-code: every 24h access link if filename differs from the name of the existing file (e.g. previously downloaded) OR there's no such a file download file else skip I'd be glad for the simplest solution. Maybe a tutorial? Thanks ! PS I want it to be implemented into django app, so please do not suggest using cron -
Travis CI - ImportError: cannot import name 'User'
I am trying to deploy my django project to Travis CI, but I keep on getting this error on the Uer model : ImportError: cannot import name 'User' The User object am using is from this class : from django.contrib.auth.models import User But locally on the machine, it works as expected, This is the full logs : File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/django/contrib/auth/base_user.py", line 47, in class AbstractBaseUser(models.Model): File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/django/db/models/base.py", line 107, in new app_config = apps.get_containing_app_config(module) File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/django/apps/registry.py", line 252, in get_containing_app_config self.check_apps_ready() File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/django/apps/registry.py", line 134, in check_apps_ready settings.INSTALLED_APPS File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/django/conf/init.py", line 76, in getattr self._setup(name) File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/django/conf/init.py", line 63, in _setup self._wrapped = Settings(settings_module) File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/django/conf/init.py", line 142, in init mod = importlib.import_module(self.SETTINGS_MODULE) File "/home/travis/virtualenv/python3.6.7/lib/python3.6/importlib/init.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "/home/travis/build/huxaiphaer/huxy_travels_2/huxy_travels_2/settings.py", line 121, in django.setup() File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/django/init.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/django/apps/registry.py", line 122, in populate app_config.ready() File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/django/contrib/admin/apps.py", line 24, in ready self.module.autodiscover() File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/django/contrib/admin/init.py", line 26, in autodiscover autodiscover_modules('admin', register_to=site) File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/django/utils/module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "/home/travis/virtualenv/python3.6.7/lib/python3.6/importlib/init.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/django/contrib/auth/admin.py", line 6, in from django.contrib.auth.forms import ( File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/django/contrib/auth/forms.py", line 10, in from django.contrib.auth.models import User ImportError: cannot import name 'User' … -
How to add css for both lable and input field in django from form.py
I want to create Django form with label and input. i successfully add css class to input field but i don't know how to add css class to its input label form.py from django import forms from .models import TestForm class addForm(forms.ModelForm): class Meta: model = TestForm fields = ('name', 'address', 'mobile') widgets = { 'name': forms.TextInput(attrs={'class': 'form-control'}), 'name.label_tag': forms.TextInput(attrs={'class': 'form-control'}), 'address': forms.Textarea(attrs={'class': 'form-control'}), 'mobile': forms.TextInput(attrs={'class': 'form-control'}) } Model.py from django.db import models # Create your models here. class TestForm(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=200) mobile = models.CharField(max_length=20) addform.html {%extends 'base.html'%} {%block main%} <div class="row clearfix" xmlns="http://www.w3.org/1999/html"> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <div class="card"> <div class="body"> <h2 class="card-inside-title">Floating Label Examples</h2> <div class="row clearfix"> <div class="col-sm-12"> <div class="form-group form-float"> <div class="form-line"> <form method="post"/> {% csrf_token%} {{form.as_p}} </form> </div> </div> </div> </div> </div> </div> </div> </div> {%endblock%} Current Output:- <label for="id_name">Name:</label> <input type="text" name="name" class="form-control" maxlength="50" required id="id_name"> Required Output :- <input type="text" class="form-control"> <label class="form-label">Username</label> Did not get class in label, guys please help me how can i get class in label -
Getting an error for cerbot with docker-compose, nginx, gunicorn and django
I am getting the below error when using certbot with nginx in ubuntu 18.04. Error Details: Attaching to certbot certbot | Saving debug log to /var/log/letsencrypt/letsencrypt.log certbot | Plugins selected: Authenticator webroot, Installer None certbot | Obtaining a new certificate certbot | Performing the following challenges: certbot | http-01 challenge for example.com certbot | http-01 challenge for www.example.com certbot | Using the webroot path /var/www/html for all unmatched domains. certbot | Waiting for verification... certbot | Challenge failed for domain example.com certbot | Challenge failed for domain www.example.com certbot | http-01 challenge for example.com certbot | http-01 challenge for www.example.com certbot | Cleaning up challenges certbot | Some challenges have failed. certbot | IMPORTANT NOTES: certbot | - The following errors were reported by the server: certbot | certbot | Domain: example.com certbot | Type: connection certbot | Detail: Fetching certbot | http://example.com/.well-known/acme-challenge/3xVDLqF-YtEGo99rqnsKGk5wiaP9ct-WtahxOetrCPc: certbot | Connection refused certbot | certbot | Domain: www.example.com certbot | Type: connection certbot | Detail: Fetching certbot | http://www.example.com/.well-known/acme-challenge/zsONhLSTJF18mcGdXpKZ6_3BnKf_uaKg-0DYP2rGLi4: certbot | Connection refused certbot | certbot | To fix these errors, please make sure that your domain name was certbot | entered correctly and the DNS A/AAAA record(s) for that domain certbot | contain(s) the … -
How to execute two things in parallel in django rest_framework?
I am developing a simple view_count. I just want to count the views if the requesting user has not seen the object for a day with its existing user account or ip address. I am using Django and djangorestframework. Here is some sample code for retrieve action. def get_ip_address(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') return ip def create_post_view(post, user, request): print("before sleeping") PostView.objects.create(post=post, user=user, ip_address=get_ip_address(request) ) post.view_count += 1 post.save(update_fields=("view_count", )) print(post) class PostModelViewSet(ModelViewSet): queryset = Post.objects.all() serializer_class = PostSerializer permission_classes = [IsAdminOrReadOnly, ] pagination_class = DefaultLimitOffsetPagination def retrieve(self, request, *args, **kwargs): obj = self.get_object() user = request.user if request.user.id else None vwd = PostView.objects.filter(post=obj.id, user=user, ip_address=get_ip_address(request), viewed_on__startswith=date.today()) if not vwd: create_post_view(obj, user, request) obj.view_count += 1 return Response(PostDetailSerializer(obj).data, status=status.HTTP_200_OK) It is pretty simple. I get the requesting object from database and check if the object is viewed by the the user or the same ip address in a day. If the post object is not viewed I simple need to create PostView instance which means that next view is not going to be counted on viewed day. My question: How can I run it in a way that I will return the … -
Can I dockerize only Django (backend) with React JS (frontend) rendered on same server as Django runs on?
I've developed Django as backend with ReactJS as frontend being served on Django server (127.0.0.1:8000) by putting frontend folder inside backend folder and using static files with path to build/static of frontend in settings.py. So I'm able to run reactjs app on localhost:8000. That's fine. Now question is if it's possible to dockerize only Django backend, which will have everything including frontend contents and run single docker container opening react js app? Or shall I dockerize frontend as well separately? Looking forward to your inputs. Regards Please note that I've also done with both backend and frontend running separately on 2 servers (localhost:8000 and localhost:3000), used docker-compose to build 2 dockerfiles and them talking each other. So my above q is about possibility to dockerize only backend as a single container image which has frontend static files inside. -
How to change select tag options according to another select tag's option in Django admin?
I have this in admin.py class BrandAdmin(admin.ModelAdmin): list_display = ('name','category','date') form = BrandAdminForm class Media: js = ('own.js',) admin.site.register(Brand,BrandAdmin) and models.py class Category(models.Model): name = models.CharField(max_length=100) class Subcategory(models.Model): name = models.CharField(max_length=100) category = models.Foreignkey(Category, on_delete=models.CASCADE) class Brand(models.Model): name = models.CharField(max_length=100) category = models.Foreignkey(Category, on_delete=models.CASCADE) subcategory = models.Foreignkey(Subcategory, on_delete=models.CASCADE) date = models.DateTimeField() so how can I select brands subcategory according to category ? -
GraphQL: [Errno 111] Connection refused
Description I am trying to build an API for a transportation system which has different kind of users (Driver, Customer, SystemAdmin and Authorizer). For this purpose I created an AbstractUser and use inheritance relationship for the all of the above different users. For adding JWT to the model, I have read the official tutorial, but whenever I want to create a new user like the following I faced to the error: mutation { register( email: "new_user@email.com", username: "new_user", password1: "supersecretpassword", password2: "supersecretpassword", ) { success, errors, token, refreshToken } } Steps to Reproduce Here is my model: from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class Usermodel(AbstractUser, models.Model): phone_no = models.CharField( max_length=11, blank=True, verbose_name="Phone Number" ) USERNAME_FIELD = "username" # e.g: "username", "email" EMAIL_FIELD = "email" # e.g: "email", "primary_email" def __str__(self): return self.username class Driver(Usermodel, models.Model): national_id = models.CharField( max_length=10, blank=True, verbose_name="National ID" ) profile_picture = models.ImageField( blank=True, null=True ) STATUS_CHOICES = [ ('1', 'Free'), ('2', 'Busy') ] driver_status = models.CharField( max_length=1, choices=STATUS_CHOICES ) rating = models.FloatField( default=-1 ) ranking = models.IntegerField( default=-1 ) class Meta: verbose_name = 'Driver' verbose_name_plural = 'Drivers' class Authorizer(Usermodel, models.Model): class Meta: verbose_name = 'Authorizer' verbose_name_plural = 'Authorizers' class … -
Django Form Validation Error Displaying Django Debug Page
I have a signup view which takes an email, password, confirm password, and extra string, which must be unique. All of my validation errors return properly (e.g. if an email is duplicated, it displays this must be unique, and if the passwords don't match is displays passwords don't match). However, the extra string displays the django debug page with the validation error, rather than displaying it to the form. Why is this happening? Django debug page error: ValidationError at /signup/ ['Extra string must be unique.'] Excerpt of template: {% for field in form %} <div class="form-group"> {% for error in field.errors %} <p style="color: red">{{ error }}</p> {% endfor %} <label for="{{ field.id_for_label }}">{{ field.label }}:</label> {{ field }} </div> {% endfor %} Form: class UserCreationForm(forms.ModelForm): password1 = forms.CharField(label='Password', widget=forms.PasswordInput(attrs={'class': 'form-control'})) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput(attrs={'class': 'form-control'})) email = forms.CharField(label='Email', widget=forms.EmailInput(attrs={'class': 'form-control'})) extra_string = forms.CharField(label='Extra String (Must be unique)', widget=forms.TextInput(attrs={'class': 'form-control'})) class Meta: model = User fields = ('email',) def clean_password2(self): """A function to check that the two passwords provided by the user match.""" # Check that the two password entries match #: User's password. password1 = self.cleaned_data.get("password1") #: Password confirm. password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 … -
Counting distinct elements in Django ArrayField
I have a model defined by from django.contrib.postgres.fields import ArrayField class Model(models.Model): name = models.CharField(max_length=255) tags = ArrayField(models.CharField(max_length=255)) I would like a way to efficiently grab the count of each distinct element in my tags ArrayField. I put together this piece of code to do try to do that. Model.objects.annotate(elems=Func(F('tags'), function='unnest')).values_list('elems', flat=True).annotate(c=Count('elems')) But it returns an error ...aggregate function calls cannot contain set-returning function calls LINE 1: ...COUNT(unnest("... ^ HINT: You might be able to move the set-returning function into a LATERAL FROM item. Any ideas on how to make this query work? -
Django IntegrityError - NOT NULL constraint failed: f_question.url
this error popped up probably because of models.py file models.py from django.db import models # ---------- Question ---------- class Question(models.Model): ''' Questions ''' author = models.CharField('Author', max_length=45) title = models.CharField('Title', max_length=300) body = models.TextField('Body') date = models.DateTimeField(auto_now_add=True, db_index=True) def __str__(self): return self.title class Meta: verbose_name_plural = 'Questions' verbose_name = 'Question' urls.py from django.urls import path, register_converter from . import views, converter register_converter(converter.HexConverter, 'hex') urlpatterns = [ path('', views.QuestionView, name='f'), path('ask/', views.ask, name='ask'), path('<hex:pk>/', views.QuestionCurrent, name='question_current'), ] why is making websites so hard?aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -
I'm getting an error whe I use json file firebase SDK in django
I adding the firebase json file to use firebase_admin with django. the code I'm using in Django is: import os import firebase_admin from firebase_admin import credentials from firebase_admin import auth BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) cred = credentials.RefreshToken(os.path.join(BASE_DIR, 'firebase-sdk.json')) firebase_admin.initialize_app(cred) and the error I get is: File "/home/eavinti/Documentos/AGMATIS/venv-entrely/entrely/apps/legacy/management/commands/import_auth.py", line 17, in <module> cred = credentials.RefreshToken(os.path.join(BASE_DIR, 'firebase-sdk.json')) File "/home/eavinti/Documentos/AGMATIS/venv-entrely/lib/python3.8/site-packages/firebase_admin/credentials.py", line 193, in __init__ raise ValueError('Invalid refresh token configuration. JSON must contain a ' ValueError: Invalid refresh token configuration. JSON must contain a "type" field set to "authorized_user". I just run it without django and works perfectly: import firebase_admin from firebase_admin import credentials cred = credentials.Certificate("firebase-sdk.json") firebase_admin.initialize_app(cred) I'm not sure what I'm doing wrong in django. -
Getting json decoder error. But I am not able to figure out what the error is?
This is the code in my html in script tags document.getElementById('payment-info').addEventListener('click',function(e){ submitFormData() }) function submitFormData(){ console.log('Payment Button Clicked') var userFormData={ 'name':null, 'email':null, 'total':total, } var shippingInfo={ 'address':null, 'city':null, 'state':null, 'zipcode':null, } shippingInfo.address = form.address.value shippingInfo.city = form.city.value shippingInfo.state = form.state.value shippingInfo.zipcode = form.zipcode.value var url="/process_order/" fetch(url, { method:'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({'form':userFormData,'shipping':shippingInfo}), }) .then((response) => response.json()) .then((data) => { console.log('Success:',data); alert('Transaction Completed') window.location.href="{% url 'index' %}" }) } And this is my views.py def processOrder(request): transaction_id=datetime.datetime.now().timestamp() data = json.loads(request.body) customer=request.user.customer order, created=Order.objects.get_or_create(customer=customer,complete=False) total=float(data['form']['total']) order.transaction_id=transaction_id if total == float(order.get_cart_total): order.complete = True order.save() ShippingAddress.objects.create( customer=customer, order=order, address=data['shipping']['address'], city=data['shipping']['city'], state=data['shipping']['state'], zipcode=data['shipping']['zipcode'], ) It was working fine till i added data=json.loads(request.body) till zipcode.When I added that part of code it starts showing me this error: raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) Without adding that section I was able to print this successfully: print('data:',request.body) but after adding that part of code I am getting this error. I have tried to see what the problem is but its been a day and i am not able to find the problem. Any help would be appriciated,Thanks -
django get different value from ready() in apps.py and view.py
I got different values from view.py and ready(),I'm sure the same code (len(mymodel.objects.values())) in view.py is correct, but it got differnt value in ready() function in apps.py (it missed a lot) in app.py class BuilderAppConfig(AppConfig): name = 'builder_app' def ready(self): from .models import mymodel print(len(mymodel.objects.values()),"here") -
Django Rest Framework showing ValueError:Cannot use QuerySet for "Post": Use a QuerySet for "Account"
I am trying to list and paginate favourite post of users. I got a custom pagination snippet from so, which I am using here, But I am getting this error. ValueError:Cannot use QuerySet for "Post": Use a QuerySet for "Account". I guess, there are problems with my serializer or views. can anyone please help me fix this issue? These are the codes: serializers: class PostSerializer(serializers.ModelSerializer): user = serializers.ReadOnlyField(source='user.username') post_date = serializers.ReadOnlyField() comment_set = CommentSerializer(many=True) class Meta: model = Post fields = ['id','title', 'post_date', 'user', 'image', 'comment_set'] class PostFavouriteListSerializer(serializers.ModelSerializer): favourite = PostSerializer(many=True, read_only=True) class Meta: model = Post fields = ['favourite',] views class CustomPaginator(PageNumberPagination): page_size = 3 def generate_response(self, query_set, serializer_obj, request): try: page_data = self.paginate_queryset(query_set, request) except NotFoundError: return Response({"error": "No results found for the requested page"}, status=status.HTTP_400_BAD_REQUEST) serialized_page = serializer_obj(page_data, many=True) return self.get_paginated_response(serialized_page.data) class FavouritePostAPIView(APIView): authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) def get(self, request): user = self.request.user favourite_posts = Post.objects.filter(favourite=user.post_favourite.all()) paginator = CustomPaginator() response = paginator.generate_response(post, PostFavouriteListSerializer, request) return response -
Django How to Update Quantity for a Variant of an Item
I am trying to fix a bug in my project. When a user goes to the product detail page, the user can select a variant size (Small, medium or Large). Then next goes to the Order Summary page with all the items looped with its variation. If Item 1 with Small and Item 1 with Medium and the quantity for each. In the Order Summary, there is an option to add or remove single items for each, and this is where the bug is. Example (the sequence is important): Added Item 1 to cart with a size Small. Added another Item 1 to cart with size Medium So now in the Order Summary, I have a table with the following Item 1 Size: Small Quantity: 1 Item 1 Size: Medium Quantity: 1 Now if I want to change the quantity of Item 1 Size: Medium, the very first item select is the one which is updated: Item 1 Size: Small Quantity: 2 Item 1 Size: Medium Quantity: 1 The reason behind this is because when add to cart or remove to cart in the template is reflecting the slug of the item not identifying the variation of the selected item … -
Retrieving Dates more than Current Time in From Django Database
I am struggling to understand how the date queries work in Django as I am storing a database with train times. I want to get times that are greater than the current time. The query looks like this, but returns zero results: latestdepartures = LatestDepartures.objects.filter(station=startstation,earliest__gte=timezone.now().astimezone(pytz.utc)) My database has the entry below for example. When I run the query, I get the results below (first line is print(timezone.now().astimezone(pytz.utc)): 2020-08-01 15:49:06.610055+00:00 <QuerySet []> The code which adds the data to the database looks like: def convert_date_time(o): if isinstance(o, datetime): return o.__str__() def updateservices(stationname,destination): now = datetime.now() # dd/mm/YY H:M:S datenow = now.strftime("%d/%m/%Y") board = DARWIN_SESH.get_station_board(stationname) stationdict = dict() stationdict['from'] = stationname stationdict['name'] = board.location_name stationdict['servicelist']=[] services = board.train_services for s in services: traindict = dict() service_details = DARWIN_SESH.get_service_details(s.service_id) traindict['departuretime'] = datetime.strptime(datenow + " " + service_details.std,'%m/%d/%Y %H:%M').astimezone(pytz.utc) traindict['callingpoints'] = [] callingpoints = service_details.subsequent_calling_points for c in callingpoints: if c.crs == destination: callingpointdict = dict() callingpointdict['code'] = c.crs callingpointdict['name'] = c.location_name callingpointdict['arrivaltime'] = datetime.strptime(datenow + " " + c.st,'%m/%d/%Y %H:%M').astimezone(pytz.utc) traindict['callingpoints'].append(callingpointdict) if len(traindict['callingpoints']) > 0: stationdict['servicelist'].append(traindict) #For getting the minimum departure departures = [s['departuretime'] for s in stationdict['servicelist']] #Store the train departure object in the database stationdata = json.dumps(stationdict, default=convert_date_time) LatestDepartures.objects.create( station = … -
dynamic error message in django modelform
I have this in my forms.py file from django import forms from django.utils.translation import gettext as _ from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class CreateUserForm(UserCreationForm): password2 = forms.CharField( label=_("Confirm password"), widget=forms.PasswordInput(attrs={'autocomplete': 'new-password'}), strip=False, help_text=_("Enter the same password as before, for verification."), ) class Meta: model = User fields = ['username','email','first_name','last_name','password1','password2'] error_messages = { 'username': { 'unique': 'user already exist, }, } I wnat to dislpay a dynamic error message when a user register with an existing username. For exmple I my superuser is called 'admin' , if a suer try to rgister with the username 'admin' I want to show him an error message at the end of the form like that: user with the username 'admin' already exist So how can I do that ??