Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot assign "'4'": "Element.value_code" must be a "Value" instance
I'm trying to save element.value_code, but this error occurs. If I get the value_code on the getlist, my mission will be over. How should I correct this error? I'd really appreciate it if you could let me know. Error: Cannot assign "'4'": "Element.value_code" must be a "Value" instance. models.py There were only models related to Value and Element, but we added all models to help you understand why option_code and designated_code exist. class Option(models.Model): option_code = models.AutoField(primary_key=True) name = models.CharField(max_length=32) product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code') def __str__(self): return self.name class Meta: ordering = ['option_code'] class Value(models.Model): value_code = models.AutoField(primary_key=True) option_code = models.ForeignKey(Option, on_delete=models.CASCADE, db_column='option_code') product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code') name = models.CharField(max_length=32) extra_cost = models.IntegerField() def __str__(self): return self.name class Meta: ordering = ['value_code'] class Designated(models.Model): designated_code = models.AutoField(primary_key=True) product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code') price = models.IntegerField() rep_price = models.BooleanField(default=True) class Meta: ordering = ['designated_code'] def __str__(self): return str(self.designated_code) class Element(models.Model): element_code = models.AutoField(primary_key=True) designated_code = models.ForeignKey(Designated, on_delete=models.CASCADE, db_column='designated_code') value_code = models.ForeignKey(Value, on_delete=models.CASCADE, db_column='value_code', null=True, blank=True) class Meta: ordering = ['element_code'] def __str__(self): return str(self.element_code) views.py if request.method == "POST": form = ElementForm(request.POST) if form.is_valid(): for value_code2 in request.POST.getlist('value_code2'): element = Element() element.designated_code = Designated.objects.get(product_code=id) element.value_code = value_code2 element.save() else: … -
Update django database automatically with schedule
I am working on a Django project to track my daily tasks. I hope my database can automatically create a new record as "unfinished" at midnight each day. How can I implement this feature in Django + React? -
How to render template without extending?
I want to make a template in which i don't want base.html content but when i don't extend base.html template my code doesn't work. So is there any way by which i can make a template without extending base.html file ? -
Count consecutive days of user visit
I am building a BlogApp and I am trying to count user's visited days. Like stackoverflow does. User have visited two consecutive days. When user login in last 24 hours in a day then count that days, AND if user missed a day then days will add from starting. I also tried by adding a decorator :- def W_update_user_login(func): @wraps(func) def wrapper(*args, **kwargs): request = args[0] if request.user.is_authenticated: user=User.objects.get(username=request.user) user.last_login=timezone.now() user.save() return wrapper BUT it shows The view app.views.home didn't return an HttpResponse object. It returned None instead. Then i thought about make a IntegerField in Profile which will count last login which has happened in last 24 hours BUT then i figured that it will count in every time user log in. @receiver(user_logged_in) def sig_user_logged_in(sender,user,request,**kwargs): user.profile.last_login = datetime.now() user.profile.save() I have no idea how can i do it. Any help would be much Appreciated. Thank You in Advance. -
How to change values of select box by another value?
I have three models. class Country(models.Model): title = models.CharField(max_length = 100, null = True) def __str__(self): return self.title class Province(models.Model): title = models.CharField(max_length = 100,null = True) country= models.ForeignKey(Country ,on_delete=models.SET_NULL, null = True,blank=True) def __str__(self): return self.title class Flower(models.Model): name = models.CharField(max_length = 200) country = models.ManyToManyField(Country, null = True,blank=True) provinces = models.ManyToManyField(Province, null = True,blank=True) I have the below admin when i add Flower: I want to show provinces/states of Germany in Provinces when Germany is selected in the Country field. How can i do it? -
django one to many polymorphic (comment model)
how to create a comment model that can be used on two models at once. in this case I want to create a post and video model but only with one comment model. -
how can I filter that elements?
I am a beginner at Django. How can I filter that element in Django? Here is my views.py for teacherhome & commentpost enter image description here enter image description here Here is my models.py for UserComment enter image description here -
django.db.utils.OperationalError: (1292, "Truncated incorrect INTEGER value: 'incompleted'") django
i tried to change a field type from CharField to BooleanField , change this completed = _('completed ') incompleted = _('incompleted ') payment_status = ( (completed,completed), (incompleted,incompleted), ) payment_status = models.CharField(max_length=25,choices=payment_status,default=incompleted) to payment_status = models.BooleanField(default=False) python manage.py makemigrations created the changed in migrations folders but when i tried to migrate it raises this error: django.db.utils.OperationalError: (1292, "Truncated incorrect INTEGER value: 'incompleted'") django django version : 3.2 , db : mysql i also tried remove that field but still raise the same error? i dont want to lose my data into my databse -
Deleted all my migrations including __init.py__
I am a beginner using Django. I have recently been working on a website that has a few different pages. I reference a couple of views from other apps in urls.py. One app I used to take inputs and make some calculations, so it had some forms defined. It was all working fine and I was able to import the views fine, but I changed one of my form field names. This caused some problems because I was storing these values in a database. That made sense to me because I had already saved some data with the previous naming convention and now I had changed it. So, I figured that deleting my database and migrations would allow me to start over and start a new database with my updated fields. I messed up though because I read that I should not have deleted my init.py file in my migrations folder. I have tried re-doing my migrations with makemigrations and migrate but I keep getting an error saying that no changes are made and no new migrations show up in my folder. Also, now when I look in my urls.py file, the imported views and apps are showing up with … -
Django + Daphne app running in only one thread
I configured a Django app in a Vagrant to run with Daphne and Nginx and it works, however, when Django application processes a long-running request, the whole app freezes until request completes. I excepted Daphne to be multithreaded, just as Gunicorn --workers option. But it does not work this way. Here is my /etc/systemd/system/ daphne services: daphne.service: [Unit] Description=daphne daemon Requires=daphne.socket After=network.target [Service] User=www-data Group=www-data WorkingDirectory=/vagrant/app/ ExecStart=/vagrant/app/venv/bin/daphne \ -u /run/daphne/daphne.sock \ --proxy-headers \ app.asgi:application [Install] WantedBy=multi-user.target daphne.socket: [Unit] Description=daphne socket [Socket] ListenStream=/run/daphne/daphne.sock [Install] WantedBy=sockets.target How to make it multithreaded? Or should I switch to Hypercorn? -
Django Select2 order of selected items after drag and drop
If you want to django select2 in with drag and drop then you need to add some JS in your code to save data as you selected in form. you need to first install django-select2 https://pypi.org/project/django-select2/ Models.py from django_select2 import forms as s2forms from django import forms from .models import Achievement, Industries class IndustriesWidget(s2forms.ModelSelect2MultipleWidget): search_fields = [ "name__icontains", ] class SkillsWidget(s2forms.ModelSelect2MultipleWidget): search_fields = [ "name__icontains", ] class AchievementForm(forms.ModelForm): class Meta: model =Achievement fields = ["title", 'skills', 'industries'] widgets = { "skills": SkillsWidget, "industries": IndustriesWidget } def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super(AchievementForm, self).__init__(*args, **kwargs) self.fields['skills'].widget.attrs.update({'class' : 'form-control custom-select select2-selection'}) self.fields['industries'].widget.attrs.update({'class' : 'form-control custom-select select2-selection'}) django form I have created three django model and i am using model into django forms. class IndustriesWidget(s2forms.ModelSelect2MultipleWidget): search_fields = [ "name__icontains", ] class SkillsWidget(s2forms.ModelSelect2MultipleWidget): search_fields = [ "name__icontains", ] class AchievementForm(forms.ModelForm): class Meta: model =Achievement fields = ["title", 'skills', 'industries'] widgets = { "skills": SkillsWidget, "industries": IndustriesWidget } def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super(AchievementForm, self).__init__(*args, **kwargs) self.fields['skills'].widget.attrs.update({'class' : 'form-control custom-select select2-selection'}) self.fields['industries'].widget.attrs.update({'class' : 'form-control custom-select select2-selection'}) JQuery $(document).ready(function () { function convertObjectToSelectOptions(obj) { var htmlTags = ''; for (var tag in obj) { for (const [key, value] of Object.entries(obj[tag])) { … -
How to convert relative path to full URL in Django?
I am trying to make the url shortener app like bit.ly with Django. It works when the {var} leads to absolute URL but I cannot figure out how to redirect links without "http//:www." prefix. So far I tried HttpResponseRedirect(link) and redirect(link) Example: link = "https://www.postgresql.org/docs/current/" => works as expected link = "postgresql.org/docs/current/" => redirects to "http://127.0.0.1:8000/{var}/postgresql.org/docs/current/" How to convert something like this "postgresql.org/docs/current/" to full URL? -
How do I translate this condition from SQL to Django
How does the following SQL query translate into the Django Queryset, assuming 'BP' and 'BS' being the models for the : SELECT SUM(case when BP.ERR in ('0') then 1 else 0 end) SUCCESS FROM BP,BS WHERE BP.TIME> sysdate-(60/1440) #Picking the data updated in the past 1hour AND BP.ID=BS.CODE AND BS.TYPE='3'; I tried this using a while loop along with sum+case+when() which returns no data. -
2 django serializers in 1 generic api view
I can't grasp the logic on how to do what I want. I do have 2 serializers: 1.CreateStudentProfileSerializer and 2.CreateStudentInfoSerializer serializer 1 looks like this: class CreateStudentProfileSerializer(serializers.ModelSerializer): user = CreateStudentUserSerializer(many= False) ... serializer 2: class CreateStudentInfoSerializer(serializers.ModelSerializer): student = serializers.StringRelatedField(many=False) adviser = serializers.StringRelatedField(many=False) profile = serializers.StringRelatedField(many=False) section = serializers.StringRelatedField(many=False) class Meta: Model = Student fields= [ 'id','student', 'period', 'adviser', 'profile', 'section' ] and I have a page that has a form that will take all required data for the 2 serializers, how do I save those 2 serializers at the same time in one view? Or should I do this in another way? -
Accessing dictionary inside Django template
I am customizing my item query result and marking these items as added in the cart based on DB values, i have succeeded in making this dictionary but the issue is how to access its values now inside the template my view menu_items =[] menus = MenuItem.objects.all().order_by('-date_added') for item in menus: print(item.id) menus_added['item']=item if item.id in cartitem: menus_added['is_added']=True else: menus_added['is_added']=False menu_items.append(menus_added) menus_added = {} print(menu_items) restaurants = Restaurants.objects.all() categories= Category.objects.all() return render(request,'store/store.html',context={ 'product':menu_items, <-- i want access this dictionary 'restaurants':restaurants, 'categories':categories }) this approach is not working template {% for item in product.item %} <div class="col-md-4"> <figure class="card card-product-grid"> <div class="img-wrap"> <img src="{{item.image_url}}"> </div> <!-- img-wrap.// --> <figcaption class="info-wrap"> <div class="fix-height"> <a href="{% url 'menus:item' item.id %}" class="title">{{item.item_name}}</a> <div class="price-wrap mt-2"> <span class="price">{{item.price}}</span> <del class="price-old">${{item.price}}</del> </div> <!-- price-wrap.// --> </div> {% if is_added %} <a href="#" class="btn btn-block btn-success">Added ! </a> {% else %} <a href="#" class="btn btn-block btn-primary">Add to cart </a> {% endif %} </figcaption> </figure> </div> <!-- col.// --> {% endfor %} -
Python finding the real availability comparing weekly based opening hour and booking
This is python problem, Let's say Jhon Doe is a tutor, and he has an appointment with student in following dates appointment = [ {'date': '2021-08-02','from_hour': '12:30', 'to_hour': '12:15' }, # monday {'date': '2021-08-04','from_hour': '02:30', 'to_hour': '03:15' }, # Wednesday ] and in the application, he choose his weekly based availability when weekday 1 is monday, 2 tueday, 3 wednesday, and so on available_based_on_weekday = [ { "weekday": 1, 'opening_hour_time': [ # monday {'from_hour': '12:30', 'to_hour': '12:15'}, {'from_hour': '12:30', 'to_hour': '12:15'}, {'from_hour': '12:30', 'to_hour': '12:15'} ] }, { "weekday": 7, 'opening_hour_time': [ # Saturday {'from_hour': '13:30', 'to_hour': '15:15'}, {'from_hour': '15:30', 'to_hour': '16:15'}, {'from_hour': '19:30', 'to_hour': '20:15'}, {'from_hour': '23:30', 'to_hour': '23:45'} ] }, { "weekday": 3, 'opening_hour_time': [ # Wednesday {'from_hour': '02:30', 'to_hour': '03:30'}, {'from_hour': '17:30', 'to_hour': '18:15'}, {'from_hour': '19:30', 'to_hour': '20:15'}, {'from_hour': '21:30', 'to_hour': '22:30'} ] } ] We want to know a tutor actual avaialability. coz, as there is already appointment booked in certain weekday time slot, that is mean the time slot no longer available. I am expecting this output based on month actual_availability = [ { 'date': '2021-08-01', 'available': [] }, { 'date': '2021-08-02', 'available': [ {'from_hour': '12:30', 'to_hour': '12:15'}, {'from_hour': '12:30', 'to_hour': '12:15'} ] }, { … -
how to set a field from another model to another with FK relation django
i've build a hotel management system , for pay methods for example in a booking room from 14-8-2021 to 20-8-2021 the price of rooms will be change depend on how long he/she remains in the hotel class BookingPayment(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) booking = models.ForeignKey(Booking,on_delete=models.CASCADE,related_name='bookings') start_date = models.DateTimeField(default=timezone.now) end_date = models.DateTimeField() price = models.DecimalField(max_digits=20,decimal_places=2) class Booking(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) room_no = models.ForeignKey(Room,on_delete=models.CASCADE,blank=True,related_name='rooms') takes_by = models.ManyToManyField('vistors.Vistor',through='BookingVisitor',related_name='vistors') check_in = models.DateTimeField(default=timezone.now) check_out = models.DateTimeField(blank=True,null=True) payment_status = models.BooleanField(default=False) if payment_status is False then it means the takers should still pay , whenever the takers paid full of the price then it will be True , but because the prices will change depend on how far he/she remains i cant depend on a specific price the change it using django signals is there another way to bring payment_status to BookingPayment Model Form please? class BookingPaymentForm(forms.ModelForm): class Meta: model = BookingPayment fields = ['start_date','end_date','price'] i want to add payment_status to the BookingPaymentForm without adding new field to BookingPayment model ?! is it possible please , then whenever it will be the last time to pay then the admin check it as True ?thank you for helping .. -
I am following a Django REST API tutorial and doing exactly as same a the instructor is doing. However, getting error
ImproperlyConfigured at /watch/stream/ Could not resolve URL for hyperlinked relationship using view name "streamplatform-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. Getting the Error mentioned above while hitting the URL(127.0.0.1:8000/watch/stream/) Models.py from django.db import models class StreamPlatform(models.Model): name = models.CharField(max_length=30) about = models.CharField(max_length=150) website = models.URLField(max_length=100) def __str__(self): return self.name class WatchList(models.Model): title = models.CharField(max_length=50) storyline = models.CharField(max_length=200) platform = models.ForeignKey(StreamPlatform, on_delete=models.CASCADE, related_name="watchlist") active = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title urls.py from django.urls import path, include from watchlist_app.api.views import WatchListAV, WatchDetailAV, StreamPlatformAV, StreamDetailAV urlpatterns = [ path('list/', WatchListAV.as_view(), name='movie-list'), path('<int:pk>/', WatchDetailAV.as_view(), name='movie-details'), path('stream/', StreamPlatformAV.as_view(), name='stream-list'), path('stream/<int:pk>/', StreamDetailAV.as_view(), name='stream-details'), ] views.py from rest_framework.response import Response from rest_framework.views import APIView from rest_framework import status from watchlist_app.models import WatchList, StreamPlatform from watchlist_app.api.serializers import WatchListSerializer, StreamPlatformSerializer class StreamPlatformAV(APIView): def get(self, request): platform = StreamPlatform.objects.all() Serializer = StreamPlatformSerializer(platform, many=True, context={'request': request}) return Response(Serializer.data) def post(self, request): serializer = StreamPlatformSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return Response(serializer.errors) class StreamDetailAV(APIView): def get(self, request, pk): try: platform = StreamPlatform.objects.get(pk=pk) except StreamPlatform.DoesNotExist: return Response({'error': 'Not found'}, status=status.HTTP_404_NOT_FOUND) serializer = StreamPlatformSerializer(platform) return Response(serializer.data) def put(self, request, pk): platform = StreamPlatform.objects.get(pk=pk) serializer = … -
Annotate a queryset with successive values in a dictionary
How can we annotate a queryset with successive values in a dictionary? Something similar to the first object in the queryset will be annotated with the first value in the dictionary and so on... till the end of the queryset -
My form does not save item even from admin panel in django
i create a app name order in it a model name order but when i tried to save some data in that model from the user view it doesn't save it then i tried to save it doesn't even got save from there i don't understand what causing the problem class BuyOrder(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,) address = models.ForeignKey(Address, default= True, on_delete=models.CASCADE ) status = models.IntegerField(choices = status_choices, default=1) method = models.CharField(max_length=50, blank=False,) total_price = models.FloatField(blank=False, default=0) payment_status = models.IntegerField(choices = payment_status_choices, default=3) order_id = models.CharField(unique=True, max_length=200, null=True, default=None) datetime_of_payment = models.DateTimeField(default=timezone.now) # related to razorpay razorpay_order_id = models.CharField(max_length=1000, null=True, blank=True) razorpay_payment_id = models.CharField(max_length=1000, null=True, blank=True) razorpay_signature = models.CharField(max_length=1000, null=True, blank=True) def save(self, *args, **kwargs): if self.order_id is None and self.datetime_of_payment and self.id: self.order_id = self.datetime_of_payment.strftime('COOLBUYORDER%Y%m%dODR') + str(self.id) return super().save(*args, **kwargs) else: pass def __str__(self): return self.user.username + " " + str(self.order_id) + " " + str(self.id) here is the screenshot of admin panel even from their i unable to save any data in that form -
NoReverseMatch at /home/category/doggo/
i am getting an error: Reverse for 'blog' with keyword arguments '{'_id': ''}' not found. 1 pattern(s) tried: ['home/category/(?P<id>[-a-zA-Z0-9]+)/$'] here is my views.py views.py def BlogDetailView(request,_id): try: navbar_list = Navbar.objects.exclude(name='default') category_list = Category.objects.exclude(name='default') dataset = BlogModel.newmanager.all() data = BlogModel.newmanager.get(slug =_id) comments = CommentModel.objects.filter(blog = data, status=True) except BlogModel.DoesNotExist: raise Http404('Data does not exist') if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): Comment = CommentModel(your_name= form.cleaned_data['your_name'], comment = form.cleaned_data['comment'], blog=data) Comment.save() return redirect(f'/home/category/{_id}') else: form = CommentForm() context = { 'data':data, 'form':form, 'comments':comments, 'dataset': dataset, "category_list": category_list, 'navbar_list': navbar_list, } return render(request,'layout/post-details-main.html',context) class CatListView(ListView): template_name = 'layout/category-main.html' context_object_name = 'catlist' def get_queryset(self): content = { 'cat' : self.kwargs['category'], 'posts' : BlogModel.objects.filter(category__name=self.kwargs['category']).filter(status='published') } return content def category_list(request): category_list = Category.objects.exclude(name='default') context = { "category_list": category_list, } return context class Navbar_view(ListView): template_name = 'layout/navbar_show_main.html' context_object_name = 'navbar' def get_queryset(self): content = { 'nav' : self.kwargs['navbar'], 'details' : BlogModel.objects.filter(category__name=self.kwargs['navbar']).filter(status='published') } return content def navbar_list(request): navbar_list = Navbar.objects.exclude(name='default') context = { "navbar_list": navbar_list, } return context i successfully render the CatListView and the category_list and the models of it, before i added the the Navbar_view and navbar_list and register it urls.py path('home/category/<navbar>/', views.Navbar_view.as_view(), name="navbar"), path('home/category/<category>/', views.CatListView.as_view(), name="category"), path('', views.BlogListView, name="blogs"), path('home/search/', views.searchposts, name= "searchposts"), … -
Syntax highlighting in Django using PrimJS
I'm working on a project using Django(3) in which I have blog posts and in these blog posts, I need to highlight code chunks in case we are writing a programming article. So, I decided to use PrismJS library. I have added the required CSS and JS files of the library: <link rel="stylesheet" href="{% static 'css/prism.css' %}" data-noprefix/> <link rel="stylesheet" href="{% static 'css/prism-synthwave84.css' %}"/> <link rel="stylesheet" href="{% static 'css/prism-line-numbers.css' %}"/> <script type="application/javascript" src="{% static 'js/prism.js' %}"></script> <script type="application/javascript" src="{% static 'js/prism-line-numbers.js' %}"></script> Now, inside the admin panel, I have integrated "ckEditor" for writing content. To highlight the code we need to place it inside the <pre><code> tags and add a css class as language-python to highlight python code. The problem is when we add this class and save the blog posts, this class disappears automatically. Don't know why it behaves like this? Sometimes it remains but if we update the blog posts, it disappears automaticly. -
while following a tutorial on youtube I encountered this while correcting the padding using Django. Error: TemplateDoesNotExist at /products/
The tutorial asked me to place the base.html module under the main project 'Pyshop' in templates directory. I have tried the following methods in the settings module of my app but still it doesn't solve my error, please help as I'm a beginner and learning how to code. Thanks import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, -
NLP: How to tell wether a text is talking about which topic
I am a noob in python I was just making a website for studying for children so, I wanted the student to enter their response to a question and then their text response is reviewed and then it checks whether the child has given a response on a particular topic and whether the answer talks about a few key points, so how do I make it and implement it using Django, btw I started web dev a week ago so I am very new to this. Please help me! thank you !! -
How to submit a form in base file in django?
my Views.py def subscribers(request): subscriber_email = request.POST.get('email') isuser = Subscriber.objects.filter(email = subscriber_email) if request.method == "POST": if isuser: Subscriber.objects.filter(is_user = True) subscriber = Subscriber.objects.create( email = subscriber_email ) subscriber.save() messages.success(request , "Thank You for subscribing") return HttpResponseRedirect('index') my base.html file form which <form action="{% url 'subscribers' %}" method="POST"> {% csrf_token %} <div class="form-group row" style="width: 100%"> <div class="col-lg-8 col-md-12"> <input name="email" placeholder="Enter Email" required="" type="email"> </div> <div class="col-lg-4 col-md-12"> <button class="nw-btn primary-btn" type="submit">Subscribe<span class="lnr lnr-arrow-right"></span></button> </div> </div> </form> my models.py class Subscriber(models.Model): email = models.EmailField(max_length=256) is_user = models.BooleanField(default=False) I can't understand what is my path for base file in urls.py file path('' , subscribers , name="subscribers")