Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
my tag isn't working with my if statement in my template
So I am trying to display a badge notifier on my inbox only if I have > 0 messages. For some reason, my if statement isn't working. I'm not sure if it's a syntax issue or if my logic is wrong. I am returning a count of my messages, which is displaying and working correctly. I simple want to run my if statement on that count. base.html/ message counter part {% if unread_messages > 0 %} <li> <a ref = 'stylesheet' href="{% url 'dating_app:conversations' user.id %}" type="text/css" class="notification"> <span>Inbox</span> <span class="badge">{% unread_messages request.user %}</span> </a> </li> {% else %} <li> <a ref = 'stylesheet' href="{% url 'dating_app:conversations' user.id %}"> <span>Inbox</span> </a> </li> {% endif %} unread_messages_counter.py @register.simple_tag def unread_messages(user): return user.receiver.filter(viewed=False).count() -
How to make an API call with user input from Django template
I want to make a call to the Yelp API using zip code that the user inputs. I do not need to save this zip code in a database or anything, simply use it to make the call. yelp.py (the "location" parameter would be the zip code) def get_name(location): """ makes call to Yelp API and returns list of establishments within the given zip code """ restaurants = [] url = 'https://api.yelp.com/v3/businesses/search' params = { 'location': f'{location}' } headers = {'Authorization': f'Bearer {YELP_KEY}'} response = requests.get(url, params=params, headers=headers).json() for business in response['businesses']: restaurants.append(business['name']) return restaurants homepage.html <form method="POST" action="{% url 'homepage' %}"> {% csrf_token %} {{ new_zip_form }} <button type="submit">Add</button> </form> {% for city in cities %} <div> {{ city.zipCode }} </div> {% empty %} <p>There are no cities</p> {% endfor %} forms.py from django import forms class get_zip(forms.Form): zip_code = forms.CharField(required=True, label='Zip Code', max_length=5) views.py import requests from django.shortcuts import render from .forms import get_zip def homepage(request): new_zip_form = get_zip() return render(request, 'restroom_rater/homepage.html', { 'new_zip_form': new_zip_form}) models.py from django.db import models class Establishment(models.Model): name = models.CharField(max_length=200, blank=False) city = models.CharField(max_length=200, blank=False) state = models.CharField(max_length=2, blank=False) def __str__(self): return f'Establishment name: {self.name} in {self.city}, {self.state}' I feel like I have … -
How to fix pip in terminal?
Hello everyone I just started a Django tutorial today and and in order for me to follow along i had to update the version of python on my computer, sadly after updating it the pip command in the terminal no longer works, when trying to use the pip freeze command an error occurs, I have done some research on how to fix the problem but, it seems that i must have a wrong path or I might have installed something i should not have as, just starting out it would be grateful if someone could help me solve this problem so I could get back to work as soon as possible. Bellow is the error message that appears on the terminal. ERROR:root:code for hash md5 was not found. Traceback (most recent call last): File "/usr/local/Cellar/python@2/2.7.15_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module> globals()[__func_name] = __get_hash(__func_name) File "/usr/local/Cellar/python@2/2.7.15_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor raise ValueError('unsupported hash type ' + name) ValueError: unsupported hash type md5 ERROR:root:code for hash sha1 was not found. Traceback (most recent call last): File "/usr/local/Cellar/python@2/2.7.15_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module> globals()[__func_name] = __get_hash(__func_name) File "/usr/local/Cellar/python@2/2.7.15_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor raise ValueError('unsupported hash type ' + name) ValueError: unsupported hash type sha1 ERROR:root:code … -
Django Polls Project: Reverse for 'polls.index' not found
I'm trying to finish my Django Polls Project from the Django Documentation but I ran into the "Reverse for 'polls.index' not found. 'polls.index' is not a valid view function or pattern name." error. The full error details can be seen here The following are my files. base.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous" /> <title>Pollster {% block title %}{% endblock %}</title> </head> <body> <div class="container"> <div class="row"> <div class="col-md-6 m-auto"> {% block content %}{% endblock %} </div> </div> </div> </body> </html> index.html {% extends 'base.html' %} {% block content %} <h1 class="text-center mb-3">Poll Questions</h1> {% if latest_question_list %} {% for question in latest_question_list %} <div class="card mb-3"> <div class="card-body"> <p class="lead">{{ question.question_text}}</p> <a href="{% url 'polls:detail' question.id %}" class="btb btn-primary btn-sm">Vote Now</a> <a href="{% url 'polls:results' question.id %}" class="btb btn-secondary btn-sm">Results</a> </div> </div> {% endfor %} {% else %} <p>No polls available</p> {% endif %} {% endblock %} mysite.urls from django.contrib import admin from django.urls import include, path urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] polls.urls from django.urls import path from . import views #from ALL import views app_name = 'polls' urlpatterns = [ path('', views.index, name='index'), … -
I am trying to delete a user from the django database but there ir a IntegrityError at /admin/auth/user/ error occurs
I want to delete a user from the database that django comes with, i entered the admin site using my superuser but when i try to delete any user manually, which i created for testing purposes, it gives the error y mentioned above. These is my model from django.db import models from django.contrib.auth.models import User # Create your models here. class UserRegister(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) first_name = models.CharField(max_length=256, default='', blank=False,) last_name = models.CharField(max_length=256, default='', blank=False) email = models.EmailField(unique=True, blank=False,default='') def __str__(self): return self.user.username This is my form from django import forms from .models import * from django.contrib.auth.models import User #Create your forms here! class UserRegisterForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta(): model = User fields = ('username','password') class UserRegisterInfoForm(forms.ModelForm): class Meta(): model = UserRegister fields = ('first_name','last_name','email') This is my view def UserRegisterFormView(request): registered = False if request.method == 'POST': userform = UserRegisterForm(data=request.POST) userinfoform = UserRegisterInfoForm(data=request.POST) if userform.is_valid() and userinfoform.is_valid(): user = userform.save() user.set_password(user.password) user.save() profile = userinfoform.save(commit=False) profile.user = user profile.save() registered = True else: print(userform.errors, userinfoform.errors) else: userform = UserRegisterForm userinfoform = UserRegisterInfoForm return render(request,'register/register.html'{'userform':userform,'userinfoform':userinfoform,'registered':registered}) -
How to deploy multi Django projects with same IIS 80 port?
I have a Django project running with IIS8 on 80 port. Now, i am going to deploy another Django projects. May i know how could i deploy multi Django projects with same IIS 80 port? -
Django : How can i set editable = False all field with empty value
How can i hide field with empty value in change view. i have groupe of permission goup1 and group 2 and group 3 group 1 : permission = can edit + can add + can view + can delete group 2 : permission = can edit + can dd group 3 permission = can view the problem is in group3 , i have empty field (file field or charfield ...) i need to hide theme to group3 so the group can see juste field with value and not the empty (se image example) i need to hide the empty field ,it's dynamic field , id'ont have the same fields always ,maybe one maybe more file field also , if no file , so they must be hiden Admin.py class AnnexeCooperationBilateraleInline(admin.StackedInline): model = Annexe extra = 1 #formset = RequiredInlineFormSet exclude =["cooperationMultilaterale",'am','calip'] class InstrumentJuridiqueDocCooperationBilateraleInline(admin.StackedInline): model = InstrumentJuridiqueDoc extra = 1 max_num = 1 #formset = RequiredInlineFormSet exclude =["cooperationMultilaterale",'am','calip'] class CooperationBilateraleAdmin(ManyToManyAdmin): fieldsets = [ ( '', { 'fields': ['paysPartenaires', 'instrumentJuridique',('partenaire','gouvernement','paysP','etat','adefinir'),'objet', 'axeCooperation'] }), ('Autres élements à rajouter ?', { 'fields': ['infoPlus', ] }), ('', { 'fields': [ 'acteJuridique',('dateSignature','dateEntreeVigueur' ),('duree','dureeplus5ans', 'renouvellement'), ('pays', 'villeSignature')] }), ('Base Documentaire', { 'fields': [], 'description': 'Joindre le(s) fichier(s) '}), … -
How to implement session idle timeout in DRF
I am using Django==2.2.7, djangorestframework==3.10.3 and django-oauth-toolkit==1.2.0. Below is the config for limiting age of access token, I want to know how can I timeout idle session from server side. I tried using django-session-timeout but it did not work. Please help. LOGIN_TOKEN_EXPIRE_SECONDS = 3600 * 24 * 365 OAUTH 2 PROVIDER OAUTH2_PROVIDER = { 'ACCESS_TOKEN_EXPIRE_SECONDS': LOGIN_TOKEN_EXPIRE_SECONDS, 'OAUTH_DELETE_EXPIRED' : True, 'OAUTH2_BACKEND_CLASS': 'oauth2_provider.oauth2_backends.JSONOAuthLibCore' } -
Which is the best route for becoming a Full Stack Developer?
I'm in a position where I can study full-time for the rest of 2020 but by 2021 I would need a job. My goal is to become a Full-Stack Developer. Although I'd be happy with just being a Back-End Developer. I'm more interested in Back-end Development than Front-end but I feel it's better to learn both because there are more opportunities for a Full-Stack Developer and more money. I recently completed the Python Bootcamp course Zero to Hero from Udemy and I just started the Python and Django Full Stack Web Developer Bootcamp which teaches HTML, CSS, Bootstrap, JavaScript, jQuery, Python 3, and Django. I recently came across a YouTube video from Software Engineer saying that it takes a couple years to learn HTML, CSS, JavaScript, Python 3, Django, and SQL. The guy said a better route to become a Full-Stack Developer is to fist learn SQL because it will only take 3 months to learn it and then you can get as a SQL Developer and learn the other languages will you're making my working with SQL. He mentioned that there are more SQL Developer jobs than any other of the languages. What do you guys think? Is this … -
Djanog user case insensitive
I am working in django 2.2 and I authenticate the user, using the following function user = authenticate(username=username, password=password) The problem is that, If username is James. And I type james it doesn't work because the J not capital. How can I make authenticate case insensitive in django 2.2? -
Django Huey post execution hook doesn't work
huey = RedisHuey("blah") @huey.task() def doSomething(): print("STARTING") print("ENDING") return 234 @huey.post_execute() def post_execute_hook(task, task_value, exc): print("FFFFFFFFF") This is what I have in my tasks.py in Django project currently. I followed the official doc and code sample (for django). https://huey.readthedocs.io/en/latest/shared_resources.html#pre-and-post-execute-hooks https://github.com/coleifer/huey/blob/master/examples/django_ex/djangoex/test_app/tasks.py The code perfectly works if post execution hook was to be removed entirely Otherwise, it keeps giving either of the following errors depending on whether decorators are prefixed by "huey" (as in @huey.task() for eg) "huey.exceptions.HueyException: myapp.tasks.doSomething not found in TaskRegistry" error or "ValueError: Attempting to register a task with the same identifier as existing task. Specify a different name= to register this task. "myapp.tasks.doSomething"" -
Django NoReverseMatch in production; works fine on localhost
So I recently moved my app to PythonAnywhere. The URL dispatchers were working fine on localhost. After moving to PythonAnywhere, I keep getting this error: django.urls.exceptions.NoReverseMatch: Reverse for 'blockdata' with arguments '('nameofdistrict',)' not found. 1 pattern(s) tried: ['rmgcovid/<districtid>'] districtid variable is a string and therefore my app's url.py file also represent it as a slug: url('<slug:districtid>',views.blockdata,name='blockdata') Here is the part of my template that causes the app to crash and throw the error mentioned above: <form action='{% url "blockdata" districtid %}' method="POST"> My views are ok because if I pass 200 as HttpResponse, it shows up that. But with this form action, it is unable to match the URL. I have tried solving this for a good 10 hours now. I would appreciate any help at this moment. Why is it working on local host fine but now on PythonAnywhere it crashes? Here is my project's URL snapshot as well: url(r'^customurl/',include('myappname.urls')) the customurl is replaced with my specific url -
mysql unique index on char column not getting used with IN clause
Mysql version - 5.7.22 Table definition CREATE TABLE `books` ( `id` int(11) NOT NULL AUTO_INCREMENT, `uuid` char(32) COLLATE utf8mb4_unicode_ci NOT NULL, `title` varchar(254) COLLATE utf8mb4_unicode_ci NOT NULL, `created` datetime(6) NOT NULL, `modified` datetime(6) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `book_uuid` (`uuid`), ) ENGINE=InnoDB AUTO_INCREMENT=115 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci Query SELECT DISTINCT `books`.`id`, `books`.`uuid`, `books`.`title` FROM `books` WHERE (`books`.`uuid` IN ("334222a0e99b4a3e97f577665055208e", "979c059840964934816280ba85c67221", "4e2978c765dd435998666ea3083666e5", "535aa78ba80e4215bbf75fb1e20cc5f3", "f969fb10c72b4875aabdf75c1b493524", "1daa0015055444a4b1c0821618a7a4d9", "04f34ede284a4b86b0adddb405d30a75", "513cad12c88c44c6ab248d43643459b9", "de2bde6d016f4381ad0ba714234386fa", "f645c2c9f1594a199a960b97b7015986", "3ce02c072f24447a8a7b269a19ec554f", "75450daf9d024d9d9c0df038437ae2c2", "0e822042b50b4f79bb38304e0acde6f0", "38d808fb3f9a4f57b4f7b30a141e7169", "ecd424abd3a94a339383f6f8e668655e")) ORDER BY `books`.`id` DESC LIMIT 15; when i do explain on this query it doesn't pick the index +----+-------------+-----------------+------------+------+---------------+------+---------+------+------+----------+-----------------------------+ | id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra | +----+-------------+-----------------+------------+------+---------------+------+---------+------+------+----------+-----------------------------+ | 1 | SIMPLE | books | NULL | ALL | book_uuid | NULL | NULL | NULL | 107 | 12.15 | Using where; Using filesort | +----+-------------+-----------------+------------+------+---------------+------+---------+------+------+----------+-----------------------------+ strangely the index is correctly used when there are 12 or less entries passed to the IN clause (without forcing index) forcing the index works, but I cannot force index as this query is created by django ORM, cannot use django-mysql 's force_index as I am on Innodb Note: I know 'distinct' … -
Why is Django's factory-boy trying to create a factory when I'm not asking it to?
I'm trying to use Django's factory-bot module to create factories for my models. I'm also using pytest. I have created these factories ... import factory from maps.models import CoopType, Coop from address.models import AddressField from phonenumber_field.modelfields import PhoneNumberField from address.models import State, Country, Locality class CountryFactory(factory.DjangoModelFactory): """ Define Country Factory """ class Meta: model = Country name = "Narnia" code = "NN" class StateFactory(factory.DjangoModelFactory): """ Define State Factory """ class Meta: model = State name = "Narnia" code = "NN" country = CountryFactory() class LocalityFactory(factory.DjangoModelFactory): """ Define Locality Factory """ class Meta: model = Locality name = "Narnia" postal_code = "60605" state = StateFactory() class AddressFactory(factory.DjangoModelFactory): """ Define Address Factory """ class Meta: model = Address street_number = "123" route = "Rd" raw = "123 Fake Rd" formatted = "123 Fake Rd." latitude = 87.1234 longitude = -100.12342 locality = LocalityFactory() class CoopTypeFactory(factory.DjangoModelFactory): """ Define Coop Type Factory """ class Meta: model = CoopType I have a very simple test file thus far. It only has one test ... import pytest from django.test import TestCase from .factories import CoopTypeFactory, CoopFactory class ModelTests(TestCase): @classmethod def setUpTestData(cls): print("setUpTestData: Run once to set up non-modified data for all class methods.") #management.call_command('loaddata', 'test_data.yaml', verbosity=0) … -
is there any way to add admin filter to a django tempalte
i want to filter the content of a page dynamically, like the filters in django admin page. i want to do something like modelForms, where i use fildes of a model in a template, but using the filter like admin page. -
django ORM subtract calculation of two model in annote
I have a complex calculation that mainly subtracts from two annotate item This is my of Meal: class Meal(models.Model): number_of_meal = models.FloatField(default=1) meal_for = models.ForeignKey( User, on_delete=models.SET_NULL, related_name='meal_entry_for', ) and this my Purchase class Purchase(models.Model): amount = models.DecimalField( max_digits=6, decimal_places=2, default=0.00 ) entry_for = models.ForeignKey( User, on_delete=models.CASCADE, related_name='ledger_entry_for', ) This is my current query and working good till now meal = Meal.objects.all() purchase = Purchase.objects.all() total_purchase = Purchase.objects.aggregate(total_purchase=Sum('amount')) total_meal = Meal.objects.aggregate(total_meal=Sum('number_of_meal')) cost_per_meal = float(total_purchase['total_purchase']) / float(total_meal['total_meal']) user_wise_meal_cost = User.objects.annotate( total_meal_cost=Coalesce(Sum('meal_entry_for__number_of_meal'), Value(0)) * cost_per_meal ) user_wise_payable_receivable = User.objects.annotate( receivable_payable=Coalesce(Sum('ledger_entry_for__amount'), Value(0)) ) I am trying subtract user_wise_meal_cost from this calculation Coalesce(Sum('ledger_entry_for__amount'), Value(0)) in user_wise_payable_receivable I mean, I want to determine which user needs to pay or receive how much. a user total purchase from user total meal cost will be minimized. it's simple business logic. Can anyone help to achieve which user needs pay how much and which user needs to get how much based on their purchase on meal consume? -
How to access an extra field in an m2m intermediary table from my admin model?
I have two models Tender and Status joined in a M2M relationship by a bridge table TenderStatus. The bridge table has an extra date field in it. I'm using an inline for the admin form. But I want to be able to display the date from the intermediary table in the admin view. I can access the name of the Status, so I can easily show a comma-separated list of statuses for example, but I cannot figure out how to access the date field. I've tried using a callable in the admin class to no avail (I think I just don't know how to access the date field from the callable). I also created a custom str function for TenderStatus, but it doesn't seem to pay attention to that. Here's the code I have so far: models.py class Tender(models.Model): name = models.CharField(max_length=255) tender_status = models.ManyToManyField( 'Status', through='TenderStatus', related_name='tender_status' ) class Meta: managed = False db_table = 'tender' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def __str__(self): return self.name class TenderStatus(models.Model): tender = models.ForeignKey('Tender', on_delete=models.DO_NOTHING, blank=True, null=False) status = models.ForeignKey('Status', on_delete=models.DO_NOTHING, null=False,) date = models.DateField(blank=True, null=False) def __str__(self): return str(self.date) + ': ' + str(self.status) class Meta: managed = False db_table = … -
Returning to post/<slug:pk_slug>/ once comment has been deleted
I can delete comment 52 (see screenshot below). My difficulty is then taking the user back to the page localhost:8000/post/8/. I am currently using return render(request, 'blog/home.html') as a temporary solution while I figure out the answer to my problem. I have included my code for views.py, I have a hash (#) in front of most of the lines of code. That represents my multiple failed attempts. views.py def delete_own_comment(request, pk): #template_name = 'post_detail.html' comment = get_object_or_404(Comment, id=pk) #comments = Comment.objects.filter(post=post.id ,active=True) #comment_form=CommentForm() #post = Post.objects.filter(id=8).first() comment.delete() return render(request, 'blog/home.html') #return HttpResponseRedirect(reverse('post_detail', kwargs={'pk_slug':comment.post})) #return redirect('post_detail', pk=comment.post.id) #return render(request, template_name, {'comment_form': comment_form}) #'comments': comments, urls.py path('post/<slug:pk_slug>/', views.post_detail, name='post-detail'), models.py # Create your models here. class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now()) author = models.ForeignKey(User, on_delete=models.CASCADE) url = models.SlugField(max_length=500, blank=True) def save(self, *args, **kwargs): self.url= slugify(self.title) super().save(*args, **kwargs) def __str__(self): return self.title def get_absolute_url(self): #return reverse('article_detail', kwargs={'slug': self.slug}) return reverse('post-detail', kwargs={'pk_slug': self.slug}) class Comment(models.Model): #The foriegn key is linked to the ID field in the Post model #id = models.IntegerField(primary_key=True, blank=False) post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created_on= models.DateTimeField(default = timezone.now()) active = models.BooleanField(default=True) url= models.SlugField(max_length=500, blank=True) #id = models.AutoField(primary_key=True) class Meta: … -
Django: How to reset single model/class database in app managing several different classes?
Can django delete/erease/clean data of single database/class in an app managing more disjunctive classes? Or is it safer to build separate app for each separate/disjunctive database? I have found how to delete all data from all project databases, i.e.: python manage.py flush I was only surpruised that user IDs and class IDs have not been reset to 1, but previously used ID numbers stayed somewhere in project memory. I have also found that it is possible to delete/clean all databases of signle app, e.g. here or here. python manage.py migrate <app> zero Here even IDs were reset. Does somebody know how to reset user IDs to start again from number 1? But nowhere, I have found how to delete/erase/clean/reset signle database/class of the app with more than one database. I have only found for ruby that there it could be possible like: Model.delete_all or Model.destroy_all But nobody confirmed there, that commads really work. Will/Can it work also in django? Kind regards, Rene -
Migrating geodjango postgis database to Heroku
My issue: I have deployed my first django app on Heroku. The app uses a postgis database. I can see a database exists , but I cannot access the content through admin, or the app. I wonder what I have done wrong or missed/if there is a standard way to link postgis database with app? What I have tried: -ran heroku run python manage.py migrate -used dj_database_url have the following lines at the bottom of my settings: import dj_database_url DATABASES['default'] = dj_database_url.config(conn_max_age=600, ssl_require=True) DATABASES['default']['ENGINE'] = 'django.contrib.gis.db.backends.postgis' -this link, and this link which both tell me to create extension postgis $ heroku pg:psql create extension postgis; Would appreciate any hints! -
Pass Model Field Value Via a URL in Django Using FormView
I have two different views that work together. A Formview and a ListView. They are working fine. Here is my HTML: <form method="GET" autocomplete=off action="{% url 'Book:book_by_name_list' %}"> <div> {{ form.dropdown }} </div> <button type="submit" class="button1">Submit</h3></div></button> </form> Here is my FormView: class BookByNameView(LoginRequiredMixin,FormView): form_class = BookByNameForm template_name = 'book_by_name.html' def get_form_kwargs(self): kwargs = super(BookByNameView, self).get_form_kwargs() kwargs['user'] = self.request.user return kwargs Here is my Form: class BookByNameForm(forms.Form): dropdown = forms.ModelChoiceField(queryset=Book.objects.none(),required=False) def __init__(self, *args, **kwargs): user = kwargs.pop('user') dropdown = kwargs.pop('dropdown', None) super(BookByNameForm, self).__init__(*args, **kwargs) self.fields['dropdown'].widget.attrs['class'] = 'choices6' qs = Book.objects.all() self.fields['dropdown'].queryset = qs Here is the URL that I am using: url(r'^book_by_name_list/(?P<pk>\d+)/$',views.BookByNameListView.as_view(),name='book_by_name_list'), When the user clicks on the form.dropdown, view and clicks submit, the book_by_name_list URL is returned via the following ListView: class BookByNameListView(LoginRequiredMixin,ListView): model = Book context_object_name = 'book_list' template_name = 'book_by_name_list.html' paginate_by = 15 def get_form_kwargs(self): kwargs = super(BookByNameListView, self).get_form_kwargs() kwargs['user'] = self.request.user return kwargs def get_context_data(self, **kwargs): context = super(BookByNameListView, self).get_context_data(**kwargs) dropdown = self.request.GET.get("dropdown", None) context['dropdown'] = dropdown return context def get_queryset(self): dropdown = self.request.GET.get("dropdown", None) user = self.request.user if dropdown: queryset = Book.objects.filter(Q(id__exact=dropdown)).distinct() else: queryset = Book.objects.none() return queryset Using the code above the dropdown is retrieved via the HTML GET and the ID of the dropdown … -
Trying to connect Django and MySQL
I've been using Django with Sqlite to learn and now waned to start on a first real project. I'm looking to use MySQL as the database. I installed MySQLClient but keep running into this error when trying to run a migration. I've spent several hours trying to look through other posts but just can't seem to figure this out. Any direction on this out would be greatly appreciated. My setup is: Python - 3.8 Django - 3.0.6 MySQL - 5.7 MSQLClient - 1.4.6 macOS - Catalina Traceback (most recent call last): File "/Users/usman/PycharmProjects/untitled/venv/lib/python3.8/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/Users/usman/PycharmProjects/untitled/venv/lib/python3.8/site-packages/django/core/management/base.py", line 366, in execute self.check() File "/Users/usman/PycharmProjects/untitled/venv/lib/python3.8/site-packages/django/core/management/base.py", line 392, in check all_issues = self._run_checks( File "/Users/usman/PycharmProjects/untitled/venv/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 63, in _run_checks issues = run_checks(tags=[Tags.database]) File "/Users/usman/PycharmProjects/untitled/venv/lib/python3.8/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/Users/usman/PycharmProjects/untitled/venv/lib/python3.8/site-packages/django/core/checks/database.py", line 9, in check_database_backends for conn in connections.all(): File "/Users/usman/PycharmProjects/untitled/venv/lib/python3.8/site-packages/django/db/utils.py", line 222, in all return [self[alias] for alias in self] File "/Users/usman/PycharmProjects/untitled/venv/lib/python3.8/site-packages/django/db/utils.py", line 219, in __iter__ return iter(self.databases) File "/Users/usman/PycharmProjects/untitled/venv/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/usman/PycharmProjects/untitled/venv/lib/python3.8/site-packages/django/db/utils.py", line 153, in databases self._databases = settings.DATABASES File "/Users/usman/PycharmProjects/untitled/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 76, in __getattr__ self._setup(name) File "/Users/usman/PycharmProjects/untitled/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 63, in _setup self._wrapped = Settings(settings_module) File … -
Display user's posts in their profile on django
I have been trying to make the profile page of a user have the user's posts but everytime I run my code nothing shows up only the user's username and user's email. I've tried multiple ways to make it work but somehow it doesn't. I think the profile.html has the error in it. views.py def profile(request, pk=None): if pk: post_owner = get_object_or_404(User, pk=pk) user_posts=Post.objects.filter(posti=request.user) else: post_owner = request.user user_posts=Post.objects.filter(posti=request.user) return render(request, 'profile.html', {'post_owner': post_owner, 'user_posts': user_posts}) models.py class Post(models.Model): text = models.CharField(max_length=200) posti = models.ImageField(upload_to='media/images', null=True, blank="True") user = models.ForeignKey(User, related_name='imageuser', on_delete=models.CASCADE, default=2) profile.html <div class="content-section"> <div class="media"> <img class="rounded-circle account-img" src="{{ user.profile.image.url }}"> <div class="media-body"> <h2 class="account-heading">{{ post_owner.username }}</h2> <p class="text-secondary">{{ post_owner.email }}</p> </div> {% for Post in user_posts %} <li class="list-group-item">{{ Post.text }} <a href="{% url 'profile_pk' pk=image.user.pk %}">{{ Post.user }}</a> {% if Post.posti %} <img src="{{ image.posti.url }}" alt="image here" style="max-width: 300px; max-height: 300px"> {% endif %} {% if Post.user == user %} <div class="float-right"> <form action="delete_image/{{ image.id }}/" action="post"> <button type="submit" class="btn btn-outline-danger btn-sm">Delete</button> </form> </div> {% endif %} </li> {% endfor %} </div> </div> -
Template Variations title not showing
I have made a variation to an Item class in models.py and I think i got the template syntax right but apparently there are something wrong which i can't figure it out Here is the model class Item(models.Model): title = models.CharField(max_length=100) description = models.TextField() price = models.FloatField() slug = models.SlugField(unique=True) image = models.ImageField(blank=False, upload_to='approved designs') def __str__(self): return self.title class Meta: unique_together = ('title', 'slug') class Variation(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) title = models.CharField(max_length=120) image = models.ImageField(null=True, blank=True) price = models.FloatField(null=True, blank=True) def __str__(self): return self.title and here is the template {% if item.variation_set.all %} <select class='form-control' name='size'> {% for items in item.variation_set.all %} <option value='{item.variation|lower}'>{{title.title|capfirst}}</option> {% endfor %} </select> {% endif %} -
Need help formulating a query
I have a model named Portfolios, where one field contains a set of Widgets. I am trying to create a query that will return me the Unique set of Widgets from a selected set of Portfolios. list(Portfolio.objects.filter(user=user).values('widgets').distinct()) From this query, I am getting back a list that looks like this [{'widgets': 2}, {'widgets': 6}, {'widgets': 159}, {'widgets': 184}, {'widgets': 291}] What I can't figure out is how to have it return the list of the resolved Widget instances. Ultimately, what I need, is this. [WidgetInst1, WidgetInst2, WidgetInst3, WidgetInst4, WidgetInst5] I can of course pull the instances out of the dictionary entries if they have to come back that way. I am trying to do this with the best performance possible, since I am trying to resolve performance issues from manually iterating over results and doing additionally queries. In addition to the list of Widgets, I also need to get the list of all of the Portfolios that the Widgets are contained in. What would be the best way to go about that from a performance stand point? Do I need to iterate over each of the Widgets and do a separate query for each one?