Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
using .all() in views and for loop in template shows all content created from Album model
I have two model: Album and Primary model, I want to submit Primary model using pure Html Form but as you can see in the Primary model there is a field that has a relationship with a Album model using ForeignKey, when user is trying to create Primary model in form he\she may sees all the content that is created in the Album model using this method: def primary_submit_form(request): albums = Album.objects.all() if request.method == 'POST': admisssion_number = request.method.POST['admisssion_number'] profile_picture = request.FILES['profile_picture'] first_name = request.method.POST['first_name'] sure_name = request.method.POST['sure_name'] gender = request.method.POST['gender'] student_create = Primary.objects.create( admisssion_number=admisssion_number, profile_picture=profile_picture, first_name=first_name, sure_name=sure_name, gender=gender, year_of_graduations=year_of_graduations ) student_create.save() return redirect('Primary-Albums') return render(request, 'create_primary_student_information.html') My templates: <select class="form-select"\> {% for album in albums %} <option value="1"\>{{album.name}}\</option\> {% endfor %} </select\> my models: class Album(models.Model): name = models.CharField(max_length=100) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name class Primary(models.Model): addminssion_number = models.CharField(max_length=40) profilePicture = models.ImageField(upload_to='image') first_name = models.CharField(max_length=40) sure_name = models.CharField(max_length=40) gender = models.CharField(max_length=25) year_of_graduations = models.ForeignKey(Album, on_delete=models.CASCADE) How can i allow user to create primary model without seeing all album that is created by other's user, i dont want my user to see the content that he\she does not create. I knew using .all() method in views and … -
What is the best way to query ChatGPT regarding writing code?
I have been interacting with ChatGPT on openAI.com and trying out the code it has written. I have asked it various questions regarding Django, python and pyQuil. It comes back with a general outline of how to proceed usually in a text or conversational form if you don't request code examples. It has written a Django app for me after requesting a code example. How can I make use of its code writing ability more effectively? I also want to build it into a code writing app which I have yet to design. This question is my attempt to earn a silver badge on StackOverflow.com . I have yet to fully investigate other people's work regarding getting the chat-bot to write useful code. The bot does have limitations, it has been trained on data ending in late 2021 and can't execute a single line of code itself, not even to show the results of example code it has just written, when provided with input data. It can tell you how to write most code, but usually comes up with something simple and somewhat incomplete. In the Django code app question it didn't write models.py until prompted. It didn't include a … -
Django change field value in queryset
#models.py class Product(models.Model): price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, default=0.0000) discount = models.DecimalField(max_digits=10, decimal_places=2, blank=True, default=0.0000) is_discount = models.BooleanField(default=False) #views.py def page(request): product = Product.objects.get(pk=1) I have main product price, sometime I need to enable discount price, so if I enabled it in "is_discount" and when I make product instance at result I need to get by product.price the value from "discount". I understand that I can make it with price = product.price if product.is_discount: price = product.discount but this solution is not good for me. -
DRF Serialize prefetch_related query set
DRF Serialize prefetch_related query set Help in how to read the data, below is what I am doing. serializer.py class CustomerSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault()) phonebook = PhonebookSerializer() phonenumbers_set = PhonenumbersSerializer(many=True) customerdisposition_set = CustomerDispositionSerializer(many=True) class Meta: model = Customers fields = '__all__' queryset queryset = Customers.objects.select_related('user', 'phonebook').prefetch_related('phonebook__phonenumbers_set', 'customerdisposition_set').all() queryset.filter(value=value).first() {'status': u't', 'phonebook_id': 1L, 'modified_dt': datetime.datetime(2022, 2, 24, 5, 57, 38, tzinfo=), 'user_id': 1L, 'followup_dt': None, 'notes': None, '_state': <django.db.models.base.ModelState object at 0x12f6eae08>, 'refid': None, 'source': None, '_user_cache': <User: test>, 'agent_id': None, '_prefetched_objects_cache': {u'customerdisposition_set': []}, '_phonebook_cache': <Phonebook: 6,ree>, 'id': 9L, 'created_dt': datetime.datetime(2022, 3, 4, 6, 28, 58, 125834, tzinfo=)} Error AttributeError: Got AttributeError when attempting to get a value for field phonenumbers_set on serializer CustomerSerializer. -
Deploy Django project in railway
I try to move my project from HEROKU to RAILWAY, but i got this error When try to start a new project i get the same error Using Nixpacks context: 0fc4691a3fee078c9c01afe01d008723 Nixpacks build failed Error: Error reading runtime.txt Caused by: stream did not contain valid UTF-8 I tried to redo the project from the beginning, but nothings change -
Why django-rest-framework is generating same api url for two views (both views having same queryset)?
My Project Configuration is this. This is realated to Contact Form. Here I have two approach: Customer from frontend can only post (i.e. send message) and admin can only retrieve and list the contacts. Models.py class Contact(models.Model): full_name = models.CharField(max_length=100) email = models.EmailField() phone_no = models.CharField(max_length=10, validators=[validate_phone_no]) message = models.TextField() created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) def __str__(self): return self.email serializers.py class ContactSerializer(serializers.ModelSerializer): class Meta: model = Contact fields = [ 'full_name', 'email', 'phone_no', 'message', ] Views.py class ContactViewset(viewsets.ModelViewSet): permission_classes = [IsAuthenticated] queryset = Contact.objects.all() search_fields = [] ordering_fields = [] ordering = [] http_method_names = ["options", "head", "get"] serializer_class = ContactSerializer class CustomerContactViewSet(viewsets.ModelViewSet): permission_classes = [AllowAny] queryset = Contact.objects.all() http_method_names = ['post'] serializer_class = ContactSerializer urls.py router.register("contacts-detail", ContactViewset) router.register("contact-form", CustomerContactViewSet) My question is: Why DRF is generating the same url for both views although I have given different names for both: 'contact-form'----> for posting and 'contact-detail'--------> for listing the contacts Both views are pointing to same Model - Is this the Reason? Click Here to see generated api url See last urls are same: and redirecting to "contact-form". and I know I can give base_name to seperate both. But I wanted to know the mechanism behind generating same url: If … -
Reverse for 'Project' with arguments '('',)' not found. 1 pattern(s) tried: ['Project/(?P<id>[^/]+)/\\Z']
I got this error This the view of my projectThis is the url of my projectThis is the templates of my second view functionThis is the template of my first view functionThis the model of my project I tried to render the the data in my first view linked template but the second template data does not render in my page . I want to render the data of my second template in my first template through url -
What is "django_admin_log" used for in Django Admin?
When adding data: "django_admin_log" is inserted as shown below: And, when changing data: "django_admin_log" is inserted as shown below: And, when clicking Delete on Change page: Then, clicking Yes, I'm sure to delete data: "django_admin_log" is inserted as shown below: So, what is "django_admin_log" used for in Django Admin? -
Django - How to filter form field many to many after search result
I currently have a sports many to many field that contains multiple sports such as Tennis, Football, Rugby etc. What i am trying to do is pass a search result to the form which will filter and update the sports field and then redisplay the field with only the search result. So if i search for "Tennis" the sports field should only display "Tennis" and not a list of other sports field. However, i cannot figure out how to do this. I have tried using a post function in the class based view which filters sports field (it works) but i cannot pass this back to the form where it can update the filtered sports field. I currently return the filtered result (which i believe is wrong) and i get the error "too many values to unpack (expected 2)" I have also tried removing the post function from the class based view and placing the post function in the the form class and that also does not work as it just updates the form. Here are my models: class SportsTag(models.Model): name = models.CharField(max_length=50, unique=True) def __str__(self): return self.name class ProfileUser(AbstractUser): ... sports = models.ManyToManyField(SportsTag, blank=True) Here is the code for … -
Add Django pytest test database migrations only for tests
I am looking for a decent solution for any migrations in database itself. We have custom SQL script which adds pg_trgm extention to PostgreSQL database, which is simply CREATE EXTENSION pg_trgm; and FROM postgres:14.5-alpine COPY init.sql /docker-entrypoint-initdb.d/init.sql in database`s Dockerfile After that I can easily add specialized GIN indexes to models, i.e. class MyModel(models.Model): """ My model comment """ objects = MyManager() field = models.CharField(max_length=100) class Meta: indexes = ( models.Index(Upper("field"), name="field_idx"), GinIndex( fields=["field"], opclasses=["gin_trgm_ops"], name="field_gin_idx", ), GinIndex( OpClass(Upper("field"), name="gin_trgm_ops"), name="field_gin_idx", ), So I want to reflect that "custom script" in Django pytest tests. P.S.: I know there is a trigram extention for that purpose, but it was a TL decision to put custom database migration in separate place Do you have any idea on how to prepare such fixture? I was looking for related pytest fixtures but haven't found any solution -
How to use a Regex pattern in a Django form field widget attribute using JQuery
I'm using JQuery Mask Plugin in a Django form to specify input masks. I'm able to specify simple masks like the following simple mask which works: cost = forms.DecimalField(widget = forms.TextInput(attrs={'class':'js-input-mask form-control', 'data-hs-mask-options':'{"mask":"00.00"}') My problem is specifying regex patterns; I don't know how to pass the pattern to the 'data-hs-mask-options'. See the example below. How can I pass the translation dictionary to the 'data-hs-mask-options'? ip_address = forms.CharField(widget = forms.TextInput(attrs={'class':'js-input-mask form-control', 'data-hs-mask-options':'{"mask":"0ZZ.0ZZ.0ZZ.0ZZ"}') ('.ip_address').mask('0ZZ.0ZZ.0ZZ.0ZZ', { translation: { 'Z': { pattern: /[0-9]/, optional: true } } }) -
Django/Python - I don't use my django admin page to Add information my site because the admin field is empty
I'm not sure what happened but for the first time ever, i'm unable to use my admin fields. The fields are empty, and i can't use the models i can created on Django. I tried creating a new project but still no luck and i don't know how to resolve this. My Models.py is from django.db import models # Create your models here. class PersonModel(models.Model): Gender = { ('Male','Male'), ('Female','Female'), } Adult = { ('Non-Adult','Non-Adult'), ('Adult','Adult'), } Date = models.DateTimeField(auto_now_add=True), Name = models.CharField(max_length=50, blank=True, null=True), Surname = models.CharField(max_length=50, blank=True, null=True), The_gender = models.CharField(max_length=10, blank=True, null=True), The_Adult = models.CharField(max_length=10, blank=True, null=True), def __str__(self): return self.Name my admin.py is from django.contrib import admin from . models import PersonModel # Register your models here. admin.site.register(PersonModel) views.py from django.shortcuts import render from . models import PersonModel # Create your views here. def Home(request): Persons = PersonModel.objects.all() return render(request, 'Practice_2_app/Home.html', {'Persons':Persons}) def The_form(request): return render(request, 'Practice_2_app/The_form.html', {}) -
How can i print number of days between of each products expiry date and today date in a template //django view and html template
I have model called product in which i have expiry date as DateFiled, i need to calculate number of days left for expiry for all the products and display the product name and number of days left for expiry of every products from product table. class Product(models.Model): category = models.ForeignKey('store.Category',on_delete=models.CASCADE,default='SYRUP') itemname = models.CharField(max_length=50,blank=True,null=True) itemexpdate = models.DateField(auto_now_add=False, auto_now=False,blank=True,null=True) class Category(models.Model): name = models.CharField(max_length=200,blank=True) def days_left_for_expiry(expiry_date): today = date.today() expiry = expiry_date delta = expiry - today return str(delta.days) def home(request): d = Product.objects.all() for product in d: expiry_date = product.itemexpdate days_left= days_left_for_expiry(expiry_date) return render(request,'store/dashboard.html',{'days_left':days_left}) {% for i in d %} <tr> <td>{{ i.itemname }}</td> <td>{{ i.itemexpdate }}</td> <td><b>{{days_left}}</b></td> </tr> {% endfor %} output: image attached -
post action drops part of the url in django app
I'm building my first ecommerce app, while attempting to gain more skills in Django. I have a form problem, where I am either adding a product, or editing one, using the same Template. My problem is where the action call drops part of the url when submitting POST back to the server ( right now, it's just the python manage.py runserver). When I go to edit, I see the url: http://127.0.0.1:8000/mystore/edit-product/4 When I edit the product and click submit, I get the Request URL: http://127.0.0.1:8000/mystore/edit-product/ page not found error. and I don't make it back to the server to determine anything else. It looks like I'm missing something. this is what I have url.py from django.urls import path from django.contrib.auth import views as auth_views from . import views urlpatterns = [ path('signup/', views.signup, name='signup'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), path('login/', auth_views.LoginView.as_view(template_name='userprofile/login.html'), name='login'), path('myaccount/', views.myaccount, name='myaccount'), path('mystore/', views.my_store, name='my_store'), path('mystore/add-product/', views.add_product, name='add-product'), path('mystore/edit-product/<int:pk>', views.edit_product, name='edit-product'), path('vendors/<int:pk>/', views.vendor_detail, name='vendor_detail') ] Views @login_required def add_product(request): if request.method == 'POST': form = ProductForm(request.POST, request.FILES) if form.is_valid(): title = request.POST.get('title') slug = slugify(title) product = form.save(commit=False) product.user = request.user product.slug = slug product.save() return redirect('my_store') else: form = ProductForm() return render(request, 'userprofile/add-product.html', { 'title': 'Add Product', 'form':form … -
Django - Password Reset Page Not Found (404)
i try to add password reset function to my app but i get error at final step. It says: Here is the error screenshot: It says: “C:\Users\yusuf\Desktop\Klasörler\Marmara Üniversitesi Bilgisayar Programcılığı\3. Güz 2022-23\İnternet Programlama I (BLY2005)\360121065-main\yusuferselbal templatemo_526_vanilla\mytemplate\account\password_reset_confirm\MTM\set-password” does not exist This is my urls.py: path('password_reset/', authViews.PasswordResetView.as_view( template_name = 'account/user/password_reset_form.html', success_url = 'password_reset_email_confirm', email_template_name = 'account/user/password_reset_email.html', form_class = PwdResetForm), name = 'pwdreset'), path('password_reset_confirm/<uidb64>/<token>', authViews.PasswordResetConfirmView.as_view( template_name = 'account/user/password_reset_confirm.html', success_url = '/account/password_reset_complete/', form_class = PwdResetConfirmForm), name = 'password_reset_confirm'), path('password_reset/password_reset_email_confirm', TemplateView.as_view( template_name = 'account/user/reset_status.html', ), name = 'password_reset_done'), path('password_reset_complete/', TemplateView.as_view( template_name = 'account/user/reset_status.html', ), name = 'password_reset_complete'), This is my password_reset_confirm.html template: {% load i18n %}{% autoescape off %} {% blocktranslate %}You're receiving this email because you requested a password reset for your user account at {{ site_name }}.{% endblocktranslate %} {% translate "Please go to the following page and choose a new password:" %} {% block reset_link %} {{ protocol }}://{{ domain }}{% url 'account:password_reset_confirm' uidb64=uid token=token %} {% endblock %} {% translate 'Your username, in case you’ve forgotten:' %} {{ user.get_username }} {% translate "Thanks for using our site!" %} {% blocktranslate %}The {{ site_name }} team{% endblocktranslate %} {% endautoescape %} -
Django FileField saving empty file to database
I have a view that should generate a temporary JSON file and save this TempFile to the database. The content to this file, a dictionary named assets, is created using DRF using serializers. This file should be written to the database in a model called CollectionSnapshot. class CollectionSnapshotCreate(generics.CreateAPIView): permission_classes = [MemberPermission, ] def create(self, request, *args, **kwargs): collection = get_collection(request.data['collection_id']) items = Item.objects.filter(collection=collection) assets = { "collection": CollectionSerializer(collection, many=False).data, "items": ItemSerializer(items, many=True).data, } fp = tempfile.TemporaryFile(mode="w+") json.dump(assets, fp) fp.flush() CollectionSnapshot.objects.create( final=False, created_by=request.user, collection_id=collection.id, file=ContentFile(fp.read(), name="assets.json") ) fp.close() return JsonResponse({}, status=200) Printing assets returns the dictionary correctly. So I am getting the dictionary normally. Following the solution below I do get the file saved to the db, but without any content: copy file from one model to another Seems that json.dump(assets, fp) is failing silently, or I am missing something to actually save the content to the temp file prior to sending it to the database. The question is: why is the files in the db empty? -
Django - How can i resize the svg in the html template
I just created a matplot figure from a csv in django (line graph) and rendering it to the html template and I can't modify its dimensions imgdata = io.StringIO() fig.savefig(imgdata, format='svg') imgdata.seek(0) data = imgdata.getvalue() return data data = isolate(selected_loc) return render(request, 'hello.html', {'data': data, 'locations' : list(locations)}) html template <div class="figure" style="">{{ data|safe }}</div> i tried styling the div in css .figure { width: 40%; height: 500px; } and it doesnt working only the div container expands but not the svg that just rendered enter image description here -
I get this error [assert image.thumbnail.read() == expected_content AssertionError] when testing my signals.py file
When a user inputs an image the function in signals.py is supposed generates a thumbnail of that image automatically. But when I run the test in test_signals.py to check if the thumbnail is created when the image is saved it fails on line 30: assert image.thumbnail.read() == expected_content this is the model.py file this is the signals.py file this is the test causing the error -
Revert some file/directory deletions from other Revert, Recover file and directory from Commit
I made a revert that deleted some files and directories... According to the The screenshot: The Red box shows the commit with my revert. The Blue arrow shows the position inside of my project The Green arrows shows the files that I would like to recover... I see this question, but that is recovering all, and this How do I reset or revert a file to a specific revision? shows only file. This Git revert just some files in commit is about single file. How I Could do the recovery with directory? Is it possible do this operation directly from IntelliJ? Is it possible do this operation interactively (in order to select what recover)? -
The annotation 'id' conflicts with a field on the model
In Annotate I am trying to get the count of quires for which is_healthy is True but I am getting an Error The annotation 'id' conflicts with a field on the model. Any solution to solve this? and why is this causing how can i resolve this? DeviceHealthHistory.objects.filter(**filter_data).values( id = F('id'), ).annotate( healthy_count=Count('id', filter=Q(is_healthy=True)), ) -
inconsistency between databases created with pandas and models.py in django
I am trying to generate a database in sqlite3 with pandas and so far everything is fine, it is generated as I need it, the problem is that when trying to access that database through a models created identical to the one created by pandas it breaks and django does not manages to access that database. I have the following file "output.txt" which was basically generated by a function in views.py Interface Status Protocol Description BE9 down down BE9.1 down down BE9.100 down down Lo0 up up Lo8 up up Lo30 up up Lo100 up up ***MERGE LOOPBACK 100**** Lo111 up up Configured by NETCONF Lo200 up up ***MERGE LOOPBACK 200**** Gi0/0/0/0 down down Gi0/0/0/1 down down Gi0/0/0/2 admin-down admin-down Gi0/0/0/3 admin-down admin-down Gi0/0/0/4 admin-down admin-down Gi0/0/0/5 admin-down admin-down Gi0/0/0/6 admin-down admin-down and through that same function there is a fragment that takes that info and transfers it to the database: #Converting txt to Detafrare df = pd.read_fwf("output.txt") #debugging df df["Description"] = (df.iloc[:, 3:].fillna("").astype(str).apply(" ".join, axis=1).str.strip()) df = df.iloc[:, :4] #Converting to SQLITE3 database,. If doesn't existe, a nre one will be created connection = sqlite3.connect("db.sqlite3") #Inserting data into SQLITE database df.to_sql( name = "Devices_App_interfaces", #this is the name format … -
How To Implement Dynamic Columns in Django models based on POST request
I have created a Django RestFramework with few models like Offers, Dailysubs and Requisitions to which I need add columns dynamically for a POST request. There should be 1-10 blank columns for a model and a Master table which has fields to configure the new column like name and other properties. I also need to implement an approach to add these dynamic columns into serializers. class Requisition(models.Model): skill = models.CharField(max_length=255) superClass = models.CharField(max_length=255) jobFamily = models.CharField(max_length=255) yearOfExp = models.CharField(max_length=255) grade = models.CharField(max_length=100) ... ... class Offer(models.Model): businessGroup = models.CharField(max_length=100) status = models.CharField(max_length=20) sNo = models.IntegerField() recruiter = models.CharField(max_length=100) manager = models.CharField(max_length=100) dateOfOffer = models.DateField() dateOfJoining = models.DateField() ... ... class MasterTable(models.Model): columnName = models.CharField(max_length=100) tableName = models.CharField(max_length=100) columnFieldType = models.CharField(max_length=100) I read another post related to this at Django Models (dynamic?) but I don't know if I should create another model to hold these blank columns or if I should add blank columns to each model. -
How can I make a user out of a model in Django?
I'm currently developing a web-application for managing driving licenses as a web development homework assignment. Instead of just storing information on every driver as a model I want to make a user for each driver. What is the easiest way to do so? What am I doing wrong? I updated a car owner model so that it is now inherited from djangdo Abstract User. # models.py class Car_owner(AbstractUser): id_owner = models.IntegerField(primary_key=True) last_name = models.CharField(max_length=30, null=False) first_name = models.CharField(max_length=30, null=False) birth_date = models.DateField(null=True) passport = models.IntegerField(null=True, blank=True) address = models.CharField(max_length=50, null=True, blank=True) nationality = models.CharField(max_length=15, null=True, blank=True) # username = models.CharField(max_length=16, unique=True, default=uuid4) # password = models.CharField(max_length=16, default='password') I also have forms.py file: from django import forms from project_first_app.models import Car_owner class CreateOwner(forms.ModelForm): class Meta: model = Car_owner fields = ['id_owner', 'last_name', 'first_name', 'birth_date', 'passport', 'address', 'nationality'] But when migrating I get the following issue: UNIQUE constraint failed: new__project_first_app_car_owner.username In migrations files I have: migrations.AddField( model_name='car_owner', name='username', field=models.CharField(default=uuid.uuid4, max_length=16, unique=True), ), and then: migrations.AlterField( model_name='car_owner', name='username', field=models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username'), ), Those are automatically generated. -
How to read URL parameters in a Wagtail model?
I am trying to read parameters from the URL in a Wagtail model function. However, the "request" parameter is not accepted in my model function. I also tried creating a fake function that doesn't read anything, just returns a constant to test that everything else was working fine. This fake function works properly but, as soon as the "request" parameter is added, the function value is not displayed. The problem is without request object, I can't get URL parameters. What am I missing? Do I have to import something for the request parameter to work in the model's functions? Why can't I use the request object in a models function? example of the URL would use: http://localhost/blog/?parameter=someValue MODELS.PY CONTENT from wagtail.core.models import Page from wagtail.core.fields import RichTextField class BlogIndexPage(Page): intro = RichTextField(blank=True) content_panels = Page.content_panels + [ FieldPanel('intro', classname="full") ] def read_parameter(self, request): my_param = request.GET.get('parameter') return my_param HTML TEMPLATE CONTENT {% block content %} <h1>My page</h1> <p>This should be the parameter: {{ page.read_parameter }} </p> {% endblock content %} EXPECTED OUTCOME: My Page This should be the parameter: someValue ACTUAL OUTCOME My Page This should be the parameter: MODELS.PY WITH THE FAKE FUNCTION ADDED class BlogIndexPage(Page): intro = RichTextField(blank=True) … -
Why the request body is empty in Django when I send a request to it from Node JS?
I am writing an application using React Native for frontend, Node JS (express, axios) for backend and Python Django (v 4.1.4) for hosting a neural network. In this app I need to send a POST request containing some parameters in body, as well as a music file. This request goes from React to Node JS to Python server. The request is successfully processed on a Node JS server, however, when I send it to Python Django server from Node, I get an empty body in the python endpoint. Now, when Python server is hosted on amazon (I use Elastic Beanstalk), the request comes with populated body, it stops working once I try to host python server locally and send a request from node js to python django server. You might ask: why bother, just use amazon hosting then? I can't because my neural network is too heavy for free tier hosting and it requires power to respond quickly. The strangest thing is that requests comes to the Python server (it does not say something like CORS error) and the response is sent from Python server, but the request body is empty. I have tried to use another IP for Django …