Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django modelformset_factory: One more Form shown than there should actually be
I have the following model: class Portfolio(models.Model): id = models.AutoField(primary_key=True) member = models.ForeignKey(Member, on_delete=models.CASCADE) For that I made the ModelForm: class PortfolioForm(forms.ModelForm): class Meta: model = Portfolio exclude = ['id'] I need many of those in one template so I am creating them in the Following way in my view def portfolio_form(request, pk): ... PortfolioFormSet = modelformset_factory(Portfolio, form=PortfolioForm) formset = PortfolioFormSet(queryset=Portfolio.objects.filter(pk__in=list_of_ids)) finally in the html I have this: everything is working fine except that one more is shown in HTML than there actually are. I have verified them in the shell. There are 3 but 4 are shown. I am displaying them in the table. I am positive that it is not the template. Please help. -
override save method django
how to override save method after using save method in my models.py class Storage(models.Model): fields def save(self,*args,**kwargs): if not self.pk: Storage.objects.filter(pk=self.model_id).update(PCs_Number_in_storage=F('PCs_Number_in_storage')-1) self.CPU = self.model.CPU self.RAM = self.model.RAM self.Hard = self.model.Hard self.price = self.model.S_Price self.Graphic = self.model.Graphic self.rest_cost = self.price - self.get_cost self.income = self.model.S_Price - self.model.cost_Bprice super().save(*args,**kwargs) -
model = User in Meta class of django
I am trying to read a code that concerns about user registration form. The code has a Meta class which I know what it does, but assigning model to User doesn't give sense to me. Can you please explain it? from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User # explain? fields = ["username", "email", "password1", "password2"] -
Display console output in django template in real time with websocket
I am new to websocket so I have some problems. I'm trying to create a web based user interface, where the user will press the button and start the script in the background and user is redirectet to display_console_output, where data will be displayed. I would like to display console output in the browser in real time. I am able to display the output when the script finished her job, and I do not know how to display data if script is working. Here is my code views.py: def display_console_output(request): if request.method == 'GET': process = subprocess.Popen('ping -t 8.8.8.8', shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE) output = process.communicate()[0] return render(request, 'update_file/display_console_output.html', {'page_title': 'Console Output', 'console_output': (output.decode('utf-8')),}) consumer.py: class ConsoleDataConsumer(AsyncConsumer): async def websocket_connect(self, event): print('connected', event) await self.send({ 'type': 'websocket.accept' }) await asyncio.sleep(10) await self.send({ 'type': 'websocket.close' }) async def websocket_recive(self, event): #when a message is recived from the websocket print('recive', event) async def websocket_disconnect(self, event): #when the socket connects print('disconnected', event) routing.py: application = ProtocolTypeRouter({ # Empty for now (http->django views is added by default) 'websocket': AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( [ url(r"^(?P<consoleOutput>[\w.@+-]+)/$", ConsoleDataConsumer), ] ) ) ) }) display_console_output.html: {% extends "update_file/layout.html" %} {% load crispy_forms_tags %} {% block content %} <div id="output" class="container … -
where to modify set_language method in django
I read this question Django 1.8 set_language view does not redirect to specified language and its answers, but I want to know where should I modify the set_language method, how can I access to the set_language view? -
Django template for duration field how to show as type: time?
I'm using a DurationField in a model, but need to show it's value to user in a html input field with type = time. class MyModel(models.Model): durata = models.DurationField(blank=True, null=True) I've tried the following in forms.py class DurationUpdateForm(forms.ModelForm): #OraBaseFormMixin): durata = forms.TimeField( widget=forms.TimeInput(attrs={'type': 'time'}, ), required=False) The field is show with correct format but with empty value "--:--". <input type="time" name="durata" value="0:00:05" class="timeinput" id="id_durata"> With default format the value is correctly shown but it's like this: <input type="text" name="durata" value="00:00:05" class="textinput textInput" id="id_durata"> Is there a way to manage this or should I rewrite the model using a TimeField? Using TimeField would make operation like Sum more difficult? Thanks, BR -
How to plot a dict in template
I am working with a dict which contains three keys index,data and column. But I am stuck at accessing the values and the label for the bar chart { 'index': [0, 1, 2, 3, 4], 'data': [ [u 'charger use', 6.122448979591836, 10.204081632653061, 83.6734693877551], [u 'great case', 0.0, 0.0, 100.0], [u 'great work', 3.508771929824561, 10.526315789473683, 85.96491228070175], [u 'charger work', 3.571428571428571, 10.714285714285714, 85.71428571428571], [u 'phone car', 0.0, 10.526315789473683, 89.47368421052632] ], 'columns': ['Aspect', 'Negative', 'Neutral', 'Positive'] } -
Twilio with Django for OTP
I am trying to verify phonenumbers and send an otp to them in django but I get this error 400 Client Error: BAD REQUEST for url: https://api.twilio.com/2010-04-01/Accounts/ACb72b622666f57139034b55062d3bbe9c/Messages.json Please what could I be doing wrong -
Django hidden input field problems
I have following model form where I have to add a hidden field. class AddEditGroupForm(forms.ModelForm): id_sel_comp = forms.CharField( label='selected company', initial=0, required=True, widget=forms.HiddenInput(attrs={'id': 'id_sel_comp'}) ) class Meta: model = Group fields = ('name', 'id_sel_comp') def __init__(self, *args, **kwargs): super(AddEditGroupForm, self).__init__(*args, **kwargs) self.fields['name'].widget.attrs.update({'class': 'form-control m-input form-control-sm'}) def as_two_col_layout(self): return self._html_output( normal_row='<div class="form-group m-form__group row"><label class="col-sm-3 col-form-label">%(label)s</label><div class="col-sm-9">%(field)s%(help_text)s</div></div>', error_row='%s', row_ender='', help_text_html=' <span class="m-form__help">%s</span>', errors_on_separate_row=True) The form displays only the hidden form field and the 'name' charfield is not displayed. When I mark the field 'id_sel_comp' as NOT hidden, all fields are displayed. What is wrong with this? -
Django Filters - ModelChoiceFilter Distinct Choices from Field
I am trying to get a list of distinct choices from my msg_direction field populate in my form. On selection and a GET, the filter is applied and the page refreshes with the filtered data. The code works up to the point I make the selection, where I get the following validation error using ModelChoiceFilter: * Select a valid choice. That choice is not one of the available choices. Here's the field definition in my model: msg_direction = models.CharField(max_length=20) Here's the filter definition in my filters.py file: msg_direction = ModelChoiceFilter(queryset=Message.objects.values_list('msg_direction', flat=True).distinct().order_by()) I have also tried ChoiceFilter instead but would rather work with a dynamically generated list from that field rather than specify a fixed list of choices. Thanks in advance! -
Problem with a new version of django and python code
I am stuck with django here, i have added the code of views.py and urls.py below. I am getting the following error: This is the error im getting Please look into it and help me if there is any solution to it. The error is at the bottom of the image. views.py from django.shortcuts import render, get_object_or_404, redirect from django.contrib.auth.decorators import login_required from django.utils import timezone from .models import Post, Comment from .forms import PostForm, CommentForm from django.views.generic import (TemplateView,ListView, DetailView,CreateView, UpdateView,DeleteView) from django.urls import reverse_lazy from django.contrib.auth.mixins import LoginRequiredMixin # Create your views here. class AboutView(TemplateView): template_name = 'blog/about.html' class PostListView(ListView): model = Post def get_queryset(self): return Post.objects.filter(published_date__lte=timezone.now()).order_by('- published_date') class PostDetailView(DetailView): model = Post class CreatePostView(LoginRequiredMixin,CreateView): login_url = '/login/' redirect_field_name = 'blog/post_detail.html' form_class = PostForm model = Post class PostUpdateView(LoginRequiredMixin,UpdateView): login_url = '/login/' redirect_field_name = 'blog/post_detail.html' form_class = PostForm model = Post class PostDeleteView(LoginRequiredMixin,DeleteView): model = Post success_url = reverse_lazy('post_list') class DraftListView(LoginRequiredMixin,ListView): login_url = '/login/' redirect_field_name = 'blog/post_draft_list.html' model = Post def get_queryset(self): return Post.objects.filter(published_date__isnull=True).order_by('created_date') @login_required def post_publish(request, pk): post = get_object_or_404(Post, pk=pk) post.publish() return redirect('post_detail', pk=pk) @login_required def add_comment_to_post(request, pk): post = get_object_or_404(Post, pk=pk) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = … -
Nginx+uWSGi+Django long task Bad Gateway error
I have a long task in one of my django's views that take 120-200 seconds to generate the response. For this particular view, Nginx raises 502 Bad Gateway after 1 minute with this error message in the logs: [error] 7719#7719: *33 upstream prematurely closed connection while reading response header from upstream, here are my Nginx configurations: upstream DjangoServer { server 127.0.0.1:8000; keepalive 300; } location / { include proxy_params; proxy_pass http://DjangoServer; allow all; proxy_http_version 1.1; proxy_set_header X-Cluster-Client-Ip $remote_addr; client_max_body_size 20M; keepalive_timeout 300; proxy_connect_timeout 300; proxy_send_timeout 300; proxy_read_timeout 300; send_timeout 300; } And here are my uWSGI Configurations: uid=www-data gid=www-data http=127.0.0.1:8000 http-keepalive=300 master=1 vacuum=1 workers=2 threads=5 log-5xx=1 Note: The Nginx and uWSGI work fine for all other views. Django development server can run the task with no problem. After the Nginx 502 error, uWSGI keeps running in the background and completes the job, (according to in view print statements). If I try to connect to uWSGI via the browser, after a while (less than 120s) it will say ERR_EMPTY_RESPONSE. You can assume the task like this def long_task_view(request): start_time = time.time() print(start_time) # doing stuff time.sleep(130) print(time.time() - start_time) return HttpResponse("The result") -
How to I can modify this code to be like this first to create cat then related evaluation test?
Model.py I have created these model I want them to behave like this first I create Category then test related to that category from django.db import models from users.models import User import re from django.utils.translation import ugettext as _ class CategoryManager(models.Manager): def new_category(self, category): new_category = self.create(category=re.sub('\s+', '-', category).lower()) new_category.save() return new_category class Category(models.Model): category = models.CharField( verbose_name=_("Category"), max_length=250, blank=True, unique=True, null=True) objects = CategoryManager() def __str__(self): return self.category class EvaluationTest(models.Model): title = models.CharField(max_length=50,blank=False) category=models.ForeignKey(Category,null=True,blank=True,on_delete=models.CASCADE) url = models.SlugField( max_length=60, blank=False, help_text=_("a user friendly url"), verbose_name=_("user friendly url")) admin = models.ForeignKey(User,on_delete=models.CASCADE) type = models.CharField(max_length=50) def save(self, force_insert=False, force_update=False, *args, **kwargs): self.url = re.sub('\s+', '-', self.url).lower() self.url = ''.join(letter for letter in self.url if letter.isalnum() or letter == '-') super(EvaluationTest, self).save(force_insert, force_update, *args, **kwargs) def __str__(self): return self.title class GradeEvaluationText(models.Model): candidate = models.ForeignKey(User, on_delete=models.CASCADE) evaluationtest = models.ForeignKey(EvaluationTest,on_delete=models.SET_NULL,blank=True, null=True) grades=models.FloatField() def __str__(self): return self.candidate.username class Choice(models.Model): title = models.CharField(max_length=50) def __str__(self): return self.title class Question(models.Model): question = models.CharField(max_length=200) category = models.ForeignKey(Category, verbose_name=_("Category"), blank=True, null=True, on_delete=models.CASCADE) choices = models.ManyToManyField(Choice) answer = models.ForeignKey(Choice,on_delete=models.CASCADE,related_name='answer', blank=True, null=True) evaluationtest = models.ForeignKey(EvaluationTest,on_delete=models.CASCADE,related_name='questions', blank=True, null=True) order =models.SmallIntegerField() def __str__(self): return self.question Serializer.py Wonder if some one can check my Update function whether it is correct or not from rest_framework import … -
OperationalError at /admin/ no such table: django_session
I just created a new django project with the command django-admin startproject my_project and when I go to the url " http://localhost:8000/admin/ " I get this error- OperationalError at /admin/ no such table: django_session Request Method: GET Request URL: http://localhost:8000/admin/ Django Version: 2.1.7 Exception Type: OperationalError Exception Value: no such table: django_session Exception Location: /home/madhuparna/.local/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py in execute, line 298 Python Executable: /home/madhuparna/anaconda3/bin/python3 Python Version: 3.6.7 Python Path: ['/home/madhuparna/Desktop/my_project', '/home/madhuparna/anaconda3/lib/python36.zip', '/home/madhuparna/anaconda3/lib/python3.6', '/home/madhuparna/anaconda3/lib/python3.6/lib-dynload', '/home/madhuparna/.local/lib/python3.6/site-packages', '/home/madhuparna/anaconda3/lib/python3.6/site-packages'] Server time: Tue, 12 Mar 2019 13:41:24 +0000 I have no idea what is the problem. -
How to install some python packages in Docker Container
I am using "reportlab". I have to install "pip install reportlab" every time whenever i entered docker environment, I do not want to install every time it any solution. -
List is working but post is not working in nested serializer in Django Rest Framework
Models.py class Kitchen(models.Model): kitchen_name = models.CharField(max_length = 100) state = models.CharField(max_length = 40, ) city = models.CharField(max_length = 40) def __str__(self): return self.kitchen_name class AssignAudit(models.Model): kitchen = models.ForeignKey(Kitchen, on_delete = models.SET_NULL, null = True) assigned_date = models.DateTimeField(default = timezone.now) assigned_by = models.ForeignKey(User, on_delete = models.SET_NULL, null = True, related_name = 'assigned_audits') Serializers.py class KitchenSerializer(serializers.ModelSerializer): class Meta: model = Kitchen fields = '__all__' class AssignAuditSerializer(serializers.ModelSerializer): kitchen = KitchenSerializer() class Meta: model = AssignAudit fields = '__all__' def create(self, validated_data): assign_audit = AssignAudit.objects.create(**validated_data) questions = Question.objects.all() for question in questions: kitchen_audit = KitchenAudit.objects.create(question=question,assign_audit=assign_audit) for images in range(question.no_of_images): KitchenAuditImage.objects.create(kitchen_audit=kitchen_audit) return assign_audit Views.py class AssignAuditSerializerListCreate(ListCreateAPIView): serializer_class = AssignAuditSerializer queryset = AssignAudit.objects.all() def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response({'audit_assign':serializer.data}) I want to combine both of my table above to display it in one API using django-rest-framework. GET method is working fine but when i am doing POST method, it's saying i have to provide kitchen value. { "kitchen": [ "This field is required." ] } -
Django IntegrityError NOT Null Constraint Failed reqs_student.section_id
I am new to django and I am trying to create an application with a user signup form where students can sign up with their name, subjects, and section. But it is having an error at the sections part. I am getting an error of NOT NULL constraint failed: reqs_student.section_id. These are the relevant bits of code: forms.py code: class StudentSignUpForm(UserCreationForm): subjects = forms.ModelMultipleChoiceField( queryset=Subject.objects.all(), widget=forms.CheckboxSelectMultiple, required=False ) section = forms.ModelChoiceField( queryset=Section.objects.all(), widget=forms.Select, required=True ) class Meta(UserCreationForm.Meta): model = User @transaction.atomic def save(self, commit = True): user = super().save() user.is_student = True user.save() student = Student.objects.create(user=user) student.subjects.add(*self.cleaned_data.get('subjects')) student.section = self.cleaned_data.get('section') return user Model code: class Section(models.Model): name = models.CharField(max_length=30) grade = models.IntegerField() subjects = models.ManyToManyField(Subject, related_name='section') def __str__(self): return self.name class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) subjects = models.ManyToManyField(Subject, related_name='subjected_students') section = models.ForeignKey(Section, on_delete=models.CASCADE, related_name='Student_Section') the view code: class StudentSignUpView(CreateView): model = User form_class = StudentSignUpForm template_name = 'registration/signup_form.html' def get_context_data(self, **kwargs): kwargs['user_type'] = 'student' return super().get_context_data(**kwargs) def form_valid(self, form): user = form.save() login(self.request, user) return redirect('students:requirement_list') According to the traceback, the code starts having an error at user = form.save() What can be going wrong here? -
Multiple user types and ratings in Django
I'm making a DRF backend with three user types: customer, personal trainer and gym owner. I want all the fields in the CustomUser class to apply to each user type. I also want some specific attributes to each user type (for example photo only for personal trainer and gym owner). Is this the right way to do it? # models.py class CustomUser(AbstractUser): USER_TYPE_CHOICES = ( ('customer'), ('personal_trainer'), ('gym_owner'), ) user_type = models.CharField(blank=False, choices=USER_TYPE_CHOICES) name = models.CharField(blank=False, max_length=255) country = models.CharField(blank=False, max_length=255) city = models.CharField(blank=False, max_length=255) phone = models.CharField(blank=True, max_length=255) ratings = models.ForeignKey(Rating, on_delete=models.CASCADE, null=True) created_at = models.DateField(auto_now_add=True) def __str__(self): return self.name class Customer(models.Model): user = models.OneToOneField( CustomUser, on_delete=models.CASCADE, primary_key=True) class PersonalTrainer(models.Model): user = models.OneToOneField( CustomUser, on_delete=models.CASCADE, primary_key=True) photo = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) class GymOwner(models.Model): user = models.OneToOneField( CustomUser, on_delete=models.CASCADE, primary_key=True) photo = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) I also have a ratings model. I want to be able to leave a rating as a customer to a personal trainer or a gym. Each rating will have a one to one relation with it's owner and it's target. I'm not sure however how I can make the relations..? # models.py class Rating(models.Model): STAR_CONVERSION = ( (1, 'One Star'), (2, 'Two Stars'), (3, 'Three Stars'), (4, … -
Django NoReverseMatch Error while Deploying
I am using Django-friendship package for follower relationship . In localhost it works great but when i deploy it . gives error as "Reverse for 'follower_add_new' with arguments '('Bora.gulerrr',)' not found. 1 pattern(s) tried: ['tr/friendship/follower/add/(?P\w+)/$']" I dont know why it gives error while deploying. views.py @login_required def follower_add(request, followee_username, template_name='friendship/follow/add.html'): """ views.py """ #ctx = {'followee_username': followee_username} if request.method == 'POST': followee = user_model.objects.get(username=followee_username) follower = request.user try: Follow.objects.add_follower(follower, followee) except AlreadyExistsError as e: ctx['errors'] = ["%s" % e] else: return redirect('followees') return render(request, template_name, ctx) ` urls.py urlpatterns = [ re_path(r'^follower/add/(?P<followee_username>\w+)/$',follower_add,name = "follower_add_new"), re_path(r'^follower/remove/(?P<followee_username>\w+)/$',follower_remove,name = "follower_remove_new"), ] home.html <div class="col"> <h4>{%trans "People and Companies" %}</h4><br><br> <h5>{%trans "Filter" %}</h5> <form method="get"> {{ filter.form| crispy }} <button type="submit">{%trans "Search" %}</button><br><br> </form> {% for user in filter.qs %} {% if not user in blocking %} {% if not user in blockers %} {% if not user in followees %} <table class="table"> <tbody id="myTable"> <tr> <th scope="row"><a href="{% url 'user:view_profile_with_pk' pk=user.pk %}"> {% if user.accounts.image %} <img src="{{user.accounts.image.url}}" width="50" alt="Profile Photo">&nbsp;&nbsp;&nbsp;&nbsp; {% else %} No Photo &nbsp;&nbsp;&nbsp;&nbsp; {% endif %} {% if user.first_name %} {{ user.first_name }}&nbsp;&nbsp;{{ user.last_name }}{% else %}{{ user.username }}{% endif %}&nbsp;&nbsp;&nbsp;&nbsp;{% if not user in followees %} <a href="{% … -
Django csrf_token works in one form but not in other
I have a page with two lists: for tasks (tareas) and sales (ventas). When you click their links each one opens it´s own modal and retrieves the info with AJAX. One works with no problem (tareas). The other one gives me a csrf_token error. I thought maybe it was a problenm of using two tokens in the same template, but I´m doing it in other templates with no problem. And if I completely remove the tareas part, the ventas one still get´s the same error. Venta form call <form name="ventas_form" action="#" id="form_venta_{{operacion.comprobante}}" method="POST"> {% csrf_token %} <input name="id" id="venta_id_submit" type="text" value="{{operacion.comprobante}}" hidden="true"/> <a style="padding-left: 1rem;" href="" id="{{operacion.comprobante}}" class="show_venta" data-toggle="modal" >{{operacion.comprobante}}</a> </form> Venta Ajax <script> $(function(){ $('.show_venta').on('click', function (e) { e.preventDefault(); let venta_id = $(this).attr('id'); $.ajax({ url:'/catalog/ventas-detail/', type:'POST', data: $('#form_venta_'+venta_id).serialize(), success:function(response){ console.log(response); $('.show_venta').trigger("reset"); openModalVentas(response); }, error:function(){ console.log('something went wrong here'); }, }); }); }); function openModalVentas(venta_data){ $('#fecha').text(venta_data.venta.fecha); $('#comprobante').text(venta_data.venta.comprobante); $('#cliente').text(venta_data.venta.cliente); $('#vendedor').text(venta_data.venta.vendedor); $('#lista').text(venta_data.venta.lista); $('#prod_codigo').text(venta_data.venta.prod_codigo); $('#prod_nombre').text(venta_data.venta.prod_nombre); $('#uds').text(venta_data.venta.uds); $('#vu').text(venta_data.venta.vu); $('#subtotal').text(venta_data.venta.subtotal); $('#bonif').text(venta_data.venta.bonif); $('#modal_ventas').modal('show'); }; </script> Venta view def VentaDetailView(request): ID = request.POST.get('id') ventas_todas = Ventas.objects.filter(pk=ID).get() venta = { "fecha": ventas_todas.fecha, "comprobante": ventas_todas.comprobante, "cliente": ventas_todas.cliente, "vendedor": ventas_todas.vendedor.nombre, "lista": ventas_todas.lista, "prod_codigo": ventas_todas.prod_codigo, "prod_nombre": ventas_todas.prod_nombre, "uds": ventas_todas.uds, "vu": ventas_todas.vu, "subtotal": ventas_todas.subtotal, "bonif": ventas_todas.bonif, } return JsonResponse({'venta': venta}) -
django CreateView set foreign key problem
Hi im using django and wanna set de foreing key to my createView manually, buy keep getting the following error. I understand this must be done in the form_valid method but dont know what im doing wrong. Cannot assign "'057e4185-c79d-40ff-b90d-0bee254754c8'": "Menu.MenuID" must be a "MenuCreateModel" instance. These are my models class MenuCreateModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) date = models.DateField(blank=False) class Menu(models.Model): option = models.IntegerField(unique=True) description = models.CharField(max_length=100) date = models.DateField(auto_now_add=True, blank=True) #slug = models.SlugField(null=True, blank=True) #MenuID = models.UUIDField(null=True) MenuID= models.ForeignKey(MenuCreateModel, default=uuid.uuid4, on_delete=models.CASCADE) this is my form class MenuCreateForm(forms.Form): option = forms.IntegerField() description = forms.CharField(required=True) MenuID = forms.UUIDField(required=True) class MenuCreate(forms.ModelForm): class Meta: model = Menu fields = [ 'option', 'description' ] And these is my createview class MenuCreateView(CreateView): form_class = MenuCreate model = Menu def dispatch(self, request, *args, **kwargs): self.mid = request.POST.get('menuCreateId') #initial = {'MenuID':self.ipsum} return super().dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['menuCreateId'] = self.mid return context def form_valid(self, form): form.instance.MenuID = self.mid return super().form_valid(form) Hope someone can help me. -
Inhereted django template loads js after jquery but $ still undefined
I have a parent.html template and a child.html template. parent.html: {% load static %} ... {% block main %} {% endblock main %} <script src="{% static 'myapp/js/jquery.min.js' %}"></script> <script src="{% static 'myapp/js/script1.js' %}"></script> <script src="{% static 'myapp/js/script2.js' %}"></script> {% block postscript %} {% endblock postscript %} child.html: {% extends "parent.html" %} {% load static %} {% block main %} ... main content ... {% endblock main %} {% block postscript %} <script src="{% static 'myapp/js/script3.js' %}"></script> {% endblock postscript %} script1.js, script2.js, and script3.js all depend on jquery and use $, but only script3.js causes the error ReferenceError: $ is not defined... 1:1. script3.js starts with: $(function() { ... }); Every question related to this problem that I can find is a more trivial example that is solved by simply loading jquery first. Here, I've done that. I've also confirmed that the final source looks exactly as expected: <!DOCTYPE html> <html lang="en"> ... main ... <script src="/static/myapp/js/jquery.min.js"></script> <script src="/static/myapp/js/script1.js"></script> <script src="/static/myapp/js/script2.js"></script> <script src="/static/myapp/js/script3.js"></script> </html> All the functionality related to script1 and script2 works perfectly. Does anyone understand what's going on here? -
When deploying django app on GAE.. ERROR: (gcloud.app.deploy) INVALID_ARGUMENT: Network 'default' does not exist
I tried to deploy my Django application on GAE and it worked on another gcp project. Now I'm trying to deploy again in a different gcp project but I get following error: ERROR: (gcloud.app.deploy) INVALID_ARGUMENT: Network 'default' does not exist Does someone now what the problem might be? Thanks in advance. -
"Cannot force an update in save() with no primary key"- when submitting an edit/update form
I have an edit form that I only want to update the "title", "content", and "category" of a Post. To this end, I have included update_fields when saving the form. However, there's a wee issue with this. Django raises a ValueError (specifically "Cannot force an update in save() with no primary key") when I submit the form. Why is it doing this, and how can I fix this? Post form: class PostForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for key in ['postTitle', 'postContent', 'category']: self.fields[key].widget.attrs.update({'class': 'form-control'}) self.fields['content'].widget.attrs.update(width='100px', height='50') class Meta: model = Post fields = ('title', 'content', 'category') Post model: class Post(models.Model): title = models.CharField(max_length = 100) URL = models.SlugField() # slug for url content = models.TextField() author = models.ForeignKey(User, on_delete = models.CASCADE, related_name = 'posts') # id of author category = models.CharField(max_length = 9, default = 'General') # category the post is in creationDate = models.DateTimeField() Edit view: def editPost(request, pk): if request.method == 'GET': post = get_object_or_404(Post, pk = pk) if post.author == request.user: form = PostForm(instance = post) return render(request, 'editPost.html', {'form': form, 'post': post}) else: return redirect('viewPost', pk = pk, postURL = post.postURL) if request.method == 'POST': post = get_object_or_404(Post, pk = pk) form = PostForm(request.POST) … -
django rest framework: How to validate a rule in serializers using a related field
I have these models: product.py: class Product(models.Model): product_title = models.CharField(max_length=100) product_price = models.DecimalField(max_digits=12, decimal_places=2) product_multiple = models.PositiveIntegerField(blank=True, null=True) order_item.py: order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='items', null=True, blank=True) product = models.ForeignKey(Product, on_delete=models.CASCADE) price = models.FloatField(default=0) quantity = models.BigIntegerField(default=1) profitability = models.CharField(max_length=50, null=True, blank=True) I want to validate in serializers.py if the order_item.quantity % product_multiple is != 0 serializers.py: class OrderItemSerializer(serializers.ModelSerializer): class Meta: model = OrderItem fields = ('id', 'order', 'product', 'price', 'quantity', 'profitability') def validate_quantity(self, value): data = self.get_initial() quantity = data.get("quantity") if int(quantity) % *product.product_multiple* != 0: raise serializers.ValidationError("Quantity is not multiple") return value How can I get the actual product_multiple inside the validate function?