Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Json characteristics
Tell me please how to add product characteristics via json for each category separately through the admin panel and how to display them in templates. I cannot add certain characteristics like brands. i use postgresql.thanks models.py class Product(models.Model): class Meta: verbose_name = 'Продукт' verbose_name_plural = 'Продукты' order_with_respect_to='slug' category = TreeForeignKey(Category, blank=True, null=True, related_name='category', verbose_name="Выберите категорию",on_delete=models.CASCADE) title = models.CharField(max_length=250,verbose_name='Наименоватние продукта') slug=models.SlugField(unique=True) image1 = models.ImageField(verbose_name='Главное изображение') image2 = models.ImageField(null=True,blank=True, verbose_name='Изображение 2') image3 = models.ImageField(null=True,blank=True, verbose_name='Изображение 3') image4 = models.ImageField(null=True,blank=True, verbose_name='Изображение 4') image5 = models.ImageField(null=True,blank=True, verbose_name='Изображение 5') characteristics = JSONField(blank=True,null=True) available = models.BooleanField(default=True) description = models.TextField(verbose_name='Описание товара',null=True) price = models.DecimalField(max_digits=10,decimal_places=2,verbose_name='Цена') def __str__(self): return self.title def get_model_name(self): return self.__class__.__name__.lower() def get_characteristics(self): res={} characteristics={ f.feature_key: {'feature_name':f.feature_name,'postfix':f.postfix_for_value} for f in ProductFeatures.objects.filter( feature_key__in=self.characteristics.keys() ).prefetch_related('category') } for feature_key,feature_value in self.characteristics.items(): postfix = characteristics[feature_key].get('postfix') if postfix: res[characteristics[feature_key]['feature_name']] = feature_value + ' ' + postfix else: res[characteristics[feature_key]['feature_name']] = feature_value return res def get_absolute_url(self): return reverse('product_detail',kwargs={'slug':self.slug}) def get_feature_value_by_key(self,key): return self.characteristics.get(key) ProductFeatureValidators class ProductFeatureValidators(models.Model): category = models.ForeignKey(Category,verbose_name='Категория',on_delete=models.CASCADE) feature= models.ForeignKey(ProductFeatures, verbose_name='Характеристика',null=True,blank=True,on_delete=models.CASCADE) feature_value= models.CharField(max_length=255,unique=True,null=True,blank=True,verbose_name='Значение хар-ки') def __str__(self): if not self.feature: return f'Валидатор категории "{self.category.name}"- Хар-ка не выбрана' return f'Валидатор категории"{self.category.name} | '\ f'Характеристика - "{self.feature.feature_name}"|'\ f'Значение - "{self.feature_value}"' ProductFeatures characterisrics class ProductFeatures(models.Model): RADIO='radio' CHECKBOX='checkbox' FILTER_TYPE_CHOICES=( (RADIO,'Радиокнопка'), (CHECKBOX,'Чекбокс') ) feature_key = models.CharField(max_length=100,verbose_name='Ключ характеристики') feature_name= models.CharField(max_length=255,verbose_name='Наименование … -
Error been thrown anytime i try to register my model in the admi.py using django
from django.contrib import admin from .models import UserProfile Register your models here. admin.site.register(UserProfile) the code above is in the admin.py file from django.db import models Create your models here. class UserProfile(models.Model): ''' Represents a "user profile" inside our system ''' email = models.EmailField(unique=True, max_length=255) full_name = models.CharField(max_length=255) def __str__(self): return '%s %s' %(self.full_name, self.email) the code above is in my model.py file The error I see anytime I run the files (admin.py and model.py) is this: Traceback (most recent call last): File "C:\Users\ogunw\Documents\Python Scripts\django scripts\health_web_site\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) The above exception (relation "main_userprofile" does not exist LINE 1: SELECT (1) AS "a" FROM "main_userprofile" WHERE "main_userpr... ^ ) was the direct cause of the following exception: File "C:\Users\ogunw\Documents\Python Scripts\django scripts\health_web_site\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\ogunw\Documents\Python Scripts\django scripts\health_web_site\venv\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\ogunw\Documents\Python Scripts\django scripts\health_web_site\venv\lib\site-packages\django\contrib\admin\options.py", line 614, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "C:\Users\ogunw\Documents\Python Scripts\django scripts\health_web_site\venv\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Users\ogunw\Documents\Python Scripts\django scripts\health_web_site\venv\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "C:\Users\ogunw\Documents\Python Scripts\django scripts\health_web_site\venv\lib\site-packages\django\contrib\admin\sites.py", line 233, in inner return view(request, *args, **kwargs) File "C:\Users\ogunw\Documents\Python Scripts\django scripts\health_web_site\venv\lib\site-packages\django\contrib\admin\options.py", line 1653, in … -
Django: How to order a queryset and move some items to end of the queryset
I have a queryset in my Django application: databytes_all = DataByte.objects Each item in the databytes_all queryset has many attributes but one of them is publish_date. I'd like to order the queryset by publish_date, however if publish_date is None, I'd like the item to be at the end of the queryset. This is what I'm trying but it's not working: databytes_all = DataByte.objects Make a queryset: filter out all of the publish dates that are None no_date = databytes_all.filter(publish_date=None) Make anohther queryset: exclude all of the items where publish date is none, then order the remaining items by publish date databytes_with_date = databytes_all.order_by('-publish_date').exclude(publish_date=None) Now combine the two querysets (however this doesnt work- the items with no publish date are first in the list when I want them to be last) databytes = databytes_with_date | no_date -
Hi, I have a bug in making Django models
For no reason, bugs are created in Django models and they are not made. Please help -
How do I try:except between development and production?
I'm just in a bog with this. Figured this should work fine on both development and production (having set the environment variables on both with two different methods, but I'm obv. wrong. It only works on production. On development it throws a long error ending with "django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty." try: SECRET_KEY = os.getenv("PRODUCTION_SECRET_KEY") except: SECRET_KEY = os.environ.get('DEVELOPMENT_SECRET_KEY') -
CSRF token missing or incorrect with AJAX
I have followed this tutorial and defined my form as below: <form action="" id="contactForm" method="post" role="form" class="contact-form"> {% csrf_token %} ... views.py: def contact(request): if request.is_ajax(): sender_name = request.POST.get('sender_name') sender_email = request.POST.get('sender_email') message_subject = request.POST.get('message_subject') message_text = request.POST.get('message_text') html_message = render_to_string('contact.html', {'sender_name': sender_name, 'sender_email': sender_email, 'message_subject': message_subject, 'message_text': message_text}) email_subject = 'Message Subject' email_from = 'My Name' email_to = ['me@mydomain.com',] send_mail(email_subject, '', email_from, email_to, html_message=html_message) response = {} return JsonResponse(response) AJAX code: $('#contactForm').submit(function(e){ e.preventDefault() $('#loading').css("display", "block") $.ajax({ type : "POST", url : "/contact/", data: { sender_name : $('#name').val(), sender_email : $('#email').val(), message_subject : $('#subject').val(), message_text : $('#message').val(), csrfmiddlewaretoken : '{{ csrf_token }}', datatype : "json", }, success: function(){ $('#loading').css("display", "none"), $('#sent-message').css("display", "block") }, }); }); However, I get the annoying "CSRF token missing or incorrect" error after submitting the form. Please assist. -
How to set url in Django?
I'm a newbie in web development and I'm learning to use Django. Unfortunately I have been stuck for more than 24 hours trying to figure out how to set the URL of a web page. I keep getting status 404 error displayed on the browser after running python server. I have checked python documentation and other documentations online but I still don't see anywhere I'm getting it wrong. I have the following files in the main Django follow: urls.py from django.contrib import admin from django.urls import path, include urlspatterns [ path('qbank', include ('qbank.url')), path ('admin/', admin.site.urls), ] settings.py INSTALLED APPS = [ 'qbank' ..... ] In my project folder(which I named qbank) I have the following files: urls.py from django.urls import path from . import views urlspatterns = [ path ('qbank'), views.index, name = 'index' ] view.py from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse ('Hello from Qbank') -
Cant conver sql to django queary (having dont work)
I have next sql: SELECT stock_id, consignment_id, SUM(qty), SUM(cost) FROM warehouse_regсonsignmentproduct Where product_id = '1' Group BY stock_id, consignment_id Having SUM(qty) > 0 So, I used django ORM to create this query: regСonsignmentProduct.objects .filter(product='1') .order_by('period') .values('stock', 'consignment') .annotate(total_qty=Sum('qty'), total_cost=Sum('cost')) .filter(total_qty__gt=0) But my django query return incorrect result. I think, problem in "annotate" Thanks! -
Django deleting records from database
I have a problem. When i delete record django is deleting record with latest id. I don't know why and can't find any solution. I tried to change form action, url from pk to id but it doesn't work . It always delete the lasted recored not choosed one. Thank u for the help models.py class Usterki (models.Model): id = models.AutoField(primary_key=True) dodany_przez = models.ForeignKey('auth.User', on_delete = models.CASCADE, null = True) samolot = models.CharField( max_length=3, choices = SAMOLOTY_CHOICES, default = LFA, ) usterka = models.CharField(max_length = 200, null = True) status = models.CharField( max_length=16, choices=STATUSY_CHOICES, default=UNACCEPTED, ) ograniczenia = models.CharField( max_length=22, choices = OGRANICZENIA_CHOICES, default = ONHOLD, ) data_dodania = models.DateTimeField(auto_now_add = True) aktualizacja = models.DateTimeField(auto_now = True) zdjecie = models.ImageField(upload_to='', null = True) naprawiona = models.BooleanField(default=False) def __str__(self): return self.usterka views.py class UsterkaDelete(DeleteView): #poprawić bo nie działa !!!!! model = Usterki success_url = reverse_lazy('mojeusterki') template_name = 'mojeusterki.html' urls.py urlpatterns = [ path('', views.index, name='index'), path('add',views.add, name='add'), path('usterka_edit/<int:pk>/edit/', views.usterka_edit, name='usterka_edit'), path('<int:pk>/remove/', views.UsterkaDelete.as_view(), name='usterka_remove'), path('mojeusterki', views.mojeusterki, name='mojeusterki'), path('change_password', views.change_password, name='change_password'), path('fuel', views.fuel, name='fuel'),] mojeusterki.html <form action="{% url 'usterka_remove' pk=usterka.pk %}" method="POST"> {% csrf_token %} <button type="submit" class="btn btn-gradient-danger btn-icon-text">Usuń</button> -
I want to Display the image on my template
I created a ImageFields in my Form.py class ProPic(forms.Form): image = forms.ImageField(help_text="Upload Profile Picture: ", required=False) and my views.py is def Profile(request): context = {} context['image'] = ProPic() return render( request, "profile.html", context) my template profile.html {% extends 'base.html' %} {% block content %} <!DOCTYPE html> <html lang="en"> <head> {% load crispy_forms_tags %} <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Profile</title> </head> <style> .align-middle { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } .card { width: auto; } </style> <body> <div class="card align-middle"> <!-- I want to Display the picture here --> <div class="card-body"> </div> <ul class="list-group list-group-flush"> <li class="list-group-item">Username: {{ user.username|title }}</li> <li class="list-group-item">Emai: {{ user.email }}</li> <li class="list-group-item">Vestibulum at eros</li> </ul> <div class="card-body"> <a href="{% url 'logout' %}" class="card-link">Logout</a><br> {{ image }} </div> </div> </body> </html> {% endblock content %} I just can't see my image when i upload it and i dont want to use models if it is possible and i want my image to appear where i put my comment in the code below -
How to use Django with Tornado web sockets?
I am trying to figure out a way to connect Django with Tornado web sockets. There will be a list of products rendered on an html page. As soon as new product is added through django admin panel, the html page will be updated without reload. -
Django: Form Won't Add to Database
I can add to the database from the admin page but the form in template won't save. When I try to submit the form it just refreshes the form. views: def newPost(request): if request.method == 'POST': form = NewPost(request.POST) if form.is_valid(): form.save() return redirect('myposts') else: form = NewPost() return render(request, 'create/new_post.html', {'title_page': 'New Post', 'form': form}) Template: <form method="POST" class="input_group" action="" enctype="multipart/form-data"> {% csrf_token %} {{ form }} <div class="submit_container"> <input class="submit_btn" type="submit" value="Submit"> </div> </form> Form: class NewPost(forms.ModelForm): title = forms.CharField(widget=forms.TextInput(attrs={'class': 'form_input_text'})) product = forms.ChoiceField(widget=forms.Select(attrs={'class': 'form_input_select'}), choices=PRODUCT_CHOICES) caption_description = forms.CharField(max_length=1000, widget=forms.Textarea(attrs={'class': 'form_input_text', 'style':'resize:none;', 'rows': '3'})) full_description = forms.CharField(max_length=2000, widget=forms.Textarea(attrs={'class': 'form_input_text', 'style':'resize:none;'}), required=False) links = forms.CharField(max_length=2000, widget=forms.Textarea(attrs={'class': 'form_input_text', 'style':'resize:none;'}), required=False) release_date = forms.DateField(widget=forms.SelectDateWidget(attrs={'class': 'form_input_select_date'}, years=YEARS, empty_label="---"), required=False) display_image = forms.ImageField(widget=forms.ClearableFileInput(attrs={'class': 'form_img_btn'})) -
Does Lambda API/Django API slows down if called from the same machine?
I have both Django API and Lambda API which just sleeps for 4 seconds. When I execute the API for multiple times, the response time is so slow even though the code only runs for 4 seconds. Is this happening because I'm calling it from the same website? If yes what's the technical reason for API slowness when it's called from the same machine? -
Can we install any module in cloud hosting?
It's my first app with Python and Django and I can't install all these modules in shared web hosting. So I have a query that can I install any module in cloud hosting such as: asgiref==3.2.10 atomicwrites==1.4.0 attrs==19.3.0 colorama==0.4.3 Django==3.1 iniconfig==1.0.1 install==1.3.3 more-itertools==8.4.0 olefile==0.46 packaging==20.4 Pillow==7.2.0 pluggy==0.13.1 psycopg2==2.8.5 psycopg2-binary==2.8.5 py==1.9.0 pyparsing==2.4.7 pytest==6.0.1 pytz==2020.1 six==1.15.0 sqlparse==0.3.1 toml==0.10.1 Please guide me a way to host my Django website... Thank You -
While installing Django i am getting the following things instead of version name
(modelformsave) C:\Users\nikhi\OneDrive\Consultadd training\Django\modelformsave>pip freeze asgiref @ file:///tmp/build/80754af9/asgiref_1605055780383/work certifi==2020.12.5 Django @ file:///tmp/build/80754af9/django_1606860386887/work psycopg2 @ file:///C:/ci/psycopg2_1608147681824/work pytz @ file:///tmp/build/80754af9/pytz_1606604771399/work sqlparse @ file:///tmp/build/80754af9/sqlparse_1602184451250/work wincertstore==0.2 I am getting the following error while trying to see the version Cannot find file file:///tmp/build/80754af9/asgiref_1605055780383/work -
Is it forbidden to use `timezone.now()` in django model helper methods?
I have a Django model that is responsible for storing verification tokens for the user's cell phone verification. The method below is part of that model which later I use in the view functions to restrict users. (They're allowed to ask for a new token every 2 minutes.) however, it doesn't work very well and on some occasions returns true even after hours. finally, I got suspicious about that, is this right to implement such a method in Django models? what about other places I used timezone.now() in the model? for example where I call that to set a field value? def token_is_generated_recently(self): """ Checks whether the verification token is generated during last 2 minutes or not """ return (self.token_created_time > timezone.now() - timedelta(minutes=2)) -
Django FilterSet field lookup dictionary format
I am learning Django, and started creating a web app, and trying to use django_filters with django_tables2, to filter on the columns in the table. What I am tyrying to change is the default 'exact' lookup method, according to the django_filters instructions. This is the example they show at FilterSet Options class UserFilter(django_filters.FilterSet): class Meta: model = User fields = { 'username': ['exact', 'contains'], 'last_login': ['exact', 'year__gt'], } What happens is that if I don't include 'exact' in the list of lookups (like for the shop__shop field below), the field is not rendered on the page. class ReceiptFilter(django_filters.FilterSet): class Meta: model = expenses fields = { 'purchase_date': ['exact'], 'shop__shop': ['iexact'], 'payment_method__payment_method': ['exact'], } Please, click here to see the web page rendered If I leave 'exact' in front of the lookup I want to add (as in the instructions), it doesn't seem to have any effect, the filter works like it was an 'exact' lookup. What am I doing wrong? Thanks, Miki. -
Error filtering a ForeignKey with UUID as pk
I'm using django-filters to filter data and display it in a table. One of the values is a ForeignKey that has as pk an UUID. When I use lookup_expr='icontains' then I get the following error: "Related Field got invalid lookup: icontains" How can I use lookup_expr='icontains' for a ForeignKey with a UUID pk? Thank you in advance. models: class Data(models.Model): data_id = models.UUIDField(primary_key=True, default=uuid.uuid4) data_device_id = models.ForeignKey(Device, models.SET_NULL, blank=True, null=True) class Device(models.Model): device_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=True) device_name = models.CharField(max_length=64) Filter: class DataFilter(django_filters.FilterSet): data_id = django_filters.CharFilter(label='Data id', lookup_expr='icontains') data_device_id = django_filters.CharFilter(label='Device id', lookup_expr='icontains') #ERROR HERE class Meta: model = Data fields = {'data_id','data_device_id'} -
desc="No web processes running" heroku project
I have a Django app which works when I run it locally heroku local. When I push my code to heroku git push heroku main it pushes without any problem, but when I opening my site it showes an 503 error in console 1 GET https://XXX.herokuapp.com/ 503 (Service Unavailable) inside my logs I get this at=error code=H14 desc="No web processes running" method=GET path="/" host=omylibrary.herokuapp.com request_id=lotofnumbers fwd="somenumbers" dyno= connect= service= status=503 bytes= protocol=https from this question I assume that the problem is in ProcFile if more precisely in web. My Procfile looks like this web: gunicorn --chdir ./Lib library.wsgi --log-file - I also tried this heroku ps:scale web=1 from previous answer. What Is wrong here ? -
Group name not showing on production
Im using Wagtail and i want to display the user group name in the admin. On local server everything works fine and the group name is displayed as expected. I tried adding this to the template but none work on production all worked local: {{ user.groups.all }} {{ user.groups.all.0 }} {{ request.user.groups.all }} {{ request.user.groups.all.0 }} -
Use cbv vIews in other place
Hello i wrote a simple login view (for example) like it: class SingInView(LoginView): template_name = 'account/auth/login.html' redirect_authenticated_user = True form_class = LoginForm and i wanna know it possible to use it in another place like: SignUpView.as_view(username="example", password="exampleStrong") there are any way?? -
How can I convert string of datetTime to dateTime
from django.urls import path from Reservations import views urlpatterns = [ path('rent/<takeDate>/<returnDate>/<id>', views.rent, name='rent'), ] def rent(request, takeDate, returnDate,id): print(takeDate) # take date is (Dec. 23, 2020, 8:23 p.m.) , i want to change it to datetime return render(request, 'reservations/rent.html') -
How can we show success message on signup page of verify gmail account in django and bootstrap?
Here i'm able to successfully register account from django but i'm having issue with showing success messages to verify the email account. I am using django and bootstrap. So tell me how to show and style those messages. accounts/views.py class SignUp(CreateView,SuccessMessageMixin): form_class = UserCreateForm template_name = 'accounts/signup.html' def get(self, request, *args, **kwargs): form = self.form_class() return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False # Deactivate account till it is confirmed user.save() current_site = get_current_site(request) subject = 'Activate Your Believer Account' message = render_to_string('accounts/account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) user.email_user(subject, message) success_registered_message = "You're register successfully" verify_message = "Please verify your account from gmail" return success_registered_message,verify_message return render(request, self.template_name, {'form': form}) templates/accounts/signup.html {% if messages %} <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> {% endif %} if more details are require then tell in a comments. I'll update my question with that information. Thank you. -
Is there a way that Users can have options to disable comments on their Blog Post?
I am going through a Django tutorial and I am making a personal blog app , like users can create blogs and comment on it. Question I have built the comment system and Now i think, what if a user don't want to let other users make comments on his/her blog. I mean , Is there a function of code in django ? , that users can decide they want comments on blog post or NOT. I have searched it but i found nothing. So if you know this function then Please tell me. I will really appreciate your Help -
Calculate the sum and multiply with the quantity to get the total in django
I have the code which calculates the sum just fine, now my question is it possible to multiple each price by quantity and then get the total sum after that in a cart on my website. I have tried with all of my logic but i have failed. The idea is to get the price of an item added to cart and multiply it by quantity and then get the total. Here is my cart mode. models.py: #cart model class Cart(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) number_of_items = models.IntegerField(default=0) user = models.ForeignKey(User, on_delete=models.CASCADE) added_datetime = models.DateTimeField(auto_now_add=True) def __str__(self): return self.item.name #Item model class Item(models.Model): CONDITION = ( ('new', 'new'), ('used', 'used'), ('not applicable', 'not applicable'), ) name = models.CharField(max_length=250) owner = models.CharField(max_length=250, default='Ludocs-emark') category = models.ForeignKey(ItemCategories, on_delete=models.CASCADE) sub_category = models.ForeignKey(SubCategory, on_delete=models.CASCADE) tag = models.ForeignKey(Tag, on_delete=models.CASCADE) Condition = models.CharField(max_length=250, null=True, choices=CONDITION) price= models.IntegerField(default=0) number_of_items = models.IntegerField(blank=True) specification_one = models.CharField(max_length=250, blank=True) specification_two = models.CharField(max_length=250, blank=True) specification_three = models.CharField(max_length=250, blank=True) specification_four = models.CharField(max_length=250, blank=True) specification_five = models.CharField(max_length=250, blank=True) specification_six = models.CharField(max_length=250, blank=True) available_colors = models.CharField(max_length=250, blank=True) description = RichTextField() thumbnail = models.ImageField(default='default.png', upload_to='images/') image_one = models.ImageField(upload_to='images/') image_two = models.ImageField(upload_to='images/') image_three = models.ImageField(upload_to='images/') image_four = models.ImageField(upload_to='images/') added_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name views.py file …