Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
local variable 'final_result' referenced before assignment I am making an django calculator web app and i got stuck with this error
from django.shortcuts import render from django.http import HttpResponse import re def index(request): if request.method=="POST": values=request.POST['values'] #string having whole ques print(values) vals=re.findall(r"(\d+)",values) #extrect values operators=['+','x','÷','-'] opr=[] for v in values: for o in operators: if v==o: opr.append(o) print(opr) #extrect operators print(re.findall(r"(\d+)",values)) for o in opr: if o=='÷': i=opr.index(o) res=float(vals[i])/float(vals[i+1]) vals.remove(vals[i+1]) opr.remove(opr[i]) vals[i]=str(res) print(vals) print(opr) elif o=='x': i=opr.index(o) res=float(vals[i])*float(vals[i+1]) vals.remove(vals[i+1]) opr.remove(opr[i]) vals[i]=str(res) print(vals) print(opr) elif o=='+': i=opr.index(o) res=float(vals[i])+float(vals[i+1]) vals.remove(vals[i+1]) opr.remove(opr[i]) vals[i]=str(res) print(vals) print(opr) else: i=opr.index(o) res=float(vals[i])-float(vals[i+1]) vals.remove(vals[i+1]) opr.remove(opr[i]) vals[i]=str(res) print(vals) print(opr) if(len(opr)!=0): if opr[0]=='÷': result = float(vals[0])/float(vals[1]) elif opr[0]=='x': result = float(vals[0])*float(vals[1]) elif opr[0]=='+': result = float(vals[0])+float(vals[1]) else : result = float(vals[0])-float(vals[1]) final_result=result print(final_result) res=render(request,'index.html',{'result':final_result,'values':values}) return res -
Django: null value in column "user_id" violates not-null constraint
I'm using Postgresql and I have created the following models in my Django Project. Models.py User = settings.AUTH_USER_MODEL Discount_Type=( ('$', '$'), ('%', '%'), ) class Invoice(models.Model): ticket = models.OneToOneField(Ticket, related_name='invoice', blank=True,null=True, on_delete=models.CASCADE) updated_by = models.ForeignKey(User, null=True, blank=True, related_name='invoice_editor', on_delete=models.SET_NULL) date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) is_paid = models.BooleanField(default=False) federal_price = models.DecimalField(default=20.00, max_digits=6, decimal_places=2) federal_qty = models.PositiveIntegerField(default=1) federal_amount = models.DecimalField(null=True, blank=True, max_digits=6, decimal_places=2) state_price = models.DecimalField(default=20.00, max_digits=6, decimal_places=2) state_qty = models.PositiveIntegerField(default=1) state_amount = models.DecimalField(null=True, blank=True, max_digits=6, decimal_places=2) discount = models.DecimalField(default=0.00, max_digits=6, decimal_places=2) discount_type = models.CharField(default='$', max_length=5, choices=Discount_Type) discount_value = models.DecimalField(null=True, blank=True, max_digits=6, decimal_places=2) amount_payable = models.DecimalField(null=True, blank=True, max_digits=6, decimal_places=2) def __str__(self): return str(self.amount_payable) class Meta: ordering = ['-date_updated'] class Ticket(models.Model): tax_year = models.CharField(max_length=50, default='2020') service = models.CharField(max_length=50, default='Tax Filing') description = models.TextField(max_length=1000, blank=True) # Customer customer = models.ForeignKey(User, related_name='ticket_customer', on_delete=models.CASCADE) My forms.py class TicketCreateForm(forms.ModelForm): class Meta: model = Ticket fields = ('tax_year', 'service', 'description',) widgets = { 'tax_year': forms.Select(attrs={'class': 'form-control'}), 'service': forms.Select(attrs={'class': 'form-control'}), 'description': forms.Textarea(attrs={'rows':3, 'cols':60, 'class':'form-control'}), } my views.py def customer_ticket_create(request): form = TicketCreateForm() if request.method == 'POST': form = TicketCreateForm(request.POST or None) if form.is_valid(): ticket = form.save(commit=False) ticket.customer = request.user ticket.save() Invoice.objects.create( ticket=ticket, updated_by=request.user) return redirect('customer_home') But I'm getting django.db.utils.IntegrityError: "user_id" violates not-null constraint. This error is because of … -
How render fields individually in Django Using Crispy Forms package
I want to register a new Student in my database, the form that I am going to collect students data should be inline. I render every field individually but it doesn't save my data to the database until I change it to something like this {{ form|crispy }} Here is my students_form.html <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="row"> <div class="gorm-group col-md-4 mb-0"> {{ form.first_name|as_crispy_field }} </div> <div class="gorm-group col-md-4 mb-0"> {{ form.last_name|as_crispy_field }} </div> <div class="gorm-group col-md-4 mb-0"> {{ form.father_name|as_crispy_field }} </div> </div> <div class="row"> <div class="gorm-group col-md-4 mb-0"> {{ form.email|as_crispy_field }} </div> <div class="gorm-group col-md-4 mb-0"> {{ form.phone|as_crispy_field }} </div> <div class="gorm-group col-md-4 mb-0"> {{ form.province|as_crispy_field }} </div> </div> <div class="row"> <div class="gorm-group col-md-4 mb-0"> {{ form.gender|as_crispy_field }} </div> <div class="gorm-group col-md-4 mb-0"> {{ form.national_id|as_crispy_field }} </div> <div class="gorm-group col-md-4 mb-0"> {{ form.semester|as_crispy_field }} </div> </div> <div class="row"> <div class="col-lg-12"> {{ form.current_address|as_crispy_field }} </div> </div> <div class="row"> <div class="gorm-group col-md-4 mb-0"> {{ form.hostel|as_crispy_field }} </div> <div class="gorm-group col-md-4 mb-0"> {{ form.budget|as_crispy_field }} </div> <div class="gorm-group col-md-4 mb-0"> {{ form.image|as_crispy_field }} </div> </div> <input type="submit" value="ذخیره" class="btn btn-success"> </form> It doesn't work but if change to {{ form|crispy }} it works I use class based views class StudentCreateView(CreateView): … -
Is Django already has a built-in microservice architecture?
I am working on a Django Project, but now it's going enormously large. I am thinking to convert it to microservice architecture but I found that Django also has a related architecture, apart from having a common database. So my question is, Is Django have a semi-microservice architecture built-in? -
multi-field login in Django
In addition to the standard name, email, and password for users in django, I want to be able to store their phone #, cell phone carrier, and a 2nd email. How do I save this additional information? -
Django Python - Itertools is not aligning products with sum of auction sales
I generate a list of Products based on two criterias Entity and Period. The list retrieved contains all Products and the sum of all auctions sales for each. The example below shows a list of 4 products for Company XZY in november. Out of all the products listed only one product (sku 30) had two auction sales $180 and $220. The problem is the rest of products had no sales so the null value is not aligning properly with the product. I will need to still list those products and show $0 in sales. Models.py class Entity(models.Model): entity = models.CharField(max_length=40) class Period(models.Model): period = models.CharField(max_length=7) class Product(models.Model): entity = models.ForeignKey(Entity, on_delete=models.CASCADE, default=None, blank=True, null=True) period = models.ForeignKey(Period, on_delete=models.CASCADE, default=None, blank=True, null=True) sku = models.CharField(max_length=40) class Post(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, default=None, blank=True, null=True) auctionsale = models.DecimalField(max_digits=11, decimal_places=2) Views.py products = Product.objects.filter(entity=entityquery, period=periodquery).values('id', 'period', 'entity', 'sku') posts = Post.objects.filter(product__sku__in=products.values('sku'), product__entity=entityquery, product__period=periodquery).annotate(total=Sum('auctionsale')) mylist = list(itertools.zip_longest(products, posts, fillvalue='0')) Query Entity: Company XZY Period: November Expected results Product Total Auction Sales sku 10 $0 sku 20 $0 sku 30 $400 sku 40 $0 The results i am getting Product Total Auction Sales sku 10 $400 sku 20 sku 30 sku 40 -
How can I cloud-host a website that only 3 or so people will use, or how to protect it from DDoS attacks?
I want to create a website with Django (I already know how to do that), but I want to host it on AWS (I can figure that out later), for I don't want my laptop to store the database. The problem is that I don't want anyone to be able to access it. I only wish for me and other 2 or 3 people to be able to see it. If this is not possible, I could make a simple login page and create the users myself. That way, only the people I want will be able to use the web app. But this would leave it open to DDoS and many different types of attacks I don't know how to defend/prevent. So, now the question would be, do you guys know any tutorial on protecting your website from these attacks? I have looked online on these tutorials, but I only find how to defend from PS4 or WordPress. I am not looking for anything too big, as I said, I think that I could use @login_required from Django, and the only thing I will have to defend is the login page. I am almost sure 1 of these two … -
TypeError:super(type, obj): obj must be an instance or subtype of type
I, I created CRUD posting app which can upload some images optionally in Django. And then, when I tried to create a post, this error occured to me. I have no ideas what's happening on my app. There seems to be no invalid syntax. Here's a forms.py file. The part which is causing this error is at line 37. forms.py 10 class CreateForm(forms.ModelForm): 11 max_upload_limit = 2 * 1024 * 1024 12 max_upload_limit_text = naturalsize(max_upload_limit) 13 17 picture = forms.FileField(required=False, label='File to Upload <= '+max_upload_limit_text, 18 widget=forms.ClearableFileInput(attrs={'multiple': True})) 19 upload_field_name = 'picture' 20 22 class Meta: 23 model = Ad 24 fields = ['title', 'category', 'text', 'picture'] 25 26 # Validate the size of the picture 27 def clean(self): 28 cleaned_data = super().clean() 29 pic = cleaned_data.get('picture') 30 if pic is None: 31 return 32 if len(pic) > self.max_upload_limit: 33 self.add_error('picture', "File must be < "+self.max_upload_limit_text+" bytes") 34 35 # Convert uploaded File object to a picture 36 def save(self, commit=True): 37 instance =super(CreateForm, self).save(commit=False) 38 40 f = instance.picture # Make a copy 41 if isinstance(f, InMemoryUploadedFile): # Extract data from the form to the model 42 bytearr = f.read() 43 instance.content_type = f.content_type 44 instance.picture = bytearr # … -
How do I query model db attributes based on drop down selection?
I am very new to Django. I am struggling to figure out how to query model attributes based off of drop down selections. The project I'm working on is a directory of animals available for adoption. Admin creates new cat or dog profiles which get added to cat app db and dog app db respectively. Customers visit the site and landing page has drop downs of "age" (e.g. baby, young, adult, etc.) and "type" (e.g. cat, dog, other) to filter the listings accordingly. Examples: CustomerA selects "baby" and "dog" from the dropdowns. I then want to query dog.models for all matches. CustomerB selects "adult" and "all" from the dropdowns. I then want to query dog.models and cat.models and other.models and return matches Is it best to create another db with foreign keys to dog, cat and other? Or can I just query from the view or template? #from cat.models class Cat(models.Model): name = models.CharField(max_length=200,validators=[MinLengthValidator(2, "Nickname must be greater than 1 character")]) breeds = models.ForeignKey(CatBreed, on_delete=models.PROTECT) age = models.PositiveIntegerField() ageGroup = models.IntegerField(choices=AgeGroup.choices, null=False, blank=False, default=0) sex = models.IntegerField(choices=SEX, blank=False, null=False, default=0) tagLine = models.CharField(max_length=150) goodWithCats = models.BooleanField(blank=False, null=False, default='Not Enough Information') goodWithDogs = models.BooleanField(null=False, blank=False, default='Not Enough Information') goodWKids = models.BooleanField(null=False, … -
AWS EC2 + djnago + uwsgi : ERR_CONNECTION_REFUSED
I am trying to follow the steps in the guie, Before I even get to the nginx part I am trying to make sure that uWSGI works correctly my folder structure is srv/unifolio-back and I try to conect like below, (unifolio-back) ubuntu@ip-172-31-37-172:/srv/unifolio-back$ sudo /usr/bin/uwsgi -i /srv/unifolio-back/.config/uwsgi/mysite.ini [uWSGI] getting INI configuration from /srv/unifolio-back/.config/uwsgi/mysite.ini but I can't connect the site, (chrome send the ERR_CONNECTION_REFUSED message) my .config/uwsgi/mysite.ini file is ; #linku_uwsgi.ini file [uwsgi] ; # Django-related settings ; # the base directory (full path) chdir = /srv/unifolio-back/ ; # Django's wsgi file module = config.wsgi:application ; # the virtualenv (full path) home = /home/ubuntu/.local/share/virtualenvs/unifolio-back-_HCbnSkq plugins = python3 socket = /tmp/mysite.sock chmod-socket = 666 chown-socket = deploy:deploy uid = deploy gid = deploy http = :8080 enable-threads = true master = true vacuum = true pidfile=/tmp/deploy.pid logto = /var/log/uwsgi/unifolio-back/@(exec://date +%%Y-%%m-%%d).log log-reopen = true and the log is like below: *** Starting uWSGI 2.0.15-debian (64bit) on [Sat Dec 19 16:50:45 2020] *** compiled with version: 7.3.0 on 28 September 2018 15:41:15 os: Linux-5.4.0-1029-aws #30~18.04.1-Ubuntu SMP Tue Oct 20 11:09:25 UTC 2020 nodename: ip-172-31-37-172 machine: x86_64 clock source: unix pcre jit disabled detected number of CPU cores: 1 current working directory: /srv/unifolio-back writing pidfile to … -
GitLab CI generates database name for Postgres that is longer than the 63 character limit (django.core.exceptions.ImproperlyConfigured)
I'm having trouble using postgres as a service in a GitLab CI job that runs pytest for a Django application. Here is my GitLab CI job: Pytest: image: python:3.8 stage: test services: - postgres:13.1 - redis:6.0.9-alpine variables: DJANGO_SETTINGS_MODULE: "backend.settings.gitlab_ci" # the database name is too long, setting here explicitly # I tried setting DATABASE_URL and it didn't work: # DATABASE_URL: "postgresql://postgres:postgres@postgres:5432/postgres" SECRET_KEY: "secret" DEBUG: "1" POSTGRES_HOST_AUTH_METHOD: trust script: - cd backend - pip install -r requirements/base.txt - pip install -r requirements/test.txt - flake8 - black -l 79 -S --diff . - pytest --cov --cov-config=.coveragerc coverage: '/TOTAL.+ ([0-9]{1,3}\.[0-9]{1,3}%)/' In backend/settings/gitlab_ci.py I have the following DATABASES settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'postgres', 'PORT': '5432', }, } Here are relevant logs from the failing CI job. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <django.db.backends.postgresql.base.DatabaseWrapper object at 0x7f8d71b8de20> def get_connection_params(self): settings_dict = self.settings_dict # None may be used to connect to the default 'postgres' db if settings_dict['NAME'] == '': … -
how to fix 'PluginReferenceField' object has no attribute 'rel' fields.py from djangocms-forms
class PluginReferenceField(models.ForeignKey): def init(self, *args, **kwargs): kwargs.update({'null': True}) # always allow Null kwargs.update({'editable': False}) # never allow edits in admin kwargs.update({'on_delete': SET_NULL}) # never delete plugin super(PluginReferenceField, self).init(*args, **kwargs) def _create(self, model_instance): return self.rel.to._default_manager.create(name=model_instance.name) def pre_save(self, model_instance, add): if not model_instance.pk and add: setattr(model_instance, self.name, self._create(model_instance)) else: reference = getattr(model_instance, self.name) if not reference: setattr(model_instance, self.name, self._create(model_instance)) reference = getattr(model_instance, self.name) if reference.name != model_instance.name: reference.name = model_instance.name reference.save() return super(PluginReferenceField, self).pre_save(model_instance, add) -
Django: AttributeError: 'NoneType' object has no attribute 'username'
I am trying to create a chat app and got stuck with this error. I am getting this error though I'm logged in as a superuser. My models.py class Message(models.Model): author = models.ForeignKey(User, null=True, related_name='author_messages', on_delete=models.CASCADE) content = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.author.username def last_10_messages(): return Message.objects.order_by('-timestamp').all()[:10] Where I try to access it: for message in messages: print("message printing") result.append(self.message_to_json(message)) then def message_to_json(self, message): print("message.id=",message.id) print(message.author.username) return { 'id': message.id, 'author': message.author.username, 'content': message.content, 'timestamp': str(message.timestamp) } When i print the length of the object i notice it says 2..idk why coz i haven't added any messages yet. As the loop goes twice i noticed that the username got printed the first time but raised an error for the second loop(though idk why it loops coz i dont even have messages to load yet) like here The error also appears to be in the return function in my models class as in here I've read other posts but their errors were different... Would be really grateful if sum1 cud help out!! -
Pagination clears my other search parameters
For my program in Django I have the following Pagination section in my HTML file {% if player_list.has_other_pages %} <ul class="pagination" style="border: 1px solid #ddd;"> {% if player_list.has_previous %} <li><a href="?ppage={{ player_list.previous_page_number }}">&laquo;</a></li> {% else %} <li class="disabled"><span>&laquo;</span></li> {% endif %} {% for i in player_list.paginator.page_range %} {% with ppage_number=player_list.number radius=8 %} {% if i >= ppage_number|sub:radius %} {% if i <= ppage_number|add:radius %} {% if player_list.number == i %} <li class="active" style="border: 1px solid #ddd;"><span>{{ i }} <span class="sr-only">(current)</span></span></li> {% else %} <li style="border: 1px solid #ddd;"><a href="?ppage={{ i }}">{{ i }}</a></li> {% endif %} {% endif %} {% endif %} {% endwith %} {% endfor %} {% if player_list.has_next %} <li><a href="?ppage={{ player_list.next_page_number }}">&raquo;</a></li> {% else %} <li class="disabled"><span>&raquo;</span></li> {% endif %} </ul> {% endif %} So when I press on any of the pagination buttons it calls the page with the search parameter ppage=### (where ### is some number). However, it clears any search parameters I had in the url befarepressing the button, anyway I can let it keep the other search parameters? This is the views function being called: . . . # player request parameters player_page = request.GET.get('ppage', 1) player_first_name = request.GET.get('pfname', None) player_last_name = … -
django.core.exceptions.FieldError: Unknown field(s) (title) specified for Customer
I am trying to register a non-Wagtail model as a snippet, and to allow the model to be created and saved from another snippet's interface. I have been getting this error and am not sure where to start. All of the other StackOverflow posts I've seen are specific to customizing the User model, which I am not doing. I've tried setting a title field for the snippet, as well as appending a 'title' to get_context. This is what I'm trying to accomplish, and I'm not certain if I'm doing it in the best way: There are customers and work orders. Each Work Order has a foreign key to a customer, and my goal is to be able to create customer models inline (or select from existing list) in the WorkOrder snippet interface. Customer Snippet @register_snippet class Customer(models.Model): """Customer model.""" customer_name = models.CharField(max_length=100, blank=False, null=False, help_text="John Doe") ...more regular customer info fields (address, city, state, etc.)... customer_home_phone = models.CharField(max_length=15, blank=False, null=False, help_text="Home Phone") panels = Page.content_panels + [ MultiFieldPanel( [ FieldPanel("customer_name"), FieldPanel("customer_home_phone"), ], heading="Customer Contact" ), ] WorkOrder Snippet @register_snippet class WorkOrder(ClusterableModel, models.Model): """Workorder model.""" STATUS_CHOICES = ( ('o', 'Open'), ('c', 'Closed'), ('x', 'Cancelled'), ) ...workorder fields (service address, city, state, … -
PARTNER_AUTHENTICATION_FAILED: The specified Integrator Key was not found or is disabled. An Integrator key was not specified
I am working on a Django Web App which is used to send documents to users via email and is using Docusign API for that purpose. I am using JWT Grant Authentication and have successfully get the access token which is working fine. Now, I want to send a document to the user via email for signing purpose. For that, I am using the following code: from django.shortcuts import render from django.http import JsonResponse from docusign_esign import EnvelopeDefinition, Recipients, Tabs, SignHere, Signer, CarbonCopy, Document, EnvelopesApi, ApiClient import base64 ACCESS_TOKEN = 'MY_ACCESS_TOKEN' ACCOUNT_ID = 'MY_ACCOUNT_ID' BASE_PATH = 'demo.docusign.net/restapi' def create_document(signer_name, signer_email, cc_name, cc_email): return f""" <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> </head> <body style="font-family:sans-serif;margin-left:2em;"> <h1 style="font-family: "Trebuchet MS", Helvetica, sans-serif; color: darkblue;margin-bottom: 0;">World Wide Corp</h1> <h2 style="font-family: "Trebuchet MS", Helvetica, sans-serif; margin-top: 0px;margin-bottom: 3.5em;font-size: 1em; color: darkblue;">Order Processing Division</h2> <h4>Ordered by {signer_name}</h4> <p style="margin-top:0em; margin-bottom:0em;">Email: {signer_email}</p> <p style="margin-top:0em; margin-bottom:0em;">Copy to: {cc_name}, {cc_email}</p> <p style="margin-top:3em;"> Candy bonbon pastry jujubes lollipop wafer biscuit biscuit. Topping brownie sesame snaps sweet roll pie. Croissant danish biscuit soufflé caramels jujubes jelly. Dragée danish caramels lemon drops dragée. Gummi bears cupcake biscuit tiramisu sugar plum pastry. Dragée gummies applicake pudding liquorice. Donut jujubes oat cake jelly-o. Dessert … -
Django: Creating a custom admin page
I am a bit confused why my changes dont show up: I am following the official tutorial https://docs.djangoproject.com/en/3.1/intro/tutorial07/#customizing-your-project-s-templates and should override the admin base_site.html my dir structure looks like this: └───mysite ├───mysite │ └───__pycache__ ├───polls │ ├───migrations │ │ └───__pycache__ │ ├───static │ │ └───polls │ │ └───images │ ├───templates │ │ └───polls │ └───__pycache__ └───template └───admin └───base_site.html my template in settings.py like this: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'], 'APP_DIRS': True, .... base_site.html contains this: .... {% block branding %} <h1 id="site-name"><a href="{% url 'admin:index' %}">mydjango</a></h1> {% endblock %} .... However, the name changes are not applied to the admin page - even after reloading. somebody has an idea why this is not working? I know that you would do it in another way as the tutorial later suggests, but to follow the tutorial it would be nice to see everything working. -
How to fix an error while loading JS file into Django?
I am making a university project in Django and when I load the JS for the responsive burger menu of the nav, it does not load properly I suppose. So the problem is that when I inspect it in chrome and check the loaded files, from the JS file which is: const navSlide = () => { const burger = document.querySelector('.burger'); const nav = document.querySelector('.nav-links') const navLinks = document.querySelectorAll('.nav-links li'); burger.addEventListener('click', () => { // toggle nav nav.classList.toggle('nav-active'); // animate links navLinks.forEach((link, index) => { if(link.style.animation) { link.style.animation = '' } else { link.style.animation = `navLinkFade 0.5s ease forwards ${index / 7 + 0.3}s`; } }); // burger animation burger.classList.toggle('toggle'); }); } navSlide(); On the event listener, it says "cannot add a property 'addEventListener' of null". Any suggestions on how to fix that? -
Iterate over 3 context variables in Django templates
Is it possible to iterate over a list of three context variables shown below so that depending on which url the user's attribute (in this instance grade, Grade 10, Grade 11, Grade 12) clicks they get the right content displayed. Current view: class SumListView(ListView): model = Summaries template_name = 'exam/summary.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['grade10'] = Summary.objects.filter(grade='Grade 10') context['grade11'] = Summary.objects.filter(grade='Grade 11') context['grade12'] = Summary.objects.filter(grade='Grade 12') return context''' Current html template block: {% block content %} {% for summary in grade10 %} <div class="container> {{ summary.content }} </div> {% endfor %} {% endblock content %} I tried this but it breaks the code since for loops and iterations are mixing: {% block content %} {% if grade10 %} {% for summary in grade10 %} <div class="container> {{ summary.content }} </div> {% endfor %} {% elif grade11 %} {% for summary in grade10 %} <div class="container> {{ summary.content }} </div> {% endfor %} {% else grade12 %} {% for summary in grade10 %} <div class="container> {{ summary.content }} </div> {% endfor %} {% enif %} {% endblock content %} What is the best way to go about this? I know I can write different urls for each context which … -
How To Solve Nested Reverse with No Arguments Found in Django
I am trying to make it so that a user can press a button to leave a review after clicking on a product/image. So I have a model that defines the top level and within that top level I allow for the option to leave a review if the user is signed in. I have been trying to troubleshoot this error for the last hour with no success. Everytime I now try to click on the product I am shown the error: Reverse for 'beaches-review' with no arguments not found. 1 pattern(s) tried: ['review/(?P[0-9]+)$'] Hopefully someone here can help me. Here is my code (P.S I am learning...): Models.py class Beach(models.Model): name = models.CharField(max_length=80) location = models.CharField(max_length=200) video = models.FileField(upload_to='beachvideo', blank=True) beachPic = models.ImageField(default='default.jpg', upload_to='beachphotos', blank=True) datetimeInfo = models.DateTimeField(auto_now=True) lat = models.FloatField() lon = models.FloatField() info = models.TextField() def average_rating(self): all_ratings = map(lambda x: x.rating, self.review_set.all()) return np.mean(all_ratings) def __str__(self): return f'{self.name}' class Review(models.Model): RATING = ( ('1', 'Avoid'), ('2', 'Not Great'), ('3', 'Decent'), ('4', 'Awesome'), ('5', 'The Best'), ) beach = models.ForeignKey(Beach, on_delete= models.CASCADE) author = models.ForeignKey(User, null=True, blank=True, on_delete= models.CASCADE) ratingRank = models.CharField(max_length= 100, blank=False, choices=RATING) waveIntensityRank = models.CharField(max_length= 100, blank=True, choices=RATING) crowdednessRank = models.CharField(max_length= 100, blank=True, choices=RATING) … -
Django filter objects by distance
Hey guys how can i filter objects by distance? Maybe anyone know a video or document about this. -
Show products of each category [wagtail]
I have just started learning wagtail. Can you tell me how to display a category name and products in that category on the page? It should look something like this: Category_name products Category_name_2 products_2 ... Category_name_N products_N Here is my code models.py class HomePage(Page): def get_context(self, request): context = super().get_context(request) context['products'] = Product.objects.child_of(self).live() context['categories'] = Category.objects.all() return context class Product(Page): sku = models.CharField(max_length=255) short_description = models.TextField(blank=True, null=True) price = models.DecimalField(decimal_places=2, max_digits=10) image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) content_panels = Page.content_panels + [ FieldPanel('sku'), FieldPanel('price'), ImageChooserPanel('image'), FieldPanel('short_description'), InlinePanel('categories', label='category'), ] class ProductCategory(models.Model): product = ParentalKey('home.Product', on_delete=models.CASCADE, related_name='categories') product_category = models.ForeignKey( 'home.Category', on_delete=models.CASCADE, related_name='products_pages') panels = [ SnippetChooserPanel('product_category'), ] class Meta: unique_together = ('product', 'product_category') @register_snippet class Category(models.Model): name = models.CharField(max_length=255, null=True) related_page = models.ForeignKey('wagtailcore.Page', null=True, blank=True, related_name='+', on_delete=models.CASCADE) panels = [ FieldPanel('name'), PageChooserPanel('related_page'), ] def __str__(self): return self.name class Meta: verbose_name = "Category" verbose_name_plural = "Categories" -
If JavaScript blocks the <textarea> tag, how does the Textfield get the value
I want to build a library for django editor (based on a great project vditor.) I read the source code of some libraries, but I was surprised to find that they all need to use to Get the value (just like this:<textarea {{ final_attrs|safe }}>{{ value }}). And vditor itself will block the tag, is there any good solution? Thank you! -
How to stop global variables from reloading when I make changes to a view in django?
I am working an a machine learning project implemented using django where i need to impute datasets for outliers and many other reasons and declare these datasets as global variables for various views to use. The problem is imputing these data sets take lot of time and each time I make a change to it is loading the project from the beginning making debugging take lot of time. Is there anyway to stop this and only apply the changes for the code i make ? -
Cannot resolve keyword 'user' into field. admin.py
im trying to override queryset in admin.py to return a queryset based on each user's group, for a model Transaction models.py class Transaction(models.Model): .... income_period_choices = (('Weekly', 'Weekly'), ('Fortnightly', 'Fortnightly')) chp_reference = models.CharField(max_length=50, unique=True) rent_effective_date = models.DateField(null=True, blank=True) income_period = models.CharField(max_length=11, choices=income_period_choices, null=True, blank=True, default='Weekly') property_market_rent = models.DecimalField(help_text='Weekly', max_digits=7, decimal_places=2, null=True, blank=True) admin.py @admin.register(Transaction) class TransactionAdmin(admin.ModelAdmin): search_fields = ['chp_reference', 'familymember__name'] inlines = [FamilyGroupInline, FamilyMemberInline] def save_model(self, request, obj, form, change): obj.user = request.user print(obj.user) super().save_model(request, obj, form, change) def get_queryset(self, request): qs = super().get_queryset(request) if request.user.is_superuser: return qs return qs.filter(user__groups__first=request.user.groups.first()) im getting the error for the last line filter query, is there any suggestions? would be so much appreciated