Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I Set Django Session Variable on one view and get it on another
I am really confused on how to set and get Django Session variable. The most confusing part is that I want my application to set the PIN form field value as a session variable on my PIN activation view and get it on my guest registration view so I can save in model field. The reason is that I don't want the guest to repeat the PIN input on the registration page. Below are my views and how I am setting the session variable on my pin_activation view: def pin_activation(request): if request.method == "POST": #Create new form with name form form = PinActivationForm(request.POST) #Get User Pin Value from Form pin_value = form['pin'].value() #Check if the the form has valid data in it if form.is_valid(): try: #Get user Pin with the one in the Database check_pin_status = Pin.objects.get(value=pin_value) except Pin.DoesNotExist: messages.error(request, f'{pin_value} Does Not Exist') return redirect('pin-activation') else: #Check PIN status if check_pin_status: #Get Event Ticket Date of the PIN event_date = check_pin_status.ticket.event.date #Get Current Date current_date = datetime.now().date() #Check if Event Date is Passed the Current Date if event_date < current_date: messages.error(request, 'Event Has Passed') return redirect('pin-activation') #Check if Event Ticket is Already Validated elif Pin.objects.filter(value=form['pin'].value(), status="Validated"): messages.error(request, 'Pin Already … -
Which is the best framework for developing realtime chatting?
I want to develop website to realtime chatting and I am confused about which framework I should use ? Django vs Nose.js -
Django - Add two names - Couldn't print results
I'm new to Django. Trying to build an app that adds two names. Pretty Basic. Built a page that collects the names but not printing the final result. Here is my code: urls.py - inside the app urlpatterns = [ path('',views.home, name='home'), path('add',views.addname,name='add') ] views.py from django.shortcuts import render from django.http import HttpResponse def home(request): return render(request,'input.html') def addname(request): val1 = (request.POST['fname']) val2 = (request.POST['lname']) res = 'Hi' + val1 +val2 return render(request, 'resultprint.html',{'resultprint':res}) templates/input.html {% block content %} <h1>Hello!</h1> <form action='addname' method='post'> {% csrf_token %} Enter 1st name : <input type='text' name='fname'><br> Enter 2nd name : <input type='text' name='lname'><br> <input type='submit'> </form> {%endblock%} templates/resultprint.html {% block content %} Result: {{resultprint}} {%endblock%} Below are the screenshots: Couldn't really find where is the mistake happening. I added the templates and app in the Settings file. -
Django convert Decimal into integer when point value is 0
I am trying to convert a Django Decimal field into an integer but only if it has a 0 point value. So basically: decimal_field = models.DecimalField(max_digits=10, decimal_places=2, default=0) Lets say we have the following decimal_field = 15.6 Then when I use if int(decimal_field): decimal_field = int(decimal_field) It gets converted to 15 instead of staying 15.6 I want this to stay the same and if the decimal is 15.0 to convert to 15 -
What is this pytest value error traceback telling me to fix?
I'm attempting to run pytest in VS Code on a Django webapp that I did not build. Pytest is already installed as a dependency, but when I run the command: pytest I receive a ValueError: ('unknown configuration type: pathlist' traceback. I receive the same command if I run directly in my VS Code terminal as I do if I open the shell of the docker container with the running application and run pytest there. I'm not sure how to interpret the results, although I read through the following to no avail: Pytest KeyError when attempting to access a command line variable https://github.com/pytest-dev/pytest/issues/3112 Here is the error traceback: Traceback (most recent call last): File "/Users/aleholland/Documents/GitHub/mos-sfs/venv/lib/python3.8/site-packages/_pytest/config/__init__.py", line 1373, in getini return self._inicache[name] KeyError: 'python_paths' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/aleholland/Documents/GitHub/mos-sfs/venv/bin/pytest", line 8, in <module> sys.exit(console_main()) File "/Users/aleholland/Documents/GitHub/mos-sfs/venv/lib/python3.8/site-packages/_pytest/config/__init__.py", line 187, in console_main code = main() File "/Users/aleholland/Documents/GitHub/mos-sfs/venv/lib/python3.8/site-packages/_pytest/config/__init__.py", line 145, in main config = _prepareconfig(args, plugins) File "/Users/aleholland/Documents/GitHub/mos-sfs/venv/lib/python3.8/site-packages/_pytest/config/__init__.py", line 324, in _prepareconfig config = pluginmanager.hook.pytest_cmdline_parse( File "/Users/aleholland/Documents/GitHub/mos-sfs/venv/lib/python3.8/site-packages/pluggy/_hooks.py", line 265, in __call__ return self._hookexec(self.name, self.get_hookimpls(), kwargs, firstresult) File "/Users/aleholland/Documents/GitHub/mos-sfs/venv/lib/python3.8/site-packages/pluggy/_manager.py", line 80, in _hookexec return self._inner_hookexec(hook_name, methods, kwargs, firstresult) File "/Users/aleholland/Documents/GitHub/mos-sfs/venv/lib/python3.8/site-packages/pluggy/_callers.py", line 55, in _multicall gen.send(outcome) … -
<frozen importlib._bootstrap> error in python django
My name of the project is Proctor and i have shifted this project from my computer to laptop due to which I am facing errors. I have tried almost everything to solve this error but none worked for me. Installed all missing modules Executed all python manage.py (makemigrations/migrate) commands Checked my installed apps. (nothing is missing) The models are migrated in the database. Now just python manage.py runserver has errors. My python version is 3.10.7 Error: Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Dalvi\Envs\proctor\lib\site-packages\django\core\servers\basehttp.py", line 47, in get_internal_wsgi_application return import_string(app_path) File "C:\Users\Dalvi\Envs\proctor\lib\site-packages\django\utils\module_loading.py", line 30, in import_string return cached_import(module_path, class_name) File "C:\Users\Dalvi\Envs\proctor\lib\site-packages\django\utils\module_loading.py", line 15, in cached_import module = import_module(module_path) File "D:\1.Coding Softwares\Python\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "C:\Users\Dalvi\Desktop\Anish\Python Project\Online-Proctor-System\proctor\proctor\wsgi.py", line 16, in <module> application = get_wsgi_application() File "C:\Users\Dalvi\Envs\proctor\lib\site-packages\django\core\wsgi.py", line 13, in get_wsgi_application return WSGIHandler() handler = self.get_handler(*args, **options) File "C:\Users\Dalvi\Envs\proctor\lib\site-packages\django\contrib\staticfiles\management\commands\runserver.py", line 31, in get_handler handler = super().get_handler(*args, **options) File "C:\Users\Dalvi\Envs\proctor\lib\site-packages\django\core\management\commands\runserver.py", line 78, … -
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?