Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError: 'Language' object has no attribute 'lang_proficiency'
My models look like these : first have user profile class UserProfile(models.Model): """user profiling """ user = models.OneToOneField(User, on_delete=models.CASCADE) location = models.CharField(max_length=255) languages = models.ManyToManyField('Language', through="UserLanguage") then have a language many to many relation class Language(models.Model): name = models.CharField(max_length=50) then have a through table to store this data class UserLanguage(models.Model): language = models.ForeignKey(Language, on_delete=models.CASCADE) user_profile = models.ForeignKey(UserProfile, on_delete=models.CASCADE) class ProficiencyStatus(models.TextChoices): FLUENT = 'FL', _('FLUENT') CONSERVATION = 'CT', _('CONSERVATIONAL') lang_proficiency = models.CharField( max_length=2, choices=ProficiencyStatus.choices, default=ProficiencyStatus.FLUENT, ) now issue is when I am inserting data in this table like : language_obj = Language.objects.create(name=language.get('name')) user_lang_obj = UserLanguage.objects.create(language=language_obj, user_profile=user_profile, lang_proficiency='FL') user_profile.languages.add(language_obj) I am getting error like: AttributeError: 'Language' object has no attribute 'lang_proficiency' -
Django Custom user model, the model saved in a separated file inside folder
I am new to Django and working on a project that needs a custom user. I created folders for models, views, URLs, and serializers. Each feature has its own file in these folders. Everything works fine until I rename models.py file to users_model.py or move it to the models folder that I created. When I makemigrations the following error appears: django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'app.AppUser' that has not been installed My code: users_model.py class AppUser(AbstractBaseUser): . . . class MyUserManager(BaseUserManager): def create_user(self, email, username, password): . . def create_superuser(self, email, username, password): . . Admin.py . . admin.site.register(AppUser) sittings.py INSTALLED_APPS = [ . . "app", ] AUTH_USER_MODEL = "app.AppUser" I tried AUTH_USER_MODEL = "app.models.users_model.AppUser" ValueError: Invalid model reference 'app.models.users_model.AppUser'. String model references must be of the form 'app_label.ModelName'. I tried AUTH_USER_MODEL = "app.models.AppUser" ValueError: Invalid model reference 'app.models.AppUser'. String model references must be of the form 'app_label.ModelName'. -
How to combine multiple models into one view template in django
I have two models class Post(models.Model): title = models.CharField(max_length=100) body = RichTextField(max_length=1000000) created_at = models.DateTimeField(default=datetime.now, blank = True) image = ResizedImageField(size=[250, 200], upload_to='img') and class Politics(models.Model): title = models.CharField(max_length=100) body = RichTextField(max_length=1000000) created_at = models.DateTimeField(default=datetime.now, blank = True) image = ResizedImageField(size=[250, 200], upload_to='img',blank = True) I want to combine them both into one template view and render them on the index.html Here is my view function def index(request): politics = Politics.objects.all() return render(request, 'index.html', {'politics':politics, 'posts': Post.objects.all()}) However, only the 'politics' object is being rendered. What could be wrong? -
django AttributeError when querying data from the database
I keep getting AttributeError: 'QuerySet' object has no attribute 'title' error whenever i use obj=Userpost.objects.all() . How will i format it so that i can use it to query all data in the database? this is my snippet code obj=Userpost.objects.all() context={ 'title':obj.title, 'content':obj.content, 'date':obj.date, } -
Django Rest Framework with shortuuid, generics.RetrieveUpdateDestroyAPIView returning 404 {"detail": "Not found."}
I was remaking a social media site as a revision of Django and the rest framework, I didn't want to use the django default linear id count and didn't like how long the uuid library's ids was, so I used the shortuuid library. I've used them on the posts and the comments just to keep the anonymity of the count of both posts and comments. On the posts side everything works for the CRUD stuff (which should be proof that the issue isn't from the shortuuid library, as far as I know), although with the comments the Create Retrieve works perfectly but the Update Destroy doesn't. so here is the code we are working with: starting with the models to know what kind of data we are working with (models.py): from shortuuid.django_fields import ShortUUIDField ... # posts likes etc class Comment(models.Model): id = ShortUUIDField(primary_key=True, length=8, max_length=10) user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) body = models.TextField(max_length=350) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) class Meta: ordering = ['created'] def __str__(self): return f'on {self.post} by {self.user}' objects = models.Manager() serializers.py: class CommentSerializer(ModelSerializer): username = SerializerMethodField() def get_username(self, comment): return str(comment.user) class Meta: model = Comment fields = ['id', … -
Django Apache - internal Server Error mod_wsgi
So I set up my django and it seemed to be working fine until I noticed my admin panel would not be styled with css. I also could not access one of my views via url getting an Internal Server Error. The Apache Error Log looks like this but I dont really get what I messed up. [Sun Jun 26 19:46:29.256896 2022] [wsgi:error] [pid 19419] [client 192.168.2.138:61502] mod_wsgi (pid=19419): Failed to exec Python script file '/home/pi/myproject/myprojectenv/myproject/myproject/wsgi.py'. [Sun Jun 26 19:46:29.257249 2022] [wsgi:error] [pid 19419] [client 192.168.2.138:61502] mod_wsgi (pid=19419): Exception occurred processing WSGI script '/home/pi/myproject/myprojectenv/myproject/myproject/wsgi.py'. [Sun Jun 26 19:46:29.257906 2022] [wsgi:error] [pid 19419] [client 192.168.2.138:61502] Traceback (most recent call last): [Sun Jun 26 19:46:29.258141 2022] [wsgi:error] [pid 19419] [client 192.168.2.138:61502] File "/home/pi/myproject/myprojectenv/myproject/myproject/wsgi.py", line 16, in <module> [Sun Jun 26 19:46:29.258201 2022] [wsgi:error] [pid 19419] [client 192.168.2.138:61502] application = get_wsgi_application() [Sun Jun 26 19:46:29.258274 2022] [wsgi:error] [pid 19419] [client 192.168.2.138:61502] File "/home/pi/myproject/myprojectenv/lib/python3.7/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application [Sun Jun 26 19:46:29.258324 2022] [wsgi:error] [pid 19419] [client 192.168.2.138:61502] django.setup(set_prefix=False) [Sun Jun 26 19:46:29.258458 2022] [wsgi:error] [pid 19419] [client 192.168.2.138:61502] File "/home/pi/myproject/myprojectenv/lib/python3.7/site-packages/django/__init__.py", line 24, in setup [Sun Jun 26 19:46:29.258508 2022] [wsgi:error] [pid 19419] [client 192.168.2.138:61502] apps.populate(settings.INSTALLED_APPS) [Sun Jun 26 19:46:29.258575 2022] [wsgi:error] [pid 19419] … -
Django Testing: DISTINCT ON fields is not supported by this database backend
i faced a weird issue while trying to run the unit test in Django, this works fine for the API but only have this issue while running the test. i think i need to have same configuration but i am not sure how i can achieve this in Django test, also i tried to rename the testing database to one that i manually created bit it does not sounds the tests are being executing in that database "Not sure if i correctly configure the testing setting" DATABASES = { "default": { "NAME": "my_database", "USER": "postgres", "PASSWORD": "postgres", "HOST": "localhost", "PORT": 5435, "ENGINE": "django.db.backends.postgresql_psycopg2", "TEST": { "NAME": "mytestdatabase", "USER": "postgres", "PASSWORD": "postgres", "HOST": "localhost", "PORT": 5435, "ENGINE": "django.db.backends.postgresql_psycopg2", }, } } -
Error: Command '['C:\\Users\\u\\de\\venv\\Scripts\\python.exe', '-Im', 'ensurepip', '--upgrade', '--default-pip']' returned non-zero exit status 101
Whenever I try to create virtual environment in python I get this error Error: Command '['C:\Users\u\Desktop\venv\Scripts\python.exe', '-Im', 'ensurepip', '--upgrade', '--default-pip']' returned non-zero exit status 101. I am using Windows 10. I tried uninstalling python and reinstalled it several times but still the problem continues. I have been using python on my computer from years but now I am facing this error. -
The field oldapp.MyModel.related was declared with a lazy reference to 'oldapp.related', but app 'oldapp' doesn't provide model 'related'
Similar questions have been asked before, but none are applicable to my situation as far as I can tell. I followed this answer to move the model Related out of oldapp and into newapp. I created the following migration in oldapp: class Migration(migrations.Migration): dependencies = [ ("oldapp", "0019_merge_20220626_1439"), ] database_operations = [ migrations.AlterModelTable("Related", "newapp_related"), migrations.AlterModelTable("AnotherRelated", "anothernewapp_AnotherRelated"), ] state_operations = [ migrations.DeleteModel("Related"), migrations.DeleteModel("AnotherRelated"), ] operations = [ migrations.SeparateDatabaseAndState( database_operations=database_operations, state_operations=state_operations, ) ] Note that I'm actually moving two models into two new apps. However, MyModel only has a foreign key to Related, so I'm only going to include example code for the Related model. Also, MyModel is still in oldapp and still has a foreign key to Related. In newapp, I added this migration (0001_initial): class Migration(migrations.Migration): initial = True dependencies = [ ("oldapp", "0020_move_related_and_anotherrelated_to_own_apps"), ] state_operations = [ migrations.CreateModel( name='Related', fields=[ # ... ], # etc. ), ] operations = [ migrations.SeparateDatabaseAndState(state_operations=state_operations) ] Running migrations, I get this error: ValueError: The field oldapp.MyModel.related was declared with a lazy reference to 'oldapp.related', but app 'oldapp' doesn't provide model 'related'. I thought I could just add this to oldapp.migrations.0020_move_related_and_anotherrelated_to_own_apps: operations = [ migrations.SeparateDatabaseAndState( database_operations=database_operations, state_operations=state_operations, ), migrations.AlterField( model_name='mymodel', name='related', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, … -
Using Django, I keep Getting Uncaught TypeError: Illegal invocation When Trying to Open a Product Modal
My Modal - just for testing I passed in images from backend: <!-- product modal area start --> {% if product_in_modal %} <div class="product__modal-area modal fade" id="productModal-{{ product.id }}" tabindex="-1" role="dialog" aria-labelledby="productModal" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="product__modal-inner position-relative"> <div class="product__modal-close"> <button data-bs-dismiss="modal" aria-label="Close"> <i class="ti-close"></i> </button> </div> <div class="product__modal-left"> <div class="tab-content mb-10" id="productModalThumb"> <div class="tab-pane fade show active" id="pro-1" role="tabpanel" aria-labelledby="pro-1-tab"> <div class="product__modal-thumb w-img"> <img src="{{ product_in_modal.product_detail_img_1.url }}" alt=""> </div> </div> <div class="tab-pane fade" id="pro-2" role="tabpanel" aria-labelledby="pro-2-tab"> <div class="product__modal-thumb w-img"> <img src="{{ product_in_modal.product_detail_img_2.url }}" alt=""> </div> </div> <div class="tab-pane fade" id="pro-3" role="tabpanel" aria-labelledby="pro-3-tab"> <div class="product__modal-thumb w-img"> <img src="{{ product_in_modal.product_detail_img_3.url }}" alt=""> </div> </div> <div class="tab-pane fade" id="pro-4" role="tabpanel" aria-labelledby="pro-4-tab"> <div class="product__modal-thumb w-img"> <img src="{{ product_in_modal.product_detail_img_4.url }}" alt=""> </div> </div> </div> <div class="product__modal-nav"> <ul class="nav nav-tabs" id="productModalNav" role="tablist"> <li class="nav-item" role="presentation"> <button class="nav-link active" id="pro-1-tab" data-bs-toggle="tab" data-bs-target="#pro-1" type="button" role="tab" aria-controls="pro-1" aria-selected="true"> <img src="{{ product_in_modal.product_detail_nav_1.url }}" alt=""> </button> </li> <li class="nav-item" role="presentation"> <button class="nav-link" id="pro-2-tab" data-bs-toggle="tab" data-bs-target="#pro-2" type="button" role="tab" aria-controls="pro-2" aria-selected="false"> <img src="{{ product_in_modal.product_detail_nav_2.url }}" alt=""> </button> </li> <li class="nav-item" role="presentation"> <button class="nav-link" id="pro-3-tab" data-bs-toggle="tab" data-bs-target="#pro-3" type="button" role="tab" aria-controls="pro-3" aria-selected="false"> <img src="{{ product_in_modal.product_detail_nav_3.url }}" alt=""> </button> </li> <li class="nav-item" role="presentation"> <button class="nav-link" id="pro-4-tab" data-bs-toggle="tab" data-bs-target="#pro-4" type="button" role="tab" aria-controls="pro-4" … -
Is there a preferred way to serialize external objects to json format in python
I am using a Client API to get data and when I use json.loads(api_response.results) it is showing TypeError('Object of type ExternalUnifiedEvent is not JSON serializable); So instead of using json.loads() I am deconstructing the data like below so that I can able to use json.dumps() later to send this data in a post request. Is this the best way to do this as ExternalUnifiedEvent type doesn't exist in my code base? def get_data(): try: api_response = client_api.get() data = [] for i in api_reponse.results: e = { "event_id": i.event_id "event_type": i.event_type "properties": i.properties } data.append(e) return data except Exception as e: print(e) headers = {"Content-Type": "application/json",} payload = get_data() response = requests.post(webhook_url, headers=headers, data=json.dumps(payload)) -
Django - Cannot add new models
Embrassing question. I cannot seem to be able to add new models. I have list of models in my models.py file which appear in admin panel. However, the new model I am trying to add does not appear. What makes it embarrassing is that it was showing earlier this afternoon. I made some changes to the code and clearly something went wrong. I deleted the code, hoping this might resolve the problem, but no. Just in case it would be related to the actual model I was creating, I completly change the code to something simple (see below) but again no change. I am not too sure what I clicked, deleted to make this happen. Any clues? (PS: I did do the migrations.) from django.db import models from django.contrib.auth.models import User from decimal import Decimal import locale import logging ... class Event(models.Model): name = models.CharField('Venue Name', max_length=120) def __str__(self): return self.name -
Show in template fields labels names instead of fields names - Django
I use to display errors from the forms.py in template using the code below: {% for key, value in form.errors.items %} <div class="alert alert-danger alert-dismissible fade show" role="alert"> <strong>Error:</strong> {% if key != '__all__' %}{{ key|title }} {% endif %} - {{ value|striptags }} </div> {% endfor %} But my project is in a different language so I don't want to show the field name but the label name. I need something like taht {{ key.label|title }} {% for key, value in form.errors.items %} <div class="alert alert-danger alert-dismissible fade show" role="alert"> <strong>Error:</strong> {% if key != '__all__' %}{{ key.label|title }} {% endif %} - {{ value|striptags }} </div> {% endfor %} How to show label names instead of field names? -
django not using custom adapter?
Project structure myproject -- app1 -- views.py etc., myoroject -- settings (folder) -- base.py (this is the settings file django uses) -- wsgi.py -- adapter.py This is my project directory structure the issue I'm facing is the custom adapter that I created is not used by django all-auth. Not sure why this is making me so tired. I have specified the module path also still django does not call save_user method in the adapter.py file. This is my code as follows from allauth.account.adapter import DefaultAccountAdapter class UserAccountAdapter(DefaultAccountAdapter): print("class loading ") def get_login_redirect_url(self, request): print(f"GET request dict is {request.GET}") return reverse('users:home') def save_user(self, request, user, form): print("working in save user", form) user = super(UserAccountAdapter, self).save(request, user, form) return user while server reloads the print statement works but the method is not called. Django does not recognizes it. In my settings folder I have a settings file called base.py where I have mentioned the path. base.py ACCOUNT_FORMS = { 'signup': 'users.forms.UserRegistrationForm' } ACCOUNT_ADAPTER = "spotify.adapter.UserAccountAdapter" I have also placed the adapter.py file inside users app too and tried changing the path but it does not work. Would be glad if someone has encountered the same and found the solution. -
Django: URL dispatcher doesn't convert DateField to '%Y-%m-%d'
I'm a newbie with Django and I'm faced with a problem — can't convert string to datetime object and back with register_converter. I have a date as Jan 1, 2000 and I need to convert to 2000-01-01. I created converter, registered it, but in the template, I see the date as Jan 1, 2000. How could I fix it? That's urls.py: from django.urls import path, register_converter from datetime import datetime class PubDateConverter: regex = r'[0-9]{4}-[0-9]{2}-[0-9]{2}' format = '%Y-%m-%d' def to_python(self, value): return datetime.strptime(value, self.format) def to_url(self, value): return value.strftime(self.format) register_converter(PubDateConverter, 'date') urlpatterns = [ path('books/<date:pub_date>/', book_view, name='book_view'), ] That's models.py: class Book(models.Model): name = models.CharField('Name', max_length=64) author = models.CharField('Author', max_length=64) pub_date = models.DateField('Pub_date') def __str__(self): return self.name + " " + self.author That's views.py: def book_list(request): return render(request, 'books/book_list.html', {'book_list': Book.objects.all()}) And in template I substitute the value as: {% for book in book_list %} <p>Date: {{ book.pub_date }}</p> {% endfor %} I use Django version is Django==4.0.5 -
edit and delete django comments not working
my Edit/delete comments is not working. Anyone got any idea why its not editing or deleteing the review comments? In views.py its under views.py def product_detail, def delete_product and def delete_review last two on the bottom of the page. forms.py Its under class ReviewForm and in models its under class Review views.py from django.shortcuts import render, redirect, reverse, get_object_or_404 from django.contrib import messages from django.contrib.auth.decorators import login_required from django.db.models import Q from django.db.models.functions import Lower from .models import Product, Category, Review from .forms import ProductForm, ReviewForm # Create your views here. def all_products(request): """ A view to show all products, including sorting and search queries """ products = Product.objects.all() query = None categories = None sort = None direction = None if request.GET: if 'sort' in request.GET: sortkey = request.GET['sort'] sort = sortkey if sortkey == 'name': sortkey = 'lower_name' products = products.annotate(lower_name=Lower('name')) if sortkey == 'category': sortkey = 'category__name' if 'direction' in request.GET: direction = request.GET['direction'] if direction == 'desc': sortkey = f'-{sortkey}' products = products.order_by(sortkey) if 'category' in request.GET: categories = request.GET['category'].split(',') products = products.filter(category__name__in=categories) categories = Category.objects.filter(name__in=categories) if 'q' in request.GET: query = request.GET['q'] if not query: messages.error(request, "You didn't enter any search criteria!") return redirect(reverse('products')) queries … -
Django overriding User model for extra fields for already created project
I am new to Django and I just followed this tutorial online but the coder used Regular User model which has only "User_name, Last_name, Email, Password" fields. I am trying to add extra fields "age, sex, department etc.." for users to fill before finishing signup, So far I managed to add extra fields to User model using OnetoOneField relationship and I can access them in Admin panel and even register users with the extra fields but when I try create new user with my registration.html file or with Shell I get error: views.py user = User.objects.create_user(first_name="Test", last_name="Test2", username="Test3", password="Test3333", extra_field="test") TypeError: User() got an unexpected keyword argument 'extra_field' Using the form registrations.html I sign up no problem but the extra field is not filled or nulled. models.py from django.db import models from django.contrib.auth.models import User class EmployeeDetail(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) empcode = models.CharField(max_length=9, unique=True) nnum = models.CharField(max_length=13, default="") contact = models.CharField(max_length=15, null=True) gender = models.CharField(max_length=50, null=True) joiningdate = models.DateField(null=True) def __str__(self): return self.empcode + ' ' + self.user.first_name + ' ' + self.user.last_name class EmployeeSalary(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) salary = models.FloatField(default=0) x= models.IntegerField(default=520) x= models.BooleanField(default=False) x= models.IntegerField(default=0) def totalsalary(self): tsalary = 0 if self.x: tsalary = self.x* … -
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 2082-2084: ordinal not in range(256)
I don't know why this is happening. Whenever I add Arabic content it shows the above error, otherwise works fine with the English language Same code is working in another project perfectly but not here. views.py def generate_pdf_for_gift_and_add_to_cart(request): cart = Cart(request) if request.method == 'POST': id = request.POST.get('project_id') selectedAmount = request.POST.get('amount') senderNameDonatedDonationPage = request.POST.get( 'senderNameDonatedDonationPage') receiverNameDonatedDonationPage = request.POST.get( 'receiverNameDonatedDonationPage') phoneNumberDonatedDonationPage = request.POST.get( 'phoneNumberDonatedDonationPage') emailDonatedDonationPage = request.POST.get('emailDonatedDonationPage') params = { "project_id": id, "selectedAmount": selectedAmount, } pdf = render_to_pdf('pdfs/gift_pdf.html', params) if pdf: response = HttpResponse(pdf, content_type='application/pdf') filename = f"Invoice_{emailDonatedDonationPage}_{datetime.now()}.pdf" content = "inline; filename='%s'" % filename download = request.POST.get("download") if download: content = "filename='%s'" % filename response['Content-Disposition'] = content receipt_file = BytesIO(pdf.content) return response utils.py I also tried utf-8 encoding, but that shows me blank boxes on the generated pdf page. from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None gift_pdf.html below is the example template, where will render that. <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Gift PDF</title> <style type="text/css"> @page { size: 6in; } … -
django inline add button missing on version 3.2
I have a Django site where the admin forms with inlines are missing the add button below the inlines. We are using Django jet if this is relevant. Thanks a lot. -
django- createview get id with which it was saved in database return none self.object.pk in form_valid is None
I have created a view with createview where I have a form, this view has the url: path('asignacionContact/<int:pk>/',AsignacionCreateView.as_view(), name='assignacion_contact') , I fill the form and effectively it is saved in the database, but I want to get the id with which it was saved in the database, so in the form_valid method I try to get the id with self.object.pk or form.instance.pk but it returns None , how can I fix this? urls.py app_name = 'gestionAsignacion' urlpatterns = [ path('asignacionContact/<int:pk>/',AsignacionCreateView.as_view(), name='asignacion_contact'), path('detalle/asignacion/<int:pk>',descargarAsignacion.as_view(), name='descargar_asignacion'), path('asignacionGeneral/',asignacionGeneral.as_view(), name='asignacion_general'), ] model.py class AsignacionContact(models.Model): id = models.IntegerField(primary_key=True) idasignacion_general = models.ForeignKey('AsignacionGeneral', models.DO_NOTHING, db_column='idasignacion_general') nombre_asignacion = models.CharField(max_length=100) fecha_inicio = models.DateField() fecha_fin = models.DateField() observacion = models.CharField(max_length=255, blank=True, null=True) estado = models.IntegerField(blank=True, null=True) def __str__(self): return self.nombre_asignacion # def get_absolute_url(self): # print('reverse') # return reverse('gestionAsignacion:asignacion_contact',kwargs={ 'pk': self.pk }) class Meta: managed = False db_table = 'asignacion_contact' view.py class AsignacionCreateView(CreateView): model=AsignacionContact form_class=AsignacionForm template_name='gestionAsignacion/asignacion_contact.html' # success_url = reverse_lazy('gestionAsignacion:asignacion_general') def form_valid(self, form): isvalid = super().form_valid(form) print('form_valid') print(form.instance.pk) print(self.object.pk) return isvalid def post(self, request, *args, **kwargs): print('post') return super().post(request, *args, **kwargs) def get_form_kwargs(self): kwargs = super(AsignacionCreateView, self).get_form_kwargs() kwargs['pk'] = self.kwargs.get('pk') return kwargs def get_success_url(self): print('hola succes') print(self.object.id) return reverse('gestionAsignacion:asignacion_general') -
How to get total cart in Django?
I have 2 models: order and cart this is the order's model: class Order(models.Model): user=models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE) product=models.ForeignKey(Product, on_delete=models.CASCADE) quantity=models.IntegerField(default=1) ordered=models.BooleanField(default=False) ordered_date= models.DateTimeField(blank=True, null=True) def __str__(self): return f'{self.product.name}({self.quantity})' def get_total(self): total=self.quantity * self.product.price return total and this is the cart'model: class Cart(models.Model): user=models.OneToOneField(AUTH_USER_MODEL, on_delete=models.CASCADE) orders=models.ManyToManyField(Order) def __str__(self): return self.user.username def get_total_cart(self): orderitem = self.orders.all() total = sum(item.get_total() for item in orderitem) return total How could I fix the get_total_cart() function please -
Strange AttributeError error due to Views (Django)
type object 'projects' has no attribute '_default_manager' I am getting this error when on a second view using the same model as the first. If the model changes, and the fields are adjusted, it works. Both views are indentical aside from their template names as I need one to simply list children in a checklist model. class project(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = projects fields = [ 'name', 'fk_state', ] template_name = '/project_details.html' context_object_name = 'projects' def form_valid(self, form): form.instance.fk_user = self.request.user form.save() # return super().form_valid(form) return HttpResponseRedirect(self.request.path_info) def test_func(self): post = self.get_object() if self.request.user == post.fk_user: return True return False class project_checklist(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = projects fields = [ 'name', 'fk_state', ] template_name = '/project_checklist.html' context_object_name = 'checklist' def form_valid(self, form): form.instance.fk_user = self.request.user form.save() # return super().form_valid(form) return HttpResponseRedirect(self.request.path_info) def test_func(self): post = self.get_object() if self.request.user == post.fk_user: return True return False Urls path('projects/project/<int:pk>',project.as_view(), name='project'), path('projects/checklist/<int:pk>',project_checklist.as_view(), name='checklist'), -
Why is my save method not returning any value
When I do investment.basic_interest I get 0. Why is it returning 0? I feel my save method is not properly written. Any idea where the problem is coming from? class Investment(models.Model): basic_deposit_amount = models.IntegerField(default=0, null=True) basic_interest = models.IntegerField(default=0, null=True) def save(self, *args, **kwargs): self.basic_interest = self.basic_deposit_amount * 365 * 0.02/2 #calculated field. super(Investment, self).save(*args, **kwargs) -
How do I include previous years in a Django Model form
Forgive me if this has already been asked I have a blog and use the template you can see on Djangos website (with minor amendments) When I create a new blog I can select the date from January 1st 2022 to December 31st However there are some writing I made last year and wish to include the correct date for them. Any help is appreciated p.s. I'm using Sqlite as my database View from django.contrib.auth.mixins import LoginRequiredMixin from django.shortcuts import get_object_or_404, render, redirect from django.views.generic import ( CreateView, ListView, UpdateView, DetailView ) from tags.models import Tag from .forms import BlogForm from .models import Blog class BlogCreateView(LoginRequiredMixin, CreateView): template_name = 'blog/create_blog.html' form_class = BlogForm queryset = Blog.objects.all() def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) class BlogUpdateView(LoginRequiredMixin, UpdateView): template_name = 'blog/create_blog.html' form_class = BlogForm queryset = Blog.objects.all() def form_valid(self, form): return super().form_valid(form) def blog_delete_view(request, slug): obj = get_object_or_404(Blog, slug=slug) if request.method == "POST": obj.delete() return redirect('blog:home') context = { "object": obj } return render(request, "blog/delete_blog.html", context) class BlogListView(ListView): template_name = "blog/home.html" model = Blog blog_public = model.objects.filter(is_public=True, tags__public=True) def get_context_data(self, *args, **kwargs): context = super(BlogListView, self).get_context_data(*args, **kwargs) request = self.request user = request.user blog_tag = Tag.objects.filter(name="blog").first() if user.is_authenticated: blog_user = self.model.objects.filter(user=user)[:5] … -
'set' object is not reversible is being raised but I'm not getting specific file or line
I'm getting this error and browser indicating that program is complaining to {% url 'login' %}. And what interesting is that I've never used set in this code. For now it's sounds stupid error for me because of error indicating html file and complaining to set type. Environment: Request Method: GET Request URL: http://0.0.0.0:8000/ Django Version: 2.2 Python Version: 3.7.13 Installed Applications: ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'users.apps.UsersConfig', 'pages.apps.PagesConfig', 'crispy_forms', 'allauth', 'allauth.account'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template /code/templates/base.html, error at line 18 'set' object is not reversible 8 : &lt;link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" 9 : integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" 10 : crossorigin="anonymous"&gt; 11 : &lt;link rel="stylesheet" href="{% static 'css/base.css' %}"&gt; 12 : &lt;/head&gt; 13 : &lt;body&gt; 14 : &lt;header&gt; 15 : &lt;!-- Fixed navbar --&gt; 16 : &lt;div class="d-flex flex-column flex-md-row align-items-center p-3 px-md-4 17 : mb-3 bg-white border-bottom shadow-sm"&gt; 18 : &lt;a href=" {% url 'home' %} " class="navbar-brand my-0 mr-md-auto font-weight-normal"&gt;Bookstore&lt;/a&gt; 19 : &lt;nav class="my-2 my-md-0 mr-md-3"&gt; 20 : &lt;a class="p-2 text-dark" href="{% url 'about' %}"&gt;About&lt;/a&gt; 21 : {% if user.is_authenticated %} 22 : &lt;a class="p-2 text-dark" href="{% url 'logout' %}"&gt;Log Out&lt;/a&gt; 23 : {% else %} 24 : &lt;a class="p-2 text-dark" href="{% …