Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'QuerySet' object has no attribute 'pesel'
I'm new with django. I'm really confused with views. Here is my models.py class Pacjent(models.Model): name= models.CharField(max_length=30) surname = models.CharField(max_length=30) pesel = models.ForeignKey(Pesel, on_delete=models.CASCADE) birth = models.DateField(datetime.date) Here is my views.py: def pacjent_view(request): obj =Pacjent.objects.all() context={'pesele': obj.pesel} return render(request,'PrzychodniaZdrowia/kartapacjenta.html',context) An error is displayed when trying to start: "Exception Value: 'QuerySet' object has no attribute 'pesel'". What is wrong with this code? How do I display this model on the website? -
Why am I getting a Django Type Error when using Taggit?
So I am following a digital book on how to add tags to Django using Taggit. The List page is also using Paginator, but what is happening is I am getting this Type Error when I click on one of the tags which is supposed to take you to keep you on the list page, but list the number of posts with the same tag. Please let me know if you need more information from me. I really appreciate all of your help. I'm excited because this is my first real Django project, creating a blog for a friend and so far things are coming along well except for this one issue that is beyond me. I also want to learn how to be able to look at error screens and know what to look for and then how to solve my own issues one day. Thanks again! Chris This is the Error Screen Shot views.py from django.shortcuts import render, redirect, get_object_or_404 from django.views.generic import ListView from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.db.models import Count from taggit.models import Tag from .models import Post from .forms import PostForm class PostListView(ListView): queryset = Post.published.all() context_object_name = 'posts' paginate_by = 3 template_name … -
Django filter results on foreign key
I am attempting to display a list of notes that are attached to a project. I can display the individual project the notes are linked to but I am not able to figure out how to display only the notes related to the project. My models are: class Project(models.Model): title = models.CharField(max_length= 200) description = models.TextField() def __str__(self): return self.title class ProjectNotes(models.Model): title = models.CharField(max_length=200) body = models.TextField() date = models.DateField(auto_now_add=True) project = models.ForeignKey(Project, default=0, blank=True, on_delete=models.CASCADE, related_name='notes') def __str__(self): return self.title The views: from django.shortcuts import get_object_or_404, render from django.urls.base import reverse from django.views.generic import ListView, DetailView from django.views.generic.edit import CreateView from .models import Project, ProjectNotes class CompanyProjects(ListView): model = Project template_name = 'company_accounts/projects.html' class CompanyProjectsDetailView(DetailView): model = Project id = Project.objects.only('id') template_name = 'company_accounts/project_detail.html' context_object_name = 'project' class ProjectNotes(ListView): model = ProjectNotes template_name = 'company_accounts/project_notes.html' def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) context['project'] = get_object_or_404(Project, id=self.kwargs.get('pk')) return context class ProjectNotesDetailview(DetailView): model = ProjectNotes template_name = 'company_accounts/project_note_detail.html' The template displays the correct project: {% extends 'base.html' %} {% block content %} <h1>Notes</h1> {{ project }} {% for note in notes %} <div class ="projectnotes-entry"> <h2><a href="">{{ note.title }}</a></h2> <p>{{ note.body … -
How do I link a Django foreign key selected in a form with an inline form?
Introduction Hello! I am a self-taught novice python/Django coder working on my family business truck maintenance Django app. I have some of the basics of Django and python3 down, but other basics escape me as everything I am learning has been done for practicality sake and not built from the foundations of these languages. I have the following types of models: Truck - a single truck Service - a single instance of a repair/maintenance service for a single truck Photo - a single picture from the photologue app PhotoExtended - an add-on model one-to-one with Photo where it can be linked to a truck and/or a service. A photo will ALWAYS be associated with a truck, but may or may not be associated with a service. relevant models.py: class PhotoExtended(models.Model): # Link back to Photologue's Photo model. photo = models.OneToOneField(Photo, related_name='extended', on_delete=models.RESTRICT) truck = models.ForeignKey('Truck', on_delete=models.CASCADE, default = DEFAULT_TRUCK_ID, help_text="Truck in the picture.") service = models.ForeignKey('Service', on_delete=models.PROTECT, null=True, blank=True, help_text="Service being performed or finished in the picture.") receipt = models.BooleanField(help_text="Is the picture for a receipt?", null=True, default=False) # Boilerplate code to make a prettier display in the admin interface. class Meta: verbose_name = u'Associated photo' verbose_name_plural = u'Associated photos' def … -
Why i get an error in django host.py file?
from django.conf import settings from django_hosts import patterns, host host_patterns = patterns('', host(r'www',settings.ROOT_URLCONF, name='www'), ) And when it runs it brings:: Traceback (most recent call last): File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 31, in start(fakepyfile,mainpyfile) File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 30, in start exec(open(mainpyfile).read(), main.dict) File "", line 7, in File "/data/user/0/ru.iiec.pydroid3/files/arm-linux-androideabi/lib/python3.9/site-packages/django/conf/init.py", line 56, in getattr self._setup(name) File "/data/user/0/ru.iiec.pydroid3/files/arm-linux-androideabi/lib/python3.9/site-packages/django/conf/init.py", line 37, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting ROOT_URLCONF, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. [Program finished] -
Git Hub we don't support that file type
I am trying to add some django project files to my github repository but for some reason github keeps saying it doesn't support the file types of my project -
How to enable css suggestions in django-html file in vscode?
Similar hints are available in html files I want to get them in django-html as well. Is there any way to enable them? I installed the following extension for vs code and enabled emmet support in django-html https://github.com/vscode-django/vscode-django -
How to check if FileField was uploaded?
I wanna store the "original" file name of an upload. This is because the file gets stored with a uuid as a new name. So I wrote this for my model: def save(self, *args, **kwargs): if self.file: self.original_filename = self.file.name super(MediaFile, self).save(*args,**kwargs) However, it also stores the filename to self.original_filename when nothing new has been uploaded. Thus the original_filename becomes the uuid the second time i save this model (e.g updating some other field in the admin). How to check in the save function if the FileField was really updated and a file has been uploaded? If possible I'd like to perform this check in the model so mit will work both for admin and custom upload pages. -
How do I set ProductDetail Page for different categories of product In Django?
I am new to Django. I am building a web store app. Case 1: I have a category for Phones with these Model: 'title', 'description', 'price', 'front camera', 'back camera', Case 2: I have another category for accessories with these Model: 'title', 'price', 'description', 'type' The problem: They both share the same ProductDetail Page...accessories detail is showing front and back camera as features which is akward although both are set to none. The Ask: How can I render different ProducDetail Page for different Categories -
Django ORM join on subquery
I have this two models: class Order(models.Model): value= models.FloatField() customer = models.ForeignKey( Customer, on_delete=models.CASCADE, related_name="orders" ) class Customer(models.Model): name = models.CharField(max_length=300, unique=True) and i want to annotate the sum of total orders purchased by the customer, this could be done pretty straightforward with this query: customer_total_subquery = Subquery( Customer.objects.filter(pk=OuterRef("customer")) .annotate(total=Coalesce(Sum("orders__value"), 0.0, output_field=FloatField())) .values("total") ) Order.objects.select_related("customer").all().annotate(customer_total=customer_total_subquery) The problem is, for only 37000 orders, this query takes 4 minutes. Produced query: SELECT "order"."id", (SELECT COALESCE(SUM(U1."order_value"), 0.0) AS "total" FROM "customer" U0 LEFT OUTER JOIN "order" U1 ON (U0."id" = U1."customer_id") WHERE U0."id" = "order"."customer_id" GROUP BY U0."id") AS "customer_total" FROM "order" LEFT OUTER JOIN "customer" ON ("order"."customer_id" = "customer"."id") We can see that there is a subquery that is executed once per row, so the customer_total subquery is executed 37000 times. The ideal solution is to query only once and use this results to append on the main query, the query bellow takes less than 100 ms: SELECT o.id, o.customer_id, subquery.customer_total from order as o left join ( select b.id, SUM(inner_order.value) as customer_total from customer b left join order inner_order on (inner_order.customer_id= b.id) group by b.id ) subquery on (subquery.id = o.customer_id) Is it possible to achieve this query (join on subquery) … -
Custom function for annotate
I am trying to extract records with my Django ORM Model: users = User.objects.values( "first_name", "last_name" ).annotate( user_level=custom_levels( F("user_level" ) ) ); The model is represented by: first_name last_name user_level: it may be [1] or [1,13] (it comes from saving a MultipleSelect throught forms.py) Goal: My goal is to process user_level in the query in order to transform those ids in text (I have a dict key:value with those ids). Any clue? Thank you -
How to create an Elasticsearch index for every instance of a Django models variable
In my Django models, for a model class named User there's a variable defined for user_id and I want to create a separate index for each and every customer using the user id. How do I modify this so that it creates a separate index based on the user_id? index_create = es.index(index="test_index", doc_type="docs", body= map_doc) #map_doc is defined elsewhere. I am trying to use this to store data in a separate index for separate users whenever this is invoked. -
email verification in django during registration
I had created Registration API which takes email and password and confirms password,and I achieved this by simply adding some lines in setting.py ACCOUNT_AUTHENTICATION_METHOD = "email" ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False and urls.py urlpatterns = [ path('admin/', admin.site.urls), path('',include('mydata.urls')), path('auth/', include('rest_auth.urls')), path('auth/registration/', include('rest_auth.registration.urls')), ] I did not make any other changes in model.py and serializer.py, Now what to do next for email verification? Are there any simple steps to achieve this? -
Django Admin template and form change list
I have a strange behavior with the admin interface. I have a form (FioleListForm) with the following init, basically prefilter foreign keys. def __init__(self, *args, **kwargs): super(FioleListForm, self).__init__(*args, **kwargs) instance = kwargs.get('instance') if instance: if instance.lot: self.fields['lot'].queryset = Lot.objects.filter(Q(produit__id=instance.produit.id, shelf_life__gt=now().date(), stock__gt=instance.dose) | Q(id=instance.lot.id)) else: self.fields['lot'].queryset = Lot.objects.filter(Q(produit__id=instance.produit.id, shelf_life__gt=now().date(), stock__gt=instance.dose)) On the admin side, I have the following: @admin.register(Fiole) class FioleAdmin(VersionAdmin): change_list_template = 'admin/flacoTIapp/fiole/change_list.html' def get_changelist_form(self, request, **kwargs): return FioleListForm My issue is change_list_template is overriding the form. Thus the foreign key prefilter is not working. And if I do not put "change_list_template", Django is using the Django Admin contrib template. Thank you for your help. -
Javascript files in django have 404 error on Chrome
I think my javascript files are somehow not being read by Chrome. In the "Network" section of the developer tools (inspect) in Chrome, my js file has a status 404 and is colored red. The below script is the code in my html file: <script src="js/checkout.js" type="text/javascript"></script> The src path is correct, because vscode shows me the correct js file when I click the src=js/checkout.js of the script tag. I removed all cache from the browser, but the problem still persists. I hope you can guys can help me, and please leave a question if you have one. -
How to show only related objects in a django admin model
In a django admin model with inlines other admin model I want to show only related objects. simplified example: class Business(models.Model): name = models.TextField() class BusinessAddress(models.Model): business = models.ForeignKey(Business) address = models.TextField() class Pos(models.Model): business = models.ForeignKey(Business) label = models.TextField() class PosAddress(models.Model): pos = models.ForeignKey(Pos) address = models.ForeignKey(Address) So I want to retrieve only the related addresses of the selected pos in PosAddress and not all the available addresses class PosAddressAdmin(admin.ModelAdmin): model = PosAddress extra = 1 class PosAdmin(admin.ModelAdmin): model = Pos inlines = [PosAddressAdmin] How is that possible, if it is possible? -
'tuple' object has no attribute '_meta'
why is my queryset throwing this error whenever i make a search to the backend of account object ? def auto_search(request): user = request.user search_query = request.GET.get('q') payload = [] if search_query : search_results = Account.objects.filter(email__icontains=search_query).filter(username__icontains=search_query).distinct() user = request.user if user.is_authenticated: # get the authenticated users friend list auth_user_friend_list = FriendList.objects.get(user=user) for account in search_results: payload.append((account, auth_user_friend_list.is_mutual_friend(account))) payload = serializers.serialize('json',payload) return JsonResponse({'status':200 , 'data':payload}) Account model.py class Account(AbstractBaseUser): email = models.EmailField(unique=True) username = models.CharField(max_length=150, unique=True) first_name = models.CharField(max_length=150,blank=True) profile_image = models.ImageField(max_length=255,upload_to=get_profile_image_filepath, null=True, blank=True, default=get_default_profile_image) last_name = models.CharField(max_length=150,blank=True) phone_number = models.CharField(max_length=50, unique=True) date_of_birth = models.DateField(blank=True, null=True) friendlist models.py class FriendList(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="user") friends = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name="friends") # set up the reverse relation to GenericForeignKey notifications = GenericRelation(Notification) -
Got an error in cpanel column must appear in the GROUP BY clause
My app are working fine in my local pc. But problem arise when I am using this app to c panel. When I do a search query I got this error 'column "acc_installerledger.sales_invoice" must appear in the GROUP BY clause or be used in an aggregate function' Here acc my app, InstallerLedger my table name and sales_invoice is column name. def installerLedger(request): form = DateRangeForm() details = () installer = Installer.objects.order_by('name') if request.method == 'POST': installer_name = request.POST['installer'] form = DateRangeForm(request.POST or None) if form.is_valid(): details = InstallerLedger.objects.filter(name=installer_name, date__range=( form.cleaned_data['start_date'], form.cleaned_data['end_date'])).order_by('- id').annotate(balancecomm=Window(Sum('comm_balance'), order_by=F('id').asc()), balancecable=Window(Sum('cable_balance'), order_by=F('id').asc()), sales_invoicem=Min('sales_invoice'), namem=Min('name'), datem=Min('date') ) return render(request, 'installer/installer_ledger.html', {'tempo': details, 'form': form, 'installer': installer}) I am using Django 3.2 version. -
I can't create super user postgresql and Django
I am doing a project with Django in which I try to change the database from SQLITE to Postqresql. When I try to create the super user I get this error. Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 79, in execute return super().execute(*args, **options) File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 189, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\contrib\auth\models.py", line 163, in create_superuser return self._create_user(username, email, password, **extra_fields) File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\contrib\auth\models.py", line 146, in _create_user user.save(using=self._db) File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\contrib\auth\base_user.py", line 67, in save super().save(*args, **kwargs) File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\db\models\base.py", line 726, in save self.save_base(using=using, force_insert=force_insert, File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\db\models\base.py", line 774, in save_base post_save.send( File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\dispatch\dispatcher.py", line 180, in send return [ File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\dispatch\dispatcher.py", line 181, in <listcomp> (receiver, receiver(signal=self, sender=sender, **named)) File "C:\Users\l\Desktop\django-course\Django(02-09-21)\crm1\accounts\signals.py", line 7, in customer_profile group = Group.objects.get(name='customer') File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\db\models\query.py", line 435, in get raise self.model.DoesNotExist( django.contrib.auth.models.DoesNotExist: Group matching query does not exist. settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': … -
getting error after submitting form inside detail view
I'm trying to create a dashboard for the staff users to fill in and edit some info regarding their users. the form works saves successfully but when I submit it I get this error: NoReverseMatch at /surveys/scientific/3 Reverse for 'scientific-info' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['surveys/scientific/(?P<pk>[^/]+)$'] this is my views.py: class ScientificInfoView(FormMixin, DetailView): model = ScientificInfo template_name = 'reg/scientific-info.html' form_class = ScientificInfoForm def get_success_url(self): return reverse('scientific-info', kwargs={'pk': self.object.id}) def get_context_data(self, **kwargs): context = super(ScientificInfoView, self).get_context_data(**kwargs) context['form'] = ScientificInfoForm(initial={'post': self.object}) return context def post(self, request, pk): user = get_object_or_404(ScientificInfo, id=pk) if request.method == 'POST': form = ScientificInfoForm(request.POST, instance=user) if form.is_valid(): form.save() redirect('scientific-info') else: form = ScientificInfoForm(instance=user) return render(request, 'reg/scientific-info.html', {'form': form}) def form_valid(self, form, *args, **kwargs): form.save() return super(ScientificInfoView, self).form_valid(form) and my template: <form method="POST" enctype="multipart/form-data" action="{% url 'scientific-info' pk=object.id %}"> {% csrf_token %} {{form}} <button type="submit">submit</button> </form> Im pretty sure that the action part in my form is causing the issue but I dont know how to solve it -
Passing Authenticated User into Model View in Django
I am creating a profile model that needs to pass the current authenticated user as the foreign key. If I do not exclude the user field, I can select from all the users, but I need to hide this field and pass the current authenticated user automatically when the form is submitted. Additional fields like name, dob, etc. will be added to the model by the user. I cannot for the life of me figure out how to add the user to the model form. What I have in my views.py file (below) is the closest I have been able to get. Models class Profile(models.Model): user = models.ForeignKey( get_user_model(), on_delete = models.CASCADE ) first_name = models.CharField(max_length = 200, blank = True) last_name = models.CharField(max_length = 200, blank = True) dob = models.DateField(blank = True) profile_photo = models.ImageField(upload_to = 'profile_photos/', blank = True) def __str__(self): return self.first_name def get_absolute_url(self): return reverse('home') Views class ProfileCreateView(LoginRequiredMixin, generic.CreateView): model = Profile template_name = 'account/profile_creation.html' fields = ['first_name', 'last_name', 'dob', 'profile_photo'] login_url = 'account_login' def form_valid(self, form): user = self.request.user self.object = form.save(commit = False) self.object.save() return super(ProfileCreateView, self).form_valid(form) Forms class CustomProfileForm(forms.Form): class Meta: model = Profile The error I am getting: null value in … -
Is it possible to set django-allauth to accept only google login?
I am implementing a web application using Django framework. In my business I need to let the users have access to the app only by google login. I also don't need to register the users in my database, it isn't a requirement. I just need that the user will uses his google account to enter the site so I will be able to get his real email to send him back the result of the session. It is a one shot app. I am using django-allauth but it exposes by default a way to login and register users locally. Is it a way to disable every kind of local registration/login and let the user enter in the app only by google login? Thank you. -
I want to sent weather conditions sms to the registered users on the website [closed]
I want to send weather condition SMS to the registered users of my website. I have done with the coding but the SMS is not received to the registered users. Please Help me. user_data=extendeduser.objects.values('phone','town','user') def printit(): threading.Timer(10, printit).start() for i in user_data: city = i['town'] src = 'http://api.openweathermap.org/data/2.5/weather?appid=' url = src + city list_of_data = requests.get(url).json() temp = list_of_data['main']['temp'] newtmp = round(temp - 273.15, 3) condition = list_of_data['weather'][0]['description'] humidity = list_of_data['main']['humidity'] data = { "city": city, "temp": newtmp, "humidity": humidity, "condition": condition, "icon": str(list_of_data['weather'][0]['icon']), } print(data) if data['condition']=="overcast clouds": euser = extendeduser.objects.values('phone', 'user') url = "https://www.fast2sms.com/dev/bulk" querystring = { "authorization": "Authorization Code", "sender_id": "Annadata", "message": "Overcast Clouds ", "language": "english", "route": "p", "numbers": phone} headers = { 'cache-control': "no-cache" } response = requests.request("GET", url, headers=headers, params=querystring) print(response.text) print('\n'+city,' user '+str(i['user'])+' overcast condition',end='\n') printit() -
Generate barcode render to template HTML in django
I need to generate barcode in django to view in html for generate PDF particularly scan the generate barcode -
Dev server Django do not run [closed]
Sorry, I need hepl. I try make first django app with guide in your site. Virt. env is started and activated, but dev server not started. comand "python manage.py runserver" returned error "No module 'mysite'" Why????