Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do you edit a many to many field in Django during save?
I currently have a model that looks like this class Sector(): featured_companies = models.ManyToManyField('Company', related_name='sectors') def save(self, **kwargs): super(Sector, self).save(**kwargs) for company in self.featured_companies.all(): company.is_active = True company.save() I know that this doesn't work because of the way Django works on save. I read in another post that adding something like this to the admin should work: def save_model(self, request, obj, form, change): if obj.featured_companies: form.cleaned_data['featured_companies'] = obj.featured_companies.all() super(SectorAdmin, self).save_model(request, obj, form, change) However, it is still not working. How would I accomplish editing the many to many field during the save process? -
How to pin posts in django?
So i want to know how to pin posts in django. When i click on check, and click create post, it should pin the post to the top. And newer posts will just appear bottom, without interfering with the pinned post. The pin system should also be able to pin multiple posts. So if i pin another post, both posts should stay at the top. The other not pinned posts should just appear below. models.py class AskSection(models.Model): title = models.CharField(max_length=100) description = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE) is_pin = models.BooleanField() likes = models.ManyToManyField(User, related_name='likes', blank=True) is_marked = models.BooleanField(default=False) date_posted = models.DateTimeField(default=timezone.now) class Meta: ordering = ['-date_posted'] verbose_name_plural = "Ask Section" def __str__(self): return str(self.title) forms.py class AskSectionCreateForm(forms.ModelForm): is_pin = forms.BooleanField(label="pin ask post", required=False) class Meta: model = AskSection fields = ('title', 'description', 'is_pin') widgets = { 'title': forms.TextInput(attrs={ 'class': 'form-control' }), 'description': forms.Textarea(attrs={ 'class': 'form-control' }), } views.py @login_required def create_ask_post(request): if request.method == "POST": form = AskSectionCreateForm(request.POST or None) if form.is_valid(): title = form.cleaned_data.get('title') description = form.cleaned_data.get('description') is_pin = form.cleaned_data.get('is_pin') obj = form.save(commit=False) obj.title = title obj.description = description obj.is_pin = is_pin obj.user = request.user obj.save() messages.success(request, f'You have posted {title} successfully') return redirect('/details_ask/' + str(title) + '/') else: … -
More efficient database query in django with python
I'm quite new to django and searching for a database query / filter to receive an object stored in a dictionary and belonging to a known primary key. My approach is found below. Even though it works I don't want to crawl the whole dict / database, there must be a more efficient way. my_class_objects_dict = { "class_1": ClassOne.objects.all().order_by("index"), "class_2": ClassTwo.objects.all().order_by("index"), "class_3": ClassThree.objects.all().order_by("index"), "class_4": ClassFour.objects.all().order_by("index"), } def get_my_class_objects_dict_value(pk): for key in my_class_objects_dict: if value.count() > 0: value = my_class_objects_dict[key].all().filter(pk=pk) return value.get() def get_my_class_objects_dict_key(model_class): if model_class == ClassOne: return ("class_1",) if model_class == ClassTwo: return ("class_2",) if model_class == ClassThree: return ("class_3",) if model_class == ClassFour: return ("class_4",) return None def reorder_objects(pk_list): for pk in pk_list: value = my_class_objects_dict(pk) value.index = new_index model_class = eval(value.__class__.__name__) value.save() new_index += 1 my_class_objects_dict_key = get_order_menu_dict_key(model_class) update_dict = {my_class_objects_dict_key: model_class.objects.all().order_by("index")} my_class_objects_dict.update(update_dict) -
'NoneType' object has no attribute 'user' ERROR DJANGO
it's this error that I don't understand , and i don't understand why i can't use user attribute off request and POST attribute urls.py from django.urls import path from . import views urlpatterns = [ path('', views.connect,name='connect'), views.py from django.shortcuts import render from .models import * from .form import * from django.contrib.auth.models import User from django.contrib.auth import logout from django.contrib.auth import authenticate, login def connect(request): if request.user.is_authenticated == True: test=True form = connect(request.POST or None) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(request, username=username, password=password) if user == None: return render(request,'etudiant/home.html',locals()) else: parent = Parent.objects.get(personne=user) admin = Administrateur.objects.get(personne=user) if parent != None: par=True if admin != None: ad=True return render(request, 'etudiant/home.html', locals()) -
How to assure that the model only creates an instance only if another already exist
In the model I need to prevent orphan terms (synonyms or related of the preferred term) from being created using the same identifier code. For now I have the following: from django.utils.translation import gettext_lazy as _ from django.db import models class TopographyCodes(models.Model): code = models.CharField( max_length=5, primary_key=True, ) class TopographyFourCharactersDescription(models.Model): code = models.ForeignKey( 'TopographyCodes', on_delete=models.CASCADE, ) term = models.CharField(max_length=200) class TermType(models.IntegerChoices): PREFERRED = 1, _('Preferred term') SYNONYM = 2, _('Synonym') RELATED = 3, _('Related or equivalent') term_type = models.IntegerField( max_lenght=1, choices=TermType.choices, default=TermType.PREFERRED, ) def is_preferred(self): return self.type in { self.TermType.PREFERRED, } class Meta: constraints = [ # We only support one preferred description per code models.UniqueConstraint( fields=['code'], condition=Q(term_type=1), name='unique_preferred_code'), ] Now, if a is_main returns true (or would return true) the new term should be allowed to be created. I'm using a formset for editing this model, which presumes that it's created, but I would like the model to guarantee that no term would exist if there's no entry with the same code but preferred. The database already have these kinds of problems and I would like to prevent them from occurring. -
How to save radio button value made in html to model in django
I have made an html form which takes a radio option asking the person's gender. Now, I want to save the option the person choose in the model. Please help! -
Is it mandatory to use serializer in Django viewset?
I am using viewsets in Django rest framework. I have seen many examples that serializer is being used every where. What if I don't want to use serializer, or what if I don't have a Model to use serializer? And I just want to return simple response data? Below is just an example of how I am using it. from rest_framework.response import Response from rest_framework import status, viewsets class UserViewSet(viewsets.ViewSet): def create(self, request): data = {'name': 'Shiv', 'email':'example@gmail.com'} return Response(data, status=status.HTTP_201_CREATED) As you can see, I don't have a serializer and the code works perfectly fine. So is this a good practice? I posted the same question in Code Review portal but not getting enough response. Need to clarify urgently. -
Is there a best practice to create a Django query with extensible filters?
Suppose I have a "find invoice page" where users can input (or not) different fields in order to search for invoices to display them in a list. Suppose this list of fields might grow over time with additional db fields. My current (working) solution is the following but I'm wondering if there is a better way to allow possible additional fields and adapt the query accordingly. query.py [custom query composer] from .models import Invoice class FindQuery: def __init__(self): self.filters = {} self.fq_sql = '' self.fq_select = 'SELECT * ' self.fq_from = 'FROM invoice_invoice ' self.fq_where = 'WHERE 1=1 ' self.fq_order = ' ORDER BY iv_created_at DESC' def set_filters(self, user, year, client): if user: self.filters['request_user'] = user if year: self.filters['selected_year'] = year if client: self.filters['selected_client'] = client # adding here new fields def apply_filter(self): if 'request_user' in self.filters: self.fq_where += ' AND iv_created_by = ' + str(self.filters.get('request_user')) if 'selected_year' in self.filters: self.fq_where += ' AND iv_year = ' + str(self.filters.get('selected_year')) if 'selected_client' in self.filters: self.fq_where += ' AND iv_client = ' + str(self.filters.get('selected_client')) # adding here new fields self.fq_sql = self.fq_select + self.fq_from + self.fq_where + self.fq_order return Invoice.objects.raw(self.fq_sql) views.py (Django Rest Framework) from .query import FindQuery class InvoiceViewSet(viewsets.ModelViewSet): serializer_class = … -
How can I sort that dictionnary with the attribute of a Django object?
I have two dictionnaries like that : a = {'id_1': ob1, 'id_2': ob2} b = {'id_1': 'test1', 'id_2', 'test2'} and ob1, ob2 are Django object with two properties : name and country And I would like to sort the dict b according the property name. I thought to sorted obviously but it does not work ... Could you help me please ? Thank you very much ! -
Wagtail Streamblock Template Rendering
I'm trying to create a block that allows me to add multiple blocks, where each is a different size in a size estimator. class SizeItem(blocks.StructBlock): name = blocks.CharBlock(required=True) image = ImageChooserBlock(required=True) description = blocks.TextBlock(required=True) class Meta: #noqa icon = 'arrows-up-down' label = 'Size Estimator Item' class SizeEstimator(blocks.StructBlock): description = blocks.TextBlock(required=False) size_items = blocks.StreamBlock([ ('size_item', SizeItem()) ], required=False) class Meta: #noqa template = 'streams/size_estimator.html' icon = 'list-ul' label = 'Size Estimator' The issue is that I need the names, images, and descriptions all groupped within different areas of the SizeEstimator template: <div> <div> <ul> <li>names</li> </ul> </div> <div> <div> images </div> </div> <div> descritions </div> </div> so I can't use a template on the SizeItem because there is no way to separate the pieces in the SizeEstimator template. But if I try: <div class="se-wrap flexy"> <div class="se-sizes"> {% for item in self.size_items %} <div class="se-size-btn"> {{item}} </div> {% endfor %} </div> </div> I get plain text back with each SizeItem attribute name and value. I can't just pull the values like item.name because the output is blank. What is a good way to add orderable blocks to another block where you can piece out the contents of the oderable blocks? -
Refund email with image attachment
I'm making an Api view for a Refund so when the form is filled an email get sent to the admin email with some data including an image as an attachment. I was testing my code that is included below and i am getting an error that Exception Type: AttributeError at /api/skjema/ Exception Value: 'Refund' object has no attribute 'splitlines' and when i removed the r from the ms on EmailMessage and replaced it with a string i got the email with the image and the string which probably means i have something right in my code. If someone can help me fixing the splitlines problem that would be realy appreciated. models.py from datetime import datetime class Refund(models.Model): name = models.CharField(max_length=200) email = models.CharField(max_length=100) address = models.CharField(max_length=200) subject = models.CharField(max_length=100, default = "Refund") amount = models.CharField(max_length=10) date = models.DateField() message = models.TextField(max_length=500) image = models.ImageField(upload_to='photos/%Y/%m/%d/') contact_date = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.email views.py from rest_framework.views import APIView from rest_framework.response import Response from django.core.mail import EmailMessage from email.mime.image import MIMEImage from .models import Refund class Refund(APIView): permission_classes = [permissions.IsAuthenticated] def post(self, request, format=None): data = self.request.data r = Refund(name= request.POST['name'],email=request.POST['email'],address=request.POST['address'], date=request.POST['date'],message =request.POST['message'],amount =request.POST['amount'],image = request.FILES['image']) msg = EmailMessage('Refund',r ,'user@gmail.com',['admin@gmail.com'],headers={'Message-ID': 'foo'}) … -
How to update a many to many field in Django using the Signals
I have two models: class Website(models.Model): url = models.URLField() users = models.ManyToManyField(User) def __str__(self): return str(self.url) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(null=True, blank=True) def __str__(self): return str(self.user.username) This is the signal I've tried to complete: @receiver(m2m_changed, sender=Website.users.through) def update_bio_when_websites_updated(sender, instance, action, reverse, **kwargs): pass I need to create a signal to update the bio of the user when It's websites modified or updated. But I don't have any idea. How is it possible? -
add one point every time button gets clicked
I am using django and I have this model: class Story(models.Model): title = models.CharField(max_length=200) slug = AutoSlugField(populate_from='title', unique_with='pub_date__month') body = models.TextField(blank=True) pub_date = models.DateTimeField(auto_now_add=True) type_of_story = models.CharField(max_length=20, choices=TYPES, default='dream') points = models.IntegerField(default=0) I want every time user clicks the upvote button, add one the points field, and user click another downvote button to subtract one from points. -
Using jquery autocomplete with django to select an option
this is my first post on Stackoverflow because I cannot find the answer to my issue anywhere. It may be simple but I am really confused. I successfully have implemented jquery autocomplete to show results when I search. Now I have no idea how to choose/select an option from the choices? My code is essentially the same as this. So basically my question is just how do I select one of the choices that shows up when I click? Thanks in advance and sorry if this is a basic question, I just can't find a video or thread anywhere. -
Validate a CSV file if any any errors show the errors else create the records in database in django
tasks.py def upload_deatils(client, user1, csv_file): field_map_1 = { 'Date' : 'date', 'Employee Number': 'employee_number', 'Assignment id': 'assignment', 'Rate': 'work_assign', } def get_values_remapped(row): return {field_map_1[key]: row[key].strip() for key in field_map_1} reader = csv.DictReader(csv_file,encoding='utf-8', errors='ignore') try: number = int(UploadTimesheet.objects.filter(client=client).\ order_by('-id')[0].order_number) order_number = number + 1 except: order_number = 1 error_rows = [] errors = OrderedDict([]) count = 0 messages = [] field_errors = [] duplicates = 0 try: with transaction.atomic(): for line_number, row in enumerate(reader): try: remapped_row = get_values_remapped(row) try: employee_number = ClientUser.objects.filter(employee_number__iexact=remapped_row['employee_number'],client=client).first() remapped_row['employee_number'] = employee_number.employee_number except: errors.update({line_number + 2 : 'Employee Number' + ' ' + remapped_row['employee_number'] + ' does not exists'}) try: date = row['Date'] except: errors.update({line_number +2 : 'Date is not in required format'}) try: rate_name = row['Rate'] except: errors.update({line_number+2 : 'Rate' + ' ' + remapped_row['rate'] + ' does not exists'}) assignment_id = row['Assignment id'] print("ASSIGNMENT ID OF ROW 1",assignment_id) if assignment_id: try: aasignments = Assignments.objects.get(client=client,assignment_id=assignment_id) except BaseException as e: logger.exception(e) messages.append({'error': 'Column "%s" not found.' % e.args[0]}) errors.update({line_number + 2 : 'Assignemnt with this' + ' ' + row['Assignment id'] + ' does not exists'}) else: errors.update({line_number + 2 : 'Assignment id is required'}) if aasignments: try: assignment_rates = AssignmentsRates.objects.get(assignment__client=client,assignment_id=aasignments.id,name__iexact=rate_name) except BaseException as e: logger.exception(e) messages.append({'error': 'Column … -
Messages not getting to consumer unless Heroku dyno count is scaled way up
We have built a front-end with React and a back-end with Django Rest Frameworks and channels. We are using Heroku Redis as our Redis provider. Our users connect to Channels via a ReconnectingWebSocket. We are using Python 3.6 and Channels 2.4 The issue is that our API calls are attempting to pass info to the sockets and they're not always making it to the consumer. I logged the steps of the call out via prints, printed the channel_name it's about to attempt to send it to and confirm it's what was returned to the user on connect, but the prints in the consumer don't get called and therefore the signal never sent to the user. If I increase the number dynos to more or less a 1-1 with the users connected to sockets then it seems to solve the problem (or at least makes it much more reliable). From my understanding, 1 dyno should be able to handle many socket connections. Is there a reason that my consumer is not receiving the signals? Is there a reason scaling up the number of dynos resolved the problem? On connect, I have the user join a group called "u_{their id}" to allow … -
Favicon not displaying when deployed
I have deployed a Django website on Pythonanywhere. The favicon worked on my local server but not on my Pythonanywhere site. The code in my base.html is <link rel="stylesheet" type="text/css" href="{% static 'fixtureapp/style.css' %}"> <link href="{% static 'images/scc.ico?' %}" rel="icon" type="image/x-icon" /> I've shown the stylesheet link as this is working so static is set up ok. iamges/scc.ico is in the same static file. I get the error 2021-03-10 14:52:43,422: Not Found: /favicon.ico -
How to restrict users logged in via Saml in Django
I have developed a website using Django and integrated saml sso. So whoever login to "https://testing.com/saml2.login" , they will redirected to saml2 , verified and request will be sent to "https://testing.com/home". However, I want to restrict only allowed users should be shown the webpage. Note: I can do this via Django admin's users, groups. But this login is happening via saml sso. Could you please suggest me a way on how to achieve it ? Thanks in advance. Flow diagram -
multiple delete in in genericview
I have a template in my django app that displays several checkboxes. When some of these are checked I want to delete the entries. Normaly I pass the key to the generic function to delete one. But I don't know how to pass several selected keys, any idea? views.py: class PDelete(DeleteView): template_name='kammem/delete.html' model=Person success_url=reverse_lazy('pe path('pdelete/<int:pk>/',DeleteView.as_view(model=Person,\ success_url=reverse_lazy('personer'),template_name='kammem/delete.html')), rsoner') def get_context_data(self,**kwargs): mod=self.request.kwargs['model'] context=super().get_context_data(**kwargs) context['model']=self.kwargs['model'] return mod persl.html: (there is a {% for l in pl %} but it can't be displayed correctly) <tr> <td><div class="form-check"> <input class="form-check-input" type="checkbox "value="" id="checked"> <label class="form-check-label" for="checked"> </label> </div> </div> </td> <td><a href="pupdate/{{l.pk}}"><i class="bi bi-pencil-square"></i></a></td> <td><a href="pdelete/{{l.pk}}"><i class="bi bi-trash"></i></a></td> <td>{{l.pk}}</td> <td><a href="detail/{{l.padress.pk}}">{{l.fname}}</a></td> <td>{{l.lname}}</td> <td>{{l.mobil}}</td> <td>{{l.mail}}</td> <td>{{l.padress}}</td> </tr> ursl.py path('pdelete/<int:pk>/',DeleteView.as_view(model=Person,\ success_url=reverse_lazy('personer'),template_name='kammem/delete.html')), -
How to return value to view after select item from dropdown list in django
`def store_list(request): displaystores=stores.objects.all() if request.POST: store_pk_list = request.POST.getlist('stores', None) print(request.POST.getlist('stores.unit_key', None)) selected_store_obj_list = stores.objects.filter(pk__in=store_pk_list) print(selected_store_obj_list) return render(request,'storelist.html',{'stores':displaystores}) -
How to pass pass/reference a dictionary in a request
I have made an API call with the function below that I am testing on Postman. It takes in an id(dictionary) and deletes the doctor with that id. So the solution works as it is.Problem is , the id is hard coded - id = {"id": 11} .How do I reference it so that I can feed it in postman instead of hard coding? I have tried using id = request.GET.get("id") and adding it as a parameter but it didn't work for me.Any assistance will be highly appreciated Views.py class DoctorBillingPayments(GenericAPIView): authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] @classmethod @encryption_check def delete(self, request, *args, **kwargs): id = {"id": 11} try: result = {} auth = cc_authenticate() res = deleteDoctor(auth["key"],id) result = res return Response(result, status=status.HTTP_200_OK) except Exception as e: error = getattr(e, "message", repr(e)) result["errors"] = error result["status"] = "error" return Response(result, status=status.HTTP_400_BAD_REQUEST) api_service.py def deleteDoctor(auth, data): try: headers = { "Authorization": f'Token {auth}' } url = f'{CC_URL}/doctors/' print(url) res = requests.delete(url, json=data, headers=headers) return res.json() except ConnectionError as err: print("connection exception occurred") print(err) return err -
Can't access js file in Amazon S3
I have a website running on Django. Trying to measure its performance with Django-Debug-Toolbar. I have installed it properly, run collectstatic and the script is now in my static folder in Amazon S3 bucket. When I reload the website, I don't see the panel triggered. Looking at console tells me GET https://hull2hull-bucket.s3.amazonaws.com/debug_toolbar/js/utils.js net::ERR_ABORTED 403 (Forbidden) My S3 bucket is private, but Django obviously has access to it. Some other javascripts in static folder are running fine, but not this one. I have even tried to make the whole bucket public for a while, but I was still getting 403. I've added my localhost to CORS. What's wrong with my setup? Amazon documentation is vast, but not very helpful here. -
How to add a new dependency in requirements.txt file?
I cloned a djangox repo to my local device I founded a requirements.txt file that contains some dependencies I wanna add a rest framework ( adding a new dependency ) to this file how could I do that, please ?! p.s: I usually use poetry that deals with pyproject.tomal but for using docker, I wanna use this one. -
How to pass a variable from python file to html file in django?
I want to show a variable value in webpage from the ml model connected by django -
null value in column "comment_id" of relation "blog_comment" violates not-null constraint
When attempting to create an application for comments in my Django blog, I get the "null value in column "comment_id" of relation "blog_comment" violates not-null constraint" error listed above. For the view of the page, I am using a Detail View with a FormMixin. I am not sure why I am getting this error. Any assistance is appreciated. The full error message IntegrityError at /post/7/ null value in column "comment_id" of relation "blog_comment" violates not-null constraint DETAIL: Failing row contains (6, dafsdfa, sdfasdfasdf, sdfadfa, 2021-03-10 15:03:11.283567+00, null). views.py class DetailPostView(FormMixin, DetailView): model = Post template_name = "blog/post_detail.html" context_object_name = "posts" form_class = CommentForm def form_valid(self, form): form.save() return super().form_valid(form) def post(self, request, *args, **kwargs): form = self.get_form() self.object = self.get_object() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def get_success_url(self): return reverse("post-detail", kwargs={"pk": self.object.pk}) Models.py class Comment(models.Model): comment = models.ForeignKey(Post, on_delete=models.CASCADE) title = models.CharField(max_length=200) content = models.TextField() author = models.CharField(max_length=50) created_on = models.DateTimeField(auto_now_add=True) Forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment labels = {"author": "Author", "title": "Title", "content": "Comment"} fields = ["author", "title", "content"]