Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Converting string to Django model name before calling filter() (Not duplicate)
model_name = "MyModel" model_name.objects.filter() AttributeError: 'str' object has no attribute 'objects' How can I make this work, I have already tried: exec(model_name) input(model_name) [model_name] I know there is a possible method where you import the model using apps.get_model(model_name="string") but I don't want to use this method due to the model already being imported beforehand. Is there any different way where I can convert model_name (string type) to a type that can be inserted at INSERTHERE.objects.filter() -
How to redirect two different Django applications on the same server with same url but different paths?
I have two Django applications running on the same server in Docker containers. App1 is on website.com/ using localhost:9595 and App2 other is on website.com/app2. localhost:9696 Problem begins when I go to website.com/app2/something where it redirects me to website.com/something which doesn't exist instead of going to website.com/app2/something. I can fix it in NGINX by adding: /something/{ proxy_pass localhost:9696/something/ } But then I have to do it for every subpage of my application2. -
How to document a tuple with different data types using drf-spectacular?
I'm using drf-spectacular to generate a Swagger documentation. I have a viewset that returns a dict (it doesn't go through a drf serializer as it's all native objects). The dict looks like this: data = { "lines": List[str], "points": List[Tuple[float, float, int, str]] "next_failure_date": str, "estimate_nth_failure": str "status": str, } I can't find a way for drf-spectacular to properly document the "points" key, it only gives me a "points": ["string"] What I tried : class SwaggerGrowthChartPoint: """Class used to generate the Swagger documentation""" def __init__(self, x: float, y: float, sap_id: int, created_on: str): self.x = x self.y = y self.sap_id = sap_id self.created_on = created_on class SwaggerGrowthChartPointField(serializers.Field): def to_representation(self, value: SwaggerGrowthChartPoint): return f"{value.x}, {value.y}, {value.sap_id}, {value.created_on}" def to_internal_value(self, data): return SwaggerGrowthChartPoint(*data) class SwaggerGrowthChartSerializer(serializers.Serializer): """Serializer used to generate the Swagger documentation""" lines = SwaggerGrowthChartLinesSerializer(many=True) points = serializers.ListField(child=SwaggerGrowthChartPointField()) next_failure_date = serializers.ListField(child=serializers.DateField()) estimate_nth_failure = serializers.DateField() status = serializers.CharField() But no luck. -
how to get socket id from this library
I'm using this library in my python code: ''' import socket socket.socket(socket.AF_INET,socket.SOCK_STREAM) python get socket id ''' how to get socket id (sid) and how to send message to selected client by socket id -
I can't call the function value in the model
my models.py : from django.db import models from django.urls import reverse from django.utils import timezone from django.db.models import Sum # Create your models here. class Plac(models.Model): c_name = models.CharField(max_length = 50) starting_date = models.DateTimeField(auto_now=True) posting_num = models.SmallIntegerField(default = None) payment_date = models.DateTimeField(auto_now=None) billingAm = models.SmallIntegerField(default = None) billing = models.BooleanField(default=False) def get_absolute_url(self): return reverse('place:place_detail', args=[self.pk]) def get_totalbilling(self): return Plac.objects.aggregate(Sum('billingAm'))['billingAm__sum'] or 0 class Rank(models.Model): name = models.ForeignKey(Plac,on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True,) updated_at = models.DateTimeField(auto_now=True) ranking = models.SmallIntegerField(default = None) my html : <br /> <div>TotalPrice: {{plac.place.get_totalbilling}}</div> {% endblock content %} I want to see the result of "get_totalbilling" I try it for 3days.. but I can't coz I am beginner of django. -
unable get static image on webpage even after creating static folder and updating its path in settings.py and running collectstatic
I am using vscode.I created a django project named myproject, app named myapp and static folder in myproject dir. My image is not getting displayed in webpage after trying everything.I am not getting where is the issue please help. my static folder location C:\Users\nihar\myproject\static settings dir -STATICFILES_DIR = [ os.path.join(BASE_DIR, 'static'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') html file code {% load static %} <!DOCTYPE html> <body> <img src="{% static 'images/tttbg.jpg' %}"> </body> -
I want create a inventory management system in django(CRUD OPERATION)
Want to perform a crud operation in html view in django with this given model:- class Brand_Master(models.Model)`: brand_id = models.CharField(max_length=10,unique=True,verbose_name='Brand ID') brand_name = models.CharField(max_length=30,verbose_name='Brand Name') def __str__(self): return self.brand_name class Item_Master(models.Model): brand = models.ForeignKey(Brand_Master,on_delete=models.CASCADE,verbose_name='Brand ID') item_name = models.CharField(max_length=50,verbose_name='Item Name') item_code = models.CharField(max_length=20,unique=True,verbose_name='Item Code') price = models.FloatField(verbose_name='Price') def __str__(self): return self.item_code + "-" +self.item_name class Sale_Master(models.Model): item = models.ForeignKey(Item_Master,on_delete=models.CASCADE,verbose_name='Item') customer_name = models.CharField(max_length=100,verbose_name='Customer Name') number = models.PositiveBigIntegerField(verbose_name='Number') invoice = models.PositiveIntegerField(verbose_name='Invoice') I have created backend and want frontend view crud operation ` -
how to get a link to a file with https in json in drf
I have app with api on drf I installed the ssl certificate on the site and when I try to get the file I get an error: The page at site https://www.example.com was loaded over Https, but requested an insecure resource http://api.example.com/…… I think the problem is that with a get request in json, my link starts with http... How can i solve this problem and get file link starting with https ?? or is it something else? Json from get request: { "id": 50, "name": "Образец заполнения книги учета доходов", "category": "Бухгалтерия и налоги", "count_download": 0, "type_doc": "xls", "screenshot": "http://api.example.com/media/screenshot/%.png", "add_time": "2023-03-27", "pdffile": "http://api.example.com/media/pdf_docs/%.pdf" } I think perhaps it is necessary to somehow make a proxy server, but I don’t understand how… -
Djongo/MongoDB error while doing migration using django-allauth
Error i get djongo.exceptions.SQLDecodeError: Keyword: FAILED SQL: SELECT %(0)s AS "a" FROM "django_site" LIMIT 1 Params: (1,) Version: 1.3.6 Sub SQL: None FAILED SQL: None Params: None Version: None I am trying to login using social media authentication(all-auth). But this gives error while migrating all-auth fields into database. I am using mongodb. -
How do I test url in Django with ?postId=1?
I want to test my url, but errors shows and something is wrong with this path Here is my path `path('comments/', views.get_comments_by_postid, name='comments')` and view i made `@require_http_methods(["GET"]) @login_required(login_url='login') def get_comments_by_postid(request): comment_id = request.GET.get('postId') comments_url = 'https://jsonplaceholder.typicode.com/comments' if comment_id is not None: comments_url += f'?postId={comment_id}' comments_response = requests.get(comments_url) comments = comments_response.json() return render(request, 'comments.html', {'comments': comments})` and that is the test i tried to make but it is not working, errors shows `def test_comments_by_added_postId_url(self): url = reverse('comments') + '?postId=1' print(resolve(url)) self.assertEquals(resolve(url).func, get_comments_by_postid)` -
"clean() got an unexpected keyword argument 'fix_unicode'"
clean() got an unexpected keyword argument 'fix_unicode' when i install clean-text i got errors Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [1 lines of output] ERROR: Can not execute `setup.py` since setuptools is not available in the build environment. [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output. note: This is an issue with the package mentioned above, not pip. hint: See above for details. i tried everything available on internet but could not find any solution please help me to resolve this issue -
Auto select category code when we select the respective category
I am new in Django I am creating an admin panel where admin can create category list with category code. This is working fine. now my next task is that, admin will have the functionality to add product where he has to select the category name and i want that that category code belong to selected category should be auto selected when we select the category i have created a drop down for fetching the list of category category_list = Tcategory.objects.all() <div class="col-12 col-md-6 col-xl-6"> <div class="form-group local-forms"> <label for="categories">Select Category</label> <select name="category" class="form-select form-control" id="category" name="category"> <option value="" disabled selected>Select Treatment Category</option> {%for categorys in category_list%} <option value="{{category}}">{{categorys}}</option> {%endfor%} </select> </div> </div> <div class="col-12 col-md-6 col-xl-6"> <div class="form-group local-forms"> <input class="form-control" type="text" name="Tcategoryname" value="{{categorys.Tcode}}" placeholder="tcode"> </div> </div> By this I am able to fetch the list of category 1 - how i can get list of code from my model 2 - how i can do if user select category, and category code is auto selected -
upgrade django app from version 2 to the new(4)
How do I upgrade my django app from version 2 to the new(4). how to correctly and simply update the code, how to do it. here are the versions of all libraries It works on python 3.7.4 Babel==2.7.0 certifi==2019.6.16 chardet==3.0.4 coreapi==2.3.3 coreschema==0.0.4 Django==2.2.8 django-cas-ng==3.6.0 django-enum-choices==2.1.1 django-extensions==2.2.1 django-filter==2.1.0 django-method-override==1.0.3 django-rest-swagger==2.2.0 django-webpack-loader==0.6.0 djangorestframework==3.9.4 drf-extensions==0.5.0 idna==2.8 imagesize==1.1.0 itypes==1.1.0 Jinja2==2.10.1 lxml==4.4.1 Markdown==3.1.1 MarkupSafe==1.1.1 openapi-codec==1.3.2 packaging==19.0 psycopg2==2.8.2 Pygments==2.4.2 pyparsing==2.4.1.1 python-cas==1.4.0 pytz==2019.1 requests==2.22.0 setuptools==41.6.0 simplejson==3.16.0 six==1.12.0 snowballstemmer==1.9.0 sqlparse==0.3.0 uritemplate==3.0.0 urllib3==1.25.3 uuid==1.30 drf-yasg==1.17.0 waitress==1.4.2 httpretty==0.9.7 whitenoise==4.1.4 python-dotenv==0.10.3 django-cors-headers==3.1.1 django-nose==1.4.6 coverage==4.5.4 pycodestyle==2.5.0 I tried python -Wa manage.py test but i got an error from django.db.models.fields import FieldDoesNotExist ImportError: cannot import name 'FieldDoesNotExist' from 'django.db.models.fields' -
Data from DateTimeField() to TimeField() leaving only the time in the latter without the date?
Good morning! I have a django database model table. To fill this model table, data replenishment is used - a form in the template. One of the columns from this model table is a DateTimeField() data type. I also have a second table, the Django database model. The differences from the first table described above are minimal - just an additional added column - which has a TimeField() data type. I plan to copy from the first model - part of the data from the DateTimeField() column to the second table of the model - into the column - which has the data type TimeField(). I'm planning to copy some of the DateTimeField() data - just the time without the date. Data from DateTimeField() to TimeField() leaving only the time in the latter without the date. How can you come up with something for this? -
Wrong thumbnail url returned in Django/DRF
I am trying to create an application (Django and DRF), by which you can create and view posts. The posts contain an image, and the preview is supposed to only show a thumbnail of the original image, which will be created by the application using Pillow. I mainly followed this stackoverflow post, but changed it to fit my application. However, the image is saved in /media/images/, the thumbnail is saved in /media/resize/, the thumbnail-url is saved in the database as resize/image_thumb.jpg, but the thumbnail-url in the returned json-object in Postman is the image-url, not the thumbnail-url. Where am I going wrong? settings.py MEDIA_URL = "/media/" MEDIA_ROOT = BASE_DIR / "media/" urls.py from django.conf.urls.static import static from django.conf import settings from . import views urlpatterns = [ path('feed/', PostAPIView.as_view(), name='feed_of_posts'), path('feed/<int:id>', PostDetailAPIView.as_view(), name='update_delete_posts'), ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py class PostAPIView(ListCreateAPIView): serializer_class = PostSerializer queryset = Post.objects.all() ... def perform_create(self, serializer): return serializer.save(poster = self.request.user) serializers.py class PostSerializer(serializers.ModelSerializer): thumbnail = serializers.ImageField(source='image', required=False) class Meta: model = Post fields = ('id', 'image', 'pub_date', 'imageDescription', 'poster', 'thumbnail') def to_representation(self, instance): self.fields['poster'] = PosterSerializer(read_only=True) return super(PostSerializer, self).to_representation(instance) models.py class Post(models.Model): image = models.ImageField(upload_to='images/') thumbnail = models.ImageField(upload_to='resize/', editable=False) imageDescription = models.TextField() ... pub_date = models.DateTimeField(auto_now_add=True) … -
Add Fields to Django form not present in model
I have a student model to keep data of students. Models.py class Student(models.Model): roll_no = models.IntegerField(editable=True, blank=False, primary_key=True) name = models.CharField(max_length=30) date_of_birth = models.DateField(default='1900-01-01', blank=True) admission_no = models.IntegerField(default=roll_no) admission_date = models.DateField(default=datetime.now) student_cnic = models.CharField(max_length=15) father_cnic = models.CharField(max_length=15) grade = models.ForeignKey('school.SchoolClasses', on_delete=models.CASCADE, null=True, blank=True) mobile = models.CharField(max_length=12) active = models.BooleanField(default=True) Student Form looks like Forms.py class StudentForm(forms.ModelForm): extra_fields = ['school'] class Meta: model = Student fields = ['roll_no', 'name', 'date_of_birth', 'admission_no', 'admission_date', 'student_cnic', 'father_cnic', 'mobile', 'grade'] def __init__(self, *args, **kwargs): super(StudentForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout(Row(Column('roll_no', css_class='form-group col-md-6'), Column('admission_no', css_class='form-group col-md-6'), ), Row(Column('date_of_birth', css_class='form-group col-md-6'), Column('admission_date', css_class='form-group col-md-6'), ), Row(Column('name', css_class='form-group col-md-3'), Column('student_cnic', css_class='form-group col-md-3'), Column('father_cnic', css_class='form-group col-md-3'), Column('mobile', css_class='form-group col-md-3'), ), Row( Column('school', css_class='form-group col-md-3'), Column('grade', css_class='form-group col-md-3'), ), Submit('submit', 'Add Student', css_class='btn btn-primary'), ) self.fields['date_of_birth'].widget = forms.DateInput(attrs={'type': 'date'}) self.fields['admission_date'].widget = forms.DateInput(attrs={'type': 'date'}) ` The school field is just to Filter the result for grade field to return only those grades present in the selected school But i am getting an error KeyError: "Key 'school' not found in 'StudentForm'. Choices are: admission_date, admission_no, date_of_birth, father_cnic, grade, mobile, name, roll_no, student_cnic." -
While deploying django app in jenkins why docker not run application when building image
I am new to CICD trying to understand docker. While deploying Django app using jenkins pipeline which is calling dockerfile to build docker image. The dockerfile calls runner.sh which have below line of code : uwsgi --http "0.0.0.0:${PORT}" --module my_proj.wsgi --master --processes 4 --threads 2 Everything is working fine, but i curious to know why this code not run application while building docker image and running application when this image is being run on host server. I tried running application in dockerfile in that case while deploying jenkins pipeline get stuck as it run the application and keep as stuck as application will keep on running while building image. -
How to extend the template for a Django Admin model add/create form?
In Django, you can override the Django Admin change forms by providing a path to a new template: @admin.register(MyModel) class MyModelAdmin(admin.ModelAdmin): # some other admin form config... # override change form template... change_form_template = "admin/some_custom_change_form.html" Then you can create a template within your application at app/templates/admin/some_custom_change_form.html that needs to extend the original template: {% extends "admin/change_form.html" %} <!-- Add your changes here --> <p>Hello World!</p> I am trying to override not only the change form, but the form for creation/addition too. Django also provides add_form_template for the ModelAdmin interface too: @admin.register(MyModel) class MyModelAdmin(admin.ModelAdmin): # some other admin form config... # override add and change form template... change_form_template = "admin/some_custom_change_form.html" add_form_template = "admin/some_custom_add_form.html" Now I just need the original template to override. I can't for the life of me find in documentation where the templates you can override are located, so I made a best guess and tried admin/add_form.html {% extends "admin/add_form.html" %} <!-- Add your changes here --> <p>Hello World!</p> Which throws an Exception on render of the add page, as it cannot find the chosen template to extend it. I've also tried using {% extends "admin/change_form.html" %} but that doesn't work as a different template is being used in … -
How to perform 2 operations in MathFilters ( Django )
I wanted to perform 2 operations 1: subtract entry_price from Exit_price then multiply the outcome by size. I am getting the error: Could not parse some characters: |(journals.exit_price||sub:journals.entry_price)|mul:journals.size <p class="pnl"> {% if journals.trade_direction == 'Long - Buy' %} {{ (journals.exit_price|sub:journals.entry_price)|mul:journals.size }} {% else %} {{ (journals.entry_price|sub:journals.exit_price)|mul:journals.size }} {% endif %} </p> -
django admin template overriding not working
I want to override templates/admin/change_form.html in my own django module app1, so following the standard, i added file change_form.html with following content to app1->templates->admin {% extends "admin/change_form.html" %} {% load i18n static %} {% block object-tools %} <h3>My extended html</h3> => Not rendered until => change_form_template = 'admin/change_form1.html' {{ block.super }} <script defer="defer" src="{% static 'app1/image_preview.js' %}"></script> {% endblock %} admin.py (I can achieve it by changing every admin and add giving change_form_template = 'admin/change_form1.html' but that is not the way i need it) from django.contrib import admin from .models import Model1 class Model1Admin(admin.ModelAdmin): # change_form_template = 'admin/change_form1.html' #overriding does not affect, but this does pass admin.site.register(Model1, Model1Admin) Expected output: <h3>My extended html</h3> should be the part of every change_form.html because I have extended admin/chamge_form.html without doing anything else anywhere while app1 exists in project and installed app in settings.py Complete steps (I have Django installed in default python of my system) django-admin startproject pr1 cd pr1 django-admin startapp app1 edited settings.py to append a line => INSTALLED_APPS += ['app1'] Added chnage_form.html to app1/templates/admin Made migrations, created superuser, logged in and opened http://127.0.0.1:8000/admin/app2/model1/add/ Complete code https://github.com/humblesami/django-templates -
I can't import multiselectfield
I'm trying to use multiselectfield in Django although I installed it with pip install django-multiselectfield and put it in my INSTALLED_APPS but I can't import it in my forms.py file... what can i do? -
Python Django: model <name> not recognized in views.py
Background: I want to open the CourseForm in order to edit existing course data by clicking on a link. Problem description: Running the development server, if I click on the link, I get the following error: File "/home/usr/project/workbench/courses/views.py", line 92, in ManageCourseView course = Course.objects.filter(id=id) UnboundLocalError: local variable 'Course' referenced before assignment Line 92 in ManageCourseView: from django.views import generic from .models import Course from .forms import CourseForm from django.shortcuts import render, redirect from django.http import HttpResponseRedirect def ManageCourseView(request, id): course = Course.objects.get(id=id) if request.method == 'POST': form = CourseForm(request.POST, instance=course) if form.is_valid(): # I do something with it else: form = CourseForm(instance=course) return render(request, 'courses/manage_course.html', {'form': form}) Definition of the Course model: class Course(models.Model): name = models.CharField('Kurs', max_length=200) capacity = models.PositiveSmallIntegerField('Anzahl Plätze') start_date = models.DateField('Erster Kurstag') end_date = models.DateField('Letzer Kurstag') price = models.FloatField('Preis', null=True, blank=True) def __str__(self): return self.name I am referencing the Course model in other view functions and there it works perfectly fine. Definition of the CourseForm: class CourseForm(forms.ModelForm): class Meta: model = Course exclude = ['name', 'price'] Extract of the html with the respective link: <div class="column is-two-thirds"> <a href="{% url 'courses:manage_course' course.id %}"> <div class="box has-background-info is-clickable"> <p class="title has-text-white">{{ course.name }}</p> <p class="has-text-white">{{ course.start_date … -
Daphne ModuleNotFoundError: No module named
I'm unable to get the Daphne server running. It always fails with the following error: ModuleNotFoundError: No module named 'apps' /home/prassel/sml-266/simlai-api/apps/asgi.py django_asgi_app = get_asgi_application() application = ProtocolTypeRouter( { "http": django_asgi_app, "websocket": URLRouter([path('ws/notifications/', NotificationConsumer.as_asgi())]), } ) And I invoke Daphne as follows: daphne -b 0.0.0.0 -p 8000 apps.asgi:application -
How to move Virtualenvwrapper.sh to it's appropriate location?
I am working a new project where it requires me to create a virtual environment since im working with Django frameworks. I been having trouble working creating "mkvirtualenv" and its been kicking my butt for the past couple days. I think I found the underlying problem that Virtualwrapper.sh is not in the right location. I been trying to figure out how to move it into the right location does anybody have some guidance on what to do. /Users/name/opt/anaconda3/bin ----> currently where the file is at the moment I been trying to add it to the .bashrc folder but im having a hard time adding it there. How can I do this so I can successfully run "mkvirtualenv" **I been trying for hours to write .bashrc and research anything but nothing is helping so far -
admin panel in Django creating for to change Product media and text from webpage
I have created a website in Django that contains product details and captions. Now, I want to create a dynamic admin panel that performs the following tasks without using code (because the client has no idea about coding): Add or change product photos and details. change or add any paragraphs or details on the website. ( just like we are changing the our images on social media account without using any coding like using prebuilded system) So here is what to do as the next step in processing this: pls guide me i have tried models but i don't understand it very well