Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reverse for 'cart_add' not found. 'cart_add' is not a valid view function or pattern name
I wanted to use django-shopping-cart 0.1 , but I got this error: urls.py from django.urls import path from . import views app_name='shop' urlpatterns = [ path('',views.accueil, name='home'), path('cart/add/<int:id>/', views.cart_add, name='cart_add'), path('cart/item_clear/<int:id>/', views.item_clear, name='item_clear'), path('cart/item_increment/<int:id>/', views.item_increment, name='item_increment'), path('cart/item_decrement/<int:id>/', views.item_decrement, name='item_decrement'), path('cart/cart_clear/', views.cart_clear, name='cart_clear'), path('cart/cart-detail/',views.cart_detail,name='cart_detail'), ] views.py from django.shortcuts import render, redirect from testshop.models import Product from cart.cart import Cart def cart_add(request, id): cart = Cart(request) product = Product.objects.get(id=id) cart.add(product=product) return redirect("home") def item_clear(request, id): cart = Cart(request) product = Product.objects.get(id=id) cart.remove(product) return redirect("cart_detail") def item_increment(request, id): cart = Cart(request) product = Product.objects.get(id=id) cart.add(product=product) return redirect("cart_detail") def item_decrement(request, id): cart = Cart(request) product = Product.objects.get(id=id) cart.decrement(product=product) return redirect("cart_detail") def cart_clear(request): cart = Cart(request) cart.clear() return redirect("cart_detail") def cart_detail(request): return render(request, 'cart/cart_detail.html') home.html {% for product in products %} <p>{{produit.name}}<br> {{produit.price}} <a href="{% url 'cart_add' product.id %}">Add</a> </p> {% endfor %} the link Add does not work, I have this error (Reverse for 'cart_add' not found. 'cart_add' is not a valid view function or pattern name.) Thank you for your help ! -
React, Django: Sending a PUT request to update data for one of my models but I get an error that a couple fields are required
Sending a PUT request to update data for one of my models but I get an error that a two fields are required even though they are set to blank=True and null=True in my model. When I create it works fine, it is just update. Maybe it has to do with using generic views? Using the same form in React for creating a pet and updating a pet information: export const UpdatePetInfo = async (petId, petInfo) => { try { const res = await Client.put(`pets/${petId}`, petInfo) console.log(res) return res.data } catch (error) { throw error } } const handleSubmit = async (e) => { e.preventDefault() if (editPetForm) { console.log(selectedPet) console.log(editPetForm) await UpdatePetInfo(selectedPet.id, { name: formValues.name, animal_group: formValues.animal_group, animal_kind: formValues.animal_kind, dob: formValues.dob, gotcha_date: formValues.gotcha_date, age: formValues.age, user_id: user.id }) navigate(`/dash/${selectedPet.id}`) } else { await CreatePet({ name: formValues.name, animal_group: formValues.animal_group, animal_kind: formValues.animal_kind, dob: formValues.dob, gotcha_date: formValues.gotcha_date, age: formValues.age, user_id: user.id }) // Redirects user to login navigate('/pets') } // Resets the form to blank once API req completes successfully setFormValues({ name: '', animal_group: '', animal_kind: '', dob: '', gotcha_date: '', age: '' }) setEditPetForm(false) }` models.py class Pet(models.Model): GROUP_CHOICES = ( ('Mammal', 'Mammal'), ('Bird', 'Bird'), ('Fish', 'Fish'), ('Reptile', 'Reptile'), ('Amphibian', 'Amphibian'), ('Other', … -
Django how to phasing the dollar sign using os.environ.get( )
I'm coding Django program,code is running in Linux, the env file includes : "PWD=uTfa$aB67" in settings.py: PWD = os.environ.get('PWD') Then in the code where I need this password ,I code: password = settings.PWD However every time when I print 'password' ,I only got: uTfa I have tried single quotes ,but it not works. Any suggestion ? -
How to delete template cache varing on variables in Django
In my Django template I have a block cached: {% cache 300 markers_list request.user.pk request.LANGUAGE_CODE %} {% for marker in page_obj.object_list %} {{ marker }} {% endcache %} I use a signal to invalidate a cache: @receiver(signal=[post_save, post_delete], sender=Marker) def clear_cache_block(sender, **kwargs): key = make_template_fragment_key("markers_list", [request.user.pk, request.language_code]) cache.delete(key) I do not understand how to get [request.user.pk, request.language_code]. If I add request to clear_cache_block(sender, request, **kwargs) I get an error: clear_cache_block() missing 1 required positional argument: 'request' -
how to covert a $ inside a string
I have a password: "PWD=uNloc$aB2037" In the Linux every time I print the PWD ,I got: "uNloc" Then I tried add a '/' after the dollar sign: "PWD=uNloc$/aB2037" But I got: 'uNloc$/aB2037' Any suggestion ? -
Can't install django with pipenv although it is installed and identified by the command prompt
I've been trying to set up a virtual environment for django using pipenv. I've installed pipenv and configured the path properly.Pipenv is working fine But when I attempt to install django with the following command pipenv install django I get the following error. Error I get while installing Django using pipenv I've been trying to figure this out the whole day and have tried various things but I'm new this and I can't figure out my mistake. Any help will be greatly appreciated! -
Download an uploaded django .docx file
I have a website where i upload a .docx file and then the users can download the document. my model class Files(model.Model): name = models.CharField(max_length=200) doc_File = models.FileField(upload_to='media') my View def Uploaded(request): file = Files.objects.filter('doc_File') return render(request, 'uploaded_files.html', {'file':file}) urls path('file, views.Uploaded, name='file'), my html page {% block content %} <h4>Download Document Below</h4> {% for f in file %} <a href="{% url 'f.url' %}" Download>{{f.url}}</a> {% endfor %} {% endblock %} I am not able to download the .docx file could anyone help pliz .... -
How to know what time is it in user's region django?
I have django web app with authentication. I want to see on users profile when he joined(created account). I have created model field like: joined_at = models.DateTimeField(auto_now_add=True, blank=True) but it gives me utc time. Which is 2 hours behind our time. And if someone from China would be able to create an account he would have bad experience with that too. So I want to find out what time it is in user's region and display that on field. Thanks for help:) -
Multilingual page Django
I've been planing to create my pet project, semblance of Quizlet, but stumbled upon an issue. I want my site to be in two languages(at least) and have no clue how to implement it. Googling didn't bring any results. Any ideas? -
Django - Manage related models on one page - like in django’s admin
I have 3 models: class Person(models.Model): name = models.CharField(max_length=50) class Skill(models.Model): skill_name = models.CharField(max_length=100) person = models.ForeignKey(Person, on_delete=models.CASCADE, related_name="skills") class WorkHistory(models.Model): company_name = models.CharField(max_length=100) person = models.ForeignKey(Person, on_delete=models.CASCADE, related_name="workhistories") In the django’s admin panel I can manage all 3 models on one page. In the django’s admin panel I can dynamically add or remove related models. Works lovely. But I need to create identical funcionality without using django’s admin panel. Do you know how to do it? I don’t want to reinvent the wheel. I searched the internet, but didn’t find nothing interesting. What are the best practices? Maybe you found any tutorial/solution on the internet? Thank you Example image -
How to group two same values and get value from other field in django, DRF
I am struggling with grouping two same field values and displaying their related values in one response. models.py: class Book(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE, null = True, blank = True) image = models.ImageField(default = "Nana.jpg", upload_to = 'images/', null = True, blank = True) title = models.CharField(max_length = 150, unique = True) author = models.CharField(max_length = 100) category = models.CharField(max_length = 100) description = models.TextField(max_length = 5000, null = True, blank = True) published_date = models.DateField(null = True, blank = True) language = models.CharField(max_length = 100, null = True, blank = True, default = "Not selected") read_book_count = models.IntegerField(default = 0) def __str__(self): return self.title Views.py: class BookAuthors(APIView): def get(self, request): author = Book.objects.all() serializer = AuthorSerializer(author, many = True) return Response(serializer.data) serializers.py class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ['title', 'author'] urls.py path('library/api/authors/', views.BookAuthors.as_view()), I want to combine author Homer and his two titles in same place not to be separated. -
ValueError at / Fernet key must be 32 url-safe base64-encoded bytes. keeps giving me issues
I have been getting this error for quite long now. i am trying to decrypt a text content that was encrypted using fernet. the key is passed in through an input element in my django template. after getting the value from the text input, i tried to use it to decrypt the text content but i kept getting this error. Below is my code my django template code: <form action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <h3>Welcome to Encryption, Decryption and Compression program using Python</h3> {% for field in form %} <div>{{ field }} </div> {% endfor %} <select name="choices" id="choices"> <option>Encryption</option> <option>Decryption</option> <option>Encryption and Compression</option> <option>Decryption and Compression</option> <option>Compression</option> </select> <input type="text" name="dkey" id="dkey" placeholder="Enter Decryption Key"> <button >Proceed</button> </form> my views.py def decryption(self, key): key = base64.urlsafe_b64encode(bytes(key, encoding="utf-8")) f = Fernet(key) def post(self, request): m_file = request.FILES['file'] opt = request.POST.get('choices') if opt == "Decryption": dkey = request.POST.get('dkey') decrypted = self.decryption(dkey) the error i get: ValueError at / Fernet key must be 32 url-safe base64-encoded bytes. the fernet key entered through the text input: **Pl85l36CA7TJe48jv8nWYFD4SWIhIJNFQL8CyyLlXR4=** -
Best way to model current version/single elevated list item in Django?
Suppose I'm Santa Claus and I'm making a site to keep track of kids' Christmas lists. I might have something like this: class Kid(models.Model): name = models.CharField() class Gift(models.Model): name = models.CharField() class WishList(models.Model): date_received = models.DateTimeField() kid = models.ForeignKey(Kid, on_delete=CASCADE) I have implemented the WishList model, instead of just linking Gifts to Kids with ForeignKeys directly, because I would like to keep track of individual Christmas wish lists discretely. I want to archive all the old Christmas lists as I received them. The most obvious way to implement this would be to add something like current = models.BooleanField() to the WishList class, and then filter for wishlist.current=true when I want to get the current wishlist for a given kid. However, there are two problems with this: 1. I don't know how the database query algorithm works behind the scenes, and I don't want to make the computer look through every list to find the current one, when 99% of the time that's the only one I'll be looking at, and 2. this doesn't prevent me from having two current wish lists, and I don't want to have to write special validator code to ensure that. The second option I … -
How to create complex query params using dict in django API
So I have recently discovered that is is possible to pass a dictionary as a filter argument in the django ORM. This has changed the game for a particular project I am working on. This allows me to create an endpoint where a user can effectively construct a query using a POST request. So I would like to figure out how to use django's filter methods within said dictionary. Picture this: endpoint at url.com/api/v1/data results = ModelName.objects.filter(**request.data) I have tested simple queries such as... { "modelparam1": "value 1" } which returns all objects where modelparam1="value 1" as expected... but if I wanted to do ModelName.objects.filter( modelparam1__startswith='value' ) as { "modelparam1__startswith": "value" } I am returned an empty list... Am I doing something wrong? -
How to check if database is present and migrated in elasticbeanstalk?
I have been trying to troubleshoot 500 error, on a django REST framework + reactjs app. I think the migrate is not executing correctly. The db-migrate.config file: container_commands: 01_migrate: command: "source $PYTHONPATH/activate pipenv run python manage.py migrate" leader_only: true DB_SETTINGS: eventually I want to change this to RDS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } eb deploy is successful. I still run into the 500 error, on localmachine the same endpoint works perfectly. How can I check whether the DB on elastic beanstalk has the necessary migrations? Any other causes I should be looking into? TIA -
Cannot get Python code to catch psycopg2 and Django errors
I cannot get my code to catch these exceptions: import psycopg2 from psycopg2 import IntegrityError, errors from django.db.utils import IntegrityError as ie ... try: parent = Code.objects.get(arrow=parrow) except (Code.DoesNotExist, psycopg2.errors.ForeignKeyViolation, IntegrityError, ie): logging.warning(f"Parent '{parrow}' of {child} not yet in database.") waitroom.append((parrow, child)) ... psycopg2.errors.ForeignKeyViolation: insert or update on table "codeAT_code" violates foreign key constraint "codeAT_code_childof_id_78f76bc4_fk_codeAT_code_uniqid" DETAIL: Key (childof_id)=(c74d8ad6-f23e-4b63-860f-e80f54b7c4cc) is not present in table "codeAT_code". The above exception was the direct cause of the following exception: django.db.utils.IntegrityError: insert or update on table "codeAT_code" violates foreign key constraint "codeAT_code_childof_id_78f76bc4_fk_codeAT_code_uniqid" DETAIL: Key (childof_id)=(c74d8ad6-f23e-4b63-860f-e80f54b7c4cc) is not present in table "codeAT_code" ... In addition to nothing being caught, PyCharm does not recognize psycopg2's ForeignKeyViolation, saying it is an unresolved reference. I've tried stating it many different ways. Please advise. Thanks. -
Limit characters user can enter in input in django OR html?
I had various occasions where I wanted to but couldn’t limit characters user types in html input. For example what would I do if I would only want numbers and letters? No other like £-“<#>{[. And what would I do if I would want them to only enter uppercase letters? Thanks for help:) -
Django admin search_fields FieldError
couldn't find anywhere answer to my question, and I'm trying to solve it for almost 2h right now. I have 3 models. Let's say A, B and C: class A(models.Model): product = models.ForeignKey(B, on_delete=models.CASCADE) class B(models.Model): product = models.ForeignKey(C, on_delete=models.CASCADE) class C(models.Model): name = models.CharField(max_length=200) And I want to search in my django admin by C.name in A model. How can I make it work properly? Here is my admin class: @admin.register(A) class AAdmin(admin.ModelAdmin): search_fields = ["product__product__name"] Right now im getting error: Related Field got invalid lookup: icontains -
Django dynamic form field validation
I have a form that I can set the fields for dynamically, like so: class MyForm(forms.Form): field_mappings = { 'my_field': {'field_type': forms.CharField()} } def __init__(self, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) initial_items = kwargs.get('initial') if initial_items: for k, v in initial_items.items(): field_mapping = self.field_mappings.get(k) if field_mapping: field_name = k self.fields[field_name] = field_mapping['field_type'] self.fields[field_name].initial = v During the GET request, I initialise it by passing in the initial values: MyForm(initial={'my_field', 'abcdefg'}) But I'm stuck on how to validate the fields in the POST request. From the docs, I think I should subclass the clean() method, select the field from the field mapping (depending on the POST field), and call it's validate(), method / something like this: args = args[0] if args: for k, v in args.items(): field_mapping = self.field_mappings.get(k) if field_mapping: field = field_mapping['field'] field.validate(v) but then what? -
PayPal API PopUp closes immediately after clicking PayPal button (Sandbox)
I am trying to implement the PayPal API into my Django / Vue checkout system, but everytime i try to access checkout via the paypal checkout buttons, thepopup closes immediately and i get these errors: Error messages in developer tools Obviously it has something to do with the cart's items' attributes and i tried to adjust them accordingly, but i can't figure out how to fix it. My Code: <template> <div class="page-checkout"> <div class="columns is-multiline"> <div class="column is-12"> <h1 class="title">Kasse</h1> </div> <div class="column is-12 box"> <table class="table is-fullwidth"> <thead> <tr> <th>Artikel</th> <th>Preis</th> <th>Anzahl</th> <th>Gesamt</th> </tr> </thead> <!-- vue for loop for looping through items in cart and displaying them in a table --> <tbody> <tr v-for="item in cart.items" v-bind:key="item.product.id" > <td>{{ item.product.name }}</td> <td>{{ item.product.price }}€</td> <td>{{ item.quantity }}</td> <td>{{ getItemTotal(item).toFixed(2) }}€</td> </tr> </tbody> <tfoot> <tr style="font-weight: bolder; font-size: larger;"> <td colspan="2">Insgesamt</td> <td>{{ cartTotalLength }}</td> <td>{{ cartTotalPrice.toFixed(2) }}€</td> </tr> </tfoot> </table> </div> <!-- Fields for user information --> <div class="column is-12 box"> <h2 class="subtitle">Versanddetails</h2> <p class="has-text-grey mb-4">*Felder müssen ausgefüllt sein</p> <div class="columns is-multline"> <div class="column is-6"> <div class="field"> <label>*Vorname</label> <div class="control"> <input type="text" class="input" v-model="first_name"> </div> </div> <div class="field"> <label>*Nachname</label> <div class="control"> <input type="text" class="input" v-model="last_name"> </div> </div> <div class="field"> … -
using F expression to access a field from one to many relationship not using the queryset resulted from prefetch_related method
hey guys let's say I have these models class Object1: ..... class Object2: user = models.ForeignKey(User) rel = models.ForeignKey(Object1, related_name = 'objects') isCOmpleted = models.BooleanField() and I wanted to perform this query: Object1.objects.all().prefetch_related(Prefetch('objects', Object2.objects.filter(user = specific_user))).annotate(is_completed=F('objects__isCompleted')) and the user is only related to one object from the Object2, but I got duplicate objects in my query, and I know the reason is that I have two objects from Object2 in my database for two different users, but the problem is that F expression didn't look in my prefetched query using prefetch_query, I tried the exact same thing in the shell and it's giving me the results that I have expected but not in the view, so what's the problem here exactly any help would be really appreciated -
How to make a user authentication by react django and redux
I want to make a user authentication by react, Django (using Allauth) and redux and also have Jwt authentication. what is the best way to do it? -
Django Signals maximum recursion depth when updating model field
I am trying to update a status field via signals but get a max recursion error. Using django 4.1.1. models.py class Product(models.Model): # …. PRODUCT_STATUS = ( ('P', _('Preparation')), ('S', _('Sold')), ('T', _('Shipped')), ) status = models.CharField(max_length=1, null=True, choices=PRODUCT_STATUS, default='P') price_sold = models.DecimalField( _('Price Sold'), max_digits=10, decimal_places=2, blank=True, null=True) #… signals.py @receiver(post_save, sender=Product) def post_save_product_set_status_sold_if_price_sold(sender, instance, created, **kwargs): if instance.price_sold != None: instance.status = 'S' instance.save(update_fields=['status']) I get the following error when saving RecursionError at /admin/products/product/14/change/ maximum recursion depth exceeded while calling a Python object Can somebody help? -
Access other domain files through Django sites framework
I'm trying to change the stripe api keys on the three domains that are on a digital ocean droplet. The project is using the Django sites framework to host these three domains. Therefore when I change the key it works only for one domain and not for the others. Is there a certain way to apply the changes to the other domains? -
Import django model to python script
I want to import models to a python script (test.py) using this code from .models import Template print('good') but it gives me this error : from .models import Template ImportError: attempted relative import with no known parent package this is my root : ├── project │ ├── __init__.py │ ├── modules.py │ └── test.py Any help is highly appreciated