Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - complex annotation/aggregation based on date difference
I have models Category, Lead and Event. The event describes an action of generating leads (downloaded from external source) and can be created anytime - eg 2 times a day, then 7 days nothing, then 1 time a day etc. Event has a new_leads field that keeps track of Lead objects. Each Lead has some category (like clothes, electro etc). I'm trying to predict (based on the history) how many leads would be generated if I created a new event today. I started with annotating Event queryset by the counts of leads for each category. categories = Category.DEFAULT_CATEGORIES annotations = {category[0]:Count('new_leads',filter=Q(new_leads__category__name=category[1])) for category in categories} events = Event.objects.all().annotate(**annotations) Now, for every event, I can just call the category attribute this way: event.clothes which returns a number of new clothes. This is where I don't know how to continue. I want to calculate/annotate the average new leads count per day. Eg. for a particular event and category, I'll divide the number of leads by a number of days since the Event before. Something like event.clothes_avg_per_day and then I'd aggregate the average from all the events for all the categories. That way I'd have an average number of new leads per category … -
Output HTML Table in Django For Each Date in SQL Query
I am creating a call reports dashboard in django, and I want to output a postgresql Select query in an HTML table for each date of the month like this: For whatever reason I am having a very hard time figuring this out. This is my HTML, I know I am not doing the looping right here, I've just been running out of ideas. {% for i in lt.itertuples %} <table class="table" style="float:left"> <caption>{{ i.to_date }}</caption> <thead> <tr> <th>Extension</th> <th>Calls</th> </tr> </thead> {% for d in df4.itertuples %} <tr> <td> {{ d.member_extension }} </td> <td> {{ d.count }} </td> </tr> {% endfor %} </table> {% endfor %} </div> And this is a snippet of my Python: query=pd.read_sql_query("select DISTINCT date(start_date) as 'DATE()' from Reports3; ",con3) query2=pd.read_sql_query("SELECT COUNT(*),member_extension from Reports3 group by member_extension ",con3) df4 = pd.DataFrame(query) lt = pd.DataFrame(query2) ext4=pd.unique(df4['member_extension']) context={'df4':df4, 'ex4':ext4, 'lt':lt } return render(request,'index2.html',context) -
Send to server float array using libcurl c++
I am using a portaudio callback where I receive periodically a buffer of audio and store it on main_buffer. I only set the settings bellow for curl and only use the CURLOPT_POSTFIELDS to set the float buffer before sending it with curl_easy_perform. On the server side I am using python django: float main_buffer[256]; url_global_init(CURL_GLOBAL_ALL); curl = curl_easy_init(); curl_easy_setopt(curl, CURLOPT_URL, URL); //portaudio periodic callback callback(){ //... curl_easy_setopt(curl, CURLOPT_POSTFIELDS, main_buffer); curl_easy_perform(curl); } The request received in server has no content inside body. How to send main_buffer the right way ? Thank you ! -
How to Solve this django.db.utils.IntegrityError
I have no idea why this error keeps showing. This error seems to occur whenever I try to migrate my models.py. Here is the error first: django.db.utils.IntegrityError: The row in table 'leads_lead' with primary key '1' has an invalid foreign key: leads_lead.class_duration_id contains a value '50' that does not have a corresponding value in leads_classduration.id. Here is my full lead model(commented out my classduration after this error occurred, but it is still the same): class Lead(models.Model): first_name = models.CharField(_('Korean Name'), max_length=20) last_name = models.CharField(_('English Name'), max_length=20) username = models.CharField(max_length=100, null=True, blank=True) age = models.IntegerField(default=0) organisation = models.ForeignKey(UserProfile, null=True, blank=True, on_delete=models.SET_NULL) agent = models.ForeignKey("Agent", null=True, blank=True, on_delete=models.SET_NULL) category = models.ForeignKey("Category", related_name="leads", null=True, blank=True, on_delete=models.SET_NULL) description = models.TextField(null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) phone_number = models.CharField(max_length=20) email = models.EmailField() # ENROLLED IN CLASS FROM WHEN TO WHEN class_start_date = models.DateField(null=True, blank=True, default=datetime.date(1111,11,11)) class_end_date = models.DateField(null=True, blank=True, default=datetime.date(1111,11,11)) weekday = models.ManyToManyField('Weekday', blank=True, help_text='Select weekdays for the student') time = models.TimeField(null=True, blank=True, default=datetime.time(0,0)) # LEAD_CLASS_DURATION = ( # (10, '10 minutes'), # (20, '20 minutes'), # (25, '25 minutes'), # (30, '30 minutes'), # (50, '50 minutes'), # ) # class_duration = models.IntegerField( # choices=LEAD_CLASS_DURATION, # null=True, # blank=True, # ) # input_classes: managed by … -
trying to use custom user model with django-allauth framework
i have a custom user model that looks like this from django.db import models from django.contrib.auth.models import AbstractUser from django.contrib.auth.base_user import BaseUserManager # user manager code class MyUserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): """ Creates and saves a User with the given email, first name, last name and password. """ if not email: raise ValueError("Users must have an email address") user = self.model( email=self.normalize_email(email), **extra_fields, ) user.set_password(password) user.save(using=self._db) return user # Create your models here. class CustomUser(AbstractUser): email = models.EmailField(unique=True) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] def __str__(self): return self.email my serializer.py class RegisteSerializer(serializers.Serializer): password = serializers.CharField(style={"input_type": "password"}, write_only=True) password2 = serializers.CharField(style={"input_type": "password"}, write_only=True) email = serializers.EmailField(required=allauth_settings.EMAIL_REQUIRED) first_name = serializers.CharField(min_length=2, max_length=50) last_name = serializers.CharField(min_length=2, max_length=50) USERNAME_FIELD = 'email' class Meta: model = User fields = [ 'id', 'first_name', 'last_name', "email", "password", "password2", ] extra_kwargs = {'password': {'write_only': True}} def validate_email(self, email): email = get_adapter().clean_email(email) if allauth_settings.UNIQUE_EMAIL: if email and email_address_exists(email): raise serializers.ValidationError( ("A user is already registered with this e-mail address.")) return email def validate_password(self, password): return get_adapter().clean_password(password) def validate(self, data): if data['password'] != data['password2']: raise serializers.ValidationError( ("The two password fields didn't match.")) return data def get_cleaned_data(self): return { 'first_name': self.validated_data.get('first_name', ''), 'last_name': self.validated_data.get('last_name', ''), 'password': … -
django User matching query does not exist
i'm trying to signup with an otp for verification by sending email to the user mail, but getting this error, trying to signup with an otp for verification by sending email to the user mail, but getting this error, if is there any better solution do this with django would be appreciate, models.py class User(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] is_buyer = models.BooleanField(default=False) is_vendor = models.BooleanField(default=False) objects = CustomUserManager() def __str__(self): return self.email class UserOTP(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE) time_st = models.DateTimeField(auto_now = True) otp = models.SmallIntegerField() class Vendor(models.Model): user = models.OneToOneField(User, related_name='vendor', on_delete=models.CASCADE) business_name = models.CharField(max_length=50) def __str__(self): return self.user.email forms.py class VendorSignUpForm(UserCreationForm): business_name = forms.CharField(required=True) email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') class Meta: model = User fields = ('business_name', 'email', 'password1', 'password2', ) @transaction.atomic def save(self): user = super().save(commit=False) user.is_vendor = True user.save() customer = Vendor.objects.create(user=user) customer.business_name=self.cleaned_data.get('business_name') customer.save() return user views.py def signup(request): if request.method == 'POST': get_otp = request.POST.get('otp') print(get_otp) if get_otp: get_user = request.POST.get('user') user = User.objects.get(email=get_user) if int(get_otp) == UserOTP.objects.filter(user = user).last().otp: user.is_active = True user.save() messages.success(request, f'Account is Created For {user.email}') return redirect('login') else: messages.warning(request, f'You Entered a Wrong OTP') … -
Exclude object from queryset if any of it's many to many related objects has a given property value
let's say I have a models like this: class Bar(Model): value = IntegerField() class Foo(Model): bars = ManyToManyField(Bar) Now, how do I get a queryset of Foo objects, excluding the ones, which have any of bars object with value of 0? Corresponding Python code would be like this: foos_ids_to_exclude = [] for foo in Foo.objects.all(): for bar in foo.bars.all(): if bar.value == 0: foos_ids_to_exclude.append(foo.id) break resulting_queryset = Foo.objects.exclude(id__in=foos_ids_to_exclude) But how do I do this on DjangoORM level? It's even possible? I want to do this without evaluating the queryset if possible. -
What extensions of python markdown can be used to parse sequence charts and flow charts?
I'm developing a blog app by using django, there's a feature is that showing articles written by markdown.I have imported django-mdeditor to edit markdown content. Now I want to parse and show it on another page. I parse markdown contents like this: import markdown content = markdown.markdown(markdown_string) Now I have been able to successfully parse some markdown syntax, but I can't do it well on sequence charts and flow charts. Are there some extensions of python-markdown or some other modules can do it well? Thank for your answer firstly!! -
The page code in Django is output instead of the form
I output it in html in this way - {{news}} When you open the page, it shows the code of the page itself ................................................................................ Views.py from django.shortcuts import render from .models import Comment from .forms import CommentForms def index(request): return render(request , 'mainToo/index.html') def reviews(request): form = CommentForms() data = { 'form' : form } news = Comment.objects.all() return render(request , 'mainToo/reviews.html', {'news':news} , data) models.py from django.db import models class Comment(models.Model): nameAndSurname = models.CharField('Фамилия и имя' , max_length=50 ) text = models.TextField('Ваш отзыв' , max_length=1000 ,) date = models.DateTimeField('Дата и время') def __str__(self): return self.nameAndSurname class Meta: verbose_name='Отзыв' verbose_name_plural='Отзывы' forms.py from .models import Comment from django.forms import ModelForm , TextInput class CommentForms(ModelForm): class Meta: model = Comment fields = ['nameAndSurname' , 'text' , 'date'] urls.py from django.urls import path from . import views urlpatterns = [ path('' , views.index , name='home'), path( 'reviews/' , views.reviews , name='reviews'), ] -
If we are using Generic views in Django, then the templates must be present within the templates folder in the app in which the views are specified?
I am new to Django framework and the instructor what normally does is that he joins the path with the base dir for generic templates like base.html and all ,and for login and signup and app specific templates he creates a dir within the app and populates the html there, he never mentioned how it works and I am confused what method would I follow , can someone explain this in an easy way!! -
I am trying to build a website with django and it is giving me this error [closed]
I am trying to build a website with Django and it is giving me error. I run with python manage.py runserver. Traceback (most recent call last): File "C:\CS\Projects\ideas\New folder (2)\study-planner-master\manage.py", line 21, in <module> main() File "C:\CS\Projects\ideas\New folder (2)\study-planner-master\manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\Anurag\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Anurag\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Anurag\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Anurag\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 61, in execute super().execute(*args, **options) File "C:\Users\Anurag\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Users\Anurag\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 68, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "C:\Users\Anurag\AppData\Local\Programs\Python\Python39\lib\site-packages\django\conf\__init__.py", line 82, in __getattr__ self._setup(name) File "C:\Users\Anurag\AppData\Local\Programs\Python\Python39\lib\site-packages\django\conf\__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "C:\Users\Anurag\AppData\Local\Programs\Python\Python39\lib\site-packages\django\conf\__init__.py", line 189, in __init__ raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. -
I think my django view is making 16 forms instead of 15
Frist of all sorry for my bad english but i'm french ! So my problem is that i've written a django view to configure my CompactRIO from a web page. I have written a form to display things like baudrate and stop bit and i have created a formset to display multiple forms at once ( so i can configure multiple connections at once ). But when i run configure it, it stops right after the configuration of the last connection. So i am able to configure all 15 connections, the code runs fine, and then it stops working and i crashes. I think that maybe it comes from the fact that i create 16 forms instead of the 15 i want but the web page prints 15 forms so i dont know. Anyway thank you for taking the time to read my problem ! So this is my view : def config(request): if request.method == 'POST': ConfigFormSet = formset_factory(ConfigForm) formset = ConfigFormSet(request.POST) if formset.is_valid(): for form in formset: if form.is_valid(): entete = form.cleaned_data['Entete'] liaison = form.cleaned_data['Liaison'] baudrate = form.cleaned_data['Baudrate'] dataBit = form.cleaned_data['choixDataBit'] parityBit = form.cleaned_data['choixParityBit'] stopBit = form.cleaned_data['choixStopBit'] activate = form.cleaned_data['activate'] print(liaison) print(baudrate) print(dataBit) print(parityBit) print(stopBit) print(activate) # ------------------ … -
Dynamically filter queryset with AJAX and Django Rest Framework
models.py from django.db import models from django.utils import timezone import datetime from django.core.validators import RegexValidator, MinLengthValidator from .validator import validate_gearshift class Coche(models.Model): matricula = models.CharField(max_length=7,primary_key=True,validators=[RegexValidator(regex='^[1-9]{4}[A-Z]{3}$',message="La matr> concesionario = models.ForeignKey('Concesionario', on_delete=models.CASCADE) brand = models.ForeignKey('CocheBrand', on_delete=models.CASCADE) model_name= models.ForeignKey('CocheModel', on_delete=models.CASCADE) type_car = models.ForeignKey('CocheType', on_delete=models.CASCADE) location = models.ForeignKey('Localidad', on_delete=models.CASCADE) warranty = models.ForeignKey('CocheWarranty', on_delete=models.CASCADE) doors = models.ForeignKey('CocheDoors', on_delete=models.CASCADE) gearshift = models.ForeignKey('CocheGearshift', on_delete=models.CASCADE) precio = models.DecimalField(verbose_name="Precio",max_digits=10, decimal_places=5, validators=[RegexValidator(regex='^[1-9][0-9]> rebaja = models.DecimalField(verbose_name="Rebaja",max_digits=10, decimal_places=5, validators=[RegexValidator(regex='^[0-9]$|^[1> precio_final = models.DecimalField(verbose_name="Precio Final",max_digits=10, decimal_places=5, null=True, blank=True) #se calcul> kilometres = models.IntegerField(verbose_name="Kilometros", validators=[RegexValidator(regex='^[0-9]$|^[0-9][0-9]$|^[0-9][0-9][0-> years = models.IntegerField(verbose_name="Años", validators=[RegexValidator(regex='^[0-9]$|^[12][0-9]$|^(30)$',message="La antigu> horsepower = models.IntegerField(verbose_name="Caballos", validators=[RegexValidator(regex='^[6789][0-9]$|^[12][0-9][0-9]$|^(300)> description = models.CharField(verbose_name="Descripcion", max_length=512) reserved = models.BooleanField(verbose_name="Reservado") sold = models.BooleanField(verbose_name="Vendido") create_at = models.DateTimeField(auto_now_add=True,verbose_name="Fecha Creacion") def __str__(self): return self.matricula def FormatoFecha(self): return self.fecha.strftime('%d - %b -%y') views.py from .models import Coche, CocheGearshift, CocheDoors, CocheWarranty, Localidad, CocheType, CocheModel, CocheBrand, Concesionario, Co>from django.views.generic import ListView from django.shortcuts import render from .forms import IndexSearch from django.http import JsonResponse from rest_framework.generics import ListAPIView from .serializers import CocheSerializers from .pagination import StandardResultsSetPagination def CocheList(request): return render(request,'wallacar_app/prueba.html', {}) class CochesListing(ListAPIView): pagination_class = StandardResultsSetPagination serializer_class = CocheSerializers def get_queryset(self): queryList = Coche.objects.all() brand = self.request.query_params.get('brand',None) model_name = self.request.query_params.get('model_name',None) type_car = self.request.query_params.get('type_car',None) location = self.request.query_params.get('location',None) doors = self.request.query_params.get('doors',None) gearshift = self.request.query_params.get('gearshift',None) sort_by = self.request.query_params.get('sort_by',None) horsepower = self.request.query_params.get('horsepower',None) if brand: queryList … -
Django Flashing/Flickering on each Render on CRUD function and also Displaying data from API URL
I'm working on a Django REST Framework task. Every time I perform a Create, Retrieve, Update, and Delete function the list item item of div is flashing every time. How can I stop this flashing/flickering. From API URL I have to display the paginated data. If I click the next page then also flickering is occurred. How can I get rid of this flickering/flashing issue. main.html {% extends 'todo/index.html' %} {% block content %} <div class="center-column" id="center-column"> <h5 class="card-title" id="welcome" data-id={{ request.user.id }}> Hello {{ request.user.username }}, Create your todo list </h5> <div id="addTodoForm"> <form action="" method=""> <div class="input-group-append"> <input type="text" class="title-input" required name="title" placeholder="e.g. Chemistry"> <button type="submit" class="form-control btn btn-primary mr-sm-2" id="addTodobtn"> Add Todo </button> </div> </form> </div> </div> <div class="row" id="row"> <div class="col-sm-5"> <div class="card"> <div class="card-body"> <h5 class="card-title"> Incomplete Todo Items </h5> <hr /> <div class="list-group" id="incompleteTodo"> </div> <hr> <nav aria-label="..." id="incompletePagination"> <ul class="pagination justify-content-center"> <li class="page-item"> <button class="page-link" tabindex="-1" id="prevPageI">&laquo</button> </li> <li class="page-item"><button class="page-link" id="currPageI">1</button></li> <li class="page-item"><button class="page-link" id="nextPageI">&raquo</button></li> </ul> </nav> </div> </div> </div> <div class="col-sm-5"> <div class="card"> <div class="card-body"> <h5 class="card-title"> Completed Todo Items </h5> <hr> <div class="list-group" id="completedTodo"> </div> <hr> <nav aria-label="..." id="completedPagination"> <ul class="pagination justify-content-center"> <li class="page-item"> <button class="page-link" tabindex="-1" id="prevPageC">&laquo</button> </li> <li … -
How I can flatten many to many relationship using djnago serializer
I am new to Django. While I am try to implement serializer for many to many relationship I got problem.I want to serialize a many to many field and need to create a dictionary based on the nested object. models.py class ClassRoom(models.Model): name = models.CharField(max_length=10) def __str__(self): return self.name class Teacher(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Teacher(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name serializers.py class Student(models.Model): name = models.CharField(max_length=50) class_room = models.ForeignKey(ClassRoom, on_delete=models.CASCADE) teacher = models.ManyToManyField(Teacher) def __str__(self): return self.name class TeacherSerializer(serializers.Serializer): teacher_name = serializers.CharField(source="name", label="Teacher") class Meta: model = Teacher fields = ['name'] class StudentSerializer(serializers.Serializer): class_room = serializers.CharField(source="class_room.name") teacher = TeacherSerializer(many=True) student_name = serializers.CharField(source='name', label="Student") class Meta: model = Student fields = ['student_name', 'teacher', 'class_room'] views.py class HomeclassView(viewsets.ModelViewSet): queryset = Student.objects.all() serializer_class = StudentSerializer I got the response like this: { results: [ { "class_room": "Class 1", "teacher": [ { "teacher_name": "Maria" }, { "teacher_name": "sara" } ], "student_name": "John" } ] } But I am expecting the result in : { results: [ { "class_room": "Class 1", "teacher_name": "Maria", "student_name": "John" }, { "class_room": "Class 1", "teacher_name": "sara", "student_name": "John" }, ] } Please help me to achieve this. Thanks in advance -
Can't access Django's login page using Ingress. NodePort and LoadBalancer work fine
I have a django app which has been migrated to Kubernetes. Exposing the service with NodePort or LoadBalancer (AWS) works just fine, however when I'm using Ingress (nginx), it's not redirecting to the login page, and I always get an "authentication credentials were not provided" message. I had never used Ingress before, so maybe I'm missing something. apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: django-ingress annotations: nginx.ingress.kubernetes.io/rewrite-target: / spec: rules: - http: paths: - path: /app pathType: Exact backend: service: name: django port: number: {{ .Values.service.port }} the idea is that if I visit localhost/app/admin, it should go to localhost/app/login and back to localhost/app/admin. But such redirection is not done by Ingress. As I said, it's working with NodePort and LoadBalancer. For example, localhost:30000/admin will redirect to localhost:30000/admin/login and then upon signing in, the form will go back to localhost:30000/admin Any idea about what might be missing? -
Django filter().first() returning different result than get()
I can't figure out how to debug this. I have this Django model: from django.db import models from django.utils.translation import ugettext_lazy as _ # ... class AbstractPhrase(models.Model): term2_past_tense = models.TextField(_('term 2 past tense')) # ... other simple fields and methods class Meta: abstract = True class CommentPhrase(AbstractPhrase, models.Model): """A phrase that comprises part of a report card comment""" skill = models.ForeignKey(Skill, null=True, on_delete=models.SET_NULL) question = models.ForeignKey( Question, null=True, on_delete=models.SET_NULL, related_name='phrases') old_id = models.CharField( _('old ID'), max_length=10, blank=True, null=True) # ... Other simple fields class Meta: ordering = ('skill', 'question_number') verbose_name = _('comment phrase') verbose_name_plural = _('comment phrases') An administrator reported that the model couldn't be updated in the Django admin. After saving, the Django admin would report that the model updated successfully, but when they refreshed the page the data was still out of date. I opened up a Django shell and investigate: In [3]: cp = CommentPhrase.objects.get(pk=10280) In [4]: cp Out[4]: <CommentPhrase: lorem ipsum> In [5]: cp.term2_past_tense Out[5]: '' In [6]: cp.term2_past_tense = "Test" In [7]: cp.save() In [8]: cp.term2_past_tense Out[8]: 'Test' In [9]: cp.refresh_from_db() In [10]: cp.term2_past_tense Out[10]: '' I further tried doing a queryset update(), and this had the same result. It got weirder when I looked … -
Is it possible to choose between multiple tables from the database (POSTGRES) in the Dash Plotly drop down menu?
I have a database connected to my project. Now I would like to have a selection from the tables that are available in my database in my dropdown. So I want to be able to select my tables from the database in the drop-down menu. i am working with django plotly dash. if you nedd my code i can upload it also. thanks -
Access local dockerized django project via ip without port
I got a small django project wich runs within a docker container and it is locally only (no need to expose it to the whole internet, just my office), but since it's a coporate project I want to give the persons who use it the possibility to access it via the ip address of host machine instead ip address:port (wich in my opinion is less readable). Being honest, I have no experience configuring nginx. This is my nginx config file (see it's a very simple configuration): client_max_body_size 10M; upstream web{ ip_hash; server web:8000; } server { location /static/ { autoindex on; alias /src/static/; } location /media/ { autoindex on; alias /src/media/; } location / { proxy_pass http://web/; } listen 8000; server_name localhost; } And my django image entry point: CMD ["sh", "-c", "python manage.py collectstatic --no-input; python manage.py migrate; gunicorn project.wsgi -b 0.0.0.0:8000"] Both containers expose to same port. -
ModelForm instance doesn't store primary key
Upon trying to save a Model instance as a result of saving a ModelForm, I'm getting the following error: ValueError: "<Question: NameError: 'x' is not defined>" needs to have a value for field "id" before this many-to-many relationship can be used. The question instance is being created to an extent, yet the primary key is not being generated. What needs to be fixed in order for the primary key to be attached so it can be stored in the database? class PostQuestionPage(QuestionPage): template_name="questions/create_question.html" def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['question_form'] = QuestionForm(self.request.POST or None) con return context def get(self, request): context = self.get_context_data() return self.render_to_response(context) def post(self, request): context = self.get_context_data() form = context['question_form'] import pdb; pdb.set_trace() if form.is_valid(): question = form.save(commit=False) question.user_account = request.user.account question.save() form.save_m2m() return HttpResponseRedirect( reverse("questions:question", kwargs={'id': question.id}) ) return self.render_to_response(context) class Question(models.Model): title = models.CharField(max_length=50) body = models.TextField() dated = models.DateField(default=date.today) likes = models.IntegerField(default=0) user_account = models.ForeignKey( 'users.UserAccount', on_delete=models.SET_NULL, null=True, blank=True, related_name="questions" ) tags = models.ManyToManyField(Tag, related_name='questions') objects = models.Manager() dateranges = DateRangeQuerySet.as_manager() status = QuestionStatusQuerySet.as_manager() class Meta: ordering = ['-dated'] default_manager_name = "objects" def __str__(self): return self.title class TestPostQuestionPageAdded(TestCase): '''Verify that a User has succesfully added a question''' @classmethod def setUpTestData(cls): cls.user … -
Django: How to use data from a function as a field in Meta class
I've created a function in my serializers.py that call an external API and give me a dict back. How can I use the output from return downloads in the get_all_files as a field in class Meta? With my solution I've got the following error: Field name get_all_files.downloads is not valid for model Application. serializers.py class OsdSerializer(serializers.ModelSerializer): bands = BandSerializer(source='indice_to_use.needed_bands', many=True) satellite = SatelliteSerializer(source='indice_to_use.satellite_to_use') indice = IndiceSerializer(source='indice_to_use') # configuration url = 'https://earth-search.aws.element84.com/v0' # URL to Sentinel 2 AWS catalog collection = 'sentinel-s2-l2a-cogs' # search parameter startDate = '2021-04-10' endDate = '2021-04-12' location = [ 13.6677, 43.7232, 16.2605, 45.4522 ] def get_all_files(*bandss): bbox_search = Search( bbox=location, datetime=startDate+"/"+endDate, query={'eo:cloud_cover': {'lt': 50}}, collections=[collection], url=url, sort={'field': 'eo:cloud_cover', 'direction': 'desc'}, ) items = bbox_search.items() downloads = {} for i, item in enumerate(items): data = {} data['Product ID']= item.properties["sentinel:product_id"] data['Preview']= item.asset("thumbnail")["href"] data['Date']= item.properties["datetime"] data['Cloud cover']= item.properties["eo:cloud_cover"] for band in bandss: data[band] = item.asset(band)["href"] downloads[i] = data return downloads class Meta: model = Application fields = ['machine_name', 'name', 'description', 'indice', 'satellite', 'bands', 'get_all_files.downloads', ] -
How to join 2 routers in DRF. Not extend, join
I need to join 2 routers like that I got router that generates /course/<course_id> i got router that generates /lesson/<lesson_id> i need to combine this two urls to /course/<course_id>/lesson/<lesson_id> this is what i tried router = routers.SimpleRouter() router.register(r'courses', CourseViewSet) lesson_router = routers.SimpleRouter() lesson_router.register('courses/<int:id>/lessons', LessonViewSet) it does't work correctly. It works but only if the url is /courses/<int:id>/lesson/1 where <int:id> is string not mock -
Reverse for 'like' not found. 'like' is not a valid view function or pattern name
I'm trying to create a like button using ajax in my project. But it gives error : Reverse for 'like' not found. 'like' is not a valid view function or pattern name. Here's my code. View.py def like(request): blog = get_object_or_404(Blogs, sno = request.POST.get('blog_id')) is_liked = False if blog.likes.filter(username = request.user).exists(): blog.likes.remove(request.user) is_liked = False else: blog.likes.add(request.user) is_liked = True context = { 'is_liked' : is_liked, 'blog' : blog, 'total_like': blog.total_like(), } if request.is_ajax(): html = render_to_string('like_section.html',context,request=request) return JsonResponse({'form':html}) urls.py urlpatterns = [ path('',views.blogs, name='blogs'), path('blog/<int:id>/<str:slug>',views.showblog, name='showblog'), path('writeblog/',views.writeblog, name='writeblog'), path('publish',views.publishBlog, name='publishblog'), path('like',views.like, name='like'),] template <p> Likes : {{total_likes}} Like{{total_likes| pluralize}} </p> {% if is_liked %} <button type="button" class="btn" id="like" name="blog_id" value="{{blog.sno}}"><i class="fa fa-thumbs-up">Dislike </i></button> {% else %} <button type="button" class="btn" id="like" name="blog_id" value="{{blog.sno}}"><i class="fa fa-thumbs-up"> Like </i></button> {% endif %} <script> $(document).ready(function (event) { $('#like').click(function(){ var pk = $(this).attr('value'); const path = '{% url "like" %}'; $.ajax({ type: "POST", url: path, data : {'id':pk, 'csrfmiddlewaretoken':'{{ csrf_token }}'}, dataType:'json', success:function(event){ $('#like-section').html(resopnse['form']); console.log($('#like-section').html(resopnse['form'])); } }); }); }); </script> -
Nginx passes the websocket request to Gunicorn instead of Daphne
I am setting up a production server with nginx and Gunicorn+Daphne. Everything is working well except the ws proxy_pass. I followed this two tutorials. https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-14-04 https://github.com/mitchtabian/HOWTO-django-channels-daphne etc/nginx/sites-aviable/multichats.conf server { listen 80; server_name 127.0.0.1; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/vagrant/multichat; } location /ws/ { proxy_pass http://0.0.0.0:8001; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } For some reason the websocket request is passed to Gunicorn instaed of Daphne: Apr 26 01:55:08 multichats gunicorn[16099]: Not Found: /chat/stream/ Apr 26 01:55:08 multichats gunicorn[16099]: - - [25/Apr/2021:23:55:08 +0000] "GET /chat/stream/ HTTP/1.0" 404 2307 "-" "Mozilla/5.0 (Windows NT 10.0; nginx.conf user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; # server_tokens off; # server_names_hash_bucket_size 64; # server_name_in_redirect off; include /etc/nginx/mime.types; default_type application/octet-stream; ## # SSL Settings ## ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # Gzip … -
Lock web page in Django admin if another user in that page
I'm new to Django. I'm looking for a way to lock a custom template in the Django admin for accessing more than 1 user at a time. Is there a way to do it with Sessions? Or do it with javascript? Thanks in advance!