Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how can I create a Like button with generic relations?
*class Like(model.Models) object_content_type = models.ForeignKey( ContentType, blank=True, null=True, related_name='object_notifications', on_delete=models.CASCADE,) object_id = models.CharField(max_length=50, blank=True, null=True) action_object = GenericForeignKey('object_content_type', 'object_id')* this is my class that i saw in django documentions but i need a full code explain for views.py and templates, =) -
Django Migration Error With MSSQL Database With Schemas
I just start to create the settings for Django backend (All in Python). I use MS SQL and I run my django in Linux to connect to MSSQL. After setting the databases specifications, I run into the following error. Given that my database has more than schemas, I assume i have to tell django which schema to use in the database, but i fail to find the right place. Any ideas ? My settings: DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'MyDB', 'HOST': '********', 'PASSWORD': '**************', 'AUTOCOMMIT': True, 'USER': 'root', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', }, }, }``` Error: ```django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table (('42000', "[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Hello there. It looks like you're trying to create an object without specifying a schema name. Please create in a named schema, eg schemaname.tablename\r\n\t (50000) (SQLExecDirectW)"))``` -
Javascript file incorrect? Django
I am writing a Django website. I am trying to use a JavaScript file to move a mobile nav bar into the page when clicking on the burger icon. I have successfully loaded a JavaScript file from the static folder. (I checked with the alert function.) However, once I write more code in the JavaScript file, the JavaScript file doesn't work and I don't get the alert "Hello, javascript file loaded" upon refreshing the website page. Is my javascript incorrect? Is the format incorrect for use in Django? Any help would be much appreciated, thanks for reading. App.js alert("Hello, javascript file loaded"); const navSlide = () => { const burger = document.querySelector('.burger'); const nav = document.querySelector('.nav-links'); burger.addEventListener('click', () = > { nav.classList.toggle('nav-active'); }); } navSlide(); Base.html {% load static %} <html> <head> <title>Pep Genie</title> <link rel="stylesheet" type="text/css" href="{% static 'genie/style.css' %}"> </head> <body> {% block content %}{% endblock %} <script src="{% static 'genie/app.js' type="text/javascript" %}"></script> </body> </html> Index.html {% extends 'genie/base.html' %} {% block content %} <nav> <div class="logo"> <h4>The Logo</h4> </div> <ul class="nav-links"> <li> <a href="#">Home</a> </li> <li> <a href="#">About</a> </li> <li> <a href="#">Work</a> </li> <li> <a href="#">Our Projects</a> </li> </ul> <div class="burger"> <div class="line1"></div> <div class="line2"></div> <div class="line3"></div> … -
Django FileField Multiple data uploading is not working
i want to upload multiple files from Django FileField. The code below upload single file instead of multiple files. i also define attr for multiple files in forms.py. The form is only save single file in database when i try to add multiple item in FileField. I would be grateful for any help. models.py class Article(models.Model): title = models.CharField(max_length=300) file_data = models.FileField(upload_to='stories', blank=True, null=True) author = models.ForeignKey(User, on_delete=models.CASCADE) forms.py class ArticleForm(forms.ModelForm): file_data = forms.FileField(required=False, widget=forms.FileInput( attrs={'accept': 'image/*,video/*', 'multiple': True})) class Meta: model = Article fields = [ 'title', 'file_data', ] views.py class NewsCreateView(CreateView): form_class = ArticleForm template_name = 'create.html' success_url = '/' def form_valid(self, form): # check author validation form.instance.author = self.request.user return super().form_valid(form) -
(internal error) Ngnix + uwsgi +django : no module named django
So im trying to deploy a django app with nginx and uwsgi , ngnix is running well and the django app is working well with manage.py runserver , but when i try to deploy it with uwsgi it said Internal Server Error , and when i check my uwsgi logs that what i get (No module named django) the virtualenv python version is 3.6.9 ,i'dont know if this error is caused because of imcompatibilty with python version of virtual environement and the Uwsgi one or just because i missed somethings , my uwsgi specs are this is my uwsgi ini file : [uwsgi] vhost = true plugins = python socket = /tmp/mainsock master = true enable-threads = true processes = 4 wsgi-file = /var/www/PTapp-launch/ptapp/wsgi.py virtualenv = /var/www/venv/site chdir = /var/www/PTapp-launch touch-reload = /var/www/PTapp-launch/reload env = DJANGO_ENV=production env = DATABASE_NAME=personal_trainer env = DATABASE_USER=postgres env = DATABASE_PASSWORD=teemo1313 env = DATABASE_HOST=localhost env = DATABASE_PORT=5432 env = ALLOWED_HOSTS=141.136.36.27 -
django Datefield is taken as UTC even though I have set it to 'Asia/Kolkata' in postgresql but in DateTimeField is taken time 'Asia/Kolkata' why
My Models saleDate = models.DateField(auto_now_add=True) #this field taken UTC saleTime = models.DateTimeField(auto_now_add=True) #this field taken 'Asia/Kolkata Settings.py LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Calcutta' USE_I18N = True USE_L10N = True USE_TZ = True using AWS Mumbai Region -
NestedSimpleRouter without using lookup in router
I am using drf-nested-router something like the following in my url.py router = SimpleRouter() profile_router = routers.NestedSimpleRouter(router, r'profile', lookup='user') profile_router.register(r'comments', UserCommentViewSet, basename='profile-comments') The viewset is class UserCommentViewSet(CommentViewSet): def get_queryset(self): return Comment.objects.filter(owner=self.request.user) So the URL is something like, mydomain.com/profile/{profile_id}/comments/ it gives me right results. But the following URL is also giving me right results, mydomain.com/profile/{anything}/comments/ because I am using the session user info to filter the data. Is it possible to make the URL like mydomain.com/profile/comments/ Thanks in Advance. -
Looking for suggestions... Which language/framework should I use for my project?
For a project in my mind -and to learn while doing- I have to choose a language / framework and start learning. My goal is to quickly create a mvp that looks good and has basic functions. I have good command of basic programming concepts. I know html and css, but I'm not very dominant, but I can reveal what I want by looking at the documentation. I know basic sql queries. I don't have any experience in js or php. I have been building many websites with wordpress for a long time, but of course it is not useful for this project. Hosting part is not an issue for me, I can host the project on my home server or on the AWS. There will be simple crud operations in the project; Create product / service / user profiles Listing and filtering within these profiles Matching between profiles Send requests to matching services (all or selected) (can be via email) As a result of my rapid research, django one came out, but I am not sure if the learning process will take a long time. I learned php in college years ago, I am not thinking whether to try … -
Django: tinymce HTML format
I just installed django-tinymce however when I display the content I'm getting HTML format. How can I fix this? Something <p>Some <strong>random </strong>text 123 123 123 <strong><br /></strong></p> admin -
Django ManyToManyField Persistence Fails
I have a simple Django 3.1.0 app I need to create in order to assign Tasks with Tags (or assign tags into tasks). My Model class Task(models.Model): user = models.CharField(max_length=33) time = models.DateTimeField(auto_now_add=True) task = models.CharField(max_length=500) tags = models.ForeignKey('Tag', on_delete=models.SET_NULL, null=True) class Tag(models.Model): tag = models.CharField(max_length=30, default="No Tag") members = models.ManyToManyField('Task') class Meta: verbose_name = "tag" verbose_name_plural = "tags" My Form class TaskForm(ModelForm): class Meta: model = Task fields = ['user', 'task', 'tags'] template_name = 'tasks.html' tags = ModelMultipleChoiceField( queryset=Tag.objects.values().all(), widget=CheckboxSelectMultiple() ) My View def main(request): model = Task.objects.values().all() form = TaskForm() con = {'context': list(model), 'form': form} if request.method == 'POST': form = TaskForm(request.POST) if form.is_valid(): obj = form.save(commit=False) form.save_m2m() return redirect('/') else: form = TaskForm() return render(request, "tasks.html", con) The migrations are successfull, and with the above code, the view shows a checkbox list with the fetched tags, but the problem is that when I hit Submit on the form, the values are not saved/written on the database but the page reloads successfully. However, if I turn the following: obj = form.save(commit=False) form.save_m2m() into form.save(commit=True) #form.save_m2m() the values are written only from the fields 'user', 'task' - without the 'tags' It's also funny that what fetches back on … -
Django html Check form type
I'm trying to build an html page in Django, where depending on the form passed the page will render different things. How can I know in the HTML the type of form passed? I want to do something like this: {% block content %} <div class="content-section container" > {% if form.type == 'ModelAForm' %} <div class="content-section"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.driver_color }} </form> </div> {% endif %} {% if form.type == 'ModelBForm' %} <div class="content-section"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.driver_name}} </form> </div> {% endif %} </div> {% endblock content %} On the {% if form.type == 'ModelAForm' %} how can I know the form type? -
Class 'Post' has no 'objects' memberpylint(no-member)
I am new in django and was following a tutorial to learn. This is the tutorial https://tutorial.djangogirls.org/en/django_templates/. #This is the views.py #enter image description here from django.shortcuts import render from django.utils import timezone from .models import Post def post_list(request): posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, 'blog/post_list.html', {'posts': posts}) -
What happens when only 1 product available and 2 user clicks buy now
I am doing an online shopping site. I need to know that if only 1 stock available for a product and 2 user clicks buy now at same time. How to deal such a scenario -
Django ORM QuerySet with Aggregation Max function
I tried to Convert the SQL command: SELECT fname,lname FROM customer WHERE id > (SELECT max(id) FROM customer WHERE state = 'TX'); to an ORM (Django) QuerySet. At my first try I use: Customer.objects.filter(id__gt=Customer.objects.filter(state='TX').values('id')).values('fname','lname') But it gave me the wrong output (I compare with the raw sql query) So, I learn more and achieve the following: Customer.objects.filter(id__gt=Customer.objects.filter(state='TX').values('id').aggregate(Max('id'))['id__max']).values('fname','lname') I'm a junior so think to address SO for the following two questions: I have two questions: What happens in the first QuerySet, that output the wrong results ? (It doesnt crash) The QuerySet with the correct result, is long and complex in comparison to the SQL raw query. Is it the correct QuerySet ? Can I achieve the same result with a more simple QuerySet ? Thanks ! -
tinymce form doesn't show in Django
I have a form which I want one field to be a tinymce field and after I add {{form.media}} to the template it doesn't show the form. forms.py: from tinymce.widgets import TinyMCE class ArticleCreationForm(forms.ModelForm): class Meta: model = Article fields = ('title','description', 'text') exclude = ['votes', 'author'] widgets = { 'text' : TinyMCE(attrs={'cols': 80, 'rows': 10,'class': 'form-control'}), } I use django-tinymce and I do exactly as it says in the docs. -
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 460: invalid continuation byte
i've got a problem with the command "loaddata" of my django app. when i run this command, this UnicodeDecodeError appears because of the "é" that are in my database table. i've try with many type of database on pgAdmin with different encode type like "UTF-8", "latin-1" or "win1252" or different "character type" or "collation" settings like "C" or "french_switzerland.1252" but everytime there is this error. i give you few more informations about my work space. say it to me if you need more informations, i don't give you too much, i don't want to give useless one. thank you i am on windows 10 i'm using pycharm 2020.3.2 pgadmin v4 the complete error : `` (venv) C:\Users\Mathias\PycharmProjects\yufindProject>python manage.py loaddata ask/dumps/ask.json Traceback (most recent call last): File "manage.py", line 22, in main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Mathias\PycharmProjects\yufindProject\venv\lib\site-packages\django\core\management_init_.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Mathias\PycharmProjects\yufindProject\venv\lib\site-packages\django\core\management_init_.py", line 395, in execut self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Mathias\PycharmProjects\yufindProject\venv\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Mathias\PycharmProjects\yufindProject\venv\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Users\Mathias\PycharmProjects\yufindProject\venv\lib\site-packages\django\core\management\commands\loaddata.py", line 72, in handle self.loaddata(fixture_labels) File "C:\Users\Mathias\PycharmProjects\yufindProject\venv\lib\site-packages\django\core\management\commands\loaddata.py", line 114, in loaddata self.load_label(fixture_label) File "C:\Users\Mathias\PycharmProjects\yufindProject\venv\lib\site-packages\django\core\management\commands\loaddata.py", line 172, in load_label for obj in objects: File "C:\Users\Mathias\PycharmProjects\yufindProject\venv\lib\site-packages\django\core\serializers\json.py", line 67, in Deserializer … -
how to send a message and wait for a reply in python, twilio in whatsapp
i want to take the details of a person on whatsapp and store it but it seems its not working as i want it. its not waiting for the user to input the first data before the second one coming. this is my #models.py class student_Account(models.Model): name = models.CharField(max_length = 30) place_of_stay = models.CharField(max_length = 30) def __str__(self): return self.name and this is my views.py @csrf_exempt def sms(request): incoming_msg = request.POST.get('Body', '').lower() resp = MessagingResponse() msg = resp.message() msg1 = resp.message() if 'hi' in incoming_msg: reply = ("Hello and welcome to kkk banking system WhatsApp bot!\n\n" "What would you like to do\n" "1. Create an accout?\n" "2. Check your account balance\n") msg.body(reply) if incoming_msg == '1': reply = ("Enter your name") a = incoming_msg student.name = a reply = ("Enter your place of stay") b = incoming_msg student.place_of_stay = b msg.body(reply) student.save() reply = ("Your details has been saved!!.") msg.body(reply) -
What would I miss, if I don't use any authentication in django and login the user using django query filter with a manually hashed password
I have seen the default user authentication and custom user uathentication in django, I would like to know what would I be missing if I just login a user by using a normal query like, ____.objects.get(password = ______, email = ______) and just hash the password stored in the model column.And store the login details in session and clear them on logout. Would it ruin the security altogether or is it something else I wouldn't get which is found in the normal django authentication? -
Why TabularInline looks different on differen sites. How to control its apperence
I have 2 different registers on my admin panel and on one TabularInline allows multiple choice: and on another not: They are created absolutely the same way: class GenreInlineAdmin(admin.TabularInline): model = FilmWork.genre.through class PersonInlineAdmin(admin.TabularInline): model = Person.movie.through Where does the difference come from? How can I control it? -
Booking system for fitness / gym company - Where to store booking data, what django-models should I use?
I have to make (high school project) booking/reservation system for fitness / gymnastics service company. Users (clients) can have: tickets - for 1 hour (on 1 day) - "single ticket" subscription - 1 hour a day for one, two or three months. Overall, I have some idea how to make this application, but only need help with choosing best / optimal Django model for storing booking / reservation information. Assuming that there can be maximum N ( N ~ 15) persons in fitness club at the same time, I can sell limited number of tickets and subscriptions for particular day/hour. Where (what Django model suits best) should I store booking / reservation informations, For example: User No. 0001 is taking fitness at Monday, 25 January, 2021, 5 pm to 6 pm (single ticket) User No. 0002 is taking fitness at Friday, 30 January, 2021, 11 am to 12 am (single ticket) ..... User No. 0055 is taking fitness every weekday from 3 pm to 4 pm for whole January and February (subscription) ..... etc. What Django model do You recommend in my case? -
Django and Heroku - Migration is applied before its dependency
I'm having trouble getting my Django web app from a local server to Heroku. To try and troubleshoot I created a new app from scratch and managed to push that through to Heroku with no problems. The issue comes when I add class User(AbstractUser): pass to models.py, then run makemigrations and migrate. The error is: django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency mainapp.0001_initial on database 'default'. One thing that might be causing it is that I'm using sqlite3 on localhost then Postgres on the Heroku server (although I'm not advanced enough to know if that is actually the problem!) Also my gitignore file contains: /venv __pycache__ db.sqlite3 mainapp/static/ Should it also include the migrations folder? Any help or ideas would be appreciated! Full traceback is: remote: Traceback (most recent call last): remote: File "manage.py", line 22, in <module> remote: main() remote: File "manage.py", line 18, in main remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute remote: self.fetch_command(subcommand).run_from_argv(self.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 330, in run_from_argv remote: self.execute(*args, **cmd_options) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 371, in execute remote: output = self.handle(*args, **options) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 85, in wrapped remote: res = … -
Jinja .css template logic
I am wiring my framework to wagtail. It is a custom module css framework called reely.io that is made for Hubspot. It has jinja variables for breakpoints, colors, etc. one of the variables is a multiplier for padding and margin settings. I have the css file set up and coming through to the template. the issue is with any logic in the css file: {{ spacing_multiplier * 1 + 'px' }} {{ break_sm + 30 + 'px' }} Yes, this works in Hubspot's HubL, which I always considered a derivative of Jinja, but the syntax is a bit different. am I doing it wrong? views.py from django.views.generic import TemplateView class Themes(TemplateView): template_name = "css/reely.css" content_type = "text/css" def get(self, request, *args, **kwargs): context = self.get_context_data(**kwargs) ''' Responsive Breaks ''' context["break_xl"] = 1773 context["break_lg"] = 1292 context["break_md"] = 768 context["break_sm"] = 576 context["break_xs"] = 396 ''' Spacing Multiplier ''' context["spacing_multiplier"] = 10 ''' Font ''' context['google_font_link'] = "https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@300;400;600;700&display=swap" context['font_family_1'] = "'IBM Plex Sans', sans-serif;" ''' Color Set 1 ''' context["primary_color"] = '#333333' '''rgb(51,51,51)''' context["secondary_color"] = '#555555' '''rgb(85,85,85)''' context["tertiary_color"] = '#FFFFFF' '''rgb(255,255,255)''' ''' Color Set 2 ''' context["primary_font_color"] = '#333333' '''rgb(51,51,51)''' context["secondary_font_color"] = '#555555' '''rgb(85,85,85)''' context["tertiary_font_color"] = '#FFFFFF' '''rgb(255,255,255)''' ''' Color Set … -
Django website is in constant loading and it doesn't show anything
I don't know what's happening but the website doesn't load correctly. This is the following traceback of the error. I've put everything correctly, the static tags, the img static tags for them to work on Django and it still doesn't load. Any help I would really appreciate it! Thank you: Django version 3.1.3, using settings 'ecommerce.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Not Found: /custom/js/mresto.js Not Found: /custom/js/select2.js [23/Jan/2021 13:07:15] "GET /custom/js/select2.js HTTP/1.1" 404 2163 [23/Jan/2021 13:07:15] "GET /custom/js/mresto.js HTTP/1.1" 404 2160 Not Found: /vendor/select2/select2.min.js [23/Jan/2021 13:07:15] "GET /vendor/select2/select2.min.js HTTP/1.1" 404 2190 Not Found: /custom/js/js.js Not Found: /vendor/vue/vue.js [23/Jan/2021 13:07:15] "GET /custom/js/js.js?id=1.9.7 HTTP/1.1" 404 2157 Not Found: /vendor/axios/axios.min.js [23/Jan/2021 13:07:15] "GET /vendor/vue/vue.js HTTP/1.1" 404 2154 [23/Jan/2021 13:07:15] "GET /vendor/axios/axios.min.js HTTP/1.1" 404 2178 Not Found: /vendor/flatpickr/flatpickr.js Not Found: /custom/js/notify.min.js Not Found: /custom/js/rmap.js [23/Jan/2021 13:07:15] "GET /vendor/flatpickr/flatpickr.js HTTP/1.1" 404 2190 [23/Jan/2021 13:07:15] "GET /custom/js/notify.min.js HTTP/1.1" 404 2172 [23/Jan/2021 13:07:15] "GET /custom/js/rmap.js HTTP/1.1" 404 2154 Not Found: /default/logo_qrzebra.png [23/Jan/2021 13:07:15] "GET /default/logo_qrzebra.png HTTP/1.1" 404 2175 Not Found: /manifest.json [23/Jan/2021 13:07:16] "GET /manifest.json HTTP/1.1" 404 2142 Not Found: /serviceworker.js [23/Jan/2021 13:07:18] "GET /serviceworker.js HTTP/1.1" 404 2151 [23/Jan/2021 13:07:24] "GET / HTTP/1.1" 200 37802 Traceback (most recent call last): File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\wsgiref\handlers.py", … -
How to load form content into a table, and then save this content in a database
Hello guys. I have a template in Django that has a form. When I hit the Submit button, I need to load this data into a table, without loading it into a database at the moment. Then, in the table I have another button that has to validate that information from the table and if it is correct then it has to save it in a database. Do you have any idea how to do it? Thank you all. -
DigitalOcean django application with Gunicorn and Nginx issue
I am having an issue getting my gunicorn service to boot. I am working in digitalocean droplet. gunicorn.service: [Unit] Description=Gunicorn daemon for Django Project Before=nginx.service After=network.target [Service] WorkingDirectory=/home/django/papayas/ ExecStart=/home/django/papayas/env/bin/gunicorn --bind unix:/home/django/gunicorn.socket --config /etc/gunicorn.d/gunicorn.py config.wsgi:application User=django Group=django [Install] WantedBy=multi-user.target error: ● gunicorn.service - Gunicorn daemon for Django Project Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Sat 2021-01-23 11:50:27 UTC; 2s ago Process: 16563 ExecStart=/home/django/papayas/env/bin/gunicorn --bind unix:/home/django/gunicorn.socket --config /etc/gunicorn.d/gunicorn.py config.wsgi:application (code=exited, status=1/FAILURE) Main PID: 16563 (code=exited, status=1/FAILURE) DigitalOcean gives you a project that is working and that gunicorn.service is: [Unit] Description=Gunicorn daemon for Django Project Before=nginx.service After=network.target [Service] WorkingDirectory=/home/django/django_project ExecStart=/usr/bin/gunicorn3 --name=django_project --pythonpath=/home/django/django_project --bind unix:/home/django/gunicorn.socket --config /etc/gunicorn.d/gunicorn.py django_project.wsgi:application Restart=always SyslogIdentifier=gunicorn User=django Group=django [Install] WantedBy=multi-user.target I have been trying to fix this for days now. I don't know what to do anymore. please help.