Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django render multiple ModelForm in template and save
I have a django Entry model which takes in several values related to an entity like height,weight etc. This value has to be entered every month. For each month, a new form along with the previous month's data has to be displayed on the template. My views look somewhat like this: ntt=Entry.objects.get(pk=6) lastmonth=EntryForm(instance=ntt) thismonth=EntryForm() return render(request, 'show.htm', {'thismonth':thismonth,'lastmonth':lastmonth}) I am not sure how to display the two values side by side, one line for each attribute like so: <tr><td><input type=text>thismonth.weight</input></td><td>lastmonth.weight</td></tr> <tr><td><input type=text>thismonth.height</input></td><td>lastmonth.height</td></tr> Using the common way of rendering a form like {{thismonth.as_p}}{{lastmonth.as_p}} <table> <tr> <td>{{thismonth.as_p}}</td> <td>{{lastmonth.as_p}}</td> </tr> </table> I was able to render them on the same rows but with labels on both of them. Is there a way to render the form where only the label will be displayed for thismonth, while lastmonth will only display the values and without manually specifying the field id and name? Also, since I don't want to change the value of lastmonth is there a way to get only the thismonth values from request.POST in order to save/update it? -
Django: Forms: Unable to validate ModelChoiceField/Radio Button
I want to run required field validate using the clean function in my form class. I also wanted to validate this with self.add_error to access the field in template. my form.py class Step2(forms.Form): special_purpose = forms.ModelChoiceField( empty_label=None, queryset=SpecialPurpose.objects.all(), to_field_name="id", widget=forms.RadioSelect(attrs={'style': 'list-style:none'}), required=False ) def clean(self): cleaned_data = super().clean() special_purpose = cleaned_data.get("special_purpose") if special_purpose is '': self.add_error('special_purpose', 'This field is required') then in my template <label id="{{ form.special_purpose.id_for_label }}-error" class="error" for="{{ form.special_purpose.name }}">{{ form.special_purpose.errors|striptags }}</label> {{ form.special_purpose.0 }}<br> {{ form.special_purpose.1 }}<br> {{ form.special_purpose.2 }}<br> {{ form.special_purpose.3 }}<br> Is there a specific way for doing this for Radio buttons/ModelChoice field -
Filter data in a model with list of ids filtered from the related model
I've 3 models which are related weirdly though it is a one-to-many relationship (between 2 models). Now I've no option to change the model structure but to work with it however it is. Models class Note(models.Model): user_owner = models.ForeignKey('User',blank=True, null=True,related_name='note_owner') message = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) ... ... ... class SalesLead(models.Model): user_owner = models.ForeignKey(User, models.DO_NOTHING, blank=True, null=True) status = models.ForeignKey(LeadStatus, models.DO_NOTHING, blank=True, null=True) name = models.CharField(max_length=255) first_name = models.CharField(max_length=255, blank=True, null=True) middle_name = models.CharField(max_length=255, blank=True, null=True) last_name = models.CharField(max_length=255, blank=True, null=True) ... ... ... class LeadNoteRelation(models.Model): note = models.ForeignKey(Note, models.DO_NOTHING, primary_key=True, related_name = "lead_note") lead = models.ForeignKey('SalesLead', models.DO_NOTHING) class Meta: unique_together = (('note', 'lead'),) I'm trying to write a function-based view which takes the SalesLead id and User id as inputs. The response should include all Notes related to this lead id and user_owner as the input User id I tried: LeadNoteRelation.objects.filter(lead__id = INPUT ID).select_related() But this did not give me the desired result. Kindly help me with this one. Thanks in advance. -
Get the last used value of the forloop counter
I'm using the forloop counter to assing unique ids to three which I later populate with data. <td id="menge{{ forloop.counter }}">{{ d.menge }}</td> <td id="preis{{ forloop.counter }}" name="preis">{{ d.preis }}</td> <td>{{ d.einheit }}</td> <td id="preisprostuekc{{ forloop.counter }}" name="{{ d.id }}"></td> Lets say the loop runs 10 times. This means the last assigned value is 10. Can i get that value, the last value of the counter, to reuse it in a javascript function? If yes: how? Thanks! -
How do you import a CSV file into django with foriegn keys
I'm trying to import data from a csv file into Django but I keep getting this error : NOT NULL constraint failed: error_boilermodel.ModelBrand_id my models are this : from django.db import models # Create your models here. class BoilerBrand(models.Model): BrandName = models.CharField(max_length=40, blank=False) def __str__(self): return self.BrandName class meta: db_table = 'Boiler_Brand' class BoilerModel(models.Model): ModelBrand = models.ForeignKey('BoilerBrand', on_delete=models.CASCADE,) ModelName = models.CharField(max_length=600, blank=False) def __str__(self): return self.ModelName class meta: db_table = 'Boiler_Model' class BoilerError(models.Model): BoilerBrand = models.ForeignKey('BoilerBrand', on_delete=models.CASCADE,) BoilerModel = models.ForeignKey('BoilerModel', on_delete=models.CASCADE,) ErrorCode = models.CharField(max_length=40, blank=False) ErrorDesc = models.CharField(max_length=200, blank=False) ErrorFix = models.CharField(max_length=200, blank=False, default="Call a technician") def __str__(self): return self.ErrorCode class meta: db_table = 'Boiler_Error' My import code is this : import csv from error.models import BoilerError,BoilerBrand,BoilerModel ImportBrandName = "worcester-bosch" def run(): file = open("D:/python tratining/boilererror/error/csv-error-codes/worcester-bosch-error-codes-Copy.csv") reader = csv.reader(file) BoilerError.objects.all().delete() BoilerModel.objects.all().delete() BoilerBrand.objects.all().delete() for row in reader: print(row) a, created = BoilerBrand.objects.get_or_create(BrandName=ImportBrandName) b, created = BoilerModel.objects.get_or_create(ModelName=row[2]) c, created = BoilerModel.objects.get_or_create(ModelBrand=ImportBrandName) d, created = BoilerError.objects.get_or_create(BoilerBrand=ImportBrandName) e, created = BoilerError.objects.get_or_create(ErrorCode=row[0]) f, created = BoilerError.objects.get_or_create(ErrorDesc=row[1]) g, created = BoilerError.objects.get_or_create(ModelName="Contact a Technician") here is a sample of the CSV I'm using: 200 O ,Boiler in heating mode , Greenstar 8000 Boiler 201 O ,Boiler in hot water mode , Greenstar 8000 Boiler -
adding a new decorator for restframework viewset action decorator
I've a django viewset, to which I've added a functions with action decorator. I want to add a custom decorator for this function. @action( methods=["post"], detail=True, permission_classes=[], url_path="remove-rfq-manufacturer", url_name="remove_rfq_manufacturer", ) def rename_book(self, request, pk=None): book_instance = self.get_object() book_instance.name = request.data['name'] book_instance.save() return Response({"message":"Done"}) I want to add a custom decorator for authentication and checking the user anonymity. Any idea on how to move forward? -
Is there a way for me to set up virtual environment without having the error below?
PS C:\Users\Jereh Lomak\Desktop\django tutorials> py -m venv myenv Error: Command '['C:\Users\Jereh Lomak\Desktop\django tutorials\myenv\Scripts\python.exe', '-Im', 'ensurepip', '--upgrade', '--de fault-pip']' returned non-zero exit status 1. PS C:\Users\Jereh Lomak\Desktop\django tutorials> -
Django saves on sqlite3 but not on postgresql
I have a cronjob for my django project. It's working on my local machine with sqlite3 db for development environment. But it's not working on production server with postgresql database. yenisiparis.save() command not working for some reason. class TrendyCron(CronJobBase): RUN_EVERY_MINS = 5 schedule = Schedule(run_every_mins=RUN_EVERY_MINS) code = 'trendycron' def do(self): URL = "https://api.**.com/sapigw/suppliers/***/orders?status=Created&orderByField=PackageLastModifiedDate&orderByDirection=DESC" URL2 = "https://api.**.com/sapigw/suppliers/***/orders?status=Cancelled&orderByField=PackageLastModifiedDate&orderByDirection=DESC" try: r=requests.get(URL, auth=('**','**')) veri = r.json() siparisler = veri['content'] for siparis in siparisler: siparis_no = siparis['orderNumber'] print(siparis_no) qs = Siparisler.objects.filter(siparis_no=siparis_no) exists = qs.exists() if not exists: print("!", siparis_no, " kayıt ediliyor..") try: pazar_yeri_kargo_kodu = siparis['cargoTrackingNumber'] siparis_tarih = siparis['orderDate'] siparis_tarihi = datetime.fromtimestamp(siparis_tarih/1000.0) + timedelta(hours=-3) siparis_gun = siparis_tarihi.date() siparis_saat = siparis_tarihi.time() iskonto = siparis['totalDiscount'] net_toplam = siparis['totalPrice'] cari_hesap_ozel_kodu = "Api" musteri_adi = siparis['customerFirstName'] musteri_soyadi = siparis['customerLastName'] teslim_alici = musteri_adi + " " + musteri_soyadi teslim_firma = siparis['cargoProviderName'] kargo_kodu = pazar_yeri_kargo_kodu odeme_sekli = "SATICI ÖDER" siparis_durum = 1 yenisiparis = Siparisler(siparis_no=siparis_no, pazar_yeri_kargo_kodu=pazar_yeri_kargo_kodu, siparis_tarih=siparis_gun, siparis_saat=siparis_saat, iskonto=iskonto, net_toplam=net_toplam, cari_hesap_ozel_kodu=cari_hesap_ozel_kodu,teslim_alici=teslim_alici,siparis_durum=siparis_durum,teslim_firma=teslim_firma,kargo_kodu=kargo_kodu,odeme_sekli=odeme_sekli) yenisiparis.save() print("!", siparis_no, " kayıt edildi..") satirlar = siparis['lines'] for satir in satirlar: print("Satırlar Kaydediliyor") try: siparisim = get_object_or_404(Siparisler, siparis_no=siparis_no) barkod = satir['barcode'] urun_kodu = satir['merchantSku'] pq = Urunler.objects.filter(barkod=barkod) exists = pq.exists() uqs = Urunler.objects.filter(urun_kodu=urun_kodu) exists2 = uqs.exists() if exists: print(barkod, " Ürün veritabanında var..") urunum = Urunler.objects.filter(barkod=barkod).first() elif exists2: … -
How browsable api works in django rest Framewor?
I want to know how browsable api works. When i open browsable api with a browser it renders a html page. But when i fetch json data from postman or any other service it gives json data. So how it works. And how can i make it without django rest framework. -
Django items = order.orderitem_set.all() returning empty value for quantity
when i try and put the {{ item.product.quantity }} in it returns an empty value. the quantity value is filled in in the database. i cant seem t pinpoint the problem. i have tried printing the quantity value but get the same resaults. cart.html {% extends 'store/main.html' %} {% load static %} {% block content %} <div class="row"> <div class="col-lg-12"> <div class="box-element"> <a class="btn btn-outline-dark" href="{% url 'store' %}">&#x2190; Continue Shopping</a> <br> <br> <table class="table"> <tr> <th><h5>Items: <strong>3</strong></h5></th> <th><h5>Total:<strong> $42</strong></h5></th> <th> <a style="float:right; margin:5px;" class="btn btn-success" href="{% url 'checkout' %}">Checkout</a> </th> </tr> </table> </div> <br> <div class="box-element"> <div class="cart-row"> <div style="flex:2"></div> <div style="flex:2"><strong>Item</strong></div> <div style="flex:1"><strong>Price</strong></div> <div style="flex:1"><strong>Quantity</strong></div> <div style="flex:1"><strong>Total</strong></div> </div> {% for item in items %} <div class="cart-row"> <div style="flex:2"><img class="row-image" src="{{ item.product.imageURL }}"></div> <div style="flex:2"><p>{{ item.product.name }}</p></div> <div style="flex:1"><p>R{{ item.product.price|floatformat:2 }}</p></div> <div style="flex:1"> <p class="quantity">{{ item.product.quantity }}</p> <div class="quantity"> <img class="chg-quantity" src="{% static 'images/arrow-up.png' %}"> <img class="chg-quantity" src="{% static 'images/arrow-down.png' %}"> </div> </div> <div style="flex:1"><p>$32</p></div> </div> {% endfor %} </div> </div> </div> {% endblock content %} views.py from django.shortcuts import render from .models import * def store(request): search = request.GET.get('search') products = Product.objects.all() if search != '' and search is not None: products = products.filter(name__icontains=search) context= {'products': products} return … -
Missing entry field in django admin's site after import Tinymce
After import the Tinymce, the entry of the models.post in the admin's site not show up(red draw). When i restart the page, it's show in a momment then off completely Here is screenshot main.admin.py from django.contrib import admin from .models import Author, Category, Post admin.site.register(Author) admin.site.register(Category) admin.site.register(Post) main.models.py from django.db import models from tinymce.models import HTMLField from django.contrib.auth import get_user_model from django.urls import reverse User = get_user_model() class Author(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_picture = models.ImageField() def __str__(self): return self.user.username class Category(models.Model): title = models.CharField(max_length=40) def __str__(self): return self.title class Post(models.Model): title = models.CharField(max_length=100) overview = models.TextField() detail = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) content = HTMLField(default='') comment_count = models.IntegerField(default=0) view_count = models.IntegerField(default=0) author = models.ForeignKey(Author, on_delete=models.CASCADE) thumbnail = models.ImageField() categories = models.ManyToManyField(Category) featured = models.BooleanField() def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={ 'id': self.id }) -
Does not save email field in database
After the implementation of checking email for uniqueness, the field is no longer saved in the database forms.py class Register(UserCreationForm): def clean_email(self): super().clean() email = self.cleaned_data.get("email") if User.objects.filter(email=email).exists(): msg = "Этот адресс уже зарегестрирован." self.add_error('email', msg) class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] views class MyRegisterFormView(FormView): # Указажем какую форму мы будем использовать для регистрации наших пользователей, в нашем случае # это UserCreationForm - стандартный класс Django унаследованный form_class = Register # Ссылка, на которую будет перенаправляться пользователь в случае успешной регистрации. success_url = "/accounts/login/" # Шаблон, который будет использоваться при отображении представления. template_name = "registration/register.html" def form_valid(self, form): form.save() return super(MyRegisterFormView, self).form_valid(form) def form_invalid(self, form): return super(MyRegisterFormView, self).form_invalid(form) -
Django, does a model object-field exist?
When i create an object i want to run a method which gets that objects parent and then returns that value into a normal model-field. I can't seem to find any information on that exact problem. Can it be done? Thanks in advance! -
Django Queryset Returning Empty '[]'
I have a list of movie genre. Each genre has its own movie. For instance, there is a list of movies for every movie genre but the object_list is empty. My View: class MovieCategory(ListView): model = Movie paginate_by = 2 def get_queryset(self): self.category = self.kwargs['category'] return Movie.objects.filter(category=self.category) def get_context_data(self , **kwargs): context = super(MovieCategory , self).get_context_data(**kwargs) context['movie_category'] = self.category print(context) return context My Models: ACTION = 'action' DRAMA = 'drama' COMEDY = 'comedy' ROMANCE = 'romance' CATEGORY_CHOICES = ( (ACTION, 'Action'), (DRAMA, 'Drama'), (COMEDY, 'Comedy'), (ROMANCE, 'Romance'), ) class Movie(models.Model): title = models.CharField(max_length=200) description = models.TextField(max_length=2000) image = models.ImageField(upload_to='movies') category = models.CharField(choices=CATEGORY_CHOICES, max_length=10) language = models.CharField(choices=LANGUAGE_CHOICES, max_length=7) status = models.CharField(choices=STATUS_CHOICES, max_length=2) cast = models.CharField(max_length=100) year_of_production = models.DateField() views_count = models.IntegerField(default=0) def __str__(self): return self.title my Urls: from django.urls import path from . import views app_name = 'movie' urlpatterns = [ path('', views.HomeView.as_view(), name='home'), path('list/', views.MovieListView.as_view(), name='movie_list'), path('category/<str:category>', views.MovieCategory.as_view() , name='movie_category'), path('language/<str:lang>', views.MovieLanguage.as_view(), name='movie_language'), path('search/', views.MovieSearch.as_view() , name='movie_search'), path('<int:pk>/', views.MovieDetailView.as_view(), name='movie_detail'), ] when i print(context) I get 'object_list': <QuerySet []>, 'movie_list': <QuerySet []> Thanks In Advance... -
ListView is missing a Queryset
I have several models in my Django project : a User model, (from builtin User class ) : attributes username, first_name, last_name etc a Course model, with course properties PurchasedCourses model, with users that purchased the course In my Dbeaver SQL program i can see the PurchasedCourses SQL Table like this : User model is builtin and the last two models are listed below . class Course(models.Model): course_name=models.CharField(max_length=128) description=models.TextField(max_length=500,blank=True) course_level=models.TextChoices('course_level', 'Beginner Intermediate Advanced') level=models.CharField(blank=False, choices=course_level.choices,max_length=20) def get_absolute_url(self): return reverse('basicapp:course_detail',kwargs={'pk':self.pk}) def __str__(self): return self.course_name class PurchasedCourses(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE) course=models.ForeignKey(Course,on_delete=models.CASCADE) purchase_date=models.DateTimeField() def __str__(self): return self.user.first_name+ "_" +self.user.last_name+"_"+self.course.course_name.replace(" ","_") I want for a user based on his id to get a HTML template with the user's purchased courses. So , I created a PurchasedCoursesView where i override the get_queryset() method to show only the purchased courses belonging to that user. basicapp/views.py: from django.views.generic import ListView, from . import models class PurchasedCoursesView(ListView): context_object_name='my_courses' models=models.PurchasedCourses template_name='basicapp/my_courses.html' def get_queryset(self,*args,**kwargs): qs=super().get_queryset(*args, **kwargs) qs=qs.filter(user_id=self.request.user.id) return qs basicapp/urls.py: from django.urls import path from basicapp import views app_name='basicapp' urlpatterns = [ url(r'^$',views.index,name='index'), path(r'my_courses/',views.PurchasedCoursesView.as_view(),name='my_courses'), ] I get the error that the queryset is empty and i don't know why . My models are populated with entries in my database: -
how can i implement two step registration with phone number in django?
i'm trying to make a django app that needs to implement two step registration with phone number and i searched for it and i did not find useful result. i have this idea that take phone number and then generate random hash URL then redirect them into it for registration. is that good implementation? and if you have better idea for doing this please help me. and sorry for my bad English. -
Django: SECRET_KEY improperly configured error in settings.py when importing a module
I wanted to authenticate users by email so I wrote a EmailBackend class in backends.py. AUTHENTICATION_BACKENDS = ['backends.EmailBackend'] I made this change in settings.py as said. My backends.py file is a brother of settings.py (both sit in the same main directory). However, when I run this, I get an error: ModuleNotFoundError: No module named 'backends' When I try to import this file in settings.py using from .backends import EmailBackend I get an error that secret key is incorrectly configure, when I have,'t even touched the key: File "C:\Users\dell\PycharmProjects\myDjangoSite\myDjangoSite\settings.py", line 14, in <module> from .backends import EmailBackend File "C:\Users\dell\PycharmProjects\myDjangoSite\myDjangoSite\backends.py", line 1, in <module> from django.contrib.auth.backends import ModelBackend File "D:\Python\lib\site-packages\django\contrib\auth\backends.py", line 5, in <module> from django.contrib.auth.models import Permission File "D:\Python\lib\site-packages\django\contrib\auth\models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "D:\Python\lib\site-packages\django\contrib\auth\base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "D:\Python\lib\site-packages\django\db\models\base.py", line 107, in __new__ app_config = apps.get_containing_app_config(module) File "D:\Python\lib\site-packages\django\apps\registry.py", line 252, in get_containing_app_config self.check_apps_ready() File "D:\Python\lib\site-packages\django\apps\registry.py", line 134, in check_apps_ready settings.INSTALLED_APPS File "D:\Python\lib\site-packages\django\conf\__init__.py", line 76, in __getattr__ self._setup(name) File "D:\Python\lib\site-packages\django\conf\__init__.py", line 63, in _setup self._wrapped = Settings(settings_module) File "D:\Python\lib\site-packages\django\conf\__init__.py", line 161, in __init__ raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. The same happens even … -
mysql.connector.errors.DatabaseError: 2005 (HY000): Unknown MySQL server host 'db' (2)
I've dockerized my django web app. Whenever i run "docker-compose up" everything works fine and it opens locally But when i run "python manage.py runserver" it pops up an error mysql.connector.errors.DatabaseError: 2005 (HY000): Unknown MySQL server host 'db' (2) This is the same error it is showing when i deployed it to azure When docker-compose up runs without error locally and the web app works well here is my docker-compose.yml file services: db: image: mysql ports: - '3306:3306' environment: MYSQL_DATABASE: 'app' MYSQL_USER: 'root' MYSQL_PASSWORD: 'aspilos' MYSQL_ROOT_PASSWORD: 'aspilos' web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/aspilos ports: - "8000:8000" depends_on: - db Here is my utils.py file import mysql.connector mydb = mysql.connector.connect( host="db", user="root", passwd="aspilos", database="aspilos_log", auth_plugin="mysql_native_password" ) mycursor = mydb.cursor() mycursor.execute("SELECT CONCAT('+', PHONE_NUMBER) FROM category2") results = mycursor.fetchall() for i in zip(*results): number = list(i) number1 = '+2348076548894' print (number) Here is my settings.py file DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'app', 'USER': 'root', 'PASSWORD': 'aspilos', 'HOST': 'db', 'PORT': '3306', }, } -
django and JavaScript form context, loading variables in JS
main.js is called in my template. Is the following syntax okay? Or is there another way? or do i have to name each element manually in JS jQuery('#{{ form.use_acn.id_for_label|escapejs }}').click(function(){ -
Django: Call custom function within generic views
I'm new to Django and am using Django's generic editing views to add/edit/delete entities. Eg, the views for adding and editing look like this: class QuoteCreate(CreateView): template_name = 'quotes/quote_form.html' model = Quote fields = ['quote_text'] class QuoteUpdate(UpdateView): model = Quote fields = ['quote_text'] This works fine and I'm happy with how everything is rendered. I'd just like to call an extra, custom function whenever a new object is created or edited (to send myself notifications). How can I do that? I couldn't find anything useful in the documentation. -
'tuple' object is not callable , machine learning API using Django API
I am trying build a machine learning API using DJANGO rest framework API. After creating a project and configuring model.py of created project 'MyAPI' ,for required approvals. And used the following commend to run the server, got following error. how to fix them ?, Please guide me. ````C:\Users\Padmini\DjangoAPI>python manage.py runserver``` error Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Padmini\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 926, in _bootstrap_inner self.run() File "C:\Users\Padmini\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Padmini\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Padmini\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\Padmini\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception raise _exception[1] File "C:\Users\Padmini\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "C:\Users\Padmini\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Padmini\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Padmini\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\Padmini\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\Padmini\AppData\Local\Programs\Python\Python37-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\Padmini\DjangoAPI\MyAPI\models.py", line 4, in <module> class approvals(models.Model): File "C:\Users\Padmini\DjangoAPI\MyAPI\models.py", line 7, … -
Decrementing a value in a foreign key model (when creating or updating instances)
I currently have models shown below class Product(models.Model): name = models.CharField(max_length=200, null=True) stock = models.CharField(max_length=200, null=True) class Order(models.Model): product = models.ForeignKey(Product, null=True, on_delete = models.SET_NULL) As you can see the order model has the product model as a foreign key. When I create or update instances based upon on the order model, I would like to decrement one value from the stock field in the products model. See below for the my views for both when creating and updating instances. @login_required def newOrder(request): form = CreateOrderForm() if request.method == 'POST': form = CreateOrderForm(request.POST or None) if form.is_valid(): form.save() return redirect('customer_order_list') return render(request, 'accounts/new_order.html', {'form': form}) @login_required def editOrder(request, pk): order = Order.objects.get(id=pk) sho = Order.objects.all().values_list('date_created') order_date = sho.filter(id=pk) form = CreateOrderForm(instance=order) if request.method == "POST": form = CreateOrderForm(request.POST, instance=order) if form.is_valid(): form.save() return redirect('customer_order_list') return render(request, 'accounts/edit_order.html', {'form': form, 'order_date': order_date}) I am aware that using the a similar example below will need to be implemented, however I will have to use the primary key of that particular instance. with transaction.atomic(): product = ( Product.objects .select_for_update() .get(id=1) ) product.inventory -= 1 product.save() However this example will not apply for when creating instance based on the order form. How can one … -
Django on Docker: How to access a file from views.py
I've been developing a web application under the docker environment. On that way, the approach that views.py in the container access to an other file failed. Following is the logs when the container named ‘web’ run And, demo/demo_app_views.py is class TestViews(TemplateView): template_name='top.html' with open('usr/src/demo/data/a', 'rb') as data: b = pickle.load(data) elder_brother=b['1'] def get_context_data(self, **kwargs): context=super().get_context_data(**kwargs) context['brother']=elder_brother return context top=TestViews.as_view() No matter of course, I confirmed the file ‘a’ stored on ‘data’ folder in ‘web’ container I’m not good in docker, so please tell me how to access the file ‘a’, which is dictionary type file, not database Thank you -
How to remove the list from a list of dictionaries
In Django, I do a 3rd party API call and get a list of dictionaries as a result. I would like to use this in my return render call in Django. But when I do this, I get: 'Context must be a dict rather than list' How can I remove the list part and just keep the dictionary? So for example, make: [{'key1':'value1', 'key2', 'value2'}, {'key1':'value3', 'key2', 'value4'}] a valid dictionary to use as context -
How to allow delete user object in django with complete profile
Hello i am working on a project which in i want to delete user object with all data about user in django i want to use built-in function any one tell me how i allow user for delete User own account such as instagram