Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trying to create a cronjob in django using faust
I'm trying to create a cronjob in django using faust. If I create a simple cronjob printing somethin' on screen it works, but if I try to use some ORM thing it doesn't. @sync_to_async def get_products(): return Product.objects.filter(active=True) @app.crontab('* * * * *') async def run_very_minute(): product = await get_products() print(product) I also tried to do like this: @app.crontab('* * * * *') async def run_very_minute(): products = await sync_to_async(list)(Product.objects.filter(active=True)) print(product) -
how to accept all the answers from form?
this is my form in which i am conducting a quiz <form action="test" method="post"> {% csrf_token %} {% for question in questions %} {{question.question}} <input type="radio" id="1" name="{{question.qno}}" value="1">:{{question.option1}}<br> <input type="radio" id="2" name="{{question.qno}}" value="2">:{{question.option2}}<br> <input type="radio" id="3" name="{{question.qno}}" value="3">:{{question.option3}}<br> <input type="radio" id="4" name="{{question.qno}}" value="4">:{{question.option4}}<br> {% endfor %} <input type="submit" value="submit"> </form> there are multiple questions generated on the screen as per my database. I have to accept all the values and pass it to my views.py for further processing how to do so? -
Returning GraphQL object in Django Saleor
In Django Saleor, what is right way to get the GraphQL objects from the API. For example if I wanted to retrieve the shippingMethods, I am running: { shippingMethods { name } } The error I get is: Cannot query field "shippingMethods" on type "Query" Link to API Doc: https://docs.saleor.io/docs/api-reference#shippingmethod Any help is appreciated -
How do i specify a queryset to a django form widget in a generic UpdateView
My model : class TarifGe(models.Model): mise_a_disposition = models.ForeignKey(MiseADisposition) tarif_son = models.ForeignKey("TarifGe", on_delete=models.CASCADE, null=True, default=None, blank=True) My View : class TarifGeUpdate(LoginRequiredMixin, UpdateView): model = TarifGe template_name = "tarifs_form.html" fields = ['tarif_son',] tarif_fils is a TarifGe related object (father -> Son) I would like to filter the initial values of the widget of de tarif_son field, to only have TarifGe objects that have the same mise_a_disposition field, instead of all the TarifGe objects. Where and how can i specify the queryset for the "tarif_son" field's widget ? Thanks in advance for your help. -
Django can't search "method not allowed"
im new to django and im currently doing a website for my friend. he wants me to make a system where the users can search the database and the website gives the relevent items according to their serial number. i followed a tutorial from the following site: https://learndjango.com/tutorials/django-search-tutorial to figure out how to do db searchs which helped a lot, but im still having a problem: my search bar works, and the result page also works but it only works when i manually type the query on the searchbar myself (e.x. results/?q=number1). However when i search using the input bar and the submit button it sends me to /results/ page and the page gives this: This page isn’t working If the problem continues, contact the site owner. HTTP ERROR 405 -when i open up pycharm to see the error in terminal it says: Method Not Allowed (POST): /result/ Method Not Allowed: /result/ [27/Oct/2020 20:06:02] "POST /result/ HTTP/1.1" 405 0 here are my codes(python3.7,pycharm) websites/urls: from . import views from django.urls import path from django.contrib.auth import views as auth_views urlpatterns = [ path('register/',views.UserFormView.as_view(), name='register'), path('login/', auth_views.LoginView.as_view(), name='login'), path('', views.IndexViews.as_view(), name='index'), path('scan/', views.ScanView.as_view(), name='scan'), path('result/', views.SearchResultsView.as_view(), name='result'), ] websites/views: class IndexViews(generic.ListView): template_name … -
How to implemment Datatable server-sided smart searching
How do i use Datatable smart searching on a server-sided table. I'm using a server-sided Datatable table on my website with ~3500 entries, it loaded very slowly on mobile devices so i went server-sided processing on the table. Once i got the table to be server-sided using django-rest-framework i lost the datatable ability to smart search. I already did a search on datatable's forums but with no luck at all. JS code: <script> $(document).ready(function() { var table = $('#bibs').DataTable({ "serverSide": true, "ajax": "/api/livros/?format=datatables", "columnDefs": [ { "targets": [0,1,2,3,4,5], // "visible": false, "searchable": true, "orderable": true, } ], "columns": [ { "className": 'details-control', "orderable": false, "data": null, "defaultContent": '', "render": function () { return '<i class="fa fa-plus-square" aria-hidden="true"></i>'; }, width:"25px" }, {"data": "autor"}, {"data": "ano"}, {"data": "titulo"}, {"data": "referencia"}, {"data": "tema"}, {"data": "tipo"}, ], "dom":'<"toolbar">Brtip', }); </script> -
Django: generate pdf file from a formset view
I have a model formset where the user input input information. I am trying to make possible for the user to download a pdf file where the data inputed in being rendered. Here is what my formset view look like: def New_Sales(request): #context = {} form = modelformset_factory(historical_recent_data, fields=('id','Id', 'Date','Quantity', 'NetAmount', 'customer_name')) if request.method == 'GET': formset = form(queryset= historical_recent_data.objects.none()) #blank_form = formset.empty_form elif request.method == 'POST': formset = form(request.POST) #blank_form = formset.empty_form if formset.is_valid(): request.session['sale'] = request.POST['sale'] for check_form in formset: check_form.save() quantity = check_form.cleaned_data.get('Quantity') id = check_form.cleaned_data.get('Id') update = replenishment.objects.filter(Id = id).update(StockOnHand = F('StockOnHand') - quantity) update2 = Item2.objects.filter(reference = id).update(stock_reel = F('stock_reel') - quantity) return redirect('/dash2.html') #else: #form = form(queryset= historical_recent_data.objects.none()) return render(request, 'new_sale.html', {'formset':formset}) and here is what my pdf_generator view looks like: def get_pdf_invoice(request): pdf = render_to_pdf('pdf/invoice_generator.html', request.session.get('sale')) if pdf: response = HttpResponse(pdf, content_type='application/pdf') filename = "Melt_Invoice_{}.pdf".format(request.session.get('sale').get('customer_name')) content = "inline; filename={}".format(filename) content = "attachment; filename={}".format(filename) response['Content-Disposition'] = content return response return HttpResponse("Not found") and here is what i try to render as template with the pdf format: {% load static %} <!DOCTYPE html> <html> <head> <style> table { width:100%; } table, th, td { border: 1px solid black; border-collapse: collapse; } th, td { padding: … -
Best way to integrate OpenId connect / (Keycloak) with Django and Django Rest framework
I'm looking for advice on the best way to integrate Django / Django Rest Framework with OpenId connect (we're using Keycloak but I think using the protocol is probably more flexible). There seems to be several option out there, but it would be good to have something that works as seamlessly as possible with Django and DRF – so session and API authentication working like the baked in Django version, and ideally access to external logon screens if using admin/DRF API endpoint. What is straightforward to set up and well supported? What I will ultimately be doing is trying to change an existing Django/React application, but for the purposes of this discussion let's assume it's a basic application something like the ones set up in the Django tutorial and Django Rest framework quickstart (https://docs.djangoproject.com/en/3.1/intro/tutorial01/ to tutorial01 and https://www.django-rest-framework.org/tutorial/quickstart/). I hope that's enough as I fairly new to this – I can create some sort of simple application in Github if this isn't a clear enough basis for a discussion. Any help would be much appreciated. Even better if you have an example (!). -
Customizing unit choices in a django-measurement form
I am quite new to Django and looking for a package that helps handling units in a Django app. Django-measurements seemed like a good starting point for me and I tried to modify the units displayed in the dropdown of a form as shown in the documentation: # my_app/forms.py from measurement.measures import Volume from django_measurement.models import MeasurementField class BeerForm(forms.Form): volume = MeasurementField( measurement=Volume, unit_choices=(("l","l"), ("oz","oz")), ) However when playing with this form in the django shell, it seems there are no fields: from my_app.forms import BeerForm b = BeerForm() b.fields >> {} b.as_table() >> '' Am I missing something here? Any advice welcome, thanks! django = "~=3.1.0" django-measurement = "==3.2.3" python_version = "3.8" -
Django: Trying to render and update a second formset within a view
I have one view, let's call it UpdateFruit. That view renders a formset which allows one to update a specific piece of fruits attributes. In the same view, there is a button to open a modal within which the piece of fruit has a list of fruit Observations that iterates out as a list of observations and can theoretically be added to via a form. I have inherited code that built the observations form using Django formsets and I want to be able to make a POST to the view to update the database. I have never used django forms before, and I'm trying to understand how I can make this post without ajax and differentiate it from the post to the UpdateFruit view that already exists from the other formset. To start, this is how I intend to post the form... <form id="form-container" action="{% url 'update-fruit' fruit.id %}" method="POST"> How do I post it to a specific method other than post? Can I do this something akin to: path('update-fruit/<pk>', views.UpdateFruit.as_view(), name='update-fruit'), -
Django app with potentially very long task run-time
I have a Django app which lets the user execute (potentially very) time consuming computations. This is not an issue per se as the user is aware of the long runtime. How can I have the user execute tasks and then log out (or terminate the web app) while keeping the task running on the server? i.e. The Django app should execute regardless of whether the website is still open or the user is still logged on. Full disclosure, I am a beginner in web dev so my question may require refinement. -
Create form to update user info and its extended fields - DJANGO
I'm working on a django project. I extended the User model with extra fields by implementing this other model: class Profilo(models.Model): TYPE_CHOICES = ( ('marketing', 'Marketing'), ('web', 'Web'), ('contabilita', 'Contabilita'), ) ROLE_CHOICES = ( ('lavoratore', 'Lavoratore'), ('responsabile', 'Responsabile'), ) user = models.OneToOneField(User, on_delete=models.CASCADE) type = models.CharField(max_length=50, choices=TYPE_CHOICES, null=False, default=None) role1 = models.CharField(max_length=50, choices=ROLE_CHOICES, null=False, default=None) role2 = models.CharField(max_length=50, choices=ROLE_CHOICES, blank=True, default=None) profile_pic = models.ImageField(upload_to='media/immagini_profilo', blank=True) color = ColorField() def __str__(self): return self.user.username I want to create a view (NOT in the admin panel) where the user can modify the following information: username, first_name, last_name, email, profile_pic, color. So I implemented this form in the forms.py: from django import forms from .models import Profilo from colorfield.widgets import ColorWidget class ProfiloForm(forms.ModelForm): class Meta: model = Profilo fields = ('username','first_name','last_name','email','profile_pic', 'color',) widgets = { 'username': forms.TextInput(attrs={'class': 'form-control'}), 'first_name': forms.TextInput(attrs={'class': 'form-control'}), 'last_name': forms.TextInput(attrs={'class': 'form-control'}), 'email': forms.EmailInput(attrs={'class': 'form-control'}), 'profile_pic': forms.FileField(), 'color': ColorWidget(), } In views.py: class ModificaProfiloUtente(UpdateView): model = Profilo template_name = 'modifica-profilo-utente.html' form_class = ProfiloForm success_url = reverse_lazy('tutti-progetti-view') But i get this error: raise FieldError(message) django.core.exceptions.FieldError: Unknown field(s) (first_name, email, username, last_name) specified for Profilo So i tried several thigs: profilo__user__username (and so for the other fields as well) user__username user.username buti still get … -
Forbidden (CSRF cookie not set.) but I have {% csrf_token %} in my form
I'm getting a 403 error but I DO have {% csrf_token %} in my form. Here is my template <!DOCTYPE HTML> <html> <head> <title>Enter File Name</title> </head> <body> <h3>Enter File Name and File Delimiter</h3> <form action="processfile" method="post"> {% csrf_token %} <label>Enter a Fully Qualified File Name <input type="text" class="rcorners" id="file_name" name="file_name" size=125> </label> <br/> <br/> <label>Enter File Delimiter <input type="text" class="rcorners" id="delimiter" name="delimiter" size=5> </label> <br/> <br/> <input type="submit" class="rcorners" id="proc_file"/> </form> </body> </html> Here is my view method. def get_local_file(request): return render(request, "file_name.html") Please advise. -
Is it possible to register an instance method as a Signal receiver via decorators?
There are multiple ways to register class methods as Signal receivers in Django. Using the built-in receiver decorator is an obvious solution, but can work only with static methods or simple functions: from django.db.models.signals import post_save from django.dispatch import receiver class SignalCollection: @receiver(post_save) def some_signal(sender, instance, created, **kwargs): # code pass With instance methods, this decorator won't work as such methods require self as a first parameter. In this case, instantiating after defintion is what works: class SignalCollection: def some_signal_a(self, sender, instance, created, **kwargs): # code pass def some_signal_b(self, sender, instance, created, **kwargs): # code pass collection = SignalCollection() post_save.connect(collection.some_signal_a) post_save.connect(collection.some_signal_b) The potential issue with this is that it's not well encapsulated, and in case of many methods contains a lot of repeation. For solving this issue, I intended to apply custom decorators. My question is: is it possible to create such a decorator, either for the class itself, or for its methods, that can perform connections without instantiating the class? My research yielded no results, and many of my attempts were failed - adding receiver through method_decorator can work, but in none of my snippets were the signals triggered, meaning the connection did not happen. Creating a class decorator … -
instead of downloading the file, it downloads the HTML file
I want to download the files that I uploaded into the admin inside my template. But instead of downloading the file, it downloads the HTML file. view.py def download(request, path): file_path = os.path.join(settings.MEDIA_ROOT, path) if os.path.exists(file_path): with open(file_path, 'rb') as fh: response = HttpResponse(fh.read(), content_type="media/upload/bookfile/filepath") response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path) return response raise Http404 model.py filepath= models.FileField(upload_to='upload/bookfile', null=True, blank=False, validators=[validate_Bookfile]) url.py urlpatterns = [ url('download/(?P<path>.*)',serve,{ 'document_root':settings.MEDIA_ROOT}), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) template.html <li id="sell"><a href="{{Book.filepath.url}}" download="{{Book.filepath.url}}">download</a></li> -
How to add upload files fuctionality in changelist view page of model admin using django 3?
Code snippets that I was able to add so far: Model class: class MboxForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(MboxForm, self).__init__(*args, **kwargs) csv_file = forms.FileField(required=True, label="Select CSV file") class Meta: model = Mbox fields = ['some_field', ] widgets = { 'csv_file': forms.FileInput(), } In admin.py: class MboxAdmin(admin.ModelAdmin): actions = [import_from_csv, export_to_csv] def get_form(self, request, obj=None, **kwargs): kwargs['form'] = MboxForm return super().get_form(request, obj, **kwargs) def get_urls(self): urls = super().get_urls() my_urls = [ path("upload_csv", self.upload_csv, name='upload_csv') ] return my_urls + urls urls = property(get_urls) def upload_csv(self, request): if request.method == 'POST': form = MboxForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('admin/change_list.html') else : return render(request, 'admin/change_list.html', {'form': form, 'opts': Mbox._meta}) else: return render( request, 'admin/change_list.html', context ) def changelist_view(self, request, extra_context=None): extra_context = {} extra_context['submit_csv_form'] = MboxForm if 'action' in request.POST and request.POST['action'] == 'import_from_csv': if not request.POST.getlist(admin.ACTION_CHECKBOX_NAME): post = request.POST.copy() for u in Mbox.objects.all(): post.update({admin.ACTION_CHECKBOX_NAME: str(u.id)}) request._set_post(post) return super().changelist_view(request, extra_context=extra_context) This button displays in place of the add button in the listing page with the template but is not functional i.e. doesn't display the file browser to upload any file. It on the contrary displays error {% extends "admin/change_list.html" %} {% load i18n admin_urls static admin_list %} {% block object-tools %} {% if … -
Disable unique constraint on Django's ManyToManyField
From the Django documentation for ManyToManyField: If you don’t want multiple associations between the same instances, add a UniqueConstraint including the from and to fields. Django’s automatically generated many-to-many tables include such a constraint. How do I disable this constraint? Is the only way to provide an explicit through table? Or is there a way to tell Django to not add the UniqueConstraint to the generated many-to-many-table? -
AttributeError at /admin/accounts/school/ 'School' object has no attribute 'username'
hello am just wondering why cant I return return f'{self.user.username} Profile' form this model class School(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=200) region = models.CharField(max_length=200) district = models.CharField(max_length=200) code = models.CharField(max_length=20) logo = models.ImageField(default='default.jpg', upload_to='logos') def __str__(self): return f'{self.user.username} Profile' what should be the syntax here help -
django split data and apply search istartswith = query
I have a Project and I need to split the data in to words and apply searching. for example: my query is : 'bot' (typing 'bottle') but if I use meta_keywords__icontains = query the filter will also return queries with 'robot'. Here meta_keywords are keywords that can be used for searching. I won't be able to access data if the data in meta_keywords is 'water bottle' when I use meta_keywords__istartswith is there any way I can use in this case. I can simply create a model and for 'meta_keywords' and use the current data to assign values by splitting and saving as different data is the best way. I need some other ways to achieve it. -
what is the procedure for taking brand approval for django website?
I am making Django based news website which has both features API fetching as well as manual updating. I wanted to know that what is the procedure for taking brand approval for my website like having my brand registered and is it a costly method or cheap for free and where can I get it done?? -
How to retrieve the data corresponding to the link clicked in Django
I have database with a books = {Id, title, rating, page_count, author} In home.html I'm displaying the Title as link and when the user clicks it should redirect to a page with all the details. home.html {% for book in books %} <a href= "buy.html"> {{ book.Title }} </a> <p> Rated - {{ book.Rating }}</p> <p> {{ book.Authors }} </p> {% endfor %} Now when the user clicks on the Title it redirects to a new page buy.html and I want to display the complete details stored in my database. Can someone assist me here? -
Opencv integration with Django
I have a Opencv script that converts Videos on Django db to frame. I want to save the frame on the same folder with the video. I created a function upload_to that creates a folder to store the uploaded video. currently the generated frame is stored on the media directory not upload_to which looks like 'media/photo/name'. Opencv script import cv2 import os from .models import upload_to def video_to_frame(video): cap= cv2.VideoCapture(video) i=1 while(cap.isOpened()): ret, frame = cap.read() if ret == False: break if i%10 == 0: cv2.imwrite(os.path.join(upload_to,'new_image'+str(i)+'.jpg'),frame) i+=1 cap.release() cv2.destroyAllWindows() Model.py file from django.db import models from datetime import datetime import cv2 import tempfile from django.utils import timezone import os def upload_to(instance, filename): return os.path.join('photos', str(instance.name), filename) from .utils import video_to_frame class MyVideo(models.Model): name= models.CharField(max_length=500) date = models.DateTimeField(auto_now_add=True) videofile= models.FileField(upload_to=upload_to) def __str__(self): return self.name + ": " + str(self.videofile) def save(self, *args, **kwargs): tfile = tempfile.NamedTemporaryFile(delete=False) tfile.write(self.videofile.read()) vid = video_to_frame((tfile.name)) super(MyVideo, self).save(*args, **kwargs) -
Couldn't send email from django via sendgrid
Hope someone can help. couldn't send email from by django application via sendgrid. have created an account in sendgrid made changes as said in the documentation. tried almost everything from various blogs, but hard luck. settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_USE_TLS = True EMAIL_PORT = 465 EMAIL_HOST_USER = 'apikey' SENDGRID_API_KEY = os.environ.get('SENDGRID_API_KEY') EMAIL_HOST_PASSWORD = SENDGRID_API_KEY views.py from django.core.mail import send_mail from django.http import JsonResponse def sendEmail(request): try: subject = 'Test' message = 'Testing' from_email = <mail id> recipient_list = [<mail id>,] send_mail(subject, message, email_from, recipient_list) return JsonResponse({'message':'mail sent'}, status = 200) except Exception as e: return False -
django file field isn't showing up the first time when I load the page
I have a django html page that should show a upload button and a place where you can place your files. the first time when I load the page only the upload button is there. After I click on the button the choose your file button appears. Is there a possebility that the choose file always shows? HTML code <form action="{% url "result" %}" method="POST" enctype="multipart/form-data" action="/result/" class="form-horizontal"> {% csrf_token %} <div class="form-group"> <label for="name" class="col-md-3 col-sm-3 col-xs-12 control-label">File: </label> <p>{{ form }}</p> </div> <div class="form-group"> <div class="col-md-3 col-sm-3 col-xs-12 col-md-offset-3" style="margin-bottom:10px;"> <button class="btn btn-primary" type="submit"> <span class="glyphicon glyphicon-upload" style="margin-right:5px;"></span>Upload </button> </div> </div> </form> views.py @login_required def result(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): data = request.FILES['file'] handle_uploaded_file(data) data = pd.read_csv(data,header=0, sep=',') result = getPredictions(data) return HttpResponseRedirect(request, 'result.html', {'result': result}) else: form = UploadFileForm() return render(request, 'index.html', {'form': form}) -
How to search for the most occuring value in a one to many relationship django?
I have this one to Many relationship between pizza and restaurant. class Restaurant(Model): name = models.CharField(max_length=50) class Pizza(Model): restaurant = models.ForeignKey(Restaurent) name = models.CharFiedl(null=True, max_length=50) price = models.IntegerField(max_length=10, null= False) I would like to be able to search Restaurants for the most occurring price of their pizzas or mode https://en.wikipedia.org/wiki/Mode_(statistics). Django does not seem to have functionality to implement this easily.