Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Google App Engine Flexible - How can I list all files in the deployed application
I am using Google App Engine Flexible and I intend to see all the files deployed for the current django application. How can I achieve this ? runtime: python env: flex entrypoint: gunicorn -t 3600 -b :$PORT project_name.wsgi beta_settings: cloud_sql_instances: 'myapp:europe-west2:myapp' runtime_config: python_version: 3 -
Can't install Psycopg2 in virtual environment
I have a django project connected to a Postgresql DB so I also need Psycopg2 package installed. For some reason, I am able to install this globally on my computer and will be able to run things properly, but when I try and install it in my virtual environment I get this long return of an error. I only installed it globally for the sake of trying to narrow down the problem. I am able to install other packages in my environment without a problem. The specific problem occurs when I switch my DB settings from SQLite to PostgreSQL and it needs psycopg2. I've also tried uninstalling PostgreSQL and installing it back in case this was installed wrong in some way, but no difference. I'm thinking it has to do with folder structure somewhere but do not have much of an idea of how to go about it or if this is a reasonable thought. ERROR: Command errored out with exit status 1: command: /Users/luis/Documents/Code/bradynce-crm/env/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/hw/c0r922014qg_k21_k_zmyg6h0000gn/T/pip-install-y3pelxup/psycopg2/setup.py'"'"'; __file__='"'"'/private/var/folders/hw/c0r922014qg_k21_k_zmyg6h0000gn/T/pip-install-y3pelxup/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /private/var/folders/hw/c0r922014qg_k21_k_zmyg6h0000gn/T/pip-record-eptfxahu/install-record.txt --single-version-externally-managed --compile --install-headers /Users/luis/Documents/Code/bradynce-crm/env/include/site/python3.8/psycopg2 cwd: /private/var/folders/hw/c0r922014qg_k21_k_zmyg6h0000gn/T/pip-install-y3pelxup/psycopg2/ Complete output (151 lines): running install running build running build_py creating … -
How do i add multiple attributes to django forms
First of all i am very new to programming but i try hard to learn and i love it :). This is my model: from django.db import models from django.contrib.auth.models import User # Create your models here. class PersoonGegevens(models.Model): # Voornaam en achternaam voornaam = models.CharField(max_length=265) achternaam = models.CharField(max_length=265) #Gender keuze MENEER = 'Mr' MEVROUW = 'Mvr' GENDER = [ ('Mr', 'Meneer'), ('Mvr', 'Mevrouw'), ] gender = models.CharField(max_length=3, choices=GENDER, default=MENEER,) #Geboortedatum geboortedatum = models.DateField(auto_now=False) #emailfield email = models.EmailField(max_length=265, unique=True) #username user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return self.user.username This is my form: from django import forms from registratie.models import PersoonGegevens from django.contrib.auth.models import User class PersoonGegevensForm(forms.ModelForm): class Meta(): model = PersoonGegevens fields = ('voornaam', 'achternaam', 'gender', 'geboortedatum', 'email') class UsernameAndPasswordForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta(): model = User fields = ('username', 'password') This is are my own filters: from django import template register = template.Library() @register.filter(name='addclass') def addclass(value, arg): return value.as_widget(attrs={'class': arg}) This is my HTML code for example: <div class="wrap-input100 validate-input m-b-16" > {{pg.voornaam|addclass:'input100'}} <span class="focus-input100"></span> </div> ass you see i have added a class with the filter but i also want to add other attributes and now i saw on the internet the widget code : widget = … -
Parsing and looping through multi-level JSON data in Django
I have a Django website, and I'm making a call to Etsy's API in order to display products on the website. The data has multiple levels (abbreviated below): { "results":[ { "title":"#020", "price":"5.99", "Images":[ { "url_570xN":"www.example.com/image1.jpg" } ] }, { "title":"#051", "price":"5.99", "Images":[ { "url_570xN":"www.example.com/image2.jpg" } ] }, ] } I can successfully extract data from the results part (title, price) and display it in the template, but I can't figure out how to do the same thing for the Images part (url_570xN). I've spent a few hours trying to find the proper syntax, but I've been unsuccessful. My views.py: # Note: The commented lines are the ones giving me problems. # Removing them yields no errors and displays the info I want, # minus the images def products(request): parsed_data = [] response = requests.get('https://openapi.etsy.com/v2/shops/{SHOP_ID}/listings/active?includes=Images:1:0&api_key={KEY}') etsy_data = response.json() etsy_results = etsy_data['results'] # etsy_images = etsy_data['results']['Images'] for results in etsy_results: result_data = {} result_data['title'] = results['title'] result_data['price'] = results['price'] # for Images in etsy_images: # result_data['url_570xN'] = Images['url_570xN'] parsed_data.append(result_data) return render(request, 'blog/products.html', {'data' : parsed_data}) My products.html template: {% for result in data %} <p>Title: {{result.title}} Price: {{result.price}} <img src={{result.url_570xN}} width="200px"></p> {% endfor %} And lastly, the error message I get … -
Django pass data from one model to other model based on key fields I need occ_rating from NCR model(latest value) to Fmea model,
Models.py from django.db import models from database_app.models import Add_Part,Add_Sub_Assy,Add_Defect_category,Add_Contractor_or_Supplier,Add_Process Models.py class Ncr(models.Model): date = models.DateTimeField(default=timezone.now()) Process = models.ForeignKey(Add_Process_or_Function,on_delete=models.CASCADE,null=True) Lot_qty=models.IntegerField() qty = models.IntegerField() def occ_rating(self): ppm=self.qty/self.Lot_qty*1000000 if ppm >=1 and ppm < 10: return int(2) else: return int(1) '''Fmea Model''' from database_app.models import Add_Process_or_Function,Add_Part class Fmea(models.Model): date = models.DateField(default=timezone.now()) Process = models.ForeignKey(Add_Process_or_Function,on_delete=models.CASCADE,blank=True,null=True) #function required to get the data from ncr model def occ_rating(self): if self.Process == NCR.Process: return occ_rating -
Want to show detailview, clicking in a link in a listview
I want to show the detail from a school, which will show all the students but when i run the code, it doesnt find the url, i've been searching for the answer all over the web but still dont get it, the point is to show a list of all the schools in a list.html file, that works okay, but when i want to click in an item from that list, it supposed to show the details from that school which will be all the students attending that school, but it returns a 404 error, saying that it didnt find the url. ####MODELS # Create your models here. class School(models.Model): name = models.CharField(max_length=256) principal = models.CharField(max_length=256) location = models.CharField(max_length=256) def __str__(self): return self.name class Students(models.Model): name = models.CharField(max_length=256) age = models.PositiveIntegerField() school = models.ForeignKey(School,on_delete=models.CASCADE,related_name='students') def __str__(self): return self.name ####VIEWS from django.views.generic import View,DetailView,ListView from .models import * # Create your views here. class Index(View): def get(self,request): return HttpResponse('Hello World') class SchoolList(ListView): model = School template_name = 'firstapp/list.html' context_object_name = 'School' class SchoolDetails(DetailView): model = School template_name = 'firstapp/detail.html' context_object_name = 'School_detail' ####URLS from django.urls import path from . import views urlpatterns = [ path('list/',views.SchoolList.as_view(),name='list'), path('School_detail/<int:pk>',views.SchoolDetails.as_view(),name='details') ] ####LIST HTML {%extends 'firstapp/base.html'%} … -
Is it worth it to have an meta intermediate comparison model for Django?
I'm new to Django and I want to know how to best structure my models. I have a model Computer with fields screen_size, price, company, etc.., and eventually want to have a UI that is able to compare to other Computer instances. So for example, if we're looking at ComputerA, the UI would show all other Computer instances and and compare the price, screen size, and company relative to ComputerA Wondering if it's worth it to have an intermediate model ComputerComparison, that has two foreign keys that reference both the Computer instances I'm trying to compare? -
How to create dynamic ManyToMany field in Django?
In admin add view I would like to able to select dynamically field A_permission from selected A-object while creating new B-object A(models.Model): name = models.CharField(primary_key=True, max_length=50) permission = models.CharField(max_length=50) B(models.Model): A_name = models.ForeignKey(A) A_permissions = models.ManyToManyField(A) So I have objectA1 and objectA2 for example. While creating object B I should be able to first select one of the A objects, and then just get its permission for selection in field A_permissions Can someone please point me how to do this? I feel like I tried everything -
manage.py runserver do nothing on VPS
When I run python3 manage.py runserver on Ubuntu 16.04 VPS machine it does nothing with my project but it runs that runs on my computer. I try to run python3 -v manage.py runserver and have seen that it stopped when executing this: # code object from '/usr/lib/python3.5/site-packages/OpenSSL/__pycache__/SSL.cpython-35.pyc' import 'OpenSSL.SSL' # <_frozen_importlib_external.SourceFileLoader object at 0x2b1d1d937630> # /usr/lib/python3.5/site-packages/OpenSSL/__pycache__/version.cpython-35.pyc matches /usr/lib/python3.5/site-packages/OpenSSL/version.py # code object from '/usr/lib/python3.5/site-packages/OpenSSL/__pycache__/version.cpython-35.pyc' import 'OpenSSL.version' # <_frozen_importlib_external.SourceFileLoader object at 0x2b1d1e6a5c50> import 'OpenSSL' # <_frozen_importlib_external.SourceFileLoader object at 0x2b1d1d923da0> after last line it start to do nothing my settings.py file: """ Django settings for hahachat project. Generated by 'django-admin startproject' using Django 3.0.4. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'p#b#s#!sfv#o(o661x=kb7!-nfef&33orv%74s8*1gdi)1w1u8' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['localhost'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'main', 'rest_framework', 'rest_framework.authtoken', 'corsheaders', 'djoser', 'channels', 'room', 'chat', 'game', … -
Javascript code not working using template inheritence in Django template
I am having trouble in executing Javascript code in a Django project. The following is working fine - i.e. without using template inheritence html: <!DOCTYPE html> <html> <head> {% load static %} <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> <script src="{% static 'ads/test.js' %}" type="text/javascript"></script> <title> Test </title> </head> <body> <form action="{% url 'test' %}" method="post" id="my_form"> {% csrf_token %} <button type="submit" class="btn btn-success">Submit</button> </form> </body> </html> test.js $(document).ready(function() { $("#my_form").submit(function(){ alert('submitted'); }); }); Since the above external Javascript file test.js has executed successfully, I assume the settings of static url, static dirs, etc. are correct. Also, since jquery has worked, I assume the order of jquery first, then js code is also correct. The problem comes when I use template inheritence. base html: <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> {% block scripts %} {% endblock %} <title> {% block title %}{% endblock %} </title> </head> <body> {% block body %} {% endblock %} </body> </html> inherited template: {% extends "base.html" %} {% block scripts %} {% load static %} <script src="{% static 'ads/test2.js' %}" … -
Using Foreign Keys to import Images in Django
I am using Django 2.2 to make a project where designers upload designs and when I want to post them from admin, I want to choose their names and after I choose their names only their designs appear in the drop down list. So far I have reach the reach the designer name in a drop down list but I don't know how to link only their designs in the designs drop list. I am using 2 different apps: 1."Score" where designers can upload their designs 2."Core" where I can list the items First in the Score .model where designers upload the designs class Post(models.Model): designer_name = models.ForeignKey(User, on_delete=models.CASCADE) design = models.ImageField( blank=False, null=True, upload_to='new designs') title = models.CharField(max_length=100) def __str__(self): return self.title def get_absolute_url(self): return reverse("score:post-detail", kwargs={"pk": self.pk}) Second in the Core App Model: class Item(models.Model): title = models.CharField(max_length=100) description = models.TextField() price = models.FloatField() designer_name = models.ForeignKey(User, on_delete=models.CASCADE) image = models.ImageField(blank=False, upload_to='imgs') **How can I make this a drop down list with the selected user's (designer's) all previously uploaded images to choose from instead of uploading new images** def __str__(self): return self.title -
django-autocomplete-light doesn't show the data when editing
I'd like to have the same field autocompletion for creating and editing a model so I'm trying to use the same form. Problem is when editing the object it is not showing the selected value, I'm getting an empty value. How can I set the initial value for it? relevant view code: if request.method == 'POST': form = PuppetClassForm(request.POST, instance=class_instance) if form.is_valid(): class_instance.scope = sub_scope class_instance.module = None class_instance.save() return redirect('show.subscope', user_slug=owner.slug, platform_slug=platform.slug, scope_slug=parent_scope.slug, sub_scope_slug=sub_scope.slug) else: form = PuppetClassForm(request.GET, initial={ 'name': class_instance.id, 'description': class_instance.description }) if class_slug: return render(request, 'classes/edit.html', {'form': form, 'class_instance': class_instance}) else: return render(request, 'classes/edit.html', {'form': form }) Model: class PuppetClass(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=256, blank=False) description = models.CharField(max_length=256, default='') Form: class PuppetClassForm(forms.ModelForm): filters = ~Q(properties=None) name = forms.ModelChoiceField( queryset=PuppetClass.objects.filter(scope=None).filter(filters).order_by("name"), widget=autocomplete.ModelSelect2(url='puppetclass-autocomplete'), to_field_name="name" ) description = forms.CharField(required=False) def __init__(self, data, **kwargs): initial = kwargs.get('initial', {}) data = {**initial, **data} super().__init__(data, **kwargs) class Meta: model = PuppetClass fields = (['name', 'description']) -
here, my if condition is not working in python [closed]
for obj in cartobj: print("-------------------",pid,"----------------",obj.prodid.id) print("-------------------------",nm,"-----------",type(nm)) print("------------------------",obj.prodid.product_name,"-----------------",type(obj.prodid.product_name)) if pid == obj.prodid.id or nm == obj.prodid.product_name: print("------------------Condition True---------------") print(obj) print(obj.prodid) print(proobj) print("\n Before Quantity==",obj.qnty) obj.qnty = int(qty) print("\n After Quantity==",obj.qnty) print("\n Before rowtotal==",obj.rowtotal) obj.rowtotal=int(qty)*proobj.product_price print("\n After rowtotal==",obj.rowtotal) print("Name--------------->",obj.prodid.product_name) obj.cnm=nm obj.save() print("##################Reached#########################") return HttpResponse(1) else: print("------------------Condition False------------------") pass -
Django 2.2 error - Integrity Error, NOT NULL constraint failed
I have a sample Django 2.2 project that has a search bar in the top right corner of the nav bar (taken from the Bootstrapers): navbar.html: <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="/">Navbar</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="/">Home <span class="sr-only">(current)</span></a> </li> {% if user.is_authenticated %} <li class="nav-item"> <a class="nav-link" href="/search/">Search</a> </li> ... {% endif %} <li class="nav-item"> <a class="nav-link" href="/a/">A</a> </li> <li class="nav-item"> <a class="nav-link" href="/b/">B</a> </li> </ul> <form class="form-inline my-2 my-lg-0" action = '/search/'> <input class="form-control mr-sm-2" type="search" name="q" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> </div> </nav> It returns "You searched for [search argument]" to the url '/search/' and works fine. I would like to bring it from the nav bar under the 'Search' menu in the nav bar. I have the following: searches/models.py from django.db import models from django.conf import settings # Create your models here. class SearchQuery(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, blank = True, null=True, on_delete=models.SET_NULL) query = models.CharField(max_length=220) timestamp = models.DateTimeField(auto_now_add=True) searches/views.py: from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.contrib.admin.views.decorators import staff_member_required from .models import SearchQuery # Create your views here. … -
Is there a way to dynamically edit value in django template?
Okay so I've been trying to show time in my website, and i was successful in it, but then after the time changes in real-time it does change in the site, we will have to reload the page and then time would b updated. Is there a way to update the time without reloading the page using django templates (html). -
django - My html page have textbox or checkbook both are in loop it is save only last value but i want save all value in all selected checkbox
----------------------------------html---------------- {% for Deficiency in Deficiency_View %} <tbody> <tr> <td class="hidden-phone"> {{ Deficiency.Institute }}</td> <td class="hidden-phone"> {{ Deficiency.Course }}</td> <td class="hidden-phone"> {{ Deficiency.StudentName }}</td> <td> {{ Deficiency.FathersName }}</td> <td class="hidden-phone"> {{ Deficiency.MothersName }}</td> <td>Check: <input type="checkbox" name="EnrollmentGenerate" id="Enrollment_Generate" value="{{ Deficiency.formNo }}"></td> <td> <input type="text" name="my_list" id="EnrolNo" value=" {{ Deficiency.Institute_Code }}{{ Deficiency.Course_Code }}{{ Deficiency.Branch_Code }}"> </td> </tr> {% endfor %} ----------------------------------view---------------- formNo = request.POST.get('EnrollmentGenerate') # EnrollmentGenerate is a name="checkbox" a checkbox have loop in html enrollment_Generate = EnrollmentForm.objects.get(formNo=formNo) # this is save only last checked Row not save all , i want save all selected checkbox in model enrollment_Generate.EnrollmentNo = request.POST.get('my_list') # this is save only last value but i wanr save all (name="my_list" a text box have loop in html) enrollment_Generate.save() Note: model EnrollmentForm in EnrollmentNo (not use form use custum update data code) -
why Django button don't have auto built code as asp.net does?
I am from the background of asp.net, currently i have started working on django, I always wonder why Django button don't have a auto built code or function that will execute on button click as asp.net does ? and can we make such functionality in Django that when we add button the auto built in code for that button will generate ? I am new in Django please provide me the reason why Django use this approach and its advantages and disadvantages ? -
How to incorporate images or graphs and plain-text in same field in Django
In my web-app (say a simple polls app) I want to add images and graphs to question text and options.Can you help we with appropriate field(s) for my models(Question and Option)? I want it to look this way : ................................ . n . Question Text .. ................................ ...... (relavant images) ....... ................................ ...Option1(Maybe a graph/text).. ...Option2(Maybe images)........ -
Django reply to comment in ajax does not work
I am writing an application in django 2.2 with ajax. It's about the comments section and responses to comments. I have two problems: Writing a new comment works. The response to the comment does not work, an error appears: The view spot.views.SpotDetailView didn't return an HttpResponse object. It returned None instead. Validation - if a comment is added, it works, but the error appears on all windows to respond to comments. The validation of the response to the comment does not work, the page source appears instead of the error view.py class SpotComment(SingleObjectMixin, FormView): template_name = 'spot/spot_detail.html' form_class = CommentModelForm model = Spot def get_success_url(self): return reverse('spot_detail_url', kwargs={'slug': self.object.slug, 'id': self.object.pk}) def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.form_class(request.POST) form.instance.spot = self.object form.instance.author = self.request.user if form.is_valid(): reply = request.POST.get('comment_id') comment_qs = None if reply: comment_qs = Comment.objects.get(id=reply) form.instance.reply = comment_qs form.save() if request.is_ajax(): context = { 'form': form, 'errors': form.errors, 'object': self.object, } html = render_to_string('spot/comments.html', context, request=request) return JsonResponse({'form': html}) else: context = { 'form': form, 'errors': form.errors, 'object': self.object, } html = render_to_string('spot/comments.html', context, request=request) return JsonResponse({'form': html}) jQuery code: $(document).on('submit', '.comment-form', function(event){ event.preventDefault(); var serialized = $('.comment-form').serialize(); $.ajax({ type: 'POST', url: $(this).attr('action'), data: … -
How to filter django models based on ManytoMany relationhsip and on math calc
Guys i am learning Django and models linking to DB quite confusing for me. I would like to gte your help/guidance . Any help is very much welcomed. I have 4 models: class Profile(models.Model): player = models.CharField(max_length=150) surname=models.CharField(max_length=200) class Meta: db_table='profile' class race19(models.Model): player = models.CharField(max_length=150) profile=models.ManyToManyField(Profile) score19=models.DecimalField(decimal_places=2,max_digits=1000) distance=models.DecimalField(decimal_places=2,max_digits=1000) class Meta: db_table='race19' class race18(models.Model): player = models.CharField(max_length=150) profile=models.ManyToManyField(Profile) score18=models.DecimalField(decimal_places=2,max_digits=1000) distance=models.DecimalField(decimal_places=2,max_digits=1000) class Meta: db_table='race18' class adjustments(models.Model): player = models.CharField(max_length=150) profile=models.ManyToManyField(Profile) bonus=models.DecimalField(decimal_places=2,max_digits=1000) class Meta: db_table='adjustments' I explored django docs and could learn filtering just from 1 table as fowllowing : score_m=race19.objects.annotate(score_margin=F('score19') / F('distance')).filter(score_margin__gt=0.4,) Now i want to be able to get values such as score19, score18, bonus from different tables and i though ManytoMany would help and tried the following: score_growth=race19.objects.annotate( score_change=((F('score19')+F('bonus')) / F('score18')).filter(score_change__gt=0.10,) But this does not work. What i needed to do. Would appreciate if you could share code as thereby i would better understand. Thanks in advance. -
Why the ach form is_bound always false?
i trying to update a modelform while save another modelform, I want to update ach form with the new value from the Payments forms, the ach from is always unbound ?? forms.py : achat = get_object_or_404(Achats,pk=pk) form = Payments_Form(request.POST or None,achat_id=pk) if form.is_valid(): ach = AchatForm(instance=achat) ach.fields['Montant_pay'] = form.cleaned_data['Montant_TTC'] if ach.is_valid(): ach.fields['Montant_pay'] = form.cleaned_data['Montant_TTC'] ach.save() print(ach.errors) print(ach.is_bound) form.save() return redirect('view') forms.py : class AchatForm(ModelForm): class Meta: model = Achats fields = ('Date','Id_Fournis','Montant_HT','Montant_TVA','Montant_TTC','Montant_pay') class Payments_Form(forms.ModelForm): class Meta: model = Payements fields = ('Date', 'mode_de_payement', 'reference', 'Montant_HT','Montant_TVA','Montant_TTC', 'Numero_facture', 'Numero_payement','E_S') -
Datable not working in django/bootstrap 4
Goal: I am using django and bootstrap. I would like to use datatable jquery plugin in my bootstrap table. Issues: The table in my html stay the same and doesn`t use the datatable plugin What Ive done to resolve this issue? I`ve added the two lines in my base.html file base.html <!-- Datatable --> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css"> <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script> and the javascript code as well: <script> $(document).ready(function(){ $('#dtBasicExample').DataTable(); }); </script> <script src="http://code.jquery.com/jquery-2.0.3.min.js"></script> My table is name dtBasicExample in my html file: <div class="container-fluid"> <div class="col-sm-20"> <table id="dtBasicExample" class="table table-striped table-hover"> Is there anything I need to add in django to make it work? Many Thanks, -
Apache2&Django - NameError: name "AttributeError" is not defined
I followed pretty much every official documentation to get my Django project running on my Ubuntu 18.04 v-server. And it seems to work...sudo service apache2 status -> everything ok too. [Sun May 03 16:07:20.489608 2020] [mpm_event:notice] [pid 11531:tid 139884218760128] AH00489: Apache/2.4.29 (Ubuntu) OpenSSL/1.1.1 mod_wsgi/4.7.1 Python/3.8 configured -- resuming normal operations [Sun May 03 16:07:20.489764 2020] [core:notice] [pid 11531:tid 139884218760128] AH00094: Command line: '/usr/sbin/apache2' I first noticed that something's off when my templates wouldn't update without a server restart which is not Django's usual behaviour (even in a productive environment). Whenever I restart the server I get this error in the apache2/error.log. Although the server keeps working I want to get to the bottom of this. Exception ignored in: <function Local.__del__ at 0x7fbd983f03a0> Traceback (most recent call last): File "/var/www/my_app/.my_app/lib/python3.8/site-packages/asgiref/local.py", line 95, in __del__ NameError: name 'AttributeError' is not defined Exception ignored in: <function Local.__del__ at 0x7fbd983f03a0> Traceback (most recent call last): File "/var/www/my_app/.my_app/lib/python3.8/site-packages/asgiref/local.py", line 95, in __del__ NameError: name 'AttributeError' is not defined [Sun May 03 16:07:19.418926 2020] [core:warn] [pid 11433:tid 140452536064960] AH00045: child process 11435 still did not exit, sending a SIGTERM [Sun May 03 16:07:20.419208 2020] [mpm_event:notice] [pid 11433:tid 140452536064960] AH00491: caught SIGTERM, shutting down [Sun May 03 … -
invalid syntax in views.py in Django
The code was working. However, I got the error suddenly that can be seen in the image invalid_syntax_error . Even though the name of view and the name of function are same(in this case "addArticle"), I got this error. How can I fix that issue? Here is what my urls.py contains; from django.contrib import admin from django.urls import path from . import views app_name = "article" urlpatterns = [ path('dashboard/',views.dashboard,name = "dashboard"), path('addarticle/',views.addArticle,name = "addarticle"),] -
Django CreateView: How to create the resource before rendering the form
I have a model class for my resource, class Article(db.Model): title = models.CharField(_('title'), max_length=255, blank=False) slug = AutoSlugField(_('slug'), populate_from='title') description = models.TextField(_('description'), blank=True, null=True) content = RichTextUploadingField() Here's my form class class ArticleForm(ModelForm): class Meta: model = kb_models.Article And finally my CreateView, class CreateArticleView(generic.CreateView): form_class = ArticleForm model = Article def get_success_url(self): return "some_redirect_url" Right now I have configured my URLs like below, path('add/', CreateArticleView.as_view(), name='create_article') path('<slug:article>', ArticleDetailView.as_view(), name='article_detail'), path('<slug:article>/update', UpdateArticleView.as_view(), name='update_article') The current flow will render a form when I hit the add/ resource endpoint, and save the resource in the database only after I submit the form. After that, the article can be accessed using the slug generated from the title. What I want instead is to be able to create the Article resource before the resource is rendered, so that the add/ endpoint redirects to some add/unique-uuid endpoint, and even when the form is not submitted from the browser, this empty resource is preserved, and it can be accessed later on because of the unique-uuid. I thought of instantiating an object and redirecting that to UpdateView, but I am having difficulties in figuring out how to keep track of the unique-uuid and point both generated-uuid and slug …