Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django decimal InvalidOperation error when beginning
I'm newbie on website, and I'm using django with the mariadb. I already have mariadb database to use, and this is my new (basic) website so there are no functions yet. To migrate the origin DB to django, my command was python manage.py inspectdb > models.py but the error decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>] occurs. What I can't understand is that I don't have any other code without the basic structure code. What I only did was to run the command django-admin startproject mysite python manage.py startapp board How can I fix this error? Search for an hour, but couldn't find the answer. -
database NOT NULL constraint failed Django error
I wnat to add an option to show which user add a book in my website. and I checked that user is signed up but i got this error. who can help me? Models: `class Books(models.Model): user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) title = models.CharField(max_length=150) author = models.CharField(max_length=150) description = models.TextField() price = models.DecimalField(max_digits=5, decimal_places=2) book_cover = models.ImageField(upload_to='books covers/', blank=True) def __str__(self): return f'{self.title} by {self.author}.' def get_absolute_url(self): return reverse('book_detail', args=[self.id]) ` Views: class AddBook(LoginRequiredMixin, generic.CreateView): model = Books form_class = AddBookForm template_name = 'books/add_book.html' I got that error...: IntegrityError at /books/add_book/ NOT NULL constraint failed: books_books.user_id I tried to write code that django knows which user adds a book but it can't... if you can help me i really appreciate that. -
Django. How can I edit the text received from the database using HTML?
I have a database that stores the text. I uploaded this text to the database as a list. I need this text to be displayed on the page in the same way as a list, but it is displayed as a string. I tried to connect javascript and use a loop to track ';' and write '\n' instead. The code itself worked fine, but when I started getting an element with my text using getElementById, I ran into a problem: I get a lot of text: aligntitlelangtranslatedirhidden... etc. My JS code: function textTab(){ let text = document.getElementById('specsText'); console.log(text); let newText = ''; for(let el in text) { if (el === ';'){ newText += '\n'; } else{ newText += el; }; }; console.log(newText); text.innerHTML = newText; }; textTab() I am a beginner, so I apologize in advance for the possible inaccuracy of the question or errors in the code -
Confused in selecting file format to serve as a template
I'm serving docx file as a template to user but the docx2html module is not working well, i just want to know that which file format is served by other resume builder apps like canva and zety. Or any other suggestions may be helpful. I want to serve a template to the user so that he/she enters his details in it and download it in pdf format -
app.control.revoke() doesn't change the state in CELERY, python
i have this conditional lst_of_active_tasks = insp.active() print(lst_of_active_tasks) for task in lst_of_active_tasks["celery@DESKTOP-HM2VGD6"]: if task["args"] and task["args"][0] == psid: app.control.revoke(task["id"]) checking if the task allready exists and being processed by a worker. then: process_and_send_message.apply_async(args=[psid, page.facebook_page_id, page.facebook_papge_token, conversation_dict]) which should send this task to be processed by a worker: @shared_task(bind=True) def process_and_send_message(self,psid, page_id, page_token, conversation_dict): for _ in range(10): time.sleep(1) result = AsyncResult(self.request.id) if result.state == "REVOKED": print("REVOKED") return "REVOKED" print(f"{result.id} :::::::::>>>>>>> {result.state}") return("some text") i want the task to return REVOKED if the task state is revoked. problem is: evevn after it being flagged as REVOKED it still gets processed: [2024-02-25 09:34:59,652: INFO/MainProcess] mingle: searching for neighbors [2024-02-25 09:35:00,659: INFO/MainProcess] mingle: all alone [2024-02-25 09:35:00,670: INFO/MainProcess] celery@DESKTOP-HM2VGD6 ready. [2024-02-25 09:35:05,584: INFO/MainProcess] Task apis.tasks.process_and_send_message[13652c4a-9ec3-438e-946d-3b1d91ee592a] received [2024-02-25 09:35:06,588: WARNING/ForkPoolWorker-4] 13652c4a-9ec3-438e-946d-3b1d91ee592a :::::::::>>>>>>> PENDING [2024-02-25 09:35:07,592: WARNING/ForkPoolWorker-4] 13652c4a-9ec3-438e-946d-3b1d91ee592a :::::::::>>>>>>> PENDING [2024-02-25 09:35:08,594: WARNING/ForkPoolWorker-4] 13652c4a-9ec3-438e-946d-3b1d91ee592a :::::::::>>>>>>> PENDING [2024-02-25 09:35:08,703: INFO/MainProcess] Tasks flagged as revoked: 13652c4a-9ec3-438e-946d-3b1d91ee592a [2024-02-25 09:35:08,707: INFO/MainProcess] Task apis.tasks.process_and_send_message[bbbbfcea-0680-4f7b-9f4c-dd37ec291e89] received [2024-02-25 09:35:09,597: WARNING/ForkPoolWorker-4] 13652c4a-9ec3-438e-946d-3b1d91ee592a :::::::::>>>>>>> PENDING [2024-02-25 09:35:09,716: WARNING/ForkPoolWorker-2] bbbbfcea-0680-4f7b-9f4c-dd37ec291e89 :::::::::>>>>>>> PENDING [2024-02-25 09:35:10,600: WARNING/ForkPoolWorker-4] 13652c4a-9ec3-438e-946d-3b1d91ee592a :::::::::>>>>>>> PENDING [2024-02-25 09:35:10,719: WARNING/ForkPoolWorker-2] bbbbfcea-0680-4f7b-9f4c-dd37ec291e89 :::::::::>>>>>>> PENDING i tried: app.conf.worker_pool_restarts = True >>>> didn't work app.control.revoke(task["id"], terminate=True) >>>> terminate causes the whole worker to stop. and i'm afraid … -
why is there an error during smtp authentication when i try to send an email from python
SMTPAuthenticationError at /register (535, b'5.7.8 Username and Password not accepted. For more information, go to\n5.7.8 https://support.google.com/mail/?p=BadCredentials oq9-20020a170906cc8900b00a3e59410a75sm1286238ejb.170 - gsmtp') Request Method: POST Request URL: http://127.0.0.1:8000/register Django Version: 5.0.1 Exception Type: SMTPAuthenticationError Exception Value: (535, b'5.7.8 Username and Password not accepted. For more information, go to\n5.7.8 https://support.google.com/mail/?p=BadCredentials oq9-20020a170906cc8900b00a3e59410a75sm1286238ejb.170 - gsmtp') i tried disabling 2FA but still no change -
Is there any way I can use objs = Model.objects.raw(sql) with PageNumberPagination in django rest framework without passing list(objs) to pagination
I'm currently facing a challenge with pagination while using raw SQL queries in Django. The situation arose when I needed to apply an additional filter in the LEFT OUTER JOIN of my query, which I found wasn't directly supported by Django's ORM. Despite attempting to use FilteredRelation, I realized that it didn't fully meet my requirements. As a workaround, I opted to use raw SQL queries, which allowed me to achieve the desired filter. However, I encountered a roadblock when attempting to paginate the results. It seems that raw querysets don't support pagination out of the box. Here's a snippet of the relevant code: queryset = CheckTraModelTotal.objects.raw(sql_query) page = RawQuerySetPaginator(queryset, 15) serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) -
Django Template Skip 1 loop if the Value is Duplicate
I'm working with manytomany field because of various variant of product .But the variants are duplicating i can do the that in view.py but if any one can do it in template that would be really helpful {% for z in variant %} {% for y in z.variant.all%} {% if y.type == x %} Title: {{x.title}} Code:{{x.code}} {% endif %} {% endfor %} {% endfor %} See these are the print <QuerySet [<Variant_type: Size(Small)>, <Variant_type: Material(Polyester)>, <Variant_type: Color(Red)>]> <QuerySet [<Variant_type: Size(Small)>, <Variant_type: Material(Leather)>, <Variant_type: Color(Red)>]> <QuerySet [<Variant_type: Size(Large)>, <Variant_type: Material(Polyester)>, <Variant_type: Color(Green)>]> I want one Red only one time same goes for any other -
Data Visualization with Chart JS
I'm trying to visualize some dynamic data sent from a django backend in a HTML template using Chart JS as my visualization software... Here is the expected sample output I have the template set up and I'm able to access the data inside it Any Help on how to achieve that? -
Color choosing option
In many ecommerce website they provide options to choose your color. So I is it possible to add a colorfield for products which will content how many colors are available for the product. If it is possible how can I do it? -
Date from a user visible to other users - Django project
I'm building an educational project in Django - it's a simple task manager application. The main issue I'm facing is, when I'm adding a new task, I can see 'Categories' added by different users alongside my own categories which might cause a mess in the database and confusion. On the screenshot, 'Holidays' is displayed twice, first one added by a different user, while second one added by my user. Screenshot: https://imgur.com/GiwwfXN Models: https://github.com/jpgenari/KaTask/blob/main/tasks/models.py Views: https://github.com/jpgenari/KaTask/blob/main/tasks/views.py Forms: https://github.com/jpgenari/KaTask/blob/main/tasks/forms.py Deployed project (no CSS applied yet): https://katask-9e69d33c7144.herokuapp.com/ I want to be able to view only categories I added myself when I'm creating or editing tasks. -
how to setup dynamically , without compose, multiple django docker containers with postgres containers for each domain on the fly
How does one deal with creating multiple django docker containers and their related postgresql docker containers for N domains. I have a local dnsserver to mimic production and i setup allow *.test.com and test.com to point to my 127.0.0.1 I have created a docker network bridge for all the docker containers running under this project so that I can reach them by name of the docker. So when a client/tenant register for a system, say company "mycomp", I create a django docker container called mycomp_web, it is reachable at mycomp.test.com, Ngnix parses the domain and maps the revers_proxy to find mycomp_web django container. This works well. But now I need to switch from sqlite to postgresql. So i need to also create a postgresql container for each domain. So it would be something like mycomp_db. Now the real question is ? how do I point my django instance to the right postgres container (using name of that container). Up until know I was using docker names to find the containers. How would you set the database entry in the settings.py of django 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'erp', 'USER': 'erp_user', 'PASSWORD': '123', 'HOST': '127.0.0.1', 'PORT': '5432', } How would one … -
I cannot get the page to render for the Django Apps tutorial
I am using the django tutorial to create my first polls app and to learn Django https://docs.djangoproject.com/en/5.0/intro/tutorial01/ Here are the files I have created so far: my app's file structure in mysite/urls.py I have this: from django.contrib import admin from django.urls import include, path urlpatterns = [ path("polls/", include("polls.urls")), path("admin/", admin.site.urls), ] In polls/urls.py I have this: from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), ] And in polls/views.py I have the following: from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the polls index.") I have been trying with http://localhost:8000/polls/ and it still doesn't work! Any thoughts please on why that might be? booo! I have debugged in every way I can but everything looks correct to me. I am using GitHub's IDE but I don't think that should be the problem. -
How does `CachedReferenceField` from mongoengine work?
I'm working on a project in which I should use Django, grpc and mongodb. The db operations are readonly except when user interacts with the system for example posting comments or like a post, in that case I need to update the existing db document. I also want to store caches and I do it on retrieve() and list(). Now I have problem with updating caches when user comments for example, I am able to update caches which are made in retrieve() and list() both, but doing it also for nested documents is really hard (it's doable but is not a clean way), hence I want to know if CachedReferenceField comes handy for this purpose or not?? I mean I have my own caching method which is exteremly personal (which I don't like and wish to do it in a "cleaner" way, any help about it would be appreciated too;), doesn't this CachedReferenceField interupt my caching method? or it is internall and has nothing to do with my method of caching? I read the document but it's not so descriptive. -
Problem finding the image path in Django in one of the apps
I have 2 apps in my django project: -accounts & -ticketsales my project show images for ticketsales's model but dosen't show images for accounts's model, when I run my project, ProfileImages folder create out of media folder(that contain project's image) project's setting.py is: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR,"static/") MEDIA_URL = "/media/" MEDIA_PATH = os.path.join(BASE_DIR,"media/") my image field in accounts model.py is(dosen't show this image): ProfileImage=models.ImageField(upload_to="profileImagess",null=True) profile view: @login_required def profileView(request): profile=request.user.profile context={ "profile":profile } return render(request,"accounts/profile.html",context) The image field in ticketsales model.py(show this image): Poster=models.ImageField(upload_to="concertImage",null=True I want to show my images in project but this dosen't happen -
Not submitting images in a form in django
It is even more accurate to say that the image name is sent, but nothing changes. I have a user model. The user has his own avatar (ImageField). I have written a form and put everything in the template. When submitting the form, everything is saved except the image. But when changing in the admin everything is fine. Why? Help me please already tried everything does not help!!!! settings.py: `MEDIA_ROOT = BASE_DIR / "media"` models.py: class Women(models.Model): class Status(models.IntegerChoices): DRAFT = 0, 'Черновик' PUBLISHED = 1, 'Опубликовано' title = models.CharField(max_length=255, verbose_name="Заголовок") slug = models.SlugField(max_length=255, unique=True, db_index=True, verbose_name="Slug", validators=[ MinLengthValidator(5, message="Минимум 5 символов"), MaxLengthValidator(100, message="Максимум 100 символов"), ]) photo = models.ImageField(upload_to="photos",default=None,blank=True,null=True,verbose_name="Фото") content = models.TextField(blank=True, verbose_name="Текст статьи") time_create = models.DateTimeField(auto_now_add=True, verbose_name="Время создания") time_update = models.DateTimeField(auto_now=True, verbose_name="Время изменения") is_published = models.BooleanField(choices=tuple(map(lambda x: (bool(x[0]), x[1]), Status.choices)), default=Status.DRAFT, verbose_name="Статус") cat = models.ForeignKey('Category', on_delete=models.PROTECT, related_name='posts', verbose_name="Категории") tags = models.ManyToManyField('TagPost', blank=True, related_name='tags', verbose_name="Теги") husband = models.OneToOneField('Husband', on_delete=models.SET_NULL, null=True, blank=True, related_name='wuman', verbose_name="Муж") objects = models.Manager() published = PublishedManager() def __str__(self): return self.title class Meta: verbose_name = "Известные женщины" verbose_name_plural = "Известные женщины" ordering = ['-time_create'] indexes = [ models.Index(fields=['-time_create']) ] def get_absolute_url(self): forms.py: class AddPostForm(forms.ModelForm): cat = forms.ModelChoiceField(queryset=Category.objects.all(), empty_label="Категория не выбрана", label="Категории") husband = forms.ModelChoiceField(queryset=Husband.objects.all(), empty_label="Не замужем", required=False, … -
Django RestFrameWork.Serializers: ValueError: Cannot assign "OrderedDict()
How to solve this errorm tried almost everything. Have tried these solutions 1st from stackoverflow and 2nd from official website of DRF they did not work. class AddressCreateSerializer(ModelSerializer): class Meta: model = Address fields = '__all__' class BaseUserCreateSerializer(UserCreateSerializer): address = AddressCreateSerializer() class Meta(UserSerializer.Meta): model = BaseUser fields = ( 'inn', 'email', 'first_name', 'last_name', 'middle_name', 'date_of_birth', 'gender', 'phone_number', 'address' ) def create(self, validated_data): address_data = validated_data.pop('address') address_instance = Address.objects.create(**address_data) base_user_instance = BaseUser.objects.create(**validated_data, address=address_instance) return base_user_instance Error message: ValueError: Cannot assign "OrderedDict([('country', 'United States'), ('oblast', 'California'), ('city_village', 'Los Angeles'), ('street', 'Main Street'), ('house', '123'), ('apartment', 'Apt 456'), ('postal_code', '90001')])": "BaseUser.address" must be a "Address" instance. -
IDE cannot install Csv/Config/Decouple import
The problem is that the built-in debugger complains about these lines. from decouple import config, Csv from unipath import Path I tried to install via the IDE, as recommended by the debugger itself, but I get errors. Collecting decouple Using cached decouple-0.0.7.tar.gz (3.3 kB) Installing build dependencies: started Installing build dependencies: finished with status 'done' Getting requirements to build wheel: started Getting requirements to build wheel: finished with status 'done' ERROR: Exception: Traceback (most recent call last): File "C:\Users\OtterAndFinek\.virtualenvs\TattooFoundlerProject-1CIClaAs\Lib\site-packages\pip\_internal\cli\base_command.py", line 180, in exc_logging_wrapper status = run_func(*args) ^^^^^^^^^^^^^^^ File "C:\Users\OtterAndFinek\.virtualenvs\TattooFoundlerProject-1CIClaAs\Lib\site-packages\pip\_internal\cli\req_command.py", line 245, in wrapper return func(self, options, args) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\OtterAndFinek\.virtualenvs\TattooFoundlerProject-1CIClaAs\Lib\site-packages\pip\_internal\commands\install.py", line 377, in run requirement_set = resolver.resolve( ^^^^^^^^^^^^^^^^^ File "C:\Users\OtterAndFinek\.virtualenvs\TattooFoundlerProject-1CIClaAs\Lib\site-packages\pip\_internal\resolution\resolvelib\resolver.py", line 95, in resolve result = self._result = resolver.resolve( ^^^^^^^^^^^^^^^^^ File "C:\Users\OtterAndFinek\.virtualenvs\TattooFoundlerProject-1CIClaAs\Lib\site-packages\pip\_vendor\resolvelib\resolvers.py", line 546, in resolve state = resolution.resolve(requirements, max_rounds=max_rounds) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\OtterAndFinek\.virtualenvs\TattooFoundlerProject-1CIClaAs\Lib\site-packages\pip\_vendor\resolvelib\resolvers.py", line 397, in resolve self._add_to_criteria(self.state.criteria, r, parent=None) File "C:\Users\OtterAndFinek\.virtualenvs\TattooFoundlerProject-1CIClaAs\Lib\site-packages\pip\_vendor\resolvelib\resolvers.py", line 173, in _add_to_criteria if not criterion.candidates: ^^^^^^^^^^^^^^^^^^^^ File "C:\Users\OtterAndFinek\.virtualenvs\TattooFoundlerProject-1CIClaAs\Lib\site-packages\pip\_vendor\resolvelib\structs.py", line 156, in __bool__ return bool(self._sequence) ^^^^^^^^^^^^^^^^^^^^ File "C:\Users\OtterAndFinek\.virtualenvs\TattooFoundlerProject-1CIClaAs\Lib\site-packages\pip\_internal\resolution\resolvelib\found_candidates.py", line 155, in __bool__ return any(self) ^^^^^^^^^ File "C:\Users\OtterAndFinek\.virtualenvs\TattooFoundlerProject-1CIClaAs\Lib\site-packages\pip\_internal\resolution\resolvelib\found_candidates.py", line 143, in <genexpr> return (c for c in iterator if id(c) not in self._incompatible_ids) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\OtterAndFinek\.virtualenvs\TattooFoundlerProject-1CIClaAs\Lib\site-packages\pip\_internal\resolution\resolvelib\found_candidates.py", line 47, in _iter_built candidate = func() ^^^^^^ File "C:\Users\OtterAndFinek\.virtualenvs\TattooFoundlerProject-1CIClaAs\Lib\site-packages\pip\_internal\resolution\resolvelib\factory.py", line 182, … -
Django model ManyToManyField.add is not working
I have a model named TopicRoom and it has a field called creator which is a foreign key to the user model. And a many to many field called members which is a many to many rel to the user model @receiver(post_save, sender=models.TopicRoom) def add_topic_room_creator_as_a_member(instance, created, **kwargs): if created: print("added creator", instance.creator, instance) instance.members.add(instance.creator) print(instance.members.all()) When I create a new instance in the admin panel it prints this added creator bob@gmail.com TopicRoom object (24) <QuerySet [<User: bob@gmail.com>]> but when I view the model in the admin panel it shows that there are no members. And when I retrieve the model from the django manage.py shell, that also shows that there are no members for that object instance >>> TopicRoom.objects.get(id=24).members.all() <QuerySet []> -
How to correctly display static files in Django when debug = False?
what should I do if I used a command python manage.py collectstatic and don’t understand what needs to be done in order for static files to be located and displayed, i get only 404 when i try to load server and my css also dont working my settings.py: DEBUG = False ALLOWED_HOSTS = ['127.0.0.1'] PATH_TO_YOUR_STATIC_FOLDER= 'man/static/' STATICFILES_DIRS = [ BASE_DIR / "man/static", PATH_TO_YOUR_STATIC_FOLDER, ] STATIC_ROOT = BASE_DIR / "staticfiles" # Internationalization # https://docs.djangoproject.com/en/5.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/5.0/howto/static-files/ STATIC_URL = '/static/' # Default primary key field type # https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' my files structure maybe i need to edit STATICFILES_DIRS? i was trying to change STATICFILES_DIRS in settings, but nothing -
Django access MultilinestringM in Postgis with Geometry(dim=3)
I do have Railway-lines using "Linear Referencing" stored as MultilinestringM in a Postgis-DB (created by FME). So each line has a certain code and along that line assets are placed (km_from, km_to). I do need read access only in order to calculate Linestring from the given from-to values. I try to access that Postgis Information with Django (Geodjango). Does anybody have a clue how to do so? Since in found out Django-Models do not support M-values i thought i try MulitlinestringField with dim=3 and use the z-Dimension which actually would be the m-Dimension. When accessing the DB I only get 2-dimensional Multilinestring even when setting dim=3. geom = models.MultiLineStringField( dim=3, srid=EPSG_CODE, blank=True, null=True, spatial_index=True ) # EPSG:3128=AustriaLambert Does anybody know how I can read in all 3 values from the MultilineStringM stored in Postgis? Many thanks Since in found out Django-Models do not support M-values i thought i try MulitlinestringField with dim=3 and use the z-Dimension which actually would be the m-Dimension. When accessing the DB I only get 2-dimensional Multilinestring even when setting dim=3. -
Difficulty using multiple filters simultaneously in Django view with HTMX
I'm encountering an issue with using multiple filters simultaneously in a Django view while incorporating HTMX for asynchronous updates. Here's a breakdown of the relevant code and the problem I'm facing: Html Requests: <input id="searchInput" class="form-control mb-4" type="search" name="searchInput" placeholder="Procure produtos pelo nome..." hx-get="{% url 'filter_products' %}?searchInput={{ searchInput.value }}" hx-trigger="input changed delay:500ms, search" hx-target="#search-results"> <select name="name_category" class="form-select px-0 py-0" multiple aria-label="multiple select example" hx-get="{% url 'filter_products' %}" hx-trigger="change" hx-target="#search-results"> Filter View: def filter_products(request): category_names = request.GET.getlist('name_category', []) search_query = request.GET.get('searchInput') print(search_query) print(category_names) # Start with all products products = Products.objects.all() # Apply category filter if any category is selected if category_names: category_filters = Q() for category_name in category_names: category_filters |= Q(categoryproducts__category__name_category=category_name) products = products.filter(category_filters) # Apply search filter if a search query is provided if search_query: products = products.filter(title__icontains=search_query) # Render the response using the products found html = render_to_string('products/products_list_partial.html', {'products': products}) return HttpResponse(html) The issue arises when I attempt to use both filters simultaneously. If I select a category while a search query is applied (or vice versa), the other filter gets cleared. For instance, if I have a search query applied and then select a category, the search query disappears, and only the category filter is applied. How … -
django.db.utils.ProgrammingError: column app_table.field does not exist
I have a django app which is already in production. I added some new tables and new fields to existing tables and all went well in the feature branch, but when I merged it with the main branch then i got the following error: django.db.utils.ProgrammingError: column appname_table.field does not exist. I have tried deleting migrations, running fake migrations and a lot of other stuff but it doesn't work out. It might be possible to delete database on local but not in production because already there is user data. -
Django dynamic pages. Why is my code not working?
I am creating a website for the sale of goods, and for each product I create a card based on data from the database. When a new card appears, a dynamic page based on the same database data should be automatically connected to it. The page is created, but the data from the model is not loaded. I watched the Django guide, and it showed this method using DetailView, from where I took the code. Please help me, I don't understand what the problem is. My code: views.py: class car(DetailView): model = inventory template_name = 'main/cars.html' context_object_name = 'inventory' urls.py: urlpatterns = [ path('inventory/<int:pk>', views.car.as_view(), name='cars'), ] cats.html: {% extends 'main/layout.html' %} {% block main %} {% for el in invent %} <div class="main-card "> <img src = '{{ el.img_1 }}' style=""> <h3 style="">{{ el.name }}</h3> <h4 style="">{{ el.rent }}</h4> <button><a href="{% url 'cars' el.id %}">Details</a></button> </div> {% endfor %} {% endblock %} models.py: class inventory(models.Model): name = models.CharField('Name', max_length=100) type = models.CharField('Type of car', max_length=6) img_1 = models.ImageField(upload_to='./sql_imgs') img_2 = models.ImageField(upload_to='./sql_imgs') img_3 = models.ImageField(upload_to='./sql_imgs') img_4 = models.ImageField(upload_to='./sql_imgs') img_5 = models.ImageField(upload_to='./sql_imgs') img_6 = models.ImageField(upload_to='./sql_imgs') img_7 = models.ImageField(upload_to='./sql_imgs') img_8 = models.ImageField(upload_to='./sql_imgs') MSRP = models.CharField('msrp', max_length=40) Purchase = models.CharField('purchase', max_length=40) rent = … -
inside inner class, parameter is not accessed despite being defined inside the class [closed]
I am trying to use an inner class inside an outer class, to make it easier to deal with a large number of parameters. I am currently using Django Rest API. Here is how it looks like now : `class MeasureProcessingContext: def __init__(self, request, cache_metadata, measure_ids, user, paging_id, result,to_include): self.request = request self.cache_metadata = cache_metadata self.measure_ids = measure_ids self.user = user self.size_in_query = 'size' in self.request.query_params self.eval_in_query ='eval' in self.request.query_paramsy self.measure_in_query = 'measure' in self.request.query_params self.page_in_query = 'page' in self.request.query_params self.paging_id = int(self.page_in_query) if self.page_in_query else 0 if self.eval_in_query else -1 self.result = result self.to_include = to_include` The issue is that I get an error as part of the argument, namely paging_id, even though it is being set, I get "paging_id" is not accessedPylance.Even though it is clearly being set as part of the init call. I was expecting to be able to sovle the "paging_id" is not accessedPylance error, such that even argument of the __init___function are defined. I have also tried without using a specific class (in this case MeasureProcessingContext) but due to the number of parameters, this solution ended up being not optimal.