Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NGINX ERROR :connect() failed (111: Connection refused) while connecting to upstream
I get that error in title when I cat out the error.log this is how I set my website config inside /etc/nginx/site-availables/ArticleWebsite: server_tokens off; access_log /var/log/nginx/ArticleWebsite.access.log; error_log /var/log/nginx/ArticleWebsite.error.log; # This configuration will be changed to redirect to HTTPS later server { server_name backend.globeofarticles.com; listen 443 ssl; ssl_certificate /etc/letsencrypt/live/backend.globeofarticles.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/backend.globeofarticles.com/privkey.pem; location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $host; } } to explain my situation better, backend.globeofarticles.com is the subdomain, that where the requests are sent from globeofarticles.com or www.globeofarticles.com. Also, Django has 127.0.0.1:8000 host as default. when I access the website (backend subdomain) I get this error: when checking network tab, I get too many redirects actually: with status code 301 -
Django: Create Choices For Filter Based on Distinct Model Values
Objective: I want to have a ModelChoiceFilter rendered on the page where the options/choices for the user to select are the distinct values of a field in the model. The app allows users to track the cities that they have visited. I want users to be able to filter the model on country and for the filter options to only be countries that are in the model. I am using django-filters and do successfully have a MultipleChoiceFilter working where the choices work when hard-coded (either in the models.py or in the FilterForm class: class cityFilter(django_filters.FilterSet): continent = MultipleChoiceFilter( choices=cityModel.continent_choices, widget=forms.CheckboxSelectMultiple, label='Continent') class Meta: model = cityModel fields = ['city', 'country', 'continent'] One can also set the choices directly in the FilterSet class like this: country = MultipleChoiceFilter( choices=(('GB','United Kingdom'),('FR','France')), widget=forms.CheckboxSelectMultiple, label='Country' ) This works okay for continents but I want to allow a filter for countries. I only want to expose to the user the distinct set of countries in the model (as opposed to hard coding every country). I could do something like this to get all the distinct countries in the model: country_choices = cityModel.objects.values('country').distinct() But I'm not sure where this should be placed in the app to … -
How to increase progress bar each time input=type['radio'] is checked using javascript?
I am making a quiz app using django but I'm stuck with javascript here. I want the progress bar to increase each time any radio button is checked according to the percentage of the questions answered out of total questions. The issue here is it only increases once i.e, for only first question. For example, if there are three questions, the progress bar will be stuck at 33% no matter other are answered or not. Here's the relevant code: HTML:- <!--progress bar--> <div id="progress-bar-display">0%</div> {% for q in questions %} <h3> {{ q.id }}. {{ q.question }}</h3> <input type = "radio" name = "q{{ q.id }}" value = "a" id = "q1a" > a. {{ q.option1 }}<br><br> <input type = "radio" name = "q{{ q.id }}" value = "b" id = "q1b" > b. {{ q.option2 }}<br><br> <input type = "radio" name = "q{{ q.id }}" value = "c" id = "q1c" > c. {{ q.option3 }}<br><br> <input type = "radio" name = "q{{ q.id }}" value = "d" id = "q1d" > d. {{ q.option4 }}<br><br> {% endfor %} JavaScript :- //progress_bar_count--> var radio = document.querySelectorAll("input[type='radio']"); answered = 0; var size = 0; function animate(){ answered += (1 / … -
How to setup a delay with django-celery-beat's periodic tasks?
We have a custom periodic task (a subclass of django-celery-beat's PeriodicTask model) that's scheduled using CronSchedule. In our custom periodic task, we want to allow an optional delay to when the task is scheduled. So if the cron schedule is every 20th minute (*/20 * * * *), with a delay of 30minutes then it should be scheduled to run Without the delay: 00:00, 00:20, 00:40 With the delay: 00:30, 00:50, 01:10 At first we thought of using CRON's offset syntax: <delay>-59/<frequency> * * * * but even with the example above, it's clear that it would not work. How can we do something like this in django-celery-beat? Note that we are limited to using a CRON schedule and cannot use something like an interval schedule with a specified start date. -
Lowercase based on regex pattern in Django & Python
The script I am using calls s_lower method to transform all text to lowercase but there is a catch: if it is a link (there is a special regex), then it does not lowercase it. So, I would like to apply the same or similar logic with other regex. RE_WEBURL_NC = ( r"(?:(?:(?:(?:https?):)\/\/)(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[" r"6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?" r":[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9][a-z0-9_-]{0,62})?[a-z0-9]\.)+(?:[a-z]{2,}\.?))(?::\d{2,5})?)(?:" r"(?:[/?#](?:(?![\s\"<>{}|\\^~\[\]`])(?!&lt;|&gt;|&quot;|&#x27;).)*))?" ) def s_lower(value): url_nc = re.compile(f"({RE_WEBURL_NC})") # Do not lowercase links if url_nc.search(value): substrings = url_nc.split(value) for idx, substr in enumerate(substrings): if not url_nc.match(substr): substrings[idx] = i18n_lower(substr) return "".join(substrings) return i18n_lower(value) I want to lowercase all text other than text inside the special tags. def s_lower(value): spec_nc = re.compile(r"\[spec .*\]") # this is for [spec some raNdoM cAsE text here] if spec_nc.search(value): substrings = spec_nc.split(value) for idx, substr in enumerate(substrings): if not spec_nc.match(substr): substrings[idx] = i18n_lower(substr) return "".join(substrings) return i18n_lower(value) -
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?