Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Add To cart Function with UNIQUE constraint failed
I have an add-to-cart function that throws an error when It is triggered. The function works if a user uses the admin account, but when a user has a normal account, it shows the below error. Views.py @login_required def add_to_cart(request, slug): item = get_object_or_404(Item, slug=slug) order_item, created = OrderItem.objects.get_or_create( item=item, user=request.user, ordered=False, ) order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] # check if the order item is in the order if order.items.filter(item__slug=item.slug).exists(): order_item.quantity += 1 order_item.save() order.save() messages.success(request, "This item was updated to your cart.") else: messages.success(request, "This item was added to your cart.") order.items.add(order_item) order.save() else: ordered_date = timezone.now() order = Order.objects.get_or_create(id=item.id, user=request.user, ordered_date=ordered_date) order.items.add(order_item) order.save() messages.success(request, "This item was added to your cart.") return redirect("product", slug=slug) Models.py class Item(models.Model): title = models.CharField(max_length=100) description = models.TextField() price = models.FloatField() stored = models.DateTimeField(auto_now_add=True) item_quantity = models.IntegerField(default=1) img = models.ImageField(upload_to='images/') category = models.CharField(choices=CATEGORY_CHOICES, max_length=15) slug = models.SlugField(unique=True, default=uuid.uuid1) def __str__(self) -> str: return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Item, self).save(*args, **kwargs) def get_absolute_url(self): return reverse("product", kwargs={"slug": self.slug}) def get_add_to_cart_url(self): return reverse("add-to-cart", kwargs={ 'slug': self.slug }) def get_remove_from_cart_url(self): return reverse("remove_from_cart", kwargs={ 'slug': self.slug }) def get_add_single_item_to_cart_url(self): return reverse("add_single_item_to_cart", kwargs={ 'slug': self.slug }) def get_remove_single_item_from_cart_url(self): return reverse("remove_single_item_from_cart", kwargs={ … -
Database to store values from a python script execution
I have been developing a script that could scan a particular network and detect the devices inside the network. But apparently, I need to stores these values so that I can keep a record of the devices in the network. so can anyone give any suggestions on any simple and quick databases that I can use to store these values and to send them to my Django site on a server? -
Django admin sidebar css broken
I recently moved a Django application from an old environment (created with Django 1.x) to a current Django version (3.1.7). Everything worked well, but the admin interface is somehow garbled. I collected the new admin css etc via collectstatic and placed it in my static path, and it is found and used, but the sidebar css does not work properly. The sidebar uses the whole window, and cannot be minimised, and the list of elements is always displayed below the side bar. What is going wrong here? Is there anything beyond the admin static files I need to change in my Django app? -
DRF APIClient request session
I need to put a token into request.session and then get it from my code request.session.get('id_token') How to do this using drf APIClient()? I have tried this self.client = APIClient() self.client.session['id_token'] = 'some key' but it does not work -
Caching must be implemented at view level, in models or in serializers in Django
I have a web application purely based on REST API using Django Rest Framework. I have seen that at most of the places the response for my APIs is not changing or not changing frequently, so I'm thinking to cache such API's and for that, I'm using https://pypi.org/project/redis/ package. So my question here is what could be the better way to implement caching, it should be at the view level, at the model level, or in the serializer. How it could be done? -
How to implement filters on a ModelViewset such that filters can be implemented for multiple fields with multiple values?
I have a ModelViewset written and I want to filter like the below endpoint. https://example.com/api/v1/blog?status=active,awarded&category=sports,finance I want to implement it using a custom Django RestFramework Filter. -
django form validation error not showing in DetailView
What am i trying to do is show comment form in Detailview. it can add comment, but when user write noting in the form it doesn't show error message. I think i need to return error form somehow, i can not find how this is my code forms.py class CommentForm(forms.ModelForm): comment_text = forms.CharField(max_length=300, error_messages={'required':'need comment!!!'}, ) class Meta: model = Comment fields= ('comment_text',) views.py @login_required def add_comment(request, pk): parent_photo = get_object_or_404(Photo, pk=pk) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.parent_photo = parent_photo comment.user = request.user comment.save() return redirect(parent_photo.get_absolute_url()) else: @@@@@@@@ this part??? @@@@@@@@ return redirect(parent_photo.get_absolute_url(), {'comment_form': form }) return redirect(parent_photo.get_absolute_url()) class PhotoDetailView(DetailView): model = Photo template_name = 'photo_detail.html' def get_context_data(self, *args, **kwargs): context = super().get_context_data() object = self.get_object() total_likes = object.total_likes() context['comment_form'] = CommentForm context['total_likes'] = total_likes return context urls.py urlpatterns = [ path('<int:pk>/', views.PhotoDetailView.as_view(), name = 'detail'), path('<int:pk>/add_comment/', views.add_comment, name='add_comment'), ] templates {% if user.is_authenticated%} <div class=" my-3"> <p class='mb-0 ml-2'>Leave a comment ! </p> <form class="input-group" id='comment_form' method="POST" action="{{ photo.get_absolute_url }}add_comment/"> {% csrf_token %} {% for field in comment_form %} <input type="{{ field.field.widget.input_type }}" class="form-control" id="{{ field.id_for_label }}" name="{{ field.name }}"> {% if field.errors %} <small class='text-danger'>{{ field.errors }}</samll> {% endif %} <div … -
How to set up a react blog page with text and code with syntax highlighting?
I'm creating a blog with react frontend and Django backend. I'm not sure how to store the code snippets and text of the article in the database. If I store it together can I ignore the text when doing syntax highlighting. Or should I store the code snippets seperately from text for syntax highlighting. -
Created Database using SQL Commands, Can we use this or import as models into Django?
I am using Django as a backend and connected it using psycop2 to a PostgreSQL database. I have created all SQL commands and ran them in PostgreSQL to create my database. I realized Django has something called models which you can use to call on data from the database/create database information. However, I have already created it using SQL commands. -> I was wondering if there is anyway to use the PostgreSQL database data from within Django without models, already having added the SQL commands to the db? <- For example <h1>Title: {{ book.price }}</h1> -> This will call on the price column from the book object/entity if a model is created. With the database already created using SQL commands, is there a way to do the same in Django or perhaps a way to migrate the already created database into Django models as an alternative? <- -
How do I create a AbstractUser without username but with email and with @classethod?
I've been trying to create an AbstractUser where I omit the 'username' field and replace it with an email address. But in my 'create_user()' function, it keeps asking for a username. It says: create_user() missing 1 required positional argument: 'username' Here is my code: models.py """ Custom user model to change behaviour of the default user mode, such as validation and required fields. """ username = None email = models.EmailField(_('email address'), unique=True, null=False, blank=False) email_verified = models.BooleanField(default=False) guidelines_accepted = models.BooleanField(default=False) subscription_paid = models.BooleanField(default=False) uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] class Meta: verbose_name = "users" verbose_name_plural = "users" def __str__(self): return self.email @classmethod def create_user(cls, email=None, password=None, email_verified=None, guidelines_accepted=None, subscription_paid=None ): if not guidelines_accepted: raise ValidationError('You must confirm the guidelines.') print('almost a new user') new_user = cls.objects.create_user( email=email, password=password, email_verified=email_verified, guidelines_accepted=guidelines_accepted, subscription_paid=subscription_paid) print('New user') return new_user @classmethod def is_email_taken(cls, email): try: cls.objects.get(email=email) return True except User.DoesNotExist: return False views.py """ The API to register a new user """ parser_classes = (MultiPartParser, FormParser,) serializer_class = RegistrationSerializer def post(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) return self.on_valid_request_data(serializer.validated_data) def on_valid_request_data(self, data): email = data.get('email') password = data.get('password') email_verified = data.get('email_verified') guidelines_accepted = data.get('guidelines_accepted') subscription_paid = data.get('subscription_paid') User = get_user_model() with … -
Update values in model-database using scritps outside Django
I have a model with the fields name, email, login, have_purchased. To avoid mixing the website code and some backend/analysis code, the have_purchased (boolean) value is updated 6 times a day using some scripts on another server, since it takes a lot of time and lot of computation power, that the website should not suffer from. I'm wondering, if updating values in a model database, such as myapp_model here, outside Django e.g using pandas.df.to_sql("myapp_model") can cause some damage? If that is bad idea, what is the best idea when having other scripts running that does not do anything but update the values of the model? -
Is it possible to render multiple components inr react native using a function?
i totally noob to react native, trying to develop an app with it and django as backend for learning purpose, anyway, im trying to fetch data from the rest API and render a list of components passing that data to each of them as props, but things got confuse, i feel like what im doing is totally wrong, can anyone give me a light and point me what am i doing wrong? i print a console.log on terminal and the data is coming to the state, (im using a web json sample just for test) so the problem must be in the mapping process that im trying to use to render the components... here is my code: import React, {Component} from 'react'; import {useState, useEffect} from 'react'; import {Text, View, ScrollView, Image} from 'react-native'; import {Icon} from 'react-native-elements'; import Order from './Order'; import Checkout from './Checkout'; import { TouchableOpacity } from 'react-native-gesture-handler'; const Cart = (props) => { const [state, setState] = useState({data:[]}) useEffect (() => { fetch('https://reactnative.dev/movies.json') .then ( response => response.json() ) .then( responseJason => setState(responseJason)) }) let orderList = () => { state.map(item => { item.movies.map(movie => { return ( <Order product={movie.title}/> ) }) }) } return … -
how to create realtime notification in django without using django channels
For every action such as- log in sign up password reset Notifications should be seen to the user with a notification bell icon (just like Facebook) where real-time notifications are shown according to each action performed. Also, an email should be sent to that user. Note - (YOU CAN USE ANY DJANGO LIBRARY EXCEPT DJANGO CHANNELS) this is the question that I want to solve. please help me. -
'StoryView' object has no attribute 'object'
I am trying to create a comment system with the ability to reply to comments, creating nested comment trees. Create a comment with no parent (not a reply) works fine, but when I attempt to reply to a comment I receive an error: 'StoryView' object has no attribute 'object' views.py class StoryView(DetailView, FormView): model = Story template_name = 'core/story.html' form_class = CommentForm def form_valid(self, form): self.object = self.get_object() # assign the object to the view current_story = Story.objects.get(author__username=self.kwargs['username'], slug=self.kwargs['slug']) form.instance.story = current_story form.instance.author = self.request.user.profile form.save() return super().form_valid(form) models.py class Comment(MPTTModel): story = models.ForeignKey('Story', on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey('Profile', on_delete=models.CASCADE) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') content = models.TextField() created_time = models.DateTimeField(default=timezone.now) status = models.BooleanField(default=True) class MPTTMeta: order_insertion_by = ['-created_time'] forms.py class CommentForm(forms.ModelForm): parent = TreeNodeChoiceField(queryset=Comment.objects.all()) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['parent'].widget.attrs.update( {'class': 'd-none', 'disabled': 'true'}) self.fields['parent'].label = '' self.fields['parent'].required = False class Meta: model = Comment fields = ('content', 'parent',) def save(self, *args, **kwargs): Comment.objects.rebuild() return super(CommentForm, self).save(*args, **kwargs) I think the problem may be with how I am creating the reply system with my HTML/JS. When a user clicks on 'reply' to reply to a comment, I am then obtaining the of that original comment, which … -
I have an error when installing the SpeechRecognition
pip install SpeechRecognition I try to install SpeechRecognition with the command above but i get this message: from http import cookies ImportError: cannot import name 'cookies' from partially initialized module 'http' (most likely due to a circular import) (C:\Users\52644\venv\Lib\site-packages\django\http_init_.py) Can someone help me with this please. -
How to Encrypt data using TripleDES with Python?
I'm integrating API from a third party using TripleDES. They have a code sample with PHP, and I've been trying to do the same with Python but still not working. Below is code in PHP, any help would be really appreciate, thank you so much. class TripleDES { function mencrypt_3des($text, $key) { // echo 'plain text: '.$text; // echo '</br>'.'========='.'</br>'; // echo 'key: '.$key; $text = $this -> pkcs5_pad($text, 8); $size = mcrypt_get_iv_size(MCRYPT_3DES, MCRYPT_MODE_ECB); $iv = mcrypt_create_iv($size, MCRYPT_RAND); $bin = pack('H*', bin2hex($text)); $encrypted = mcrypt_encrypt(MCRYPT_3DES, $key, $bin, MCRYPT_MODE_ECB, $iv); $encrypted = bin2hex($encrypted); // echo '</br>'.'========='.'</br>'; // echo 'encrypted: '.$encrypted; return $encrypted; } function pkcs5_pad($text, $blocksize) { $pad = $blocksize - (strlen($text) % $blocksize); return $text . str_repeat(chr($pad), $pad); } } -
Does Django automatically create indexes?
I'm working on a Django project using Postgresql as an attached database. I've noticed that some queries took a very long time and even found that I had over a dozen indexes on many different fields in my database, some that I've deemed unnecessary. My plan is to remove the ones I do not need but I'm interested to know if Django does this in a "smart" way or there is some default mechanism in place for creating indexes that I am unaware of. -
Cannot Save Form Wizard Output to Database (with conditional logic)
I am unable to save the input from the Forms Wizard to user specific db. The most common error I receive is "UNIQUE constraint failed"; although when I have tried troubleshooting the code using common solutions, I get other error codes. Any help that you can provide would be very greatly appreciated. views.py from django.shortcuts import redirect from formtools.wizard.views import SessionWizardView, WizardView def show_message_form_condition(wizard): # try to get the cleaned data of step 1 cleaned_data = wizard.get_cleaned_data_for_step('0') or {} # check if the first choice was picked. if (str(cleaned_data.get('picked'))=="1"): return cleaned_data.get('picked', True) class ContactWizard(SessionWizardView): def done(self, form_list, **kwargs): for form in form_list: form.save() return render(self.request, 'my_app/index.html', {'form_data': [form.cleaned_data for form in form_list], }) models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class UserProfileInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return self.user.username class UserDat(models.Model): user = models.OneToOneField(User, on_delete=models.PROTECT, null=True) # model fields ch1 = models.CharField(max_length=1, choices=CHOICES) first_name = models.CharField(max_length=128) email = models.EmailField(max_length=254,unique=True) m1 = models.CharField(max_length=250) ch2 = models.CharField(max_length=1, choices=CHOICES2) picked = models.CharField(max_length=250, null=True) message = models.CharField(max_length=250, null=True) def __str__(self): if self.user: return self.user.username return "no user related to this profile" forms.py from django import forms from django.contrib.auth.models import User from my_app.models import UserProfileInfo, UserDat class … -
Django Factory Boy Simple calculation in factory is off
I've got the following factory which basically calculates dynamically the total for an OrderLine based on the generated item price and quantity: class OrderLineFactory(factory.django.DjangoModelFactory): class Meta: model = OrderLine product_id = factory.SubFactory(ProductFactory) price = factory.LazyAttribute(lambda instance: Decimal(instance.product_id.price)) quantity = fake.random_int(min=1, max=10) total = factory.LazyAttribute(lambda instance: Decimal(instance.product_id.price * instance.quantity)) @factory.post_generation def order_total(object, create, extracted, **kwargs): """ Everytime an OrderLine is created the order's total will be updated """ if not create: return print("CALCULATING TOTAL") print("Object TOTAL") print(object.total) order = Order.objects.get(pk=str(object.order_id)) print("ORDER total") print(order.total) order.total = Decimal(order.total + (object.total)) order.save() class OrderFactory(factory.django.DjangoModelFactory): class Meta: model = Order session_id = factory.Faker('uuid4') the result of total in OrderLine is always off by a few decimals. This is the result of a test object: {"id": "661a2b77-5fca-40d9-b34a-ddafee87415c", "session_id": "1742dbd5-e91a-4ef3-8eea-6ec4bd51d567", "subtotal": "0.00", "total": "680.46", "items": [{"product_id": 1, "price": "75.61", "quantity": 9, "total": "680.46"}]} total should be 680.49 but instead is 680.46. In another run: {"id": "10a79436-1bad-4d10-be61-5d87108bca0c", "session_id": "d9649ebd-1f82-424d-b65c-0212641ae987", "subtotal": "0.00", "total": "690.64", "items": [{"product_id": 1, "price": "76.74", "quantity": 9, "total": "690.64"}]} it should be 690.66 but instead I'm getting 690.64. Any idea why? -
Django Postgresql searchquery does not work on incomplete words
I have this piece of code. I am trying to use the postgresql built in full text search feature. It works perfectly fine. But it gets confused around dots and incomplete words. I was wondering if there is a way to fix this. results_list = Model.objects.annotate( search=SearchVector('column1', 'column2') ).filter( (Q(search=SearchQuery(query)) if query else Q()) ) -
How to insert image in password-reset email in Django?
Before we start, I read this question from last year, which had no answers. I have custom HTML email templates set up, one of which is for the password-reset. In all of the emails, I have an image in the HTML. For all of the emails, besides the password-reset email, the image loads. I have tested this by using a known working email and using that as the password-reset HTML email template, but it still does not load the image. The rest of the HTML for the email does load. This is the password-reset email I am trying to use, which does not load the image (or alt text), but loads the rest of the HTML: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1- transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en-US"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> {% load static %} <title>Password Reset</title> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> </head> <body> <p>Hi {{ user.first_name }},</p> <p>A request to reset your password was made through the System. To reset your password, click the link below</p> <ul> <a href="{{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %}">{{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %}</a> </ul> <p>If you did not request to reset your … -
Django how to redirect to certain page
I am using Django's built in auth to login. Every time I input 'http://127.0.0.1:8000/' it is redirected to 'http://127.0.0.1:8000/admin/login/?next=/admin/'. After successfully login I want to redirect to 'http://127.0.0.1:8000/index' again. Here is what I have done: in settings.py LOGIN_REDIRECT_URL = '/index' in urls.py urlpatterns = [path('index', views.index),] It doesn't work. I have tried many ways and I think this setting might be override by the '?next=/admin/' in 'http://127.0.0.1:8000/admin/login/?next=/admin/' So how can I really do it? -
Django Modal for User Login with AJAX doesn't POST sucessfully
Django 3 / AJAX / Jquery I'm trying to set up a login modal when the user clicks on a save button and isn't logged in yet. I'm following pretty much from here Django Modal For User Login/Register - Form Render Issue To set up a login modal on the homepage. My modal loads when it's supposed, and the login form renders. But I'm stuck after getting the POST 200 from the server but not login in. Nothing happens. I don't understand if I need a different URL for the POST. As far as I understand, I'm posting my form on the same home template, from Django default auth, so everything occurs on the 'home' view. But I might be mistaken here. I can login from the default /login/ page, which renders the default /registration/login.html template just fine. So there isn't a problem on the login per se. It must be something on the form posting. views.py: def home(request): wishlisted_list =[] produtos = Produto.objects.all() paginator = Paginator (produtos, 6) page = request.GET.get('page') signup_form = UserCreationForm() login_form = AuthenticationForm() if request.user.is_authenticated: wishlisted_list = list(Wishlist.objects.filter(user_id=request.user).values_list('produto_id',flat=True).order_by('produto_id')) try: produtos = paginator.page(page) except PageNotAnInteger: # If page is not an integer deliver 1st Page produtos … -
Django Field 'fk_a_view' has column name 'fk_a' that is used by another field
I have a these unmanaged django models: class Ticket(models.Model): fk_a = models.ForeignKey('FK_A', db_column='fk_a') fk_a_view = models.ForeignKey('FK_A_View', db_column='fk_a') class Meta: managed = False db_table = 'ticket' class FK_A(models.Model): ... class Meta: managed = False db_table = 'fk_a' class FK_A_View(models.Model): ... class Meta: managed = False db_table = 'view_fk_a' As you can see I have 2 FK point to the same column, and django is complaining I cannot have 2 fields point to the same column. How do I get around this? -
Django change IntegerField to DecimalField on inherited model
In Django I have 2 models that are inherited from an abstract base class. The base class has an IntegerField that I want to rename and change to DecimalField for some instances. There is a ForeignKey linking the 2 child models. I've read about model inheritance in docs, but there seems to be some constraints. What's the best way to change the IntegerField to DecimalField? class Parent(models.Model): intfield = models.IntegerField() class Meta: abstract=True class Child1(Parent): addedfield = models.CharField(max_length=20) class Child2(Parent): addedfield2 = models.DecimalField(max_digits=10, decimal_places=2) linked = models.ForeignKey(Child1, on_delete=models.CASCADE) class GrandChild1(Child1): # change intfield to decimal class GrandChild2(Child2): # change intfield to decimal # linked to GrandChild1 instead of Child1