Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am trying to set a user from my custom django signup form based on what option they select from a RadioButton
My forms.py users = [ ('client', 'Client'), ('customer', 'Customer'), ] class CustomSignUpForm(SignupForm): Register_as = forms.ChoiceField(choices=users, widget=forms.RadioSelect) def save(self, request): if CustomSignUpForm.Register_as.widget == 'client': user = super(CustomSignUpForm, self).save(request) user.is_client = True user.save() return user if CustomSignUpForm.Register_as.widget == 'customer': user = super(CustomSignUpForm, self).save(request) user.is_customer = True user.save() return user But after running the code, i get this error AttributeError at /accounts/signup/ type object 'CustomSignUpForm' has no attribute 'Register_as' Request Method: POST Request URL: http://localhost:8000/accounts/signup/ Django Version: 3.2.5 Exception Type: AttributeError Exception Value:type object 'CustomSignUpForm' has no attribute 'Register_as' -
I'm try to deploy my django project in Heroku by use Heroku CLI I face installation error
Everything goes right till I run this command: git push heroku master I get this massages: git push heroku master Enumerating objects: 55, done. Counting objects: 100% (55/55), done. Delta compression using up to 8 threads Compressing objects: 100% (46/46), done. Writing objects: 100% (55/55), 15.40 KiB | 685.00 KiB/s, done. Total 55 (delta 14), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Determining which buildpack to use for this app remote: ! Warning: Multiple default buildpacks reported the ability to handle this app. The first buildpack in the list below will be used. remote: Detected buildpacks: Python,Node.js remote: See https://devcenter.heroku.com/articles/buildpacks#buildpack-detect-order remote: -----> Python app detected remote: -----> No Python version was specified. Using the buildpack default: python-3.10. remote: To use a different version, see: https://devcenter.heroku.com/articles/python-runtimes remote: -----> Installing python-3.10.4 remote: -----> Installing pip 22.0.4, setuptools 60.10.0 and wheel 0.37.1 remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: Collecting argcomplete==1.8.1 remote: Downloading argcomplete-1.8.1-py2.py3-none-any.whl (34 kB) remote: Collecting argh==0.26.2 remote: Downloading argh-0.26.2-py2.py3-none-any.whl (30 kB) remote: Collecting attrs==19.3.0 remote: Downloading attrs-19.3.0-py2.py3-none-any.whl (39 kB) remote: Collecting Automat==0.8.0 remote: Downloading Automat-0.8.0-py2.py3-none-any.whl (31 kB) remote: Collecting blessings==1.6 remote: … -
Django & Ajax - "Like" button, how to make it work for mutliple posts on a page?
There are a lot of similar questions already raised, but so far haven't managed to fix my setup. I successfully created a 'like' button with a counter, but it works only on one post, where there are multiple on one page (while hitting the like button on another post, only the first one gets changed). What should I change in the code, to make it work for all posts? HTML button {% for news in newss %} <div class="col-md-6"> {% csrf_token %} <button class="like-button" value="{{ news.id }}" > Like </button> <span class="" id="like_count">{{ news.news_likes_count }}</span> </div> {% endfor %} AJAX <script> $(document).on('click', '.like-button', function (e) { e.preventDefault(); $.ajax({ type: 'POST', url: '{% url "like" %}', data: { newsid: $('.like-button').val(), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), action: 'post' }, success: function (json) { document.getElementById("like_count").innerHTML = json['result'] }, error: function(xhr, errmsg, err) { } }); }) </script> views.py @login_required def like(request): if request.POST.get('action') == 'post': result = '' id = int(request.POST.get('newsid')) news = get_object_or_404(News, id=id) if news.news_likes.filter(id=request.user.id).exists(): news.news_likes.remove(request.user) news.news_likes_count -= 1 result = news.news_likes_count news.save() else: news.news_likes.add(request.user) news.news_likes_count += 1 result = news.news_likes_count news.save() return JsonResponse({'result': result,}) urls.py path('like/', views.like, name='like') models.py class News(models.Model): news_title = models.CharField(max_length=100) news_text = models.TextField(max_length=2000) news_author = models.CharField(max_length=150) news_created_date = models.DateTimeField(default=now) … -
Why django refuses to see a folder?
Django just refuses to see libs module. Idk why it happens, it definitely kidding me. The structure goes like django app struct Can somebody tell me why exactly it happens? -
Save Data from Rest API to database using Django(view function)
I am trying to save API data to the database. I can with the print function, but I want to save without the print function. -
Partial loading using javascript in django
I have two html pages index.html and user.html. user.html contains search action.Here I've loaded user.html in index.html using jQuery.When I perform search action it's redirecting to user.html...But I want to display result in the index.html.The project is in django.Is there is any way to do this?? -
Dockerizing Django with nginx and gunicorn
This is a very basic django deployment and I am trying to configure nginx and gunicorn on it through docker It seems to run fine but there is no connection. folder path: Dockerized-Django ├── Dockerfile ├── docker-compose.yml ├── entrypoint.sh ├── nginx │ ├── Dockerfile │ └── default.conf ├── pyshop │ ├── db.sqlite3 │ ├── manage.py │ ├── products │ │ ├── __init__.py │ │ ├── __pycache__ │ │ │ ├── __init__.cpython-38.pyc │ │ │ ├── admin.cpython-38.pyc │ │ │ ├── apps.cpython-38.pyc │ │ │ ├── models.cpython-38.pyc │ │ │ ├── urls.cpython-38.pyc │ │ │ └── views.cpython-38.pyc │ │ ├── admin.py │ │ ├── apps.py │ │ ├── migrations │ │ │ ├── 0001_initial.py │ │ │ ├── 0002_offer.py │ │ │ ├── 0003_auto_20220507_1845.py │ │ │ ├── __init__.py │ │ │ └── __pycache__ │ │ │ ├── 0001_initial.cpython-38.pyc │ │ │ ├── 0002_offer.cpython-38.pyc │ │ │ ├── 0003_auto_20220507_1845.cpython-38.pyc │ │ │ └── __init__.cpython-38.pyc │ │ ├── models.py │ │ ├── templates │ │ │ ├── base.html │ │ │ └── index.html │ │ ├── tests.py │ │ ├── urls.py │ │ └── views.py │ └── pyshop │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-38.pyc │ │ ├── settings.cpython-38.pyc … -
How to configure Ngnix server with django-channels-redis
I'm trying to to configure my django chat app using django-channels and redis with ngnix server, How can I achieve this? -
Sort django admin column by __str__ method
I have a Folder model and I want to display the columns in the admin page ordered alphabetically following the __str__ method. I looked over several similar questions like this one, this one and also this one, but didn't manage to really understand the answers, or at least enough to adapt them to my problem (even though I've been trying for quite some time). Here is my Folder class, with the str method I want to sort with : class Folder(models.Model): folder_name = models.CharField(max_length=200) parent_folder = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True) def __str__(self): if self.parent_folder: return f'{self.parent_folder}/{self.folder_name}' else: return self.folder_name And my FolderAdmin class : class FolderAdmin(admin.ModelAdmin): ordering = ('str',) #I want it to do like that but don't know how to do it fieldsets = [ (None, {'fields': ['folder_name']}), ('Parent Folder', {'fields': ['parent_folder']}), ] list_display = ('folder_name', '__str__') I feel dumb for not understanding a question already answered multiple times but if you could help me understand it I'd be grateful. Thank you in advance ! -
when i remove a field my manage.py migrate raise django.db.utils.ProgrammingError
I got a problem with python manage.py migrate when I removed the field name from the oldest model. python 3.8 Dajngo 4.0.4 PostgreSQL 12 ubuntu 20.04 oldest model class BaseModel(models.Model): name = models.CharField(verbose_name=_("Name"), unique=True, max_length=255) created_time = models.DateTimeField(verbose_name=_("Created time"), auto_now_add=True) is_active = models.BooleanField(verbose_name=_("Is active"), default=True) Report model before the change class Report(BaseModel): reporter = models.ForeignKey( to="User",related_name="reporter_user", on_delete=models.CASCADE ) reported = models.ForeignKey( to="User",related_name="reported_user", on_delete=models.CASCADE ) description = models.TextField(null=True, blank=True) Repot model after change: class Report(BaseModel): name = None reporter = models.ForeignKey( to="User",related_name="reporter_user", on_delete=models.CASCADE ) reported = models.ForeignKey( to="User",related_name="reported_user", on_delete=models.CASCADE ) description = models.TextField(null=True, blank=True) python manage.py makemigrations was done successfully but when I wanted to migrate them I got this error: django.db.utils.ProgrammingError: column "name" of relation "user_report" does not exist what's my problem? -
Whats a good pattern for a web-application for serving files?
I am working on an angular Web-Application where it's possible to view pdf-files in a pdf-viewer in the browser. The Web-Application is also consuming a REST-Service in Django. In the Database the information of the pdf-files is stored. The Web-App is calling the REST-API to check where the files are stored. As I am still in the Proof-Of-Concept Phase of the project, the PDF-Files are currently stored in the assets folder of the angular web, which of course is not what I want in the end. When the Files or the Directories change, the Database should be updated automatically (or via a trigger in the app). I have two questions: Is there an obvious way to serve the files in this combination? i.e. an apache server? I imagine there are built in solutions in dedicated file servers to detect changes of the watched directory. For a partly solution would it be reasonable to write a script on the django site, which does the file-serving, the updating and also providing the REST-API? -
Django: form not showing up in rendered template
I tried to add a page in my admin panel for the user to upload a CSV file. However, the form I passed into the template is not displayed, although I followed this tutorial. https://www.youtube.com/watch?v=BLxCnD5-Uvc&t=340s (From around 14:20 to 17:30) I checked if the context containing the form is correctly passed into the template by passing in a random text, but that random text was displayed in my template and it was just the form that is not being rendered. This is my admin.py: class CsvImportForm(forms.Form): csv_upload = models.FileField() class UserAdmin(BaseUserAdmin): form = UserChangeForm add_form = UserCreationForm list_display = ('email', 'first_name', 'middle_name', 'last_name', 'role', 'subject', 'schedule_uploaded', 'is_admin') list_filter = ('is_admin',) fieldsets = ( (None, {'fields': ('email', 'password', 'first_name', 'middle_name', 'last_name', 'role', 'subject', 'schedule_uploaded')}), ('Permissions', {'fields': ('is_admin',)}) ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('email', 'password1', 'password2', 'first_name', 'middle_name', 'last_name', 'role', 'subject', 'schedule_uploaded', 'is_admin')} ), ) search_fields = ('email', 'first_name', 'middle_name', 'last_name', 'role', 'subject', 'schedule_uploaded') ordering = ('email', 'first_name', 'middle_name', 'last_name', 'role', 'subject', 'schedule_uploaded') filter_horizontal = () def get_urls(self): urls = super().get_urls() new_urls = [path('csv_upload/', self.csv_upload)] return new_urls + urls def csv_upload(self, request): form = CsvImportForm() context = {"form": form} return render(request, 'admin/csv_upload.html', context) This is my template: {% … -
How to access one Django Project Database from another Django Project?
I am trying to access one Django Project Database value from another Django Project. So far I have tried making REST API on both the applications and it is working somewhat well on the local server. However, I am concerned that when I will be deploying both the projects on the server it will create some lag to access over the API. Moreover, if one server/application is down for maintenance, the other will be inaccessible. Is it possible to directly access the other app database without using API as it will be much more faster and reliable? Thanks. -
How to display different data according to users in android using get method?
For my app, in user registration, when a user registers in the app, their data is sent to database and stored there and using GET method it is displayed in the app, Now how do I display the data in my app differently for different users because each users have their own unique data, and what I need is to display profile description of whoever fills the form. (I am using android studio and java to make android app) -
Unicode in Content-Disposition in Post-IE11 area
Accoding to this old answer you need to encode a unicode filename like this: from urllib.parse import quote disposition = 'attachment' if as_attachment else 'inline' try: filename.encode('ascii') file_expr = 'filename="{}"'.format(filename) except UnicodeEncodeError: file_expr = "filename*=utf-8''{}".format(quote(filename)) response.headers['Content-Disposition'] = '{}; {}'.format(disposition, file_expr) Just for fun I tried this: response = HttpResponse('abcd') response['Content-Disposition'] = b'attachment; filename="{}"'.format('üöä & €.txt'.encode('utf8')) return response And Chrome, Firefox and Epiphany (WebKit) where able to download the file to üöä & €.txt. Which (not outdated) http clients have trouble with this simple utf-8 encoded filename? -
Using Django ORM to sum annotated queries
I am using Django in combination with a TimescaleDB to process energy data from pv installations. Now I would like to calculate, how much energy multiple plants have generated within a given timebucket (usually per day). The plants writing the new values in a table which looks like that: customer datasource value timestamp 1 1 1 01.05.22 10:00 1 1 5 01.05.22 18:00 1 2 3 01.05.22 09:00 1 2 9 01.05.22 17:00 1 1 5 02.05.22 10:00 1 1 12 02.05.22 18:00 1 2 9 02.05.22 09:00 1 2 16 02.05.22 17:00 Now what I would like to have is, get the overal daily gain of values (so, for each day: Last Entry Value - (minus) First Entry Value) for each customer (which means, sum the daily generated energy values from all datasource which belong to the customer). In the above example that would be for customer 1: Day 01.05.22: Daily Gain of Datasource 1: 5 - 1 = 4 Daily Gain of Datasource 2: 9 - 3 = 6 Overall: 4 + 6 = 10 Day 02.05.22: Daily Gain of Datasource 1: 12 - 5 = 7 Daily Gain of Datasource 2: 16 - 9 = 7 Overall: … -
django import-export composite foreign key
I Have two models: ExternalListSettings and PriorityToolPartner. PriorityToolPartner has ForeignKey to ExternalListSettings. ExternalListSettings has complex primary key: import_date + partner. Csv file looks like this: import_date, partner, hotel_name, slug, bookings, num_in_sortorder How can i import PriorityToolPartner and combine ['import_date', 'partner'] into ForeignKey to ExternalListSettings model? Here are my models: class ExternalListSettings(DiModel): class Meta: verbose_name_plural = "External List Settings" unique_together = ['import_date', 'partner'] import_date = models.DateField( blank=False, null=False, ) partner = models.CharField( max_length=200, blank=False, null=False, ) is_top = models.BooleanField( blank=True, null=False, default=False, ) class PriorityToolPartner(DiModel): setting = models.ForeignKey( ExternalListSettings, null=False, blank=False, on_delete=models.CASCADE, default=0, ) hotel_name = models.CharField( max_length=200, blank=False, null=False, ) slug = models.CharField( max_length=300, blank=False, null=False, ) bookings = models.IntegerField( blank=True, null=True, ) num_in_sortorder = models.IntegerField( blank=True, null=True, ) -
HTMX integration with jsTree
I have integrated jsTree Library to load a tree structure menu. On click am using HTMX library to dynamically load content without page refresh. tree node click triggers well, but the htmx get request is only being sent on page load. My tree rerenders everytime I do an HTMX request since data tree is dynamic based on the request. Because I want even when I create a node (Folder), the structure itself should also refresh. Anyone who could have fully integrated such. -
python manage.py runserver : Exception in thread django-main-thread
To run django project after giving cmd "python manage.py runserver" I am getting following errors Please help to solve these errors. Errors -
The view budget.views.budget didn't return an HttpResponse object. It returned None instead
I recently added second form to my project and im struggling to make it work. The form is named AddIncome and when i fill the form and submit nothing happen, i don't see the new income. When i fill the income from admin panel on model page everthing works. Don't know how to make it work from main page. Here is my view (second form that i added is b_form, a_form is working): from django.contrib import messages from django.contrib.auth.decorators import login_required from django.core.paginator import Paginator from django.db.models import Sum from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404, redirect, render from django.urls import reverse from django.utils import timezone from .forms import AddIncome, AddItem from .models import BudgetData @login_required def budget(request): expense_items = BudgetData.objects.filter(user_expense=request.user).order_by( "-date_added" ) # Setting up pagination per expense_items paginator = Paginator(expense_items, 10, 3) # Show 10 items per page. page_number = request.GET.get("page") page_obj = paginator.get_page(page_number) total_cost = BudgetData.objects.filter(user_expense=request.user).aggregate( Sum("cost") ) total_income = BudgetData.objects.filter(user_expense=request.user).aggregate( Sum("income") ) # AddItem{category, cost} form a_form = AddItem() b_form = AddIncome() # form = AddItem(use_required_attribute=False) # ignores the field required text if request.method == "POST" and "expense" in request.POST: a_form = AddItem(request.POST) if a_form.is_valid(): a_form = a_form.save(commit=False) a_form.user_expense = request.user a_form.date_added = timezone.now() a_form.save() … -
Websocket failed in live server. WebSocket connection to 'wss://www.my_domain.com:8001/' failed:
This is the error and maybe solving this will solve the problem of websocket failing. Anyone has an idea about this error? Thank you. May 12 06:44:43 ubuntu-s-4vcpu-8gb-sgp1-01 python[1753]: return any( May 12 06:44:43 ubuntu-s-4vcpu-8gb-sgp1-01 python[1753]: File "/home/django/Projects/env/lib/python3.8/site-packages/channels/security/websocket.py", line 74, in <gene> May 12 06:44:43 ubuntu-s-4vcpu-8gb-sgp1-01 python[1753]: pattern == "*" or self.match_allowed_origin(parsed_origin, pattern) May 12 06:44:43 ubuntu-s-4vcpu-8gb-sgp1-01 python[1753]: File "/home/django/Projects/env/lib/python3.8/site-packages/channels/security/websocket.py", line 98, in match> May 12 06:44:43 ubuntu-s-4vcpu-8gb-sgp1-01 python[1753]: parsed_pattern = urlparse(pattern.lower(), scheme=None) May 12 06:44:43 ubuntu-s-4vcpu-8gb-sgp1-01 python[1753]: File "/usr/lib/python3.8/urllib/parse.py", line 376, in urlparse May 12 06:44:43 ubuntu-s-4vcpu-8gb-sgp1-01 python[1753]: splitresult = urlsplit(url, scheme, allow_fragments) May 12 06:44:43 ubuntu-s-4vcpu-8gb-sgp1-01 python[1753]: File "/usr/lib/python3.8/urllib/parse.py", line 430, in urlsplit May 12 06:44:43 ubuntu-s-4vcpu-8gb-sgp1-01 python[1753]: scheme = scheme.replace(b, "") May 12 06:44:43 ubuntu-s-4vcpu-8gb-sgp1-01 python[1753]: AttributeError: 'NoneType' object has no attribute 'replace' -
Forbidden (CSRF token missing or incorrect.): /
So i want to make models form to upload file mp3. I was copy the code from website, but suddenly it goes error. Here's error message on the website : Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: CSRF token missing or incorrect. In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure: Your browser is accepting cookies. The view function passes a request to the template's render method. In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL. If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data. The form has a valid CSRF token. After logging in in another browser tab or hitting the back button after a login, you may need to reload the page with the form, because the token is rotated after a login. You're seeing the help section of this page because you have DEBUG = True in your Django … -
How to consume TokenAuthentication based user authentication built in DRF in Django web application
I have created a WebAPI for user authentication using Token Authentication built on Django Rest Framework. with the help of Postman I am able to determine that my user is being created, authenticated and logged out successfully. I have created a Django web application and have successfully consumed the WebAPI endpoints which do not require authentication in my HTML files. Now I wish to create user Login/Logout functionality and since I am new to the subject, I don't know how to do this. Please help? a link to a tutorial would be appreciated Regards, Arun -
How can I import the file in Django from a folder without Errors
Can someone help me with my problem? I have the following project structure: check_project --- check_app --- check_project --- modules --- __init__.py --- tools.py --- robots.py I need to import my tools.py file inside robots.py And here is the problem. If I import it this way from tools.py import * I can run the file inside Visual Studio Code and it works. But when I run Django it gives an Error: "ModuleNotFoundError: No module named 'tools'" And if I import it this way from modules.tools.py import * Django works fine. But when I run the file inside Visual Studio Code it gives Error: "ModuleNotFoundError: No module named 'modules'" How can I fix this problem so, that it would work both in Django and in Visual Studio? Thank you for your help ) -
Can I turn the form on and off in Django via the admin panel?
I am currently doing a restaurant website with Django and have a reservation form there in the form of a contact form. My question is whether I can control via the admin panel whether the form is displayed on the website and not?