Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: How to format nested data, including a list of dictionaries, as multipart/form-data for posting?
How can I format nested data, including a list of dictionaries, as multipart/form-data for posting in Django? DATA = { "title": "Test Entry", "subcategory_id": subcategory.pk, "description": "Description for test entry.\n" * 2, "price": 150_000.00, "publisher": publisher.pk, "location": { "town": "Ant Town", "landmark": "Pink Poolside", }, "cover": _simple_image(), "images": [_simple_image(), _simple_image()], "specs": [ {"name": spec_field1.name, "value": "1000", "field_id": spec_field1.id}, {"name": spec_field2.name, "value": "SSD", "field_id": spec_field2.id}, ], "tags_ids": [tag.id for tag in TagFactory.create_batch(2)], } def test_something_doesnt_go_wrong(self): self.client.force_authenticate(user=UserFactory()) url = reverse("entries:entry-list") response = self.client.post(url, data, format="multipart") self.assertEqual(response.status_code, 201) self.assertEqual(len(response.data["images"]), 2) self.assertEqual(len(response.data["tags"]), 2) This is the error I get when I run my test suite. AssertionError: Test data contained a dictionary value for key 'location', but multipart uploads do not support nested data. You may want to consider using format='json' in this test case. Is this even legal? Is the API badly designed (I'm wondering). What can I do here? I can't seem to wrap my head around how to achieve this using QueryDict. -
Figma to Django (Python Web Framework) [closed]
Haii! I am new to Python web development, and I am using Python to master it further. I am trying to create a website using Django, and I already have my design in Figma. I am proficient in creating attractive user interfaces in Figma, but I have never used it with Python / exported. I do not know how to easily export Figma to Django. Does anyone know how to import Figma to Django without exporting every single item into an HTML file? Is that the only solution? Or am I doing something wrong? and are there any youtube / sites / plugin that you can recommend for me that I can try? I'm honestly lost for how to make exporting Figma to Django easier for myself. If there's no better solution, I completely understand, but I wanted to see if there was a better way than converting everything myself, which would take a significant amount of time. Thank you so much!! -
Django df add filter to df column
I am new to Django. I have a df and I can display it in the html. I use the pandas.read_sql_query to pull the data from the db. I want to realize the filter for each column in the df. views.py def index(request): dfa_query = "select * from database" dfa = pandas.read_sql_query(dfa_query,connection) dfa_html = dfa.to_html(index=False) return render(request, 'CaseTest.html',{'dfa':dfa_html}) CaseTest.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>CaseTest</title> </head> <body> <h2> dfa </h2> <div style="height: 500px; overflow: auto;"> {{dfa | safe}} </div> </body> </html> THe filter function I want to realize is sth like excel filter, for each column there is a drop down menu and you can choose the value you want, then the df will only show the value which matches the requirements. for the display for filter, I am okay with any format (1) the filter in excel (2) the filter on the top of the table, see picture below Any help is really appreciated!! -
Django create picture object based on upload_to and get response
I have this model and there is a ImageField with custom upload_to in it, so i want to create an instance and give the content of the file to my django model but i don't want to give any path or save image and i want django to handle this for me. this is the model: class UploadSorlThumbnailPictureMixin(UploadBasePictureMixin): picture = ImageField( _('picture'), max_length=255, width_field='width_field', height_field='height_field', help_text=_('The picture that is uploaded.'), upload_to=category_dir_path, validators=[validate_file_extension] ) and This is how i want to create instance: response = requests.get(base_url) # this is the image content UploadSorlThumbnailPictureMixin.objects.create( alternate_text=images['name'], picture='WHAT TO DO HERE?' ) How can i get the image from response and put create the instance with it? -
How to get the session of session with `request.session.get()` in Django?
I could get the session of session with request.session['key']['key'] as shown below: # "views.py" from django.http import HttpResponse def my_view(request): request.session['person'] = {'name':'John','age':27} print(request.session['person']['name']) # John print(request.session['person']['age']) # 27 return HttpResponse("Test") But, I couldn't get the session of session with request.session.get('key/key') as shown below: # "views.py" from django.http import HttpResponse def my_view(request): request.session['person'] = {'name':'John','age':27} print(request.session.get('person/name')) # None print(request.session.get('person/age')) # None return HttpResponse("Test") So, how can I get the session of session with request.session.get()? -
Is there a way to configure Django JWT authorisation/confirmation emails without SMTP server?
We are building an app with Django using Djoser and want it to send authorisation/confirmation emails to users. But the client said that there is no SMTP server on the domain he provides. So, is there some third-party api service that can send emails for our app? While testing we used the following code (it worked): /settings.py `DJOSER = { "HIDE_USERS": False, "LOGIN_FIELD": "email", "SERIALIZERS": { "user_create": "users.serializers.CustomUserCreateSerializer", "user": "users.serializers.CustomUserSerializer", "current_user": "users.serializers.CustomUserSerializer", }, "ACTIVATION_URL": "#/activate/{uid}/{token}", "SEND_ACTIVATION_EMAIL": True, "PASSWORD_CHANGED_EMAIL_CONFIRMATION": True, "PASSWORD_RESET_CONFIRM_URL": "#/activate/{uid}/{token}", "USERNAME_CHANGED_EMAIL_CONFIRMATION": True, } SIMPLE_JWT = { "ACCESS_TOKEN_LIFETIME": timedelta(days=1), "AUTH_HEADER_TYPES": ("Bearer",), } ... EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp.gmail.com" EMAIL_PORT = "587" EMAIL_USE_TLS = True EMAIL_HOST_USER = os.getenv("EMAIL_HOST_USER") EMAIL_HOST_PASSWORD = os.getenv("EMAIL_HOST_PASSWORD") EMAIL_SERVER = EMAIL_HOST_USER DEFAULT_FROM_EMAIL = EMAIL_HOST_USER EMAIL_ADMIN = EMAIL_HOST_USER` -
Collecting static of Swagger UI in django project on server
I setup a Swagger configuration on my Django project for a specific endpoint It worked fully completed on my local machine but when I sent it on server it seems that the static files of drf_yasg cannot be collected and show there were a blank page without any 404 Not Found error, but also on the console it wrote the Js and CSS files are 404 not found swagger.py from drf_yasg import openapi from drf_yasg.views import get_schema_view from django.urls import path from requests_app.views import RequestsVS from rest_framework import permissions single_endpoint_schema_view = get_schema_view( openapi.Info( title="/api/", default_version='v1', description="برای احراز هویت نیاز است تا کلید دریافتی در هدر درخواست ها با عنوان زیر ارسال شود", ), public=True, permission_classes=[permissions.AllowAny], patterns=[path('requests/add/outside/', RequestsVS.as_view({'post': 'create_from_outside'}))], ) swagger_urlpatterns = [ path('swagger/', single_endpoint_schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), path('redoc/', single_endpoint_schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'), ] urlpatterns = swagger_urlpatterns + [ ] settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' # Default primary key field type # https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' AUTH_USER_MODEL = 'users.User' # Swagger settings SWAGGER_SETTINGS = { 'USE_SESSION_AUTH': False, # Set this to True if you're using session authentication 'SECURITY_DEFINITIONS': { 'Bearer': { 'type': 'apiKey', 'name': 'Authorization', 'in': 'header', }, }, } urls.py … -
How to select a Django Plotly dash element in JavaScript?
I have a Django Plotly dash app where I have an HTML structure like this: html.Div( id="search-topics", className="search-topics", children=dcc.Input( id="search-topic-input", type="text", placeholder="search...", debounce=True, className="search-topic-input", ), ), I want to select the search-topics element in JavaScript so that I can manipulate its properties dynamically. However, when I try to select the element using document.getElementById("search-topics, it returns null. Is there a way to select this element in JavaScript and modify its properties? any help or guidance would be greatly appreciated. Thank you! -
Getting "Authentication credentials were not provided." error when making a request to another api endpoint with required auth, on behalf of a user
def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) username = serializer.validated_data['username'] password = serializer.validated_data['password'] user = authenticate(request, username=username, password=password) login(request, user) session_id = request.session.session_key csrf_token = get_token(request) request_headers = { 'X-CSRFToken': csrf_token, 'Cookie': f"sessionid={session_id}", } # Url to request mail for email confirmation url_path = reverse('send-mail-confirm-email') full_url = request.scheme + '://' + request.get_host() + url_path requests.get( full_url, headers=request_headers, ) return Response( serializer.data, status=status.HTTP_201_CREATED, headers=headers ) Getting "Authentication credentials were not provided." error when making a request to another api endpoint with required authentication, on behalf of a user. I have included cookie with sessionid, and csrf_token in the request headers. It doesn't work either way. -
Install requirements from Django project with VS Code
I try to run and open the development server of a Django project in VS Code, that I created with GidPod IDE. When I open the project in GidPod (where I created it), install the requirements, create an env.py, set the 'SECRET_KEY' variable and I can start the server with python3 manage.py runserver. Then I open the exact same project in VS code, I create a virtual environment and install the requirements from requirements.txt as I did in GidPod with pip3 install -r requirements.txt. If I now try to start the development server, I get the following error: (gh-env) PS C:\Users\SkywalkingTiger\Desktop\git-repos\gfeller-herbs-wf> python3 manage.py runserver Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.1264.0_x64__qbz5n2kfra8p0\Lib\threading.py", line 1038, in _bootstrap_inner self.run() File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.1264.0_x64__qbz5n2kfra8p0\Lib\threading.py", line 975, in run self._target(*self._args, **self._kwargs) File "C:\Users\SkywalkingTiger\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\SkywalkingTiger\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\core\management\commands\runserver.py", line 133, in inner_run self.check(display_num_errors=True) File "C:\Users\SkywalkingTiger\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\core\management\base.py", line 485, in check all_issues = checks.run_checks( ^^^^^^^^^^^^^^^^^^ File "C:\Users\SkywalkingTiger\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\core\checks\registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\SkywalkingTiger\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\core\checks\urls.py", line 14, in check_url_config return check_resolver(resolver) ^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\SkywalkingTiger\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\core\checks\urls.py", line 24, in check_resolver return check_method() ^^^^^^^^^^^^^^ File "C:\Users\SkywalkingTiger\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\urls\resolvers.py", line 494, in check for pattern in self.url_patterns: ^^^^^^^^^^^^^^^^^ File "C:\Users\SkywalkingTiger\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\utils\functional.py", … -
Django: TypeError: XXX() got multiple values for argument 'chat_id'
I'm using Django with Celery and getting this error: TypeError: get_response() got multiple values for argument 'chat_id' I'm calling the function via: i = get_response.delay(chat_id=chat_id, is_first_message=is_first_message,question=question,user_id=user_id) and the function header is: @shared_task(bind=True) def get_response(chat_id: int, is_first_message: bool, question:str,user_id:int) -> str: I tried running a print(chat_id) but this only confirmed the field was a single integer. Edit. Full trace: [03/Jul/2023 13:52:16] ERROR "django.request" Internal Server Error: /chat/chat/1/283/new_message/ project | Traceback (most recent call last): project | File "/usr/local/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner project | response = get_response(request) project | ^^^^^^^^^^^^^^^^^^^^^ project | File "/usr/local/lib/python3.11/site-packages/django/core/handlers/base.py", line 197, in _get_response project | response = wrapped_callback(request, *callback_args, **callback_kwargs) project | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ project | File "/code/apps/chat/views.py", line 82, in new_message project | i = get_response.delay(chat_id=chat_id, is_first_message=is_first_message,question=question,user_id=user_id) project | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ project | File "/usr/local/lib/python3.11/site-packages/celery/app/task.py", line 425, in delay project | return self.apply_async(args, kwargs) project | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ project | File "/usr/local/lib/python3.11/site-packages/celery/app/task.py", line 540, in apply_async project | check_arguments(*(args or ()), **(kwargs or {})) project | TypeError: get_response() got multiple values for argument 'chat_id' project | [03/Jul/2023 13:52:16] ERROR "django.server" "POST /chat/chat/1/283/new_message/ HTTP/1.1" 500 87645 -
Django custom widget: best approach
Django: custom widget I use a material-kit library for django which offers a design for rendering form fields except for selects which is only available in the PRO version. I coded a custom selectpicker widget which renders similar to the selectpicker of the PRO version of material-kit. In a form, I have a lot of "select" fields to render with my selectpicker widget. To limit the repetition of the code I defined a template select_field.html which displays the selectpicker.html of my widget when I insert a field having this widget in my final template using an include. Isn't there a more efficient and/or elegant way to achieve the same result? #model.py dem_sex = models.IntegerField('Sexe', null=True, blank=True) #forms.py dem_sex = forms.TypedChoiceField(widget=Selectpicker(label='Sexe - SELECTPICKER',attrs={'class': ''}),choices=SEX_CHOICES, empty_value=None,required=False) #widget.py from django.forms.widgets import TextInput class Selectpicker(TextInput): template_name = 'widgets/selectpicker.html' def __init__(self, label=None, choices=None, *args, **kwargs): self.choices = choices self.label = label super().__init__(*args, **kwargs) def get_context(self, name, value, attrs=None): context = super().get_context(name, value, attrs) if self.choices: context['choices'] = self.choices if self.label: context['label'] = self.label return context #selectpicker.html {% with css_classes=widget.attrs.class|default:'' %} <div class="row ms-3 me-3"> <div class="col-md-12 selectpicker-div"> <div class="selectpicker"> <div class="label floating-label">{{label}}</div> <input class="textBox hidden" type="{{ widget.type }}" name="{{ widget.name }}"{% if widget.value is None … -
Prefetch related not working in django admin
I'm trying to show name of related model in my django admin and i'm using prefetch related but i still got 200+ sql queries how can i solve that? models.py class ObjectList(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=True) name = models.CharField(max_length=250) sections = models.ManyToManyField('SectionList', default=None, related_name='object_sections', blank=True) class CleanSections(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=True) name = models.CharField(max_length=120) def __str__(self): return f'{self.name}' class SectionList(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=True) object = models.ManyToManyField(ObjectList, related_name='sections_object', default=None) clean_sections = models.ForeignKey(CleanSections, to_field='uuid', on_delete=models.CASCADE, null=True, related_name='sections_clean_name') def __str__(self): return f'{self.clean_sections.name}' admin.py class ObjectListAdmin(admin.ModelAdmin): list_display = ('uuid', 'name') list_filter = ('name',) search_fields = ('uuid', 'name') ordering = ('uuid', 'name') fields = ('uuid', 'name', 'sections') def get_queryset(self, request): base_qs = super(ObjectListAdmin, self).get_queryset(request) return base_qs.prefetch_related('sections__clean_sections') -
{% block content %} {% endblock %} displayed as text
I'm going through an online tutorial on python web development: https://www.youtube.com/watch?v=dam0GPOAvVI&list=PL7AeU6Jfo1ue-VZ6SI9x0EOCW2hhGC1l6&index=4&t=2214s However, despite double check all the codes are the same, I can't get visual studio to recognize the {% block content %} {% endblock %} part of the code. The expected output should be only the contents between {% block content %} {% endblock %}, which is none in this case. However, '{% block content %} {% endblock %}' is displayed as text on the web page, which it should not be. And the rest of the codes on other templates did not work as well. It seems that visual studio code does not recognize this syntax, maybe I need to configure some setting for it to work but I can't find it, any help is much appreciated. <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous" /> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" crossorigin="anonymous" /> <title> {% block title %}Home{% endblock %} </title> </head> <body> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbar"> <span class="navbar-toggler-icon"></span> </button> <div class = "collapse navbar-collapse" id="navbar"> <a class="nav-item nav-link" id="login" href="/login">Login</a> <a class="nav-item nav-link" id="SignUp" href="/sign_up">Sign Up</a> <a class="nav-item nav-link" id="logout" href="/logout">Log Out</a> <a class="nav-item … -
How can I go to homepage from another page in Django? I am unable to exit from last called definition
def save(request,id): if request.method=='POST': if request.POST.get('name'): table=Userdb.objects.get(id=id) table.name=request.POST.get('name') table.url=request.POST.get('url') table.phone=request.POST.get('phone') table.dob=request.POST.get('dob') table.save() #messages.success(request,"record saved successfully") #return redirect('userlist') #return HttpResponseRedirect({%urls 'index'% }) return render(request,"index.html") Here at last part,I have directed to index.html. But actually I am not exited the save definition. please refer next snapshot. The url in webpage dont show index.html but shows save. Also css of index webpage is lost. I tried various urls but didnt work. Also tried to change setings.py still no avail. I want to navigate to home page without trace of any older definition -
how can i fix these error in django admin and veiws files?
i have a problem witch i have a custom User model in my Account app and i just put AUTH_USER_MODEL = 'Account.User' in my setting.py. The problem i have is that when i go on admin panel and click on a user in the Users list and when i want to update or delete it i get an error (This error is not only for the User model and other models that are in the admin panel, i'm not able to delete or update them) IntegrityError at /admin/Account/user/1/delete/ FOREIGN KEY constraint failed IntegrityError at /admin/Account/user/1/change/ FOREIGN KEY constraint failed Also when i want to register a user with my register view it always gives me this error witch i choise it if the user exist in the Users list { "error": "Username has been already used." } The register view class code for checking the email and username: if User.objects.filter(email=email).exists(): return Response(data={"error": "Email has been already used."}, status=status.HTTP_400_BAD_REQUEST) if User.objects.filter(username=username).exists(): return Response(data={"error": "Username has been already used."}, status=status.HTTP_400_BAD_REQUEST) My User model: from django.db import models from django.contrib.auth.models import AbstractUser, Group, Permission class User(AbstractUser): id = models.AutoField(primary_key=True) email = models.EmailField(unique=True) full_name = models.CharField(max_length=255, default="") simple_description = models.CharField(max_length=255, default="tourist") biography = models.TextField(null=True, … -
In Django Admin site password field changes when I edit the attribute of other widgets
In the default Django Admin site, the Password field shows how it is encrypted and there's a link to change it. In my project I need to set some fields to LTR (because the site is in RTL), so this is what I do: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.utils.translation import gettext_lazy as _ from django import forms from .models import CustomUser # Register your models here. class CustomUserForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['email'].widget.attrs.update({'dir': 'ltr'}) self.fields['national_id'].widget.attrs.update({'dir': 'ltr'}) self.fields['mobile_number'].widget.attrs.update({'dir': 'ltr'}) @admin.register(CustomUser) class CustomUserAdmin(UserAdmin): form = CustomUserForm fieldsets = ( (None, {'fields': ('email', 'password')}), ( _('Personal info'), { 'fields': ( 'first_name', 'last_name', ) }, ), ( _('Profile info'), { 'fields': ( 'national_id', 'mobile_number', 'home_address', 'work_address', ) }, ), ( _('Permissions'), { 'fields': ( 'is_active', 'is_staff', 'is_superuser', 'is_verified', 'groups', 'user_permissions', ), }, ), (_('Important dates'), {'fields': ('last_login', 'date_joined')}), ) add_fieldsets = ( ( None, { 'classes': ('wide',), 'fields': ('email', 'password1', 'password2'), }, ), ) list_display = ('email', 'first_name', 'last_name', 'is_staff') list_filter = ('is_staff', 'is_superuser', 'is_active', 'groups') search_fields = ('email', 'first_name', 'last_name', 'national_id', 'mobile_number') ordering = ('email',) filter_horizontal = ( 'groups', 'user_permissions', ) But with that custom form, the Password field looks like this: I have not touched … -
Add multiple instances of a model with some shared fields at once
I'm trying to come up with a way of allowing a user to add multiple instances of a specific model at once in Django Admin, but with some fields being shared between them. Example model: class Something(models.Model): ref = models.ForeignKey(to="AnotherModel", on_delete=models.CASCADE) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) What I am trying to achieve is to have a page in Django Admin where the user would define the ref field only once, then add and populate as many name and is_active fields as he wants, press the Save button and the ref field would get automatically re-used to create as many Something instances as the user created with the name and is_active fields. I know of Django's StackedInLine and TabularInLine, but I am not able to produce the above mentioned functionality with them, at all. Thank you -
How to adjust old migrations for removals in Django?
In our Django project we are currently removing a couple of old models, which were used until recently. When running our tests now, Django tries to create and migrate to the test database, however as the first migrations point to a now not existing model, it throws ValueError: The field ticket.Ticket.ci was declared with a lazy reference to 'plugin.ci', but app 'plugin' doesn't provide model 'ci'.. Adjusting old migrations is never a good idea I suppose, so how exactly can one proceed here? The old migration looks like this: migrations.AddField( model_name='ticket', name='ci', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='plugin.ci'), ), Should I just remove this piece? -
Select2 blocks htmx hx-get
I'm using select2 on my form select with htmx but for some reason hx-get does not send any request while form field has select2 I was trying to turn off select2 and everything works fine, so how can i fix that? template.html <form method="get" class="mb-3"> <div class="well"> <div class="row"> <div class="form-group col-sm-4 col-md-4 mb-3"> <div class="custom-select"> {% render_field form.contractor_object|add_class:'form-select' hx-get="/customer/worklog/" hx-target='#id_test' hx-select="#id_test" %} </div> </div> <div class="form-group col-sm-4 col-md-4 mb-3"> <div class="custom-select" id="id_test"> {% render_field form.contractor_section|add_class:'form-select' %} </div> </div> </div> </div> <div class="mt-4 custom-label"> <div class="row"> <div class="col"> <button type="submit" class="btn btn-outline-primary">Поиск</button> <a class="btn btn-outline-primary" href="{% url 'customer_worklog' %}">Сброс</a></div> </div> </div> </form> <script> $(document).ready(function () { $("#id_contractor_object").select2(); }); </script> <script> $(document).ready(function () { $("#id_contractor_counter").select2(); }); </script> <script> $(document).ready(function () { $('#id_contractor_section').select2(); }); </script> -
Django pointfield admin widget shows wrong point (long/lat switch places)
I have a model with PointField. class Companion(models.Model): startpoint = models.PointField(srid=4326, null=True) My admin.py file class CompanionAdmin(admin.GISModelAdmin): pass admin.site.register(Companion, CompanionAdmin) When I set point in django admin and save it, all looks good. But when i try to find saved coordinates on map, it didn't find anything. As I found out it happens because coordinates switch their places (long is lat, lat is long). I used different admin classes, such as LeafletGeoAdmin, GISModelAdmin, it didn't help. How can I fix it? -
how can i delete column with sum = 0 in excelhtml5 export
i use this code to export my table to excel in datatable-django. $(document).ready(function() { $('#example').DataTable( { dom: 'Bfrtip', buttons: [ 'copy', 'csv', 'excel', 'pdf', 'print' ] } ); } ); I have a table with 72 columns. I only want to export the columns to Excel whose cell sum is not zero. How can I do this? i want just show the column with sum>0 -
Automatic set/update fields in Django
I have to models in models.py class Teams(models.Model): Name = models.CharField(verbose_name="Team Name", max_length=200) Slug = AutoSlugField(populate_from="Name", always_update=True, editable=True, verbose_name="Team Slug") Location = models.CharField(verbose_name="Team Location", max_length=200) Leader = models.ForeignKey('Members', on_delete=models.SET_NULL, null=True, blank=True) ArrivalDate = models.DateTimeField(default=timezone.now, editable=False, verbose_name="Arrival Date") DepartureDate = models.DateTimeField(null=True, blank=True, verbose_name="Departure Date") and class Members(models.Model): Name = models.CharField(verbose_name="Member Name", max_length=200) Team = models.ForeignKey(Teams, on_delete=models.CASCADE) PhoneNumber = models.CharField(max_length=20, null=True, blank=True) Email = models.EmailField(max_length=50, null=True, blank=True) BloodType = models.CharField(max_length=3, choices=BLOOD_TYPE_CHOICES, null=True, blank=True) isLeader = models.BooleanField(default=False) When isLeader field in Members field set True, I want to update Leader field in Teams model. Thanks in advance -
Duplicate entries are returning when filtering model
//Model class ClientUserSelectedPodcast(AuditModel): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='user_selected_podcast', null=True,blank=True) client_unit = models.ForeignKey(Unit, on_delete=models.CASCADE, related_name='user_selected_unit', null=True, blank=True) client_superunit = models.ForeignKey(SuperUnit, on_delete=models.CASCADE, related_name='user_selected_super_unit', null=True, blank=True) selected_type = models.CharField(max_length=100, default="FAVOURITE") class Meta: ordering = ('-pk',) //view class GetNewClientsCountViewSet(APIView): def get(self,request,*args, **kwargs): from podcast.api_serializers import UnitMiniSerializer from datetime import datetime data=[] total_listener_count={} client_count=Client.get_new_clients_count() gender_wise_count={} # gets the podcast unit count of this month podcast_count=Unit.get_new_podcast_unit_count() user_counts=ClientUser.get_new_client_user_count() most_listened_units,most_liked_units=ClientUserSelectedPodcast.get_total_listened_liked_podcast() inhouse_listened_units,inhouse_liked_units=ClientUserSelectedInhouse.get_total_listened_liked_inhouse() podcast_listener_count=ClientUserSelectedPodcast.get_total_podcast_listeners() inhouse_listener_count=ClientUserSelectedInhouse.get_total_inhouse_listeners() podcast_wise_count=ClientUserSelectedPodcast.get_gender_wise_listeners() inhouse_wise_count=ClientUserSelectedInhouse.get_gender_wise_inhouse_listeners() total_listener_count['podcast']=podcast_listener_count total_listener_count['inhouse']=inhouse_listener_count gender_wise_count['podcast']=podcast_wise_count gender_wise_count['inhouse']=inhouse_wise_count # most liked show of this month most_liked_show= ( ClientUserSelectedPodcast.objects .filter(selected_type='FAVOURITE', created_at__month=datetime.now().month) ) print(most_liked_show) data.append({ 'clients':client_count, 'podcast':podcast_count, 'user':user_counts, 'total_listener_count':total_listener_count, 'most_listened_units':most_listened_units, 'most_liked_units':most_liked_units, 'inhouse_listened_units':inhouse_listened_units, 'inhouse_liked_units':inhouse_liked_units, 'gender_wise_count':gender_wise_count }) return Response(data) i want to get the Most liked show for this month i.e selected*type='FAVOURITE'. Queryset: <QuerySet [<ClientUserSelectedPodcast: ClientUserSelectedPodcast object (552)>, <ClientUserSelectedPodcast: ClientUserSelectedPodcast object (551)>, <ClientUserSelectedPodcast: ClientUserSelectedPodcast object (550)>] The problem here is that query is returing different objects but the value in them is same ie the object 552 and 551 has the same entries i.e 552 -> {'user':224, clientunit:'94ba2e2a47254028b0d3d59eeb5b257d', 'selected*_type':FAVOURITE'}, 551-> {'user':224, clientunit:'94ba2e2a47254028b0d3d59eeb5b257d', 'selected_type':FAVOURITE'} What i want if this occurs duplicate occurs i want to take the count as one and want to return the most liked show for this month -
Why is the full path not saved in the database
I have this function in a Django model to save the profile picture to the database: def photo_directory_path(instance, filename): return "user_{0}/profiles/{1}/images/{2}".format(instance.owner.id, instance.id, filename) Here is the model that uses that function: class FounderProfile(models.Model): background_image = models.FileField( upload_to=bg_directory_path, null=True, blank=True, ) profile_picture = models.FileField( upload_to=photo_directory_path, null=True, blank=True, ) tagline = models.CharField(max_length=100, null=True, blank=True) first_name = models.CharField(max_length=30, null=True, blank=True,) middle_name = models.CharField(max_length=30, null=True, blank=True,) last_name = models.CharField(max_length=30, null=True, blank=True,) bio = models.TextField(max_length=5000, null=True, blank=True,) date_of_birth = models.DateField( null=True, blank=True,) owner = models.OneToOneField(User, on_delete=models.CASCADE, related_name="founderprofile") And here is the settings for handling images: STATIC_URL = "static/" STATICFILES_DIRS = (os.path.join(BASE_DIR, "static/"),) STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles/") MEDIA_ROOT = os.path.join(BASE_DIR, "storage").replace("\\", "/") MEDIA_URL = "/storage/" and my main urls.py file: urlpatterns = [ path("", include("pages.urls")), path("admin/", admin.site.urls), path("api/v1/", include("api.urls")), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I am using Django Rest Framework and a Vue3 front end. My question is why are the files not saved with the full url which also includes the domain name which in my case is "http://localhost:8000"? Because now I have to add "http://localhost:8000" to the image path otherwise the image does not show and it's not going to work in production