Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
api.urls are not working after using django-hosts for subdomain
i'm trying to use sub-domain for api in my project and using django-hosts for that.but after implementing it as documented there is Page not found (404) error is coming when I'm accessing any URL of my app 'api' project/hosts.py from django_hosts import patterns, host from .settings import base as settings host_patterns = patterns('', host(r'www', settings.ROOT_URLCONF, name='www'), host(r'api', 'apps.api.urls', name='api'), ) project/settings.py def ip_addresses(): ip_list = [] for interface in netifaces.interfaces(): addrs = netifaces.ifaddresses(interface) for x in (netifaces.AF_INET, netifaces.AF_INET6): if x in addrs: ip_list.append(addrs[x][0]['addr']) return ip_list ALLOWED_HOSTS = ip_addresses() ALLOWED_HOSTS.append('.localdemo.in') ALLOWED_HOSTS.append('.api.localdemo.in') INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'apps.core', 'apps.api', # Third party 'django_hosts', ] MIDDLEWARE = [ 'django_hosts.middleware.HostsRequestMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'drf_api_logger.middleware.api_logger_middleware.APILoggerMiddleware', 'django_hosts.middleware.HostsResponseMiddleware', ] ROOT_URLCONF = 'project.urls' ROOT_HOSTCONF = 'project.hosts' DEFAULT_HOST = 'www' project/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('apps.core.urls')), ] handler404 = "apps.core.views.customerrors.custom_handler404" handler403 = "apps.core.views.customerrors.custom_handler403" apps/api/urls.py from django.urls import path, include, re_path from django.conf.urls import url from .views import statisticsview urlpatterns = [ path('v1/statistics', statisticsview.StatisticsListView.as_view(), name='statistics_list'), re_path(r'^statistics/$', statisticsview.StatisticsListView.as_view(), name='statistics_list'), re_path(r'statistics/', statisticsview.StatisticsListView.as_view(), name='statistics_list'), hosts file inside windows/system32/drivers/etc/hosts 127.0.0.1 localdemo.in 127.0.0.1 api.localdemo.in now when I'm accessing localdemo.in:8000 its working fine but I'm … -
Django: How would I create a secondary ID field that is grouped (ranked) by a given foreign key?
The output could look like this, for example: id secondary_id fk 1 1 1 2 2 1 3 3 1 4 1 2 5 2 2 For context: (see models below) I have a commission structure which will have brackets depending on how much a user is earning in a month. Ideally, I need to know in my Commission Bracket model, the bracket index for a given structure. Here are my models. class CommissionStructure(APIBaseModel): advisor = models.ManyToManyField(AdviserDetail) name = models.CharField(max_length=20, blank=True, null=True, default='default') company = models.ForeignKey(Company, on_delete=models.CASCADE) start_dt = models.DateTimeField(auto_now_add=True) end_dt = models.DateTimeField(default=timezone.datetime.max) objects = CommissionStructureManager() class CommissionBracket(APIBaseModel): <secondary_id ???> commission_structure = models.ForeignKey(CommissionStructure, on_delete=models.CASCADE, related_name="brackets") lower_bound = models.DecimalField(decimal_places=2, default=0.00, max_digits=20, null=True, blank=True) upper_bound = models.DecimalField(decimal_places=2, default=0.00, max_digits=20, null=True, blank=True) Please note, I may not have to store it on my model if I can add an annotation to an aggregate set, but my preference is to follow DRY. Thank you -
problems with testing the Django REST Framework
I'm trying to perform the tests that are within the Django Rest Framework documentation. And it always gives the same error, regardless of what I'm testing. Test example: class TestRequestFactory(APITestCase): def test_request(self): factory = APIRequestFactory() request = factory.post('/list_user/', json.dumps({'title': 'new idea'}), content_type='application/json') The error I'm referring to is this django.db.utils.ProgrammingError: relation "user" does not exist LINE 1: ...ted_by", "user"."created_ts", "user"."is_active" FROM "user" I've looked in many places and the solution has always been the same, do manage.py migrate or manage.py migrate --fake bots zero, I can do everything, but in the end it gives the same error -
Azure SDK for Python: Reading blobs without downloading
I'm currently using the Azure Blob Storage SDK for Python. For my project I want to read/load the data from a specific blob without having to download it / store it on disk before accessing. According to the documentation loading a specfic blob works for my with: blob_client = BlobClient(blob_service_client.url, container_name, blob_name, credential) data_stream = blob_client.download_blob() data = data_stream.readall() The last readall() command returns me the byte information of the blob content (in my case a image). With: with open(loca_path, "wb") as local_file: data_stream.readinto(my_blob) it is possible to save the blob content on disk (classic downloading operation) BUT: Is it also possible to convert the byte data from data = data_stream.readall() directly into an image? It already tried image_data = Image.frombytes(mode="RGB", data=data, size=(1080, 1920)) but it returns me an error not enough image data -
How can I use reverse relation items in templates django
{% for order in orders %} <li>{{order.customer.last_name}} - {{ order.orderitem_set.product.unit_price }}</li> {% endfor %} How can I get products unit_price in browser, last_name shows but when I am trying to use django reverse relation created item the value don't showing -
Django Admin - Filter on Sub-Table in URL
I'm working with Django admin and I'm trying to work out how, via the URL parameters, if it is possible to filter on a different table. I have a datasource, let's say users, these users have many orders. In the users page I can view all related orders. What I want to be able to do, is filter from the users search page on those order ID's. How can I achieve this? -
forloop.counter for two dimensional array in Django Template
I'm using forloop.counter for my list. I have two-dimensional list. If I try this, all works perfect. {{team_members|index:1|index:0}} But when I try this: {{team_members|index:forloop.counter|index:0}} where forloop.counter = 1 it wrotes me list index out of range Can you please explain why? If I code like this: {{team_members|index:forloop.counter}} it works perfect too. -
Get default value for serializer field from a method
I struggle to find a way to do something I thought must be very basic. I have a serializer accepting either address (nested serializer) or coordinates (also a nested serializer). If the user supplies the address, I resolve it using some magic into coordinates and I want to provide those coordinates in the response. This is what I have so far: class AddressSerializer(serializers.Serializer): zip_code = serializers.CharField() city = serializers.CharField(required=False) street = serializers.CharField(required=False) house_number = serializers.CharField(required=False) class GeoPointSerializer(serializers.Serializer): latitude = serializers.FloatField() longitude = serializers.FloatField() class BaseMatchingCustomersSerializer(serializers.Serializer): address = AddressSerializer(required=False) coordinates = GeoPointSerializer(required=False) def validate(self, attrs): # check if the user provided either address or coordinates def resolve_address_to_coordinates(...): ... and now I have no idea how to continue. I know about SerializerMethodField which would work fine, except it is read-only. Then I was playing with default and source attributes on the coordinates field, but also no success. Can anyone unstuck me? -
How to auto populate a field in django when a value is selected from dropdown menu in another field in forms?
I have two models that are located in two different apps; Invoice and Inventory. InvoiceModel: class Invoice(models.Model): line_one = models.ForeignKey(Inventory, to_field='title', on_delete=models.CASCADE, default='', blank=True, null=True, related_name='+', verbose_name="Line 1") line_one_unit_price = models.IntegerField('Unit Price(₹)', default=0, blank=True, null=True) line_one_quantity = models.IntegerField('Quantity', default=0, blank=True, null=True) line_one_total_price = models.IntegerField('Line Total', default=0, blank=True, null=True) Invoice.line_one is referenced to Inventory.title InventoryModel: class Inventory(models.Model): product_number = models.IntegerField(blank=True, null=True) product = models.TextField(max_length=3000, default='', blank=True, null=True) title = models.CharField('Title', max_length=120, default='', blank=True, null=True, unique=True) amount = models.IntegerField('Unit Price', default=0, blank=True, null=True) def __str__(self): return self.title So basically the user adds a product using the Inventory model and then in the Invoice model, they'll have a drop-down menu for line_one and when they click a certain item, I want the line_one_unit_price to get populated with the price of the item selected in the line_one option! InvoiceForm: class InvoiceForm(forms.ModelForm): line_one_unit_price = forms.CharField(widget=forms.Select, label="Unit Price(₹)") class Meta: model = Invoice fields = ['line_one',#...] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['line_one_unit_price'].widget.choices = [(i.amount, i.amount) for i in Inventory.objects.all()] By using the above logic, I can list the amount of all products present in the Inventory but I want it to only display the amount of the product that the user has selected in line_one. … -
Facing issue in websocket in djagno
We are trying to show web pop-up on my web application when notification api call receive from any where, We implement Web socket communication in api and web app but after estable connectivity not able to send data on web serve. -
data not shown in BOTH database and webpage
Hi I am making a CRUD project of shopping based on models Products,categories,sub categories,size,colors.I am currently doing CRUD of SUBcategories which is connected to categories via foreign key. I am trying to insert data into the web page and the database but it isnt coming below is the model of sub_categories class SUBCategories(models.Model): category_name = models.ForeignKey(Categories,on_delete=models.CASCADE) sub_categories_name = models.CharField(max_length=20) sub_categories_description = models.CharField(max_length=20) isactive = models.BooleanField(default=True) def __str__(self): return self.categories_name below are the show functions and insert functions of sub categories def show_sub_categories(request): showsubcategories = SUBCategories.objects.filter(isactive=True) #print(showsubcategories) serializer = SUBCategoriesSerializer(showsubcategories,many=True) print(serializer.data) return render(request,'polls/show_sub_categories.html',{"data":serializer.data}) def insert_sub_categories(request): if request.method == "POST": insertsubcategories = {} insertsubcategories['sub_categories_name']=request.POST.get('sub_categories_name') insertsubcategories['sub_categories_description']=request.POST.get('sub_categories_description') form = SUBCategoriesSerializer(data=insertsubcategories) if form.is_valid(): form.save() print("hkjk",form.data) messages.success(request,'Record Updated Successfully...!:)') print(form.errors) return redirect('sub_categories:show_sub_categories') else: category_dict = Categories.objects.filter(isactive=True) category = CategoriesSerializer(category_dict,many=True) hm = {'context': category.data} print(hm) # print(form.errors) return render(request,'polls/insert_sub_categories.html',hm) else: category_dict = Categories.objects.filter(isactive=True) category = CategoriesSerializer(category_dict,many=True) hm = {'context': category.data} print(hm) return render(request,'polls/insert_sub_categories.html',hm) below is the show and insert pages of sub categories {% for result in data %} <tbody> <tr> <td><b>{{result.sub_categories_name}}</b></td> <td><b>{{result.sub_categories_description}}</b></td> <td style="position: relative;left:50px;"> <a href="sub_categories/edit_sub_categories/{{result.id}}"> <button class="btn btn-primary"> <i class="fa-solid fa-pen-to-square">EDIT</i> </button> </a> </td> <td> <a href="{% url 'sub_categories:delete_sub_categories' result.id %}" onclick="return confirm('Are You Sure you want to delete?')"> <button class="btn btn-danger"> <i class="fa-solid … -
Logic for Sortable table using Drag and Drop in Django
I am trying to create function for the Sortable Table. in which i am updating the position of the ids as per the given request: def put(self, request): max_len = Device.objects.count() ids = int(request.query_params.get('id')) temp = ids old = int(request.query_params.get('old')) new = int(request.query_params.get('new')) if new == old: return Response("both are equal can't go ahead") elif new > max_len: return Response("Invalid Position") elif old < new: t = Device.objects.get(id=ids) t.position = 0 print("new position Updated to 0") t.save() for i in range(old + 1, new + 1, 1): ids = ids + 1 print(ids) t = Device.objects.get(id=ids) print(t) t.position = t.position - 1 print(t.position) t.save() print(i, "value saved") t = Device.objects.get(id=temp) t.position = new print("new position Updated with ", t.position) t.save() print("new position saved") return Response("old < New") elif old > new: t = Device.objects.get(id=ids) t.position = 0 print("new position Updated to 0") t.save() for i in range(old - 1, new - 1, -1): ids = ids - 1 print(ids) t = Device.objects.get(id=ids) print(t) t.position = t.position + 1 print(t.position) t.save() print(i, "value saved") t = Device.objects.get(id=temp) t.position = new print("new position Updated with ", t.position) t.save() print("new position saved") return Response("old > New") Need help to make it more efficient, … -
How to get User instance in Django tests.py?
I'm a beginner in Django, I created a simple ecommerce app and I'm writing some tests in tests.py. I'm trying to write a test which check the correct creation of an OrderItem, but I don't know how to obtain an user instance. Should I check the logged in user or the existence of the user is enough? This is my store/models.py: from tkinter import CASCADE from django.db import models from django.conf import settings class Item(models.Model): name = models.CharField(max_length=50) price = models.FloatField() def __str__(self): return self.name class OrderItem(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) def __str__(self): return f"{self.quantity} of {self.item.name}" @property def get_total_price(self): return self.quantity*self.item.price And this store/tests.py: def create_item(name='cintura', price=10): return Item.objects.create(name=name, price=price) def get_user(): return User.objects.get(username='foo') def create_orderitem(quantity=2, user=get_user(), ordered=False): item = create_item() return OrderItem.objects.create(item=item, quantity=quantity, user=user, ordered=ordered) class OrderItemModelTest(TestCase): def test_orderitem_creation(self): order_item = create_orderitem() self.assertFalse(order_item.ordered) self.assertGreater(order_item.quantity, 0, 'Quantity must be > 0') #put here user check This is the error: django.db.utils.IntegrityError: The row in table 'store_orderitem' with primary key '1' has an invalid foreign key: store_orderitem.user_id contains a value '1' that does not have a corresponding value in auth_user.id. -
Django sitemap xml
How can i create django sitemap xml with all sub sitemaps with django pagination prefix? Or the 2nd question - how can i ping to google all paginating sitemap. For example 1st question result: <sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <sitemap> <loc>http://127.0.0.1:8000/sitemap-movies.xml</loc> </sitemap> <sitemap> <loc>http://127.0.0.1:8000/sitemap-movies.xml?p=2</loc> </sitemap> </sitemapindex> or <?xml version="1.0" encoding="UTF-8"?> <sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <sitemap> <loc>http://www.example.com/sitemap1.xml.gz</loc> </sitemap> <sitemap> <loc>http://www.example.com/sitemap2.xml.gz</loc> </sitemap> </sitemapindex> -
Django-React app search bar implementation
I want to implement a search bar on one of my pages in the Django-React app. I am a complete newbie in React and I am struggling with achieving the desired results. Basically, I created an endpoint on the backend to filter query results. Works fine in Insomnia. Now I wish to do the same on the frontend. my code so far: import React, {Component} from "react"; import {Col, Container, Row} from "reactstrap"; import SomeList from "./SomeList"; import NewSomeModal from "./NewSomeModal"; import axios from "axios"; import {BEARER_TOKEN, SOME_API_URL} from "../../constants"; const headers = { 'Content-Type': 'application/json', 'Authorization': BEARER_TOKEN }; class Some extends Component { state = { someArray: [], query: "" }; componentDidMount() { this.resetState(); } getSomeQuery = () => { axios.get(SOME_API_URL + `search?q=${this.state.query}`).then(res => this.setState({results: res.data})); }; resetState = () => { this.getSomeQuery(); }; render() { return ( <Container> <Row> <Col> <NewSomeModal create={true} resetState={this.resetState}/> </Col> </Row> <Row> <Col> <SomeList someArray={this.state.results} query={this.state.query} resetState={this.resetState} /> </Col> </Row> </Container> ); } } export default Some; This is where I create a table: import React, {Component} from "react"; import {Table} from "reactstrap"; import NewSomeModal from "./NewSomeModal"; import ConfirmRemovalModalSome from "./ConfirmRemovalModalSome"; class SomeList extends Component { handleChange = (e) => { this.setState({query: this.search.value}, () … -
Fixture not found within app tests by seen in pytest --fixtures
Are fixtures in conftest.py usable throughout and entire django project? For example I have this conftest.py located in root/fixtures from accounts.models import User from factories import UserFactory import pytest from pytest_factoryboy import register register(UserFactory) # user_factory @pytest.fixture def new_user(db, user_factory) -> User: user = user_factory.create() # Save user to test database return user However, I am getting this error when running pytest for my test in accounts/tests.py from accounts.models import User import pytest def test_new_user(new_user): print(new_user.email) count = User.objects.all().count() assert count == 1 def test_new_user(new_user): E fixture 'new_user' not found > available fixtures: _dj_autoclear_mailbox, _django_clear_site_cache, _django_db_helper, _django_db_marker, _django_set_urlconf, _django_setup_unittest, _fail_for_invalid_template_variable, _live_server_helper, _session_faker, _template_string_if_invalid_marker, admin_client, admin_user, async_client, async_rf, cache, capfd, capfdbinary, caplog, capsys, capsysbinary, client, db, django_assert_max_num_queries, django_assert_num_queries, django_capture_on_commit_callbacks, django_db_blocker, django_db_createdb, django_db_keepdb, django_db_modify_db_settings, django_db_modify_db_settings_parallel_suffix, django_db_modify_db_settings_tox_suffix, django_db_modify_db_settings_xdist_suffix, django_db_reset_sequences, django_db_serialized_rollback, django_db_setup, django_db_use_migrations, django_mail_dnsname, django_mail_patch_dns, django_test_environment, django_user_model, django_username_field, doctest_namespace, factoryboy_request, faker, live_server, mailoutbox, monkeypatch, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, rf, settings, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory, transactional_db > use 'pytest --fixtures [testpath]' for help on them. However, when I run pytest --fixtures I see --------------------------------------------------------- fixtures defined from factories.conftest --------------------------------------------------------- new_user -- factories/conftest.py:25 no docstring available -
Date lte filter in django and date localization
I am trying to get objects from django ORM upto a certain date from a DataFrame df12 which looks like this : Date Warehouse 33 2022-06-20 Delhivery Goa Warehouse 34 2022-07-04 Delhivery Goa Warehouse 35 2022-07-05 Delhivery Goa Warehouse Mu Code: for index, row in df12.iterrows(): print("date", row['Date']) print("warehouse", row['Warehouse'].split(" ")[1]) obj = RFIDTagging.objects.filter(date__lte=row['Date'], owner__in=emp) The problem is that the above code excludes objects created on 2022-07-05 which is stored in the ORM like the following: 2022-07-05 12:05:06.274462 +00:00 2022-07-05 12:05:06.227598 +00:00 2022-07-02 18:39:11.648968 +00:00 2022-07-02 18:39:11.590210 +00:00 I tried converting the Date column like the following df12["Date"] = df12["Date"].tz_localize("Asia/Kolkata").tz_convert("UTC") but getting the following error: TypeError: index is not a valid DatetimeIndex or PeriodIndex -
how to send data from websocket to django consumer.py
I am trying to send current user as argument in websocket on connect but I am unable to receive the user in websocket connect function. please find the code below. consumer.py import asyncio from channels.consumer import AsyncConsumer from channels.db import database_sync_to_async class ChatConsumer(AsyncConsumer): async def websocket_connect(self, event): self.connected = True print("connected", event) await self.send({ "type": "websocket.accept" }) while self.connected: User=event["username"] await asyncio.sleep(2) apps = await database_sync_to_async(list)(User.objects.filter(user=User) listo=[] for app in apps: username = app.username id = app.id outputDict = {"id":id,"username":username} listo.append(outputDict) await self.send({ 'type': 'websocket.send', 'text': json.dumps(listo), }) async def websocket_receive(self, event): print("receive", event) async def websocket_disconnect(self, event): print("disconnected", event) self.connected = False javascipt: var socket = new WebSocket('ws://' + window.location.host + '/ws/notif/' + socketCode + '/'); socket.onmessage = function(e){ console.log("message", e.data); }; socket.onopen = function(e){ socket.send(JSON.stringify({ 'user': 1003, })) console.log("open", e); }; socket.onerror = function(e){ console.log("error", e) }; socket.onclose = function(e){ console.log("close", e) }; } Please help me how to get data from JavaScript to websocket connect function -
Passing Data to D3.js with Django Backend
I want to build a line chart following the code here. I've made slight change to the data being passed with contains epoch time and a closing price. Following is the code {% load static %} <html> <script src="https://d3js.org/d3.v4.js"></script> <body> <h1> Hello! </h1> <div id="my_dataviz"></div> </body> <script> // set the dimensions and margins of the graph var margin = {top: 10, right: 30, bottom: 30, left: 60}, width = 460 - margin.left - margin.right, height = 400 - margin.top - margin.bottom; // append the svg object to the body of the page var svg = d3.select("#my_dataviz") .append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); //Read the data var d = { "Date":{ "0":1641168000000, "1":1641254400000, "2":1641340800000 }, "Close":{ "0":182.01, "1":179.7, "2":174.92 } }; // When reading the csv, I must format variables: d3.json(d, function(d){ return { date : d3.timeParse("%s")(d.Date), value : d.Close } }, // Now I can use this dataset: function(data) { // Add X axis --> it is a date format var x = d3.scaleTime() .domain(d3.extent(data, function(d) { return d.date; })) .range([ 0, width ]); svg.append("g") .attr("transform", "translate(0," + height + ")") .call(d3.axisBottom(x)); … -
{% csrf_token %} is empty string but {{ csrf_token }} returns a value - Django
I have to submit a form via POST method. I added to my html form the {% csrf_token %} tag but from the DOM I'm getting this: <input type="hidden" name="csrfmiddlewaretoken" value=""> But if I type {{ csrf_token }} in the template I can see the value. Why can't I set my token in the form? This is my form: <form action="{% url 'aj_upload_file' %}" method="POST"> {% csrf_token %} <a id="upload-file-btn" href="javascript:;" class="btn btn-success mr-2"> <i class="fa fa-upload" aria-hidden="true"></i> </a> <input class="d-none" multiple type="file" id="upload-file"> </form> Thank You. -
dictionary not coming in for loop despite correct syntax
I am doing crud project which has models PRoducts,categories,sub categories ,color,size. I am trying to get a django dropdown using SERIALIZERS and have connect categories and subcategories via foreignkeys below are the models below is the function of isnerting in views.py of sub categories and below is the html code for the dropdown using for loops I also tried {{c}} even that didnt work the drop down still doesnt have any options,where am I going wrong? -
How to access a foreign key related field in a template when using Django model form
My Objective Access the field name in the Parent Model ParentModel and display its content in a form instance in the template. For example, let the field parent be a foreign key in the ChildModel as described below. What I have tried Access the parent field in the form as {{ form.parent.name }} in the template Errors received Tried looking up form.parent.name in context models.py class ParentModel(models.Model): name = models.CharField() class ChildModel(models.Model): parent = models.ForeignKey(ParentModel) forms.py class ChildModelForm(ModelForm): class Meta: model = ChildModel fields = '__all__' widgets = {'parent': forms.Select(),} views.py def childView(request, pk): template = 'template.html' child = ChildModel.objects.get(parent=pk) form = ChildModelForm(instance=child) if request.method == 'POST': form = ChildModelForm(request.POST, instance=child) if form.is_valid(): form.save() else: form = ChildModelForm(instance=child) context = {'form': form, } return render(request, template, context) template.html <form method="POST" action=""> {% csrf_token %} {{form.parent.name}} <button type="submit">Save</button> </form> Now the child model form displays pk I want to display the name of the parent field I have also tried using this Django access foreignkey fields in a form but it did not work for me. -
DRF ManyToMany instances add not create
I have the following code of my model: class Recipe(BaseModel): """ Recipe model class using for contains recipe, which can be sent to chat with coach. In text recipe contains RecipeStep. """ ingredients = models.ManyToManyField( Product, verbose_name=_("ingredients"), related_name="ingredients" ) portion_size = models.PositiveSmallIntegerField( _("portion size") ) # TODO: add "add_to_meal" logic (user can add recipe to his meal). # it can be reached by using M2M with user and creating new relation for # user and recipe on user click on special button. def __str__(self) -> str: return f"recipe \"{self.title}\"" def __repr__(self) -> str: return f"Recipe({self.pk=}, {self.title=}, {self.is_published=})" class Meta: verbose_name = _("recipe") verbose_name_plural = _("recipes") BaseModel is abstract class, that has basic structure of Article-like models (title, description, published_at, etc.). And the following code of serializers for model: class RecipeSerializer(serializers.ModelSerializer): id = serializers.UUIDField(read_only=True) title = serializers.CharField(min_length=1, max_length=200, required=True) ingredients = ProductSerializer(many=True, read_only=False) portion_size = serializers.IntegerField(min_value=0, required=True) is_published = serializers.BooleanField(required=False, default=False) publish_date = serializers.DateField( allow_null=True, required=False, read_only=True ) image_add_id = serializers.UUIDField(required=True) def create(self, validated_data): validated_data.pop('image_add_id', None) return super().create(validated_data) class Meta: model = Recipe fields = "__all__" I need to create Recipe with passing list of existing ingredient pks, and not create new ingredients like: { ... "ingredients": [ "d6c065a2-7f80-47f3-8c0e-186957b07269", "4b8359d2-073a-4f41-b3cc-d8d2cfb252d5", "b39e4cc2-18c3-4e4a-880a-6cb2ed556160", … -
ModuleNotFoundError: No module named 'app' on new Django installation
I am trying to set up a simple Django==4.0.6 dev environment on my Ubuntu 20.04. I'm creating a project folder, create and activate a venv first. Then I'm installing Dajngo using pip. I'm then creating a new project in the very same directory and then for testing this out, run the usual python manage.py command. Here's a quick list of commands I am using: mkdir project && cd project python3 -m venv venv source venv/bin/activate pip install django==4.0.6 django-admin startproject major . python manage.py migrate But I'm getting the following error: Traceback (most recent call last): File "/project/venv/lib/python3.8/site-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/project/venv/lib/python3.8/site-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File "/project/venv/lib/python3.8/site-packages/django/core/management/base.py", line 95, in wrapped saved_locale = translation.get_language() File "/project/venv/lib/python3.8/site-packages/django/utils/translation/__init__.py", line 210, in get_language return _trans.get_language() File "/project/venv/lib/python3.8/site-packages/django/utils/translation/__init__.py", line 65, in __getattr__ if settings.USE_I18N: File "/project/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 87, in __getattr__ self._setup(name) File "/project/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 74, in _setup self._wrapped = Settings(settings_module) File "/project/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 183, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, … -
Javascript is not working properly inside djagno project
While my code is working when used outside of a Django project, when I place it inside one it's acting strange. More specifically, the document object does not have a body, but only the head of my html. Thus I am not able to access its classes. My guess is that something's wrong in the linking between the html and js files. settings.py STATIC_URL = 'static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>index.html</title> {% load static %} <link rel="stylesheet" href="{% static 'style.css' %}"/> <script src="{% static 'script.js' %}"></script> </head> <body> HelloWorld! </body> </html> script.js console.log(document.getElementsByTagName('html')[0].innerHTML) The return of script.js: <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>index.html</title> <link rel="stylesheet" href="/static/style.css"> <script src="/static/script.js"></script></head>