Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to update dynamic form fields in Django
The users can dynamically add more fields and edit fields to the forms. The problem is I don't know how exactly I should pass the dynamic multiple dynamic 'city' ids and edit-update them. Models.py class Cities(models.Model): cityname = models.CharField(max_length=5000, null = True, blank = True) owner = models.ForeignKey(User, null = True, on_delete=models.CASCADE) relcountry = models.ForeignKey(Country, null = True, on_delete=models.CASCADE) Index.html <form method = "post" action='cityupdate/{{city.id}}' enctype="multipart/form-data"> {% csrf_token %} {% for city in cities %} <input type="text" name = "{{city.id}}" value= "{{city.name}}" </input> {% endfor %} <input type="submit" name = "cityupdate" value= "Update" </input></a> </form> Urls.py path('cityupdate/<str:id>',views.cityupdate,name='pk') Views.py def cityupdate(request,pk): if request.method == 'POST' and 'cityupdate' in request.POST: ----------------- I need help to complete the views.py code -
How can I send Boolean fields via Django send_mail
I am fairly new to Python and Django, I am trying to use the build in send_mail and having a few issues with the boolean fields I want to be included in the email that is sent, I have had no issues with the form being printed to the terminal for testing but as soon as I added the other fields that are on the form(b oolean fields) I am getting the following error (TypeError: sequence item 4: expected str instance, bool found), probably an easy fix but I am struggling to find anything on the web that will help. I am not fussed is the boolean fields that are False are excluded on the email as this is not relevant, any help would be much appreciated. I have managed to get the email side working when it comes to Firstname, Lastname, Email, Phone, but when adding the boolean fields I am getting an error. Views.py from django.shortcuts import render, redirect from django.http import JsonResponse from main.models import WFHSHEET from django.http import HttpResponse, response, HttpResponseRedirect from .forms import WFHLIST, RETURNLIST from django.core.mail import send_mail, BadHeaderError def home(response): return render(response, 'home.html', {}) def wfhsheet(request): if request.method == 'POST': form = WFHLIST(request.POST) … -
Can't show specific model field in my HTML template
On my main page i want to show a category just like {{ post.body }} but instead {{ post.body }} would be {{ post.category }} here. {% extends "base.html" %} {% block title %}Articles{% endblock title %} {% block content %} {% for post in post_list %} <div class="card"> <div class="card-header"> <span class="font-weight-bold"><a href="{% url 'post_detail' post.pk %}">{{ post.title }}</a> | </span> &middot; <span class="text-muted">by {{ post.author }} | {{ post.created_at }}</span> </div> <div class="card-body"> <!-- Changes start here! --> <p>{{ post.body }}</p> <p>{{ post.category }}</p> <a href="{% url 'post_edit' post.pk %}">Edit</a> | <a href="{% url 'post_delete' post.pk %}">Delete</a> | <a href="{% url 'category_list' %}">Category</a> </div> <div class="card-footer"> {% for comment in post.comment_set.all %} <p> <span class="font-weight-bold"> {{ comment.author }} &middot; </span> {{ comment }} </p> {% endfor %} </div> <!-- Changes end here! --> </div> <br /> {% endfor %} {% endblock content %} but cannot to figure out how. But cannot figure out how. Here is my models from django.conf import settings from django.db import models from django.urls import reverse class Category(models.Model): name = models.CharField(max_length=255) def __str__(self): return (self.name) def get_absolute_url(self): return reverse("home") class Post(models.Model): title = models.CharField(max_length=255) body = models.TextField() author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,) created_at = models.DateTimeField(auto_now_add=True) … -
I can't get Django custom error pages to work
I am trying to get custom error pages (404 & 500) to work in my Django application. So far I have the following: urls.py handler404 = views.error_404 handle500 = views.error_500 views.py def error_500(request, exception): return render(request, '500.html', status=500) def error_404(request, exception): return render(request, '404.html', status=404) DEBUG is set to FALSE. However when I try access an error page I get the following error: "A server error occurred. Please contact the administrator." Which (obviously) is not my error template. Any help appreciated! -
Django localisation, internationalization
How to add different language buttons so that it translate my django website online? Or any other method? I want to translate my whole website. In easy way -
I hosted a django website on namecheap but it has changed structure
I have hosted a django business directory system on namecheap but the home page has changed. That's my localhost display of the front end [This is the display of app on thena.thenadaka.com][2] I checked the console to see if there's any static file that is not served but all are served. I know am supposed to learn Docker to ease this but for now your help with be paramount. The code for both is exactly the same, i also disabled Cache under Network on localhost so the locally hosted site doesn'd display cached data -
Django API rejects file
I'm trying to send a csv file to my Django API and response with process data, but when I send it, I get the error: django.utils.datastructures.MultiValueDictKeyError: 'file' this is my react code: import { useState } from 'react'; import './App.css'; function App() { const [file, setFile] = useState(null); const uploadFiles = e =>{ setFile(e); } const insertFile = async() => { const f = new FormData(); f.append("file", file); await fetch( 'http://localhost:8000/api/', { method: 'POST', headers: { 'content-type': 'multipart/form-data' }, body: f, }) .then((response) => response.json()) .then((data)=>{ console.log(data); }) .catch(error=>{ console.log(error); }); } return ( <> <input type="file" name="file" onChange={(e)=>uploadFiles(e.target.files)}/> <button onClick={()=>insertFile()}>Insertar</button> </> ); } export default App; And this is my view.py file that will process the information, for now, I just want to get the csv info in the frontend side, so the logic of how to process data doesn't matter right now. @api_view(['POST']) def eda(request): file = request.FILES['file'] data = [] with open(file, encoding='utf-8') as csvf: csvReader = csv.DictReader(csvf) for rows in csvReader: data.append(rows) response = { 'csvData': data } return Response(response) -
Get a Foreign Key value with django-rest-framework serializers
I'm using the django rest framework to create an API. models.py class DepartmentModel(models.Model): DeptID = models.AutoField(primary_key=True) DeptName = models.CharField(max_length=100) def __str__(self): return self.DeptName class Meta: verbose_name = 'Department Table' class EmployeeModel(models.Model): Level_Types = ( ('Genin', 'Genin'), ('Chunin', 'Chunin'), ('Jonin', 'Jonin'), ) EmpID = models.AutoField(primary_key=True) EmpName = models.CharField(max_length=100) Email = models.CharField(max_length=100,null=True) EmpLevel = models.CharField(max_length=20, default="Genin", choices=Level_Types) EmpPosition = models.ForeignKey(DepartmentModel, null=True, on_delete=models.SET_NULL) class Meta: verbose_name = 'EmployeeTable' # Easy readable tablename - verbose_name def __str__(self): return self.EmpName serializer.py from appemployee.models import EmployeeModel,DepartmentModel class EmployeeSerialize(serializers.ModelSerializer): class Meta: model = EmployeeModel fields = '__all__' class EmployeeSerializer(serializers.ModelSerializer): emp_dept = serializers.CharField(source='DepartmentModel.DeptName') class Meta: model = EmployeeModel fields = ('EmpID','EmpName','Email','EmpLevel','emp_dept') views.py class EmployeeTable(APIView): def get(self,request): try: emp_obj = EmployeeModel.objects.all() empserializer = EmployeeSerialize(emp_obj,many=True) except Exception as err: return Response(err) return Response(empserializer.data) this would provide me with: [ { "EmpID": 1, "EmpName": "Hashirama Senju", "Email": "hashirama.senju@konaha.com", "EmpLevel": "Jonin", "EmpPosition": 1 }, { "EmpID": 2, "EmpName": "Tobirama Senju", "Email": "tobirama.senju@konaha.com", "EmpLevel": "Jonin", "EmpPosition": 2 }, { "EmpID": 3, "EmpName": "Hiruzen Sarutobi", "Email": "hiruzen.sarutobi@konaha.com", "EmpLevel": "Jonin", "EmpPosition": 5 } ] what i really want is [ { "EmpID": 1, "EmpName": "Hashirama Senju", "Email": "hashirama.senju@konaha.com", "EmpLevel": "Jonin", "DeptName": "Hokage" }, { "EmpID": 2, "EmpName": "Tobirama Senju", "Email": "tobirama.senju@konaha.com", "EmpLevel": "Jonin", "DeptName": "Hokage" … -
any docs abot django + htmx for JSON
I found many reference (docs and video) about how to use htmx in django for doing parent-child crud UI. Is there any docs or excample on how to do 'dynamicaly added form field' with just single model class? My case is to make an app that take care of business mailing templates. models.py class MailTemplate(models.Model): code = models.CharField(verbose_name='Code',max_length=10, unique=True) name = models.CharField(verbose_name='Name', max_length=30) docx = models.FileField(verbose_name='docx File') dataschema = models.TextField(null=True, blank=True) class Mail(models.Model): mailtemplate = models.ForeignKey(MailTemplate, on_delete=models.SET_NULL) created = models.DateTimeField(auto_now_add=True) edited = models.DateTimeField(auto_now=True) data = models.TextField(null=True, blank=True) What I want is a form to add/edit record of 'MailTemplate'. that form will 'look like' 'stacked inline' but the 'child' is from parsing MailTemplate.dataschema. Example of MailTemplate.dataschema : [ { "name": "to", "label": "To", "type": "string", }, { "name": "platenumber", "label": "Plate Number", "type": "string", }, ] I really appreciate any help. Sincerely -bino- -
How do I use django templates to get a field from the parent object of a model?
I'm trying to create an interface where students can match with other students in the class for a group project based on shared interests and I have a queryset in a django view and from there I am able to use select_related to get the parent object and even print the fields in Anaconda Prompt (when running on local server) but I can't seem to get the field to show up in a template...what am I missing? Here is the relevant part of my models file: class Profile(models.Model): first_nm = models.CharField(max_length=100) last_nm = models.CharField(max_length=100) class Potential(models.Model): user1 = models.ForeignKey(Profile, related_name='user1', on_delete=models.CASCADE) user2 = models.ForeignKey(Profile, related_name='user2', on_delete=models.CASCADE) Here is the relevant part of my view: def matches(request): my_user = request.user my_id = Profile.objects.get(slug=my_user) the_matches = Potential.objects.filter(Q(user1=my_id) | Q(user2=my_id)).all().select_related('user1','user2') print(the_matches.values()) print(the_matches.values('user2__first_nm')) return render(request,'projects/matches_list.html', { 'matches':the_matches}) Here is the relevant part of the template: {% for match in matches %} <div class="matches"> <p>{{ match.user1__first_nm }}</p> <p>{{ match.user2__first_nm }}</p> </div> {% endfor %} In the template above, why does this not work? Thanks in advance! I have tried using the syntax above like: <p>{{ match.user2__first_nm }}</p> and when just printing to the console I get <QuerySet [{'user2__first_nm': 'test_nm'}]> from the second to last line … -
Uncaught (in promise) Error: Invalid hook call on fetch()
I'm working on a webapp for Django. It is a simple blog. The front end is being built in react and materials UI, it is based off of the tutorial here, but I have had to adapt much by myself because he is using a Class-oriented approach many methods of which are deprecated as React seems to be moving towards a function based model. In the model that the demonstrator created, we are passing data from our react frontend to our django backend by use of generating JSON objects which python serializes. I have built a blog post submission form that doesn't work for a reason I can't understand. CreateBlogPost.js import React, { Component } from "react"; import Grid from "@mui/material/Grid"; import { FormControl, FormHelperText, TextField, Typography, Button } from "@mui/material"; import { Link } from "react-router-dom"; import { useState } from "react"; import { Navigate } from "react-router-dom"; export default function CreateBlogPost(props) { const[title,setTitle] = useState(''); const[content,setContent] = useState(''); const[tags, setTags] = useState(''); const handleTitle = event => { setTitle(event.target.value); } const handleContent = event => { setContent(event.target.value); } const handleTags = event => { setTags(event.target.value); } const requestOptions = { method: "POST", headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ title: … -
Django queryset - fetching reverse relations
I have two models with a one-to-many relation through a ForeignKey. At some stage, I have obtained a queryset of the 'one' objects and would like to retrieve, as efficiently as possible, all of the 'many' objects that are associated with them. Here is a minimal example: class Car(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=1000) @classmethod def search(keyword): return keyword_search_cars(keyword) class Passenger(models.Model): car = models.ForeignKey(Car, on_delete=models.CASCADE) Now I would like to query the models like so: # Get all passengers in cars matching term 'truck' cars = Car.search('truck') passengers = cars.passenger_set.all() # Not permitted on querysets! But the best I can come up with is something like this: car_ids = Car.search('truck').values_list('id', flat=True) passengers = Passenger.objects.filter(car_id__in=car_ids) With hundreds of records in the cars queryset, the __in filter seems like a dumb way to query the database. According to the docs, this does not do a SQL JOIN but instead writes a huge WHERE id IN (1, 2, 3, ... ) which does not seem optimal. Does anyone know of a better approach for this? Currently my queries take 10+ seconds (with 1M+ records) which means rather poor performance for my application. It will get even slower as the database table grows … -
MultipleObjectsReturned at /vehicle/vehicle_view/ get() returned more than one Vehicle -- it returned 7
`Hello I have more then 1 vehicle in my client side when i was send request from froentend, it return error View.py File @login_required def vehicle_view(request): vehicle = get_object_or_404(Vehicle, user=request.user) form = UpdateVehicleForm(request.POST or None, request.FILES or None,instance=vehicle) context = {'form': form } if request.method == 'POST': if form.is_valid(): vehicle.save() messages.success(request, "Vehicle Updated!") return redirect('home') else: messages.error(request, "Invalid Data Provided") return render(request, "user/edit_vehicle.html", context) urls.py path('vehicle_view/',views.vehicle_view,name='vehicle_view'), ` -
I have an ecommerce website of multiple selllers
I want following solution: Client need a shipping API for domestic and international locations on the basis of multiple sellers cost and also client need all activities of shipping api done in their own website. Please Provie me the best and cheap solution according to this situation. -
Can't make jquery toggle function top show a comment form for posts lists, It opens only the first one [duplicate]
I'm working on a blog app to hone my django skills. I'm trying to create a posts list page with a quick one field comment form for each post, kind of like you will see on facebook, or linkedin. I'm decided to use jquery for this, and it only opens/toggles the first post. How do I pass a unique user or user id with jinja to jquery? Is that how you do it? Can someone please guide me to the right path to accomplish this? {% extends 'posts/base.html' %} {% block content %} <style type="text/css"> .card{ margin-bottom: 20px; } </style> <div class="container"> <div class="row"> <div class="col-md-2">left</div> <div class="col-md-8"> {% for post in posts %} <div class="card"> <div class="card_header"> <a href="{{post.get_absolute_url}}">{{post.title}}</a> </div> <div class="card_meta_header"> ... </div> <div class="card_featured_image"> <img src="{{post.featured_image.url}}" class="img-fluid"> </div> <div class="card_text"> <p>{{post.content_short|safe}}</p> </div> <div id="commenting" style="display:none;"> <label for="inputPassword5" class="form-label">Password</label> <input type="password" id="inputPassword5" class="form-control" aria-describedby="passwordHelpBlock"> </div> <script type="text/javascript"> $(document).ready(function(){ $("#openFormPanel").click(function(){ $("#commenting").toggle(); }); }); </script> <div class="card_footer"> ... </div> <button id="openFormPanel" >Open form panel to leave comment</button> </div> {% endfor %} </div> <div class="col-md-2">right</div> </div> </div> {% endblock %} {% include 'posts/footer.html' %} -
Is there any better way to do like history.back() in django backend?
In Django, I have "form view(GET)" and "action view(POST)" If there is a validation error or any other error in action view, I want browser to go back to the previous form page with the input data whote by the user remains. I tried: At first, I used return redirect(request.META.get('HTTP_REFERER')). This code goes back to the previous page well, but all the input fields became empty. And now I am using return HttpResponse("<script>history.back();</script>") this code. This works very well. but It looks weird sending javascript response. What I was expected was like return redirect.back()(with like HTTP 301 or 30X status code) I was wondering if there is any better way or a proper way like officially provided by Django. -
Normalising Data with Django
I have several datasets in csv formats and instructions are given to normalise them for Django REST API development with sqlite3. I am very new to databases and django, and having some difficulties to organise the tables. I have 3 csv datasets. First dataset - protein sequence. Two columns with 'ProteinID' and 'protein_sequence' Second dataset - protein domain assignemtns. 'ProteinID', 'Organism_taxa_id', 'Organism_clade', 'Organism_genus_species', 'domain_description', 'domain_id', 'domain_start_coord', 'domain_end_coord', 'length_of_protein' Third dataset - pfam description. Two columns with 'domain_id' and 'domain_description' I am creating an application where users can search for protein data. Conditions are: Organisms HAVE MANY Proteins Organisms HAVE A Genus name Organisms HAVE A Species name Proteins HAVE MANY domains Proteins HAVE ONE sequence Domains HAVE ONE pfam domain ID May I know how I can model the tables for efficient querying? And I have rest_specification_and_example REST Specification: POST http://127.0.0.1:8000/api/protein/ - add a new record GET http://127.0.0.1:8000/api/protein/[PROTEIN ID] - return the protein sequence and all we know about it http://127.0.0.1:8000/api/protein/A0A016S8J7 returns { "protein_id": "A0A016S8J7", "sequence": "MVIGVGFLLVLFSSSVLGILNAGVQLRIEELFDTPGHTNNWAVLVCTSRFWFNYRHVSNVLALYHTVKRLGIPDSNIILMLAEDVPCNPRNPRPEAAVLSA", "taxonomy": { "taxa_id": 53326, "clade": "E", "genus": "Ancylostoma", "species": "ceylanicum" }, "length": 101, "domains": [ { "pfam_id": { "domain_id": "PF01650", "domain_description": "PeptidaseC13family" }, "description": "Peptidase C13 legumain", "start": 40, "stop": 94 }, { … -
TypeError: create_sql() got an unexpected keyword argument 'concurrently'
I'm trying to add a GIN Index to my usernames on my user model for better trigram similarity search: class User(models.Model): ... class Meta: ordering = ["-created_at"] indexes = [ UpperGinIndex( fields=["username"], name="user_username_gintrgm", opclasses=["gin_trgm_ops"], ) ] And when I run python manage.py makemigrations, no error is produced: # Generated by Django 3.2.7 on 2023-01-06 03:00 from django.db import migrations import myproj.db class Migration(migrations.Migration): dependencies = [ ... ] operations = [ migrations.AddIndex( model_name="user", index=myproj.db.UpperGinIndex( fields=["username"], name="user_username_gintrgm", opclasses=["gin_trgm_ops"], ), ), ] However, when I run python manage.py migrate, I get this error which doesn't seem to have any easy-to-google fixes. I've already tried updating Django to 3.2.16: File "/home/codespace/.cache/pypoetry/virtualenvs/myproj-NbYkgl4C-py3.8/lib/python3.8/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/codespace/.cache/pypoetry/virtualenvs/myproj-NbYkgl4C-py3.8/lib/python3.8/site-packages/django/db/migrations/executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "/home/codespace/.cache/pypoetry/virtualenvs/myproj-NbYkgl4C-py3.8/lib/python3.8/site-packages/django/db/migrations/migration.py", line 126, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/home/codespace/.cache/pypoetry/virtualenvs/myproj-NbYkgl4C-py3.8/lib/python3.8/site-packages/django/db/migrations/operations/models.py", line 761, in database_forwards schema_editor.add_index(model, self.index) File "/home/codespace/.cache/pypoetry/virtualenvs/myproj-NbYkgl4C-py3.8/lib/python3.8/site-packages/django/db/backends/postgresql/schema.py", line 218, in add_index self.execute(index.create_sql(model, self, concurrently=concurrently), params=None) TypeError: create_sql() got an unexpected keyword argument 'concurrently' Any ideas on how to fix this? -
where in my script is causing my csv data to not line up in the table?
After building my website, I noticed some slight details were off when returning values from my GETs. For reference, I have to create my GET to return these values. NOTE: "id" here is sequential the primary key value generated by django for the table that holds the domain data GET http://127.0.0.1:8000/api/pfams/[taxa_id] - return a list of all domains in all the proteins. GET should return: http://127.0.0.1:8000/api/pfams/55661 [ { "id": 88896, "pfam_id": { "domain_id": "mobidb-lite", "domain_description": "disorder prediction" } }, { "id": 88891, "pfam_id": { "domain_id": "PF00307", "domain_description": "Calponinhomology(CH)domain" } }, { "id": 88892, "pfam_id": { "domain_id": "PF00415", "domain_description": "Regulatorofchromosomecondensation(RCC1)repeat" } }, ... ] However, my current application only prints the following in REST { "id": 37922, "pfam_id": { "domain_id": "PF00115", "domain_description": "CytochromeCandQuinoloxidasepolypeptideI" } } I'm assuming something in my script went wrong or I linked my relationships badly and I printed it to the wrong row since my values dont lie up with the reference. I'll link below the snippet of how the CSV file looks - if anyone could point me towards the right direction, it would mean a lot. Thanks in advance! (my serializers, urls, and views are set up fine so I'll leave those out) Here's my … -
(Python) how to use APIs with Django rest framework, generating endpoints which can call in my existing website
ultimate goal: change mySQL data can result changed the website data (demo pic) The original website and MySQL before change (demo pic) The idea result pic (Python) How to Connect/Integrate Django with website the last discussion came up one of the way: using the API with Django rest framework, generating endpoints which can call in my existing website the goal is still wish to connect with Django, ps. I already have website done/build separately environment: mySQL, python, windows and exist website to connect for now mySQL is connected to Django Therefore, how to use APIs with Django rest framework, generating endpoints which can call in my existing website -
Python Django settings.py Module Not Found Error (module is just local .py file)
Background info Background Info can be found on my last post - Cannot import .py file into settings.py Problem When attempting to import a python file into settings.py I get an error The code: import test Password = test.Password The Error: [wsgi:error] [pid 3908:tid 1496] import test\r [wsgi:error] [pid 3908:tid 1496] ModuleNotFoundError: No module named 'test'\r WSGIPythonPath set In my D:\Apache24\conf\httpd.conf I have the WSGIPythonPath line set: WSGIPythonPath D:\PythonEnvs\myenv\Lib\site-packages However, test is just a python file I created titled test.py located in the same directory as settings.py. It does NOT exist in the folder site-packages like the other modules. Note I can import test into other python files. However, when I try and import test.py into settings.py I get an error 500 when restarting my Apache server and get the error above from the Problem section in my error logs. -
AWS Codebuild Installing Upgraded Version of Package but Old Version Still Detected/Used
I have a Django App deployed via AWS' elastic beanstalk, that uses the CodePipeline service to build. As part of that pipeline, the CodeBuild service is used to build the app that gets deployed to the ElasticBeanstalk environment. The build failed, sending the following error message: django.core.exceptions.ImproperlyConfigured: SQLite 3.9.0 or later is required (found 3.7.17). Per Amazon's own package version listing I realize that is expected given the older version is intended to be on the Amazon Linux 2 distro. Ok. I wrote a shell script to download the latest version of SQLite and build from scratch, but I'm still getting the same issue. In the buildspec.yaml file I have the following: ... post_build: commands: - echo "beginning post-build phase..." - bash get_sqlite.sh - echo "sqlite version -- $(sqlite3 --version)" - python manage.py makemigrations ... In the CodeBuild logs, I can see the result of the echo command as such: sqlite version -- 3.40.1 2022-12-28 Yet, the build fails and the logs still show the following error: django.core.exceptions.ImproperlyConfigured: SQLite 3.9.0 or later is required (found 3.7.17). Any idea what further steps need to be taken for the updated version to be detected rather than the previous one? -
how can i select correctly many to many field django
I need to select 'changes' which related to sku id I need help with views.py models.py Change class Change (models.Model): raw_current = models.ForeignKey(Raw, blank=True, null=True, on_delete=models.CASCADE, related_name='raw_current') raw_new = models.ForeignKey(Raw, blank=True, null=True, on_delete=models.CASCADE, related_name='raw_new') created_date = models.DateTimeField(default=timezone.now) # когда была создана заявка def __str__(self): return self.raw_current.num def publish(self): self.created_date = timezone.now() self.save() Raw class Raw (models.Model): num = models.CharField(max_length=200) # артикул сырья name = models.CharField(max_length=200) # наименование layer = models.CharField(max_length=200) # название слоя на русском def __str__(self): return self.num +' ' + self.name Sku class Sku (models.Model): num = models.CharField(max_length=200) # артикул готоваой продукции (ГП) name = models.CharField(max_length=200) # наименование ГП raw = models.ManyToManyField(Raw, blank=True, null=True) # сырье weight = models.IntegerField(blank=True, null=True) # вес photo = models.ImageField(blank=True, null=True, upload_to="images/") # фото type = models.ForeignKey(ProductsTypes, blank=True, null=True, on_delete=models.CASCADE) def __str__(self): return self.num + ' ' + self.name views.py def change(request,sku_id): sku = Sku.objects.get(id=sku_id) list_change = Change.objects.filter(raw_current = sku.raw) return render(request, 'main/change.html', {'sku':sku,'list_change':list_change,'change':change,}) urls.py path('change/<sku_id>', views.change, name='change'), TypeError at /change/1 Field 'id' expected a number but got <django.db.models.fields.related_descriptors.create_forward_many_to_many_manager.<locals>.ManyRelatedManager object at 0x10920d9f0>. if in views.py def change(request,sku_id): sku = Sku.objects.get(id=sku_id) list_change = Change.objects.all() return render(request, 'main/change.html',{'sku':sku,'list_change':list_change,'change':change,}) then i have the whole list but i need only changes belongs to selected sku thanks for … -
Django Rest UpdateView: This field is required
I have the following view: class CampaignUpdate(generics.RetrieveUpdateAPIView): queryset = Campaign.objects.all() serializer_class = CampaignSerializer permission_classes = [CampaignDetailPermission] lookup_field = 'cid' And I have the following test function: def test_update_campaign(self): request = self.factory.put(f'/', {'name': 'Updated Campaign'}) force_authenticate(request, user=self.merchant) response = CampaignUpdate.as_view()(request, cid=self.campaign.cid) # Check that the response status code is 200 (OK) print(response.data) self.assertEqual(response.status_code, 200) # Check that the campaign was updated in the database self.assertEqual(Campaign.objects.get(cid=self.campaign.cid).name, 'Updated Campaign') And I am getting the following error: System check identified 4 issues (0 silenced). ..........{'shop': [ErrorDetail(string='This field is required.', code='required')]} shop field is required for creation but i do not want to update this field everytime I update some other field. How can I make it optional for update or readonly after creation? In case, you need to see serializer: class CampaignSerializer(serializers.ModelSerializer): class Meta: model = Campaign fields = '__all__' -
Why am I getting a Type error produced even though on_delete is set to models.CASCADE?
Following the django portion of the book 'Python Crash Course' by Eric Matthes where you build a django topic website the code he used seems to be deprecated. For example methods like Foreign Key require an on_delete command in current versions of django however despite adding an on_delete argument I still get a typeerror. from django.db import models # Create your models here. class Topic(models.Model): """A topic the user is learning about""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """Return a string representation of the model.""" return self.text class Entry(models.Model): """A entry in a given topic from the user""" topic = models.ForeignKey(Topic, on_delete=models.CASCADE) entry = models.TextField() date_added = models.DateTimeField(auto_now_add=True) class meta: verbose_name_plural = 'entries' def __str__(self): """Return a string representation of the model.""" return self.text[:50] + "..." the error: Traceback (most recent call last): File "D:\lafem\You Don't Know Javascript\topicwebsites\manage.py", line 22, in <module> main() File "D:\lafem\You Don't Know Javascript\topicwebsites\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Python310\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Python310\lib\site-packages\django\core\management\__init__.py", line 420, in execute django.setup() File "C:\Python310\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python310\lib\site-packages\django\apps\registry.py", line 116, in populate app_config.import_models() File "C:\Python310\lib\site-packages\django\apps\config.py", line 269, in import_models self.models_module = import_module(models_module_name) File "C:\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], …