Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
virtual env in django
While I was trying to execute the mkvirtualenv command on the command prompt, I was getting this error: 'mkvirtualenv' is not recognized as an internal or external command, operable program or batch file python 3.10 windows 11 Expecting to create a virtual env -
(fields.E300) Field defines a relation with mode which is either not installed, or is abstract. many to many Model
I have the error message "recipes.Recipe.categories: (fields.E300) Field defines a relation with model 'Catego ry', which is either not installed or is abstract. "I am at a complete loss, even though in my eyes I did everything by the book. Nor am I really any the wiser after analysing my code. The Model Recipe from backend.apps.categories.models import Category class Recipe(models.Model): title = models.CharField( db_index=True, max_length=256, unique=False, null=False, verbose_name=_("Titel") ) lang = models.ForeignKey(Language, on_delete=models.RESTRICT, verbose_name=_("Sprache")) categories = models.ManyToManyField(Category, default=None) settings.py - INSTALLED_APPS "backend.apps.categories", "backend.apps.cookbooks", "backend.apps.cookparty", "backend.apps.customer", "backend.apps.dashboard", "backend.apps.hints", "backend.apps.home", "backend.apps.lexicon", "backend.apps.masterdata", "backend.apps.seo", "backend.apps.service", "backend.apps.user", "backend.apps.recipes", "backend.apps.importer", The Model Category class Category(models.Model): name = models.CharField(max_length=50, unique=True) parent = models.ForeignKey( to="Category", on_delete=models.SET_NULL, default=None, null=True, blank=True ) is_active = models.BooleanField(default=False) slug = models.SlugField(default=None, blank=True, unique=True) In the debug, all apps are listed under 'INSTALLED_APPS'. For me, the error is completely irrational. Does anyone have a tip for me as to which screw I need to turn? -
Django - No such column: rowid when migrating Spatialite database
I am trying to create a database using GeoDjango, but when I try to migrate the database I get "error in trigger ISO_metadata_reference_row_id_value_insert: no such column: rowid". I have added the right database engine and included 'django.contrib.gis', in settings.py. Any ide what the problem might be? from django.contrib.gis.db import models # Create your models here. class Bus(models.Model): busID = models.IntegerField(primary_key=True) route = models.CharField(max_length=20) operator = models.SmallIntegerField() latitude = models.DecimalField( max_digits=8, decimal_places=6) longitude = models.DecimalField( max_digits=8, decimal_places=6) location = models.PointField(srid=4326, blank=True, null=True) updated = models.DateTimeField(blank=True, null=True) lastStop = models.IntegerField(blank=True, null=True) def __str__(self): return self.busID settings.py: DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.spatialite', 'NAME': BASE_DIR / 'db.sqlite3', } } Error: python3 ./manage.py migrate Operations to perform: Apply all migrations: admin, api, auth, contenttypes, sessions Running migrations: Applying admin.0002_logentry_remove_auto_add...Traceback (most recent call last): File "/opt/homebrew/lib/python3.11/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/opt/homebrew/lib/python3.11/site-packages/django/db/backends/sqlite3/base.py", line 357, in execute return Database.Cursor.execute(self, query, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ sqlite3.OperationalError: error in trigger ISO_metadata_reference_row_id_value_insert: no such column: rowid The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/vvv/Documents/Prosjekter/mqtt/./manage.py", line 22, in <module> main() File "/Users/vvv/Documents/Prosjekter/mqtt/./manage.py", line 18, in main execute_from_command_line(sys.argv) File "/opt/homebrew/lib/python3.11/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/opt/homebrew/lib/python3.11/site-packages/django/core/management/__init__.py", line … -
Display Username when request is set declined
class PendingRequest(models.Model): book_request = models.ForeignKey(Borrow, on_delete=models.CASCADE, null=True) member = models.ForeignKey(User, on_delete=models.CASCADE, default=None, null=True) book = models.ForeignKey(Books, on_delete=models.CASCADE, default=None, null=True) approved = models.BooleanField(default=False, verbose_name="Approved") declined = models.BooleanField(default=False, verbose_name="Declined") request_date = models.DateTimeField(auto_now_add=True) approval_date = models.DateTimeField(auto_now=True, null=True) I have a view function that loop through this above model and displays the status of every request in database and renders it out in a table in template. Whenever the request is approved, it displays True and whenever it is declined, it display False. The problem i am facing is that whenever all the request for a user is set to False, it doesn't display the username of the user in member datacell of the table Here is the template <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <body> <table border="1"> <thead> <tr> <th>Member</th> <th>Book</th> <th>Request Date</th> <th>Approval Date</th> <th>Status</th> </tr> </thead> <tbody> {% for username, requests in user_requests.items %} {% with num_requests_approved=requests.approved_requests|length num_requests_declined=requests.declined_requests|length %} {% for request in requests.approved_requests %} <tr> {% if forloop.first %} <td rowspan="{{ num_requests_approved|add:num_requests_declined }}"> {{ username }} </td> {% endif %} <td><a href="{{request.book.book.url}}">{{ request.book }}</a></td> <td>{{ request.request_date }}</td> <td>{{ request.approval_date }}</td> <td>{{ request.approved }}</td> </tr> {% endfor %} … -
ResourceWarning: unclosed file <_io.BufferedReader name=
I have used with open but no luck but I still get this error : ResourceWarning: unclosed file <_io.BufferedReader name='/home/idris/Documents/workspace/captiq/captiq/static/docs/CAPTIQ Datenschutzhinweise.pdf'> attachment=customer_profile.get_attachments(), ResourceWarning: Enable tracemalloc to get the object allocation traceback below is my function which the error points to : def get_attachments(self): files = None cp = ( self.cooperation_partner.get_cooperation_partner() if self.cooperation_partner else None) # TODO: improve implementation: too many conditions if cp and cp.custom_attachments.exists(): files = [f.attachment for f in cp.custom_attachments.all()] elif cp and cp.pool.default_b2b_attachments.exists(): files = [ f.attachment for f in cp.pool.default_b2b_attachments.all()] else: files = self.get_default_attachments() if not files: path_one = finders.find( 'docs/file_1.pdf') path_two = finders.find('docs/file_2.pdf') with open(path_one, 'rb') as f1, open(path_two, 'rb') as f2: files = [f1, f2] attachments = [ { 'filename': os.path.basename(attachment.name), 'content': attachment.read(), 'mimetype': mimetypes.guess_type(attachment.name)[0] } for attachment in files] return attachments attachments = [ { 'filename': os.path.basename(attachment.name), 'content': attachment.read(), 'mimetype': mimetypes.guess_type(attachment.name)[0] } for attachment in files] return attachments So the issue is here with this section : with open(path_one, 'rb') as f1, open(path_two, 'rb') as f2: files = [f1, f2] attachments = [ { 'filename': os.path.basename(attachment.name), 'content': attachment.read(), 'mimetype': mimetypes.guess_type(attachment.name)[0] } for attachment in files] return attachments -
pipenv install fails in Django project
i have a django project and when i tried to run python manage.py migrate i git this error django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. and i knew i had to run pipenv install so here is my pipfile and below the error ocures when i try to run pipenv install Note : I tried to open pipenv shell first then install and it didnt work pipfile-> [[source]] url = "https://pypi.org/simple" verify_ssl = true name = "pypi" [packages] django-admin = "*" django = "*" djangorestframework = "*" djangorestframework-simplejwt = "*" drf-yasg = "*" django-cors-headers = "*" django-multiupload = "*" twilio = "*" django-redis = "*" psycopg2-binary = "*" python-dotenv = "*" dj-database-url = "*" django-storages = "*" boto3 = "*" gunicorn = "*" pillow = "*" django-filter = "*" ipdata = "*" pip = "*" install = "*" [dev-packages] black = "*" [requires] python_version = "3.11"` and here is the error I get when i run pipenv install `Loading .env environment variables... Courtesy Notice: Pipenv found itself running within a virtual environment, so it will automatically use that environment, instead of creating its own for any project. You can set PIPENV_IGNORE_VIRTUALENVS=1 … -
Migrate Custom Field Renderer from Django 1.8 to Django 3.2
I am trying to migrate a custom field renderer in a Django 1.8 form to Django 3.2. The form looks like this: class SomeEditForm(forms.ModelForm): job_uuid=forms.CharField(widget=forms.HiddenInput()) class Meta: model=Job fields=('status',) widgets={'status': forms.RadioSelect(renderer=BSRadioFieldRenderer)} So as it seems there is no Rendermixin anymore which accepts a renderer in its def init(). I have read the new source code and see that RadioSelect is now a subclass of ChoiceWidget. I cant get my head around to inject my old renderer into the new structure. Can someone please point me into the right direction? Thanks for your help! :) -
How to auth users with JWT in django microservice-like project?
I already have JWT from external auth service and want to use it in my django (DRF actually) project, I also want to populate user model basing on this jwt. How can I implement this? most of libs are about django as auth service, not just client -
Django Rest Framework api: bulk_create assigning a str to the primary key and a number to my str field
I'm creating a basic Pokemon API for practise purposes, where my models include: Card, Expansion and Type (fire, water, bug, ice, etc.) I'm trying to run a script to populate the "Type" database table but I get weird results, where the type name field actually seems to contain the primary key value and the ID field contains the actual name, when it should be the other way around. When I use Type.objects.all() to print the table contents (I set __repr__ to print the primary key (ID) and the name only) I can see this: <QuerySet [Type( ID: Normal; NAME: 1), Type( ID: Fighting; NAME: 2), Type( ID: Flying; NAME: 3), Type( ID: Poison; NAME: 4), Type( ID: Ground; NAME: 5), Type( ID: Rock; NAME: 6), Type( ID: Bug; NAME: 7), Type( ID: Ghost; NAME: 8), Type( ID: Steel; NAME: 9), Type( ID: Fire; NAME: 10), Type( ID: Water; NAME: 11), Type( ID: Grass; NAME: 12), Type( ID: Electric; NAME: 13), Type( ID: Psychic; NAME: 14), Type( ID: Ice; NAME: 15), Type( ID: Dragon; NAME: 16), Type( ID: Dark; NAME: 17), Type( ID: Fairy; NAME: 18)]> Also, when trying to run Type.objects.all().delete() to clear the table records, I get "ValueError: Field … -
Submit form with only two clicks on Submit Django
I created a page with questions to the phone, I need that when, when a person clicks on the submit form, he must submit the form with one click, and change the same form with one click too. But for now, it can be done with just two mouse clicks. my models.py: class Items_buy(models.Model): class Meta: db_table = 'items_buy' verbose_name = 'Телефон который покупаем' verbose_name_plural = 'Телефоны которые покупаем' image_phone = ResizedImageField(size=[100,100], upload_to='for_sell/',verbose_name='Фотография модели телефона') model_produkt = models.TextField(max_length=80, verbose_name='Модель продукта ') text = models.TextField(max_length=500, verbose_name='Текст') max_prise = models.FloatField(verbose_name='Максимальная цена telefoha') image_phone_for_buy_bord = ResizedImageField(size=[100,100],upload_to='for_sell/',verbose_name='Фотография модели телефона ha prodazy') def __str__(self): return self.model_produkt class Question(models.Model): class Meta: db_table = 'question' verbose_name = 'Вопрос к телефону' verbose_name_plural = 'Вопросы к телефону' items_buy = models.ForeignKey(Items_buy, on_delete=models.RESTRICT) titles= models.CharField(max_length=150,verbose_name='Заголовок вопросa') question_text =models.TextField(max_length=100, verbose_name='Заголовок вопросa text') #max_prise_qustion = models.FloatField(verbose_name='Максимальная цена') def __str__(self): return self.titles class Choice(models.Model): class Meta: db_table = 'choice' verbose_name = 'Выбор ответа' verbose_name_plural = 'Выбор ответов' question = models.ForeignKey(Question, on_delete=models.RESTRICT,related_name="options") title = models.CharField(max_length=1000, verbose_name='Заголовок выбора') price_question = models.FloatField(verbose_name='Цена ответа') #lock_other = models.BooleanField(default=False, verbose_name='Смотреть другой вариант ответа') def __str__(self): return str(self.price_question) class Answer(models.Model): class Meta: db_table = 'answer' verbose_name = 'Ответ на вопрос' verbose_name_plural = 'Ответы на вопросы' items_buy = models.ForeignKey(Items_buy, on_delete=models.RESTRICT) question = … -
HTML - How to auto refresh the messages of a Chat-App
I'm working on a Chat-App with Django in Python. I tried some changes to auto refresh the messages of a chat but I had some problems: First time I tried: I used a javascript reloader for the div of the chat (but doing this, the send-message text input clears every time the auto refresher plays.) Second problem: the chat reset the height of the scroll every time the auto refresher plays. So I'm looking for a solution to refresh only the chat and keeping the scroll, without affecting other elements such as the text input. Here's the "chats.html" file: <div class="container-fluid h-100" style="posistion:absolute; margin-left:60;"> <div class="row justify-content-center h-100"> <div class="col-md-4 col-xl-3 chat"> <div class="card mb-sm-3 mb-md-0 contacts_card" style="max-height:700;min-height:700"> <div class="card-header"> <div class="input-group"> <input type="text" placeholder="Search..." name="" class="form-control search"> <div class="input-group-prepend"> <span class="input-group-text search_btn"><i class="fas fa-search"></i></span> </div> </div> </div> <div class="card-body contacts_body"> <ui class="contacts"> {% for group in groups %} <a href="/chats/{{ group.event_name }}/" style="text-decoration: none;"> {% if group.event_name == current_group.event_name %} <li class="active"> <div class="d-flex bd-highlight" > <div class="img_cont"> <img src="{{ group.event_img.url }}" class="rounded-circle user_img"> <span class="online_icon"></span> </div> <div class="user_info"> <span>{{ group.event_name }}</span> <p>Kalid is online</p> </div> </div> </li> {% else %} <li class=""> <div class="d-flex bd-highlight"> <div class="img_cont"> <img … -
Execute Celery task after Django model timestamp has passed
I am trying to build a Django app that reacts to certain events, and then after X amount of time, executes a celery task. Users with permissions are given the option of either vetoing the action, or expediting the action. I am using Django 4.1 and Python 3.10. Veto does not need to take effect immediately, as the celery task will just check for it once it runs. Expedite does need to take effect immediately, but must require more than a single user to vote on it. Votes may have their "expiry time" changed by an admin, and the celery task should change the eta accordingly (or the task revoked and a new one put in the queue, with the updated eta). The work must be done in near-real-time, so no having a daily task that checks for expired votes. An example might make it a lot more clear: Bob has quit his job, and therefore his user accounts and access need to be revoked. A celery task that does just that, is put into the celery queue, with an eta of 2 days into the future (the timestamp is also logged in a Django model). HR is notified that … -
Make a pie chart using chart.js in Django error
I am building a budget tracker application and in dashboard page, I'd like to list different graphs. The pie chart is for expense structure showing how much expense is spent in certain categories. I'm facing two problems mainly. First one is the data of model in view doesn't pass through the template which results graph not showing. Second one is that I'm trying to show proportion of certain categories of expense, not a proportion of every expense(sum of accumulation of expense has to be calculated if they're in same category.) If I can get help, I'd be so much appreciated. models.py class Transaction(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) TRANSACTION_CHOICES = [ ('Expense','Expense'), ('Income','Income'), ] transaction_type = models.CharField(max_length=10, blank=False, choices=TRANSACTION_CHOICES, default="Expense",null=True) title = models.CharField(blank = False, max_length=30) description = models.CharField(blank = True, max_length=200) amount = models.DecimalField(blank=False, max_digits=10, decimal_places=2) date_paid = models.DateField(auto_now_add=False, blank=True, null=True) time_paid = models.TimeField(auto_now_add=False, blank=True, null=True) CATEGORY_CHOICES = [ ('Groceries', 'Groceries'), ('Salary', 'Salary'), ('Bills', 'Bills'), ('Rent', 'Rent'), ('Gym', 'Gym'), ('Restaurant', 'Restaurant'), ('Vacation', 'Vacation'), ('Travel', 'Travel'), ('Gift', 'Gift'), ('Investments', 'Investments'), ('Savings', 'Savings'), ('Entertainment', 'Entertainment'), ('Internet', 'Internet'), ('Healthcare', 'Healthcare'), ('Lifestyle', 'Lifestyle'), ('Insurance', 'Insurance'), ('Other', 'Other'), ] category = models.CharField(max_length=50, blank=False, choices=CATEGORY_CHOICES) receipt = models.ImageField(upload_to='receipt_images', blank = True) def __str__(self): return self.title def … -
TypeError: unsupported operand type(s) for *: 'NoneType' and 'decimal.Decimal'
File "F:\Coding Related\Karmachari-BackEnd\Karmachari_App\mainapp\models.py", line 97, in calculate_net_salary gross_pay = self.hours_worked * self.basic_pay_rate ~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~ TypeError: unsupported operand type(s) for *: 'NoneType' and 'decimal.Decimal' These are the lasted error message in terminal. in my model.py i have class Payroll(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) basic_pay_rate = models.DecimalField(max_digits=8, default=10000, decimal_places=2) overtime = models.DecimalField(max_digits=8,null=True, decimal_places=2) hours_worked = models.FloatField(null=True, blank=True) deductions = models.DecimalField(max_digits=8,null=True, decimal_places=2) net_pay = models.DecimalField(max_digits=8,null=True, blank=True, decimal_places=2) def calculate_net_salary(self): gross_pay = self.hours_worked * self.basic_pay_rate net_pay = gross_pay + self.overtime - self.deductions self.net_pay.save() # def save(self, *args, **kwargs): # self.net_salary = self.calculate_net_salary() # super(Payroll, self).save(*args, **kwargs) def __str__(self): return self.user.username in my views.py i have def payroll(request): payrolls = Payroll.objects.all() for payroll in payrolls: payroll.calculate_net_salary() user_object = User.objects.get(username=request.user.username) profile = Profile.objects.get(user=user_object) context={ 'profile':profile, 'navbar':'salary', 'payroll': payroll, } return render(request,'Salary_Sheet.html',context) I want to access payroll of each employee and calculate net salary and provide them in pdf. This is my first project so I dont know the concept clearly and want a beginner friendly explanation or solution. -
How to add a favorite function?
First time asking here so be patient with me, also trying to learn django. I have the following codes : class Favorite(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) apartment = models.ForeignKey(Apartment, on_delete=models.CASCADE) class Meta: unique_together = ('user', 'apartment') and {% extends 'base.html' %} {% load static %} <head> <title>Browse Rooms</title> <link rel="stylesheet" type="text/css" href="{% static 'css/browse_rooms.css' %}"> </head> {% block content %} <div class="container mt-5"> <h2 class="mb-4"><i class="fas fa-search"></i> Browse Rooms</h2> <div class="row"> {% for apartment in apartments %} <div class="col-md-4 mb-4"> <div class="card"> {% if apartment.image %} <img class="card-img-top" src="{{ apartment.image.url }}" alt="Profile Image"> {% endif %} <div class="card-body"> <h5 class="card-title">{{ apartment.address }}, {{ apartment.city }}, {{ apartment.state }} {{ apartment.zipcode }}</h5> <p class="card-text">Price: ${{ apartment.price }}</p> <p class="card-text">Bedrooms: {{ apartment.bedrooms }}</p> <p class="card-text">Bathrooms: {{ apartment.bathrooms }}</p> <p class="card-text">Move-in Date: {{ apartment.move_in_date|date:"F j, Y" }}</p> <a href="{% url 'apartment_detail' apartment.id %}" class="btn btn-primary"><i class="fas fa-info-circle"></i> View Details</a> <a href="#" class="btn btn-outline-secondary" onclick="addToFavorites({{ apartment.id }})"><i class="fas fa-heart"></i> Add to Favorites</a> </div> </div> </div> {% empty %} <p>No apartments found.</p> {% endfor %} </div> </div> {% endblock %} I tried to search on web how to implement this function but there are many methods and i don't understand the logic behind cause they … -
Can I override Django rendering checkbox inputs inside a label?
I'm trying to render a form which allows for multiple selections via checkboxes. I've tried with django-multiselectfield (which I was already using) and the native CheckboxSelectMultiple widget. If I have a simple form like so: FAVORITE_COLORS_CHOICES = [ ('blue', 'Blue'), ('green', 'Green'), ('black', 'Black'), ] class SimpleForm(forms.Form): favorite_colors = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple, choices=FAVORITE_COLORS_CHOICES, ) And if I render with widget tweaks like so: {% render_field form.favorite_colors %} <div id="id_favorite_colors"> <div> <label for="id_favorite_colors_0"> <input class="form-control" id="id_favorite_colors_0" name="favorite_colors" placeholder="Your Name" type="checkbox" value="blue" /> Blue</label> </div> <div> <label for="id_favorite_colors_1"> <input class="form-control" id="id_favorite_colors_1" name="favorite_colors" placeholder="Your Name" type="checkbox" value="green" /> Green</label> </div> <div> <label for="id_favorite_colors_2"> <input class="form-control" id="id_favorite_colors_2" name="favorite_colors" placeholder="Your Name" type="checkbox" value="black" /> Black</label> </div> </div> This is causing problems for the way I want to render my form. Is there any way I can force Django to output the input and then the label, so the html would be like so: <div id="id_favorite_colors"> <div> <input class="form-control" id="id_favorite_colors_0" name="favorite_colors" placeholder="Your Name" type="checkbox" value="blue" /> <label for="id_favorite_colors_0">Blue</label> </div> <div> <input class="form-control" id="id_favorite_colors_1" name="favorite_colors" placeholder="Your Name" type="checkbox" value="green" /> <label for="id_favorite_colors_1">Green</label> </div> <div> <input class="form-control" id="id_favorite_colors_2" name="favorite_colors" placeholder="Your Name" type="checkbox" value="black" /> <label for="id_favorite_colors_2">Black</label> </div> </div> I haven't found an easy answer to this and most … -
request Timeout Error when creating pdf export for many users - django
I want to export from my users in site. but when I want to export from many users, I see this error: request Timeout I made a thread to solve this problem. But when downloading the file, the file is not downloaded, but the error is not shown on the site. Please guide def pdf(request, users): # ceating pdf code ... with open('media/pdf-export/exports/export.zip', 'rb') as fh: response = FileResponse(fh) response['Content-Disposition'] = 'inline; filename=' + os.path.basename('media/pdf-export/exports/export.zip') return response @admin.register(User) class UserAdmin(admin.ModelAdmin): list_display = ['id', 'time', 'first_name', 'last_name', 'phone_number', 'contract_number'] sortable_by = ['time'] list_filter = ['accept', 'final_submit'] search_fields = ['first_name', 'last_name', 'phone_number'] actions = ['export_to_excel', 'export_to_pdf'] .... def export_to_pdf(self, request, users): pdf_ = threading.Thread(target=pdf, args=[request, users, ], daemon=True) pdf_.start() I used thrading for control timeout error -
IntegrityError at /adduser (1048, "Column 'username' cannot be null")
I am trying to create a simple user registration following the CRUD procedure but i encounter the following problem whenever i try to key in a user`s details. Here is my adduser function. `def adduser(request): username = request.POST.get('firstname'); email = request.POST.get('email'); password = request.POST.get('password'); newuser = User(username=username, email=email, password=password); newuser.save(); return render(request, 'vinstarapp/index.html', {}) ` I tried using first_name, last_name but had a type error at adduser/ Changed it to username and now the integrity error. -
'static' appears in my url to the next page
I've hosted my web app on pythonanywhere.com but i have a problem when trying to route to the next item in a pagination object. The home page contains a list of contents (blogs) Down below, i have a pagination. Normally, when i click on the next button, the url should be "https://domain_name/?page=page_num" but instead it turns to "https://domain_name/static/?page=page_num" and it renders a 404 page The is my static url, root and dirs settings STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ "blog/static/blog" ] Static url and path on pythonanywhere -
what is m2m_changed signal for one to many(foreign key)
so I have a model A which is a foreign key in model B, and I have another model C what I need to do is once B changes from A admin inline I want to get the sum of all B instances related that A and update another model C so here are the steps I want to do: 1 - (B1,B2,B3) have A1 as fk_a all of them when A1 admin form is saved 2- I want wait for all of them to finish save() then I get the sum of their quantity and do something with it in (C1,C2,C3) class A(models.Model): name = CharField(max_length=20) class B(models.Model): quantity = IntegerField() fk_a = ForiegnKey(A) def save(): sum_of_similar_b = B.objects.filter(fk_a=self.fk_a) similar_c = C.objects.filter(fk_a=self.fk_a) update_model_c(sum_of_simlar_b, similar_c) I tried post_save() signal but it's called before the foreign keys are updated and tried A save() same. tried m2m_changed signal without "through" but it doesn't get triggered -
Can I use django rest framework with simple front end app using features from bootstrap for example?
can DRF be used with simple front end app by using ready-made features from bootstrap for example or I should use regular django since I don't have experience with front end frameworks? What choice should I adopt? -
Django installed but not able to locate module
I'm using a django web project template and its my first time creating one. I had to pip install django but the code that is existing still isnt referencing it and instead its giving a green squiggle under neath anything referencing Django. I created another blank file and ran a line with import django and it removed the green squiggles and worked. But then I dont know what changed and now its back to how it was before and even running import django before my code wont fix it like last time. It still gives the error below. I havent typed any new code to this template so there should not be any errors with the code provided. I tried first to add a new empty python file and import django. It worked the first time but went away and didnt work the second time. I tried to type import django before each file that uses django functions. It didn't remove the squiggles. From what I can tell when I run the whole file it pulls up a website with django on it and does not error out. -
Django Microservices using kubernetes, rabbitmq, docker, postgres
I'm curious about how to establish communication between Django microservices while also implementing authorization and permission protocols through a JWT authentication microservice. While I understand the general concept of how this is done, I'm unsure about the technical specifics. that's why i'm looking for guidance on developing microservices in Django using RabbitMQ and Kubernetes. Can you recommend a tutorial or someone who has experience with this. I've built a JWT microservice using Djoser, and I have another microservice that requires authentication and the user ID of a logged-in user to send requests. What's the best approach to achieve this? My initial idea is to pass the JWT token as an Authorization header in the requests from the second microservice to the first microservice. The first microservice should then verify the token and extract the user ID from it, which it can send back to the second microservice to perform user-specific operations. However, I'm unsure about the technical implementation of this approach. Should I use Django's built-in authentication middleware to check the Authorization header in the incoming requests to the second microservice? Is there a better way to achieve this? Any insights or examples on how to securely communicate between Django … -
Pycharm does not recognize Django no matter how many times I install it
I'm new to programming, so please bear with me, I have a hard time understanding what my problem even is many times, let alone explain it. I am attempting to edit a Django app in Pycharm. I have managed to set up a virtual environment, then installed Django in that environment using pip in the terminal, but Pycharm still seems to treat references to Django like they're errors. Here's what it looks like in Pycharm This ends up giving me issues where my virtual environment won't run. I feel like I'm very close to finally getting this to work, but something is wrong and I don't know why. Any help would be appreciated, thanks. I tried looking up Django plugins to install through Pycharm's Marketplace section, and none existed. I then installed Django into my virtual environment using the terminal and pip, and it still doesn't recognize Django. I get error messages whenever I try to run my Django App in the virtual environment, I get error messages. -
How to add additional choices to forms which is taken from a model in django
As in the topic is it possible to add choices to the forms that take from the model. forms.py class BookGenreForm(forms.ModelForm): class Meta: model = Book fields = ('genre',) models.py class Book(Product): GENRE_CHOICES = ( ('Fantasy', 'Fantasy'), ('Sci-Fi', 'Sci-Fi'), ('Romance', 'Romance'), ('Historical Novel', 'Historical Novel'), ('Horror', 'Horror'), ('Criminal', 'Criminal'), ('Biography', 'Biography'), ) author = models.CharField(max_length=100) isbn = models.CharField(max_length=100) genre = models.CharField(max_length=100, choices=GENRE_CHOICES) I care about adding add-ons for selection, such as alphabetically, by popularity. I can handle the creation of a view. At the same time, I would not like to just add these options in the choices model unless it is possible that later in the panel the user does not have the option to add as a genre of popularity, etc. Thank you all very much. I have an idea to make individual forms.Forms for everyone and re-create elections in them but I don't think it would be a pretty way to do it