Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filter ManyToMany by user from current model
I'm bit stuck on one stuff. How I can reach all Rerservation from the current Main model which belongs to the current user? Any help will be be appreciate class ReservationPay(generic.DetailView): model = Main def get_context_data(self, **kwargs): context = super(Reservation, self).get_context_data(**kwargs) context['user_rea'] = Main.objects.filter(all_resa__user=self.request.user).all() class Rerservation(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) prix = models.DecimalField(max_digits=6,decimal_places=2) class Main(models.Model): all_resa = models.ManyToManyField('Rerservation',blank=True, related_name='all_resa_reservation') -
Define list of objects in models.py in postgeSQL & Django-rest project
I mostly work with Node.js & MongoDB and I am pretty new to SQL dbs especially postgreSQL I am writing an application that makes use of django-rest-framework & postgreSQL as a DB. This is how my data structure as .json should look like. { id: "19eea956-34e5-11eb-adc1-0242ac120002" picture: [{ url: "", mimeType: "" }, { url: "", mimeType: "" }] } For the above data I am currently writing models.py which looks like as follows. from django.db import models from django.contrib.postgres.fields import ArrayField class Picture(models.Model): url = models.CharField() mimeType = models.CharField() class A(models.Model): id = models.CharField(max_length=120, primary_key=True) picture = ArrayField(Picture) def __str__(self): return self.id What I am trying to do in my models.py is to have picture as an Array of Objects or in python terminology List of Dictionaries. I read about ArrayField in postgreSQL but unable to find any example about how to define Array of Objects in models.py, any help here would be appreciated. Thanks :) -
Django form not showing except for submit button
I'm having this issue where the django form isn't showing up on the webpage. The only thing that shows up is the submit button. I cannot figure out the issue. Views.py class NewThreadView(CreateView): model = Thread form_class = NewThreadForm template_name = 'thread/newthread.html' def get_context_data(self, *args, **kwargs): context = super(NewThreadView, self).get_context_data(*args, **kwargs) forms.py class NewThreadForm(forms.ModelForm): class Meta: model = Thread fields = ('name', 'body', 'author', 'thread_forum') widgets = { 'name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter title'}), 'body': forms.Textarea(attrs={'class': 'form-control'}), 'author': forms.TextInput(attrs={'class': 'form-control', 'value': '', 'id': 'author', 'type': 'hidden'}), 'thread_forum': forms.Select(attrs={'class': 'form-control', 'type': 'hidden'}), } newthread.html <div class="form-group"> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-primary" name="thread_submit">Create Thread</button> </form> </div> -
I need help correcting that issue
i have that error when im trying to access an object on my admin. TypeError at /admin/core/order/11/change/ str returned non-string (type NoneType) my model for the order class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete= models.CASCADE) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) billing_address = models.ForeignKey('BillingAddress', on_delete= models.SET_NULL, blank=True, null=True) payment = models.ForeignKey('Payment', on_delete= models.SET_NULL, blank=True, null=True) def __str__(self): return self.user.username def get_total(self): total= 0 for order_item in self.items.all(): total += order_item.get_final_price() return total i cannot have access on the admin what should i do please? -
Can not paginate and write ordering for only one module from two querysets inside get_context_data
def get_context_data(self, **kwargs):\ context_data = super().get_context_data(**kwargs)\ context_data['queryset1'] = Choice.objects.all()\ context_data['queryset2'] = Timer.objects.all()\ return context_data I am a beginner in Django and I just wanted to make some "ordering" and "pagination"\ for just queryset1 but nowhere in docs it is written... Could you please help? Thank you in advance -
Django Admin: Add Action Button To Send Email
I have a model where Mail is a Foreign Key. The user can add a mail object,I want to add a button to the change form upon clicking which the email should be sent. models.py class Evaluation(models.Model): ... mail = models.ForeignKey(Mail, related_name="evaluation", null=True, blank=True, on_delete=models.CASCADE) I possibly want the button to execute something like this: def process(self): if self.mail is not None: send_mail( self.mail.subject, self.mail.body, settings.EMAIL_HOST_USER, [self.lead.user.email], fail_silently=False ) How could I achieve the same? -
Why updating nested user throws error of the field already exist?
I've tried to update a model with its related field which is customized user but after sending request with patch it returns 400 the code is here: models.py class Land(models.Model): user = models.OneToOneField(User, on_delete=models.DO_NOTHING) ... class User(AbstractBaseUser, PermissionsMixin): """Custom user model that support using national instead of username""" national_code = models.CharField(max_length=255, unique=True, blank=True) ... serializers.py class UserSerializer(serializers.ModelSerializer): """Serializer for the users object""" class Meta: model = get_user_model() fields = ('first_name', 'last_name', ...,) extra_kwargs = {'password': {'write_only': True, 'min_length': 5}} def update(self, instance, validated_data): """Update a user, setting the password correctly and return it""" password = validated_data.pop('password', None) user = super().update(instance, validated_data) if password: user.set_password(password) user.save() return user class LandSerializer(serializers.ModelSerializer): user = UserSerializer() utm_points = UTMPointsSerializer(many=True, read_only=True) letters = LettersSerializer(many=True, read_only=True) class Meta: model = Land fields = ('id', 'user', ...,) read_only_fields = ('id', 'approved',) def update(self, instance, validated_data): user = validated_data.pop('user') user_serializer = UserSerializer(data=user) if user_serializer.is_valid(): user = user_serializer.update(instance=instance.user, validated_data=user) validated_data['user'] = user instance.save() return instance views.py class LandViewSet(BasicViewSet): serializer_class = LandSerializer queryset = Land.objects.all() def get_serializer_class(self): """Return appropriate serializer class""" if self.action == 'retrieve': return self.serializer_class elif self.action == 'upload_image': return LandImageSerializer return self.serializer_class def partial_update(self, request, pk=None): land = self.get_object() # user_serializer = UserSerializer(land.user, data=request.data['user']) serializer = self.get_serializer(land, … -
Can I use Django with Next.js?
I am new to Next.js and see that there is a /api folder. This seems like it COULD replace my Django Rest Framework backend. Is that what the /api folder is intended to do? Moreover, is it common to see Django Rest Framework as a backend for Next.js? Thanks! -
Django don't save a form using Floppyforms
I have a field called medicamento in my model that is a foreign key and I want all the values in that field to be displayed in a searcheable dropdown in my form. I was able to do that but when I try to save, it says "Select a valid choice. That choice is not one of the available choices." Hope u can help dudes! Thanks in advance models.py class Stockmov(models.Model): numero = models.AutoField(primary_key=True) created= models.DateTimeField(auto_now_add=True,verbose_name="Fecha de Movimiento") author = models.ForeignKey(User,verbose_name="autor",on_delete=models.PROTECT, null=True, blank=True) medicamento= models.ForeignKey(Medicamento,on_delete=models.CASCADE) motivo= models.CharField(max_length=200) Cantidad = models.IntegerField() forms.py class StockmovForm(forms.ModelForm): class Meta: model = Stockmov fields = ['medicamento', 'motivo', 'Cantidad' ] widgets = { #'medicamento': forms.Select(attrs={'class':'form-control', 'placeholder':'Medicamento'}), 'medicamento': forms.widgets.TextInput(attrs={'class':'form-control', 'placeholder':'Medicamento'},datalist=Medicamento.objects.all()), 'motivo': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Motivo'}), 'Cantidad': forms.NumberInput(attrs={'class':'form-control', 'placeholder':'Cantidad'}), } labels = { 'medicamento':'Medicamento', 'motivo':'Motivo del Movimiento', 'Cantidad':'Cantidad del Movimiento', } views.py class StockmovCreate(CreateView): model = Stockmov form_class = StockmovForm success_url = reverse_lazy('stockmov:stockmov') def form_valid(self, form): form.instance.author = self.request.user print(self.request.user) return super(StockmovCreate, self).form_valid(form) Template <form action="" method="post">{% csrf_token %} {{ form.as_p }}`s` <div class="text-center"> <input type="submit" id="btnCrear" class="btn btn-secondary btn-block" value="Crear Movimiento" /> </div> </form> -
Django : Add different users to one project (project management web application)
I need help with implementing a form on which I can add new users to a specific project, using Django (Python) It's for a project management web application that I'm working on. Here are the necessary steps that I have accomplished before, please let me know whether I missed something. Models.py '''class Projet(models.Model): """autofield exists""" nom_projet = models.CharField(max_length=200, null=True) date_debut = models.CharField(max_length=200, null=True) date_fin = models.CharField(max_length=200, null=True) domaine = models.CharField(max_length=200, null=True) budget = models.IntegerField(null=True) description = models.CharField(max_length=500, null=True) users = models.ManyToManyField(User, blank=True, related_name='projet_users') def __str__(self): return self.nom_projet''' Forms.py class AddUserForm(forms.Form): user = forms.ModelChoiceField(queryset=User.objects.all()) Views.py def add_user_to_project(request, project_id): if request.method == "POST": form3 = AddUserForm(request.POST) if form3.is_valid(): Projet.users.add(form3.cleaned_data["user"]) return redirect("...") else: form3 = AddUserForm() return render(request, "createmembers.html", {"projet":Projet, "form3": form3}) Is this correct? What should I do next please? -
'User' object has no attribute 'get_all_permissions'
'User' object has no attribute 'get all permissions'!!! class UserManager(BaseUserManager): def create_user(self, email, username, full_name, phone, password): if not email: raise ValueError('plz input email') if not username: raise ValueError('plz input username') if not full_name: raise ValueError('plz input full_name') if not phone: raise ValueError('plz input phone') user = self.model(email=self.normalize_email(email), username=username, full_name=full_name, phone=phone) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, full_name, phone, password): user = self.create_user(email, username, full_name, phone, password) user.is_admin = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser): email = models.EmailField(max_length=50, unique=True) username = models.CharField(max_length=100, null=True, blank=True, unique=True) full_name = models.CharField(max_length=300) phone = models.CharField(max_length=15) address = models.CharField(max_length=500) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) permission = models.ManyToManyField(Permission, related_name='users') USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'full_name', 'phone'] objects = UserManager() def __str__(self): return self.email def has_perm(self, perm, obj=None): return self.is_superuser def has_module_perms(self, app_label): return self.is_superuser @property def is_staff(self): return self.is_admin -
Django Form Field Query
I have a field in my form that is a model based field and is currently pulling all students within the database. What I am trying to do is limit the amount of students in that field to a query. Attached is my forms.py, views.py , and my models.py . The query currently in my views called student_name is exactly what I want applied to the field on the form called student_name. How do I accomplish this ? Thanks views.py if request.method == "GET": class_name = Section.objects.get(sectionpsid=classid) getstudents = SectionEnrollment.objects.filter(section_id=classid).select_related().values_list('studentpsid__student_name', flat = True) student_name = getstudents.all().order_by('studentpsid') my_class_id = request.session['my_class_id'] sectionpsid = Section.objects.get(sectionpsid = my_class_id) form = Rapid_Fire_Form() context = ({'form': form, 'my_class_id': my_class_id, 'sectionpsid':sectionpsid, 'student_name': student_name}) return render(request, 'points/rapid_fire.html', context ) forms.py class Rapid_Fire_Form(forms.ModelForm): class Meta: model = K8Points fields = ('student_name', 'behavior','academic', 'time_frame','date','day','week_of','sectionpsid') labels = {'sectionpsid':_('Section Name'),'student_name':_('Student Name'),'time_frame':_('Time Frame') } def __init__(self, *args, **kwargs): super (Rapid_Fire_Form,self).__init__(*args,**kwargs ) self.fields['date'].disabled = True self.fields['day'].disabled = True self.fields['week_of'].disabled = True def clean(self): cleaned_data = super(Rapid_Fire_Form, self).clean() date = cleaned_data.get("date") time_frame = cleaned_data.get("time_frame") student_name = cleaned_data.get("student_name") if K8Points.objects.filter(date=date, time_frame=time_frame, student_name=student_name).exists(): raise forms.ValidationError('Error: This timeframe {} was already logged to the student {} on {}'.format(time_frame, student_name.student_name, date)) Model K8 Point Tracking System class K8Points(models.Model): date … -
Read data from Django templates in Vue when using webpack_loader
I'm just getting started with django-webpack_loader. I followed this guide and I now have a setup that allows me to inject vue components and pages into django templates. I have a component Question.vue that looks like this: <template> <div class="question_box"> <p class="question_text"> {{ text }} </p> <p v-for="(answer, index) in answers" :key="index" :class="{ 'correct' : (index + 1) == correct_answer_index}"> <strong>{{ index + 1 }}</strong> {{ answer }} </p> <p> {{ solution }} </p> </div> </template> <script> export default { name: 'Question', props: { }, data: () => { return { text: "", answers: [ ], correct_answer_index: -1, solution: "", } } } </script> I also have a component QuestionHistory.vue whose template looks like this <template> <div id="app"> <!-- will print some <Question />'s here based on django template context --> </div> </template> In my Django template, I get a context dictionary that contains a list of questions that I need to render using the Question component. The template is injected with QuestionHistory: {% load render_bundle from webpack_loader %} <div id="app"> <app></app> </div> {% render_bundle 'chunk-vendors' %} {% render_bundle 'vue_app_question_history' %} The thing is, I don't know how to pass the context received from Django onto my Vue components. If … -
django.urls.exceptions.NoReverseMatch: Reverse for 'update' with arguments '('',)' not found. 1 pattern(s) tried: ['update/(?P<pk>[0-9]+)$']
im trying to create a django page for update a dta inside database, i made this before in other projects and aways worked, but in my project it returns this error: django.urls.exceptions.NoReverseMatch: Reverse for 'update' with arguments '('',)' not found. 1 pattern(s) tried: ['update/(?P[0-9]+)$'] i reviewed my code a thousand times and i can't see nothing wrong, even if comparing with the other projects. Obs.: please ignore the css part of my template, i'm not used to write the css inside the html, but as it's just a test i don't create a external file. urls.py: from django.urls import path import tables1.views as vw urlpatterns = [ path('admin/', admin.site.urls, name = 'admin'), path('mytables/', vw.mytables, name = 'mytables'), path('',vw.home), path('table/<int:pk>',vw.table, name = 'tableurl'), path('newtable/',vw.newtable,name = 'newtable'), path('update/<int:pk>',vw.update,name = 'update'), path('delete/<int:pk>',vw.delete,name = 'delete'), path('new/',vw.new, name = 'newurl') ] models.py: class Table(models.Model): idd = models.AutoField(primary_key=True, default=None) name = models.CharField(max_length=100) date = models.DateField(auto_now_add=True) time = models.TimeField(auto_now_add=True) class Meta: verbose_name_plural = 'Tables' def __str__(self): return self.name class Transacao(models.Model): # Forein key defined here date = models.DateTimeField(auto_now_add=True) desc = models.CharField(max_length=200) value = models.DecimalField(max_digits=7, decimal_places=2) obs = models.TextField(null=True, blank=True) tableid = models.CharField(max_length=3) class Meta: verbose_name_plural = 'Transacoes' def __str__(self): return self.desc views.py: from .models import Table from … -
Django ajax How would I change my code to use ajax to like posts without refreshing
I'm trying to create a like button. Currently I have it so that user's can like/unlike a post on an article. However, whenever they press the button, the page resets and takes them back to the top. I want to use Ajax to fix this. These are my files. index.py <form action="{% url 'like-article-view' %}" method="POST" class="mb-1"> {% csrf_token %} <input type="hidden" name="article_id" value={{article.id}}> <button type="submit" class="ui primary button" name="{{article.id}}" id="like-unlike-btn"> {% if user not in article.liked.all%} Like {% else %} Unlike {% endif %} </button> view.py def like_unlike_post(request): user = request.user.id if request.method == 'POST': article_id = request.POST.get('article_id') article_obj = Article.objects.get(id=article_id) user_ = CustomUser.objects.get(id = user) if user_ in article_obj.liked.all(): article_obj.liked.remove(user_) else: article_obj.liked.add(user_) like, created = Like.objects.get_or_create(user=user_, article_id=article_id) if not created: if like.value=='Like': like.value='Unlike' else: like.value='Like' else: like.value='Like' article_obj.save() like.save() return redirect('index') urls.py (relevant urls) path('', views.indexView, name="index") path('liked/', views.like_unlike_post, name='like-article-view'), models.py (relevant models) class Article(models.Model): title = models.CharField(max_length=100) description = models.TextField() category = models.ForeignKey(Category, on_delete = models.CASCADE) liked = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='likes') LIKE_CHOICES = ( ('Like', 'Like'), ('Unlike', 'Unlike'), ) class Like(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) article = models.ForeignKey(Article, on_delete=models.CASCADE) value = models.CharField(choices=LIKE_CHOICES, max_length=8) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) How would I implement Ajax in this? I've … -
Django: query set, multiple filters. Can i set the order in which the WHERE clause is formed so that it will help me in indexing
I have the following query in django: end_date = timezone.now() start_date = end_date + timedelta(-5*365) queryset = ( DailyPriceHistory .objects .filter(symbol=symbol,datetime_utc__range=(start_date, end_date)) .order_by('datetime') .order_by('creation_time') .values_list('high','low','open','datetime','close','creation_time') ) the Sql it generates is SELECT `daily_price_history`.`high`, `daily_price_history`.`low`, `daily_price_history`.`open`, `daily_price_history`.`datetime`, `daily_price_history`.`close`, `daily_price_history`.`creation_time` FROM `daily_price_history` WHERE (`daily_price_history`.`datetime_utc` BETWEEN '2015-12-04 18:43:28.710229' AND '2020-12-02 18:43:28.710229' AND `daily_price_history`.`symbol` = 'A') ORDER BY `daily_price_history`.`creation_time` ASC Currently i have symbol and datatime as seperately indexed columns I found why the filter sequence is not followed. i.e .filter(symbol=symbol,datetime_utc__range=(start_date, end_date)) I wanted WHERE (`daily_price_history`.`symbol` = 'A' AND `daily_price_history`.`datetime_utc` BETWEEN '2015-12-04 18:43:28.710229' AND '2020-12-02 18:43:28.710229') but it uses WHERE (`daily_price_history`.`datetime_utc` BETWEEN '2015-12-04 18:43:28.710229' AND '2020-12-02 18:43:28.710229' AND `daily_price_history`.`symbol` = 'A') Also i dont see order_by('datetime') in the sql, is this because datetime is indexed -
DoesNotExist at /profile/1/ Profile matching query does not exist
My experience using Django is limited, but I hope I can explain my problem clearly. After successfully login to an application I am developing, I get re-directed to a user-page where I have different links. The error "DoesNotExist at /profile/1/ Profile matching query does not exist." occurs once I click on these links. My model looks like this. from django.db import models from numpy import array from django.db.models import F from django.contrib.auth.models import User from user.models import Profile class Data(models.Model): posted_by = models.ForeignKey(User, null=True, on_delete=models.CASCADE) profile = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True) Product = models.CharField(max_length=20, default="") item = models.CharField(max_length=20, null=True) quantity = models.IntegerField() price = models.IntegerField(default=0) total = models.IntegerField(editable=True,blank=True, null=True) date_created = date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return str(self.profile) def save(self, *args, **kwargs): self.total = self.price * self.quantity super().save(*args, **kwargs) @classmethod def get_projects(cls): projects = Data.objects.all() return projects @classmethod def find_projects(cls, search_term): project = Data.objects.filter(title__icontains=search_term) return project class Sales(models.Model): sales = models.IntegerField(default=0, blank=False, null=False) margin = models.IntegerField(editable=True, blank=True, null=True) user = models.ForeignKey(Profile,max_length= 20 ,null=False, on_delete=models.CASCADE, related_name='username') date_created = date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return str(self.user) def save(self, *args, **kwargs): self.margin = self.sales - Data.objects.get().total if self.sales > self.margin: self.margin = self.margin else: -self.margin return super().save( *args, **kwargs) UserModel is the … -
Pylint no value for argument phrase in method call
I am currently working on my first website, which is a dna to protein translator. What it does is you input a number of letters divisible by three and it gets translated into a protein if the chain exists. Anyways, this part of the code is working perfectly and I'd even say it looks super pythonic. Right now, I am now working on raising some error messages with the django messages. Here's the link to the document: https://docs.djangoproject.com/en/3.1/ref/contrib/messages/ What I want to do is, when you input a number of letters which isn't divisible by three, i call the message.error to tell that the chain isn't valid. Here's the code and the method call in case you need it: class TranslatorView(View): def build_protein(self, request, phrase): protein = [] i = 0 while i < len(phrase): codon = phrase[i: i + 3] amino = self.translate_amino(codon) if amino: protein.append(amino) else: print(f"The codon {codon} is not in self.mapper_1") i += 3 if len(phrase) % 3: messages.error(request, "INVALID DNA CHAIN") return protein def get(self, request, *args, **kwargs): return render(request, 'main/translator.html') def post(self, request, *args, **kwargs): phrase = request.POST.get('text', 'translation') protein = request.POST.get('text','protein') return render(request, self.template_name, {'translation': self.translate(phrase), 'protein': ", ".join(self.build_protein(protein))}) However, this pylint error … -
Trouble pushing heroku master (django - conda)
for my django app to heroku. I followed a blog steps religiously but am encountering the below error related to anaconda requirement. Then i tried https://github.com/heroku-python/conda-buildpack, but that didn't work either. Where am i going wrong? What shall be done? anaconda requirement not able -
Generalize API declaration for multiple models
In the process of developing a JWT application with Django I noticed the declaration pattern of the CRUD API View, such as: class Create(generics.CreateAPIView): queryset = <some django model>.objects.all() serializer_class = serializer # <some serializer class> class Read(generics.ListAPIView): queryset = <some django model>.objects.all() serializer_class = serializer # <some serializer class> class Update(generics.RetrieveUpdateAPIView): queryset = <some django model>.objects.all() serializer_class = serializer # <some serializer class> class Delete(generics.DestroyAPIView): queryset = <some django model>.objects.all() serializer_class = serializer # <some serializer class> Considering that my specific project has 7 models that have to have these functionalities, instead of declaring 28 versions of the above classes, I think it would be more elegant if there were a class such as: class Create(generics.CreateAPIView): def __init__(self, model, serializer): self.queryset = model.objects.all() self.serializer_class = serializer super().__init__() class Read(generics.ListAPIView): def __init__(self, model, serializer): self.queryset = model.objects.all() self.serializer_class = serializer super().__init__() class Update(generics.RetrieveUpdateAPIView): def __init__(self, model, serializer): self.queryset = model.objects.all() self.serializer_class = serializer super().__init__() class Delete(generics.DestroyAPIView): def __init__(self, model, serializer): self.queryset = model.objects.all() self.serializer_class = serializer super().__init__() class CRUD: """Base class for CRUD Operations""" def __init__(self, model, serializer): self.create = Create(model, serializer) self.read = Read(model, serializer) self.update = Update(model, serializer) self.delete = Delete(model, serializer) That is followed by those instaciations: … -
Django: ModelMultipleChoiceField is applying underlying model's max_length validator to total length of selected results
I'm using a ModelMultipleChoiceField to allow users to select certain model objects to delete. It works fine when a single object is selected, but when multiple objects are selected then a validation error is triggered: "Ensure this value has at most 50 characters". The 50 character limit is from the underlying model's max_length attribute. I'm not sure why this validation is happening at all since I am selecting existing model objects, and even less sure why they are combining the character lengths of all my selections instead of validating each selection individually. I've also noticed that they are counting approximately 20 extra characters for each object selected when totalling the character length. Any help is appreciated. Here is my code: Model: class Template(models.Model): # Relationships user = models.ForeignKey("users.CustomUser", on_delete=models.CASCADE) # Fields name = models.CharField(max_length=50) description = models.TextField(max_length=250) docx_file = models.FileField(("DOCX File"), upload_to=user_directory_path, validators=[FileExtensionValidator(allowed_extensions=['docx'])]) created = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True, editable=False) def __str__(self): return self.name Form: class TemplateChoiceDelete(forms.ModelForm): name = forms.ModelMultipleChoiceField(queryset=Template.objects.all()) class Meta: model = Template fields = ['name'] # Limit results to templates owned by the current user def __init__(self, *args, **kwargs): user = kwargs.pop('user') super(TemplateChoiceDelete, self).__init__(*args, **kwargs) self.fields['name'].queryset = Template.objects.filter(user=user) View: (ignore the filter code, that is a … -
Django catch missing manifest exceptions
Every now and then I end up with a missing file after deploy a django project, and I find it one of the hardest issues to debug because I get no logging and no error email, its just dead. I have made a custom 500 error page (followed this answer). Is it possible to show the details of which static file is missing on it? With this error Django fails before rendering a 500 page. Heres a traceback of the error: Traceback (most recent call last): File "/usr/lib/python3.8/wsgiref/handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "/home/user/venv/project/lib/python3.8/site-packages/django/core/handlers/wsgi.py", line 133, in __call__ response = self.get_response(request) File "/home/user/venv/project/lib/python3.8/site-packages/django/core/handlers/base.py", line 75, in get_response response = self._middleware_chain(request) File "/home/user/venv/project/lib/python3.8/site-packages/django/core/handlers/exception.py", line 36, in inner response = response_for_exception(request, exc) File "/home/user/venv/project/lib/python3.8/site-packages/django/core/handlers/exception.py", line 90, in response_for_exception response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) File "/home/user/venv/project/lib/python3.8/site-packages/django/core/handlers/exception.py", line 129, in handle_uncaught_exception return callback(request, **param_dict) File "/home/user/project/src/core/base/views.py", line 236, in error_500_view response = render(request, "core.base/500.html", context=context) File "/home/user/venv/project/lib/python3.8/site-packages/django/shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "/home/user/venv/project/lib/python3.8/site-packages/django/template/loader.py", line 62, in render_to_string return template.render(context, request) File "/home/user/venv/project/lib/python3.8/site-packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "/home/user/venv/project/lib/python3.8/site-packages/django/template/base.py", line 171, in render return self._render(context) File "/home/user/venv/project/lib/python3.8/site-packages/django/test/utils.py", line 95, in instrumented_test_render return self.nodelist.render(context) … -
Django Channels: Data Going to the Wrong Socket
I am facing the same issue although the as_asgi method is called in my routing. The data are always sent to the second socket. Channels v3.0 and Django V3.1.2 is in use. routing.py websocket_urlpatterns = [ re_path(WS_PREFIX + r'room/(?P<room_name>\w+)/$', RoomConsumer().as_asgi()), ] asgi.py import routing django_asgi_app = get_asgi_application() application = ProtocolTypeRouter({ "http": get_asgi_application(), # Just HTTP for now. (We can add other protocols later.) "websocket": AuthMiddlewareStack( URLRouter( routing.websocket_urlpatterns ) ), }) Local server logs: WebSocket HANDSHAKING /ws/room/2/ [127.0.0.1:63280] WebSocket CONNECT /ws/room/2/ [127.0.0.1:63280] WebSocket HANDSHAKING /ws/room/1/ [127.0.0.1:63288] WebSocket CONNECT /ws/room/1/ [127.0.0.1:63288] consumer.py: import json from channels.generic.websocket import AsyncWebsocketConsumer class RoomConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'room_%s' % self.room_name # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from WebSocket async def receive(self, text_data): text_data_json = json.loads(text_data) # Send message to room group await self.channel_layer.group_send( self.room_group_name, { 'type': 'send_data', 'message': "Message received" } ) # Receive message from room group async def send_data(self, event): # Send message to WebSocket await self.send(text_data=json.dumps(event)) This is how I send data: result['type'] = 'send_data' result['test'] = 'test' layer = get_channel_layer() async_to_sync(layer.group_send)('room_2', result) return HttpResponse(status=202) Is there … -
Multiple APIView Classes in a view.py in django rest-framework
Can we have multiple APIView Classes for different html pages in a view file in Django rest-framework? For example: views.py from rest_framework.views import APIView from rest_framework.response import Response class ABC(APIView): //methods class XYZ(APIView): //methods -
How to use radiobutton value in JS in 'for in if' Django condition?
I start using Chart.js graphic in my Django app. I start from sample line graphic https://jsfiddle.net/mdt86/219hry2s/9/. I have added radio button to be able to switch line graphic based on radio button value. I pass a list in my template (get_data_context) and do a foor loop to get data used in the labels and datastes.data as value for Chart line graphic. But I not able too pass selected country value from radio button in my for loop like this : $("#country").on('click', function () { var selected_country = $('input[name="country"]:checked').val(); }); var libelle1 = [{% for item in qs %}{% if item.country == selected_country %}'{{ item.month }}',{% endif %}{% endfor %}]; I understand django is server side and JS client side Do I need to use an ajax query?