Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Force URL to match a view with re_path
I've a view that should be called when entering: 1) stickersgallit.pe/ordenes/ingresos or 2) http://127.0.0.1:8000/ordenes/ingresos (locally). However, it is entering and activating other view AddProduct, as it is guessing ordenes is c_slug and ingresos is product_slug, when they aren't: path('<slug:c_slug>/<slug:product_slug>', views.AddProduct, name='AddProduct'), Questions: a) How to force /ordenes/ingresos to activate my classOrdersListView (in order/views/class OrdersListView(ListView))? b) Or How can I limit what the URL views.AddProduct considers as c_slug and product_slug? Proyect urls.py: from django.contrib import admin from django.urls import path, include, re_path from shop import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), re_path('^/ordenes/', include('order.urls')), path('', include('shop.urls')), path('carrito_de_compras/', include('cart.urls')), path('marketing/', include('marketing.urls')), path('registrarse/', views.signupView, name = 'signup'), path('ingresar/', views.signinView, name = 'signin'), path('salir/', views.signoutView, name = 'signout'), path('province/', views.get_province, name = 'province') ] shop URLs: from django.contrib import admin from django.urls import path, re_path from . import views app_name = 'shop' urlpatterns = [ path('admin', admin.site.urls), path('', views.allCat, name='allCat'), path('packs/', views.PacksPage, name='PacksPage'), #Todos los packs path('catalogo', views.CatalogoListView.as_view(), name='catalogo'), #Todos los productos unitarios path('muestras/', views.SamplePackPage, name='SamplePackPage'), #Todas las muestras path('province/', views.get_province, name='province'), path('district/', views.get_district, name='district'), path('quienes-somos/', views.quienes_somos, name='quienes_somos'), path('como-comprar/', views.como_comprar, name='como_comprar'), path('contactanos/', views.contactanos, name='contactanos'), path('preguntas-frecuentes/', views.preguntas_frecuentes, name='preguntas_frecuentes'), path('legales/privacidad', views.legales_privacidad, name='legales_privacidad'), path('legales/terminos', views.legales_terminos, name='legales_terminos'), path('muestras/<slug:sample_slug>/medida-y-cantidad', views.StepOneView_Sample.as_view(), name='SampleDetail'), path('muestras/<slug:sample_slug>/subir-arte', … -
Extracting array with indices from GET parameters in Django
My Django project has a page that features a table powered by DataTables. In this case, the table uses server-side processing using a Django view and the GET http method. The Django view unpacks the query string into a QueryDict object, and my task is to unpack the DataTables parameters for each column of the table from this QueryDict. Note that I must use GET, not POST, because I want to use the POST method for other things that actually change data on the server. DataTables submits data for each column in the table relating to search strings and sorting for each column. This data is submitted as per their documentation here; the main point is that columnar params are sent up in the query string like this: ...&column[5][search][value]=searchme&column[6][search][value]=more&... I would like this to be unpacked in such a way that the resultant data structure looks something like this: column = [ { 'search': { 'value': 'searchme' } }, ... ] ...With the elements of the array submitted in the query string in the order specified by their indices. Is there a standard way of accomplishing this with Django's QueryDict? -
Request.POST or Request.POST.get both not providing values in views.py
I am not using Forms in my solution and only trying to get the values from the request.POST so as to save it in the database in the Views.py. It was working before but strangely when I print the key, value pair of the request object it sometimes shows the value and sometime has None in it. HTML : <form id="modify" class="form-horizontal" action="{% url 'modify' customer.customerid %}" method="POST"> {% csrf_token %} <fieldset class="scheduler-border"> <legend class="scheduler-border">{{ customer.customername }}</legend> <div class="form-group"> <span class="col-md-1 col-md-offset-2 text-center"><i class="fa fa-building bigicon"></i><label for="txtCustomerName">Customer Name</label></span> <div class="col-md-11"> <input type="text" name="txtCustomerName" id ="txtCustomerName" class="form-control" placeholder="Customer Name" value="{{ customer.customername }}" disabled="True"> </div> </div> <div class="form-group"> <span class="col-md-1 col-md-offset-2 text-center"><i class="fa fa-building bigicon"></i><label for="txtCustShortName">Customer Short Name</label></span> <div class="col-md-11"> <input type="text" name="txtCustShortName" id="txtCustShortName" class="form-control" placeholder="Customer Short Name" value="{{ customer.customershortname }}" disabled="True"> </div> </div> <div class="form-row"> <div class="form-group col-md-5 col-md-offset-2 text-left"> <span class="col-md-1"><i class="fa fa-user bigicon"></i><label for="txtContactFirstName">Contact Person First Name</label></span> <div class="col-md-12"> <input type="text" name="txtContactFirstName" id="txtContactFirstName" placeholder="Contact Person First Name" class="form-control" value="{{ contact.firstname }}" disabled="True"> </div> </div> <div class="form-group col-md-1 text-left"> </div> <div class="form-group col-md-5 col-md-offset-2 text-left"> <span class="col-md-1"><i class="fa fa-user bigicon"></i><label for="txtContactLastName">Contact Person Last Name</label></span> <div class="col-md-12"> <input type="text" name="txtContactLastName" id="txtContactLastName" placeholder="Contact Person Last Name" class="form-control" value="{{ contact.lastname }}" disabled="True"> </div> … -
Taking a form response, making an api call then displaying the api call in Django
I'm trying to have a Django form capture data from a user's input, take the input to make an API call to Aylien API and display the raw json result on the same page. I'm able to take the form input and successfully make an API call & get the JSON to print on the console, but am having a hard time displaying the call's result on the page. I keep getting UnboundLocalError: local variable 'api_response' referenced before assignment error. Code below models.py from django.db import models # Create your models here. class News(models.Model): title = models.TextField(max_length=120) form.py from django import forms from .models import News class NewsForm(forms.ModelForm): class Meta: model = News fields = [ 'title'] views.py from django.shortcuts import render from .models import News from .form import NewsForm import requests import aylien_news_api from aylien_news_api.rest import ApiException def news_create_view(request): ## link form to model for gathering search term from user form = NewsForm(request.POST) if form.is_valid(): # create an instance of the aylien api class api_instance = aylien_news_api.DefaultApi() ## build opts for api call from the response from the user opts = { 'title': form.cleaned_data['title'], 'language': ['en'], 'not_language': ['es', 'it'], 'published_at_start': 'NOW-7DAYS', 'published_at_end': 'NOW' } try: # List the stories … -
How do I list multiple slugs in Django 2.2 without getting an error?
I am trying to have a slug in my url for a category, and then a slug behind it for a specific product. Before using worked when there was only one. Django is confused when I used it twice for 2 different links. I have tried <slug:slug>/<slug:slug>/ and im sure that isn't the right way of going about it. -
I want to deploy my text scraping program to Heroku, but the file it uses is stored on my PC
I created a text scraping program in which the user enters a word and it searches through a large text file (250MG and growing) on my computer, but now I want to deploy it through Heroku. Is there a workaround that I need to implement or is there a (rather elusive) way to accomplish this? As far as I can tell, there is no way to upload my text file to Heroku as is. -
Django python rendering on dev but not on production
I have development environment for running my new website with python manage.py runserver and I have production environment that running this website with Apache2 and mod wsgi I am sending some variables in my views.py that render successfully on my development env, but same code on the prod env render nothing to the template -
Django How to overwrite update_last_login which is a recieves the signal on successful login
I am defining a custom User and I have a need to overwrite the update_last_login which is defined in .venv/lib/python3.7/site-packages/django/contrib/auth/models.py It is as below: def update_last_login(sender, user, **kwargs): """ A signal receiver which updates the last_login date for the user logging in. """ user.last_login = timezone.now() user.save(update_fields=['last_login']) And in .venv/lib/python3.7/site-packages/django/contrib/auth/__init__.py where the signal is send from .signals import user_logged_in .... def login(request, user, backend=None): ... user_logged_in.send(sender=user.__class__, request=request, user=user) So how to overwrite the update_last_login in my custom_user. -
How to filter by BooleanField in Django?
I have been having a hard time accomplishing this task and it seems that I cannot get help anywhere I turn. I am trying to send Memos to specific user groups in Django. Each user in each group should receive the Memo and be able to change the BooleanField to True to signify that they have read it. I then need to be able to access the amount of users which received and have marked the BoolenField as True so I can create a table in a template which says [3/31 Read] and such. I would like to not use GenericForeignkeys if possible and I would like to keep it as one Model if possible but I know that may not work. Currently I was trying this: class Memo(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_time = models.DateTimeField(default=timezone.now) sender = models.ForeignKey(User, on_delete=models.CASCADE) receiver = models.ManyToManyField(Group) def __str__(self): return self.title def get_absolute_url(self): return reverse('memos-detail', kwargs={'pk': self.pk}) class ReceivedMemo(models.Model): memo = models.ForeignKey( Memo, related_name='user_memos', on_delete=models.CASCADE) receiver = models.ForeignKey( User, related_name='memos', on_delete=models.CASCADE) read = models.BooleanField(default=False) Then I was going to try to filter the ReceivedMemos by memo to see if each receiver has read the memo or not. But this is starting to … -
auto_now_add=True with null=True
I have modified on my model by adding a DateTime field as the following date_joined = models.DateTimeField(auto_now_add=True,null=True) when I migrated on the previous rows, this column is set to now value not null as the following from the admin page. Date joined: Oct. 9, 2019, 1:32 a.m. any explanation please ? -
Django Rest Framework multiple image Form cannot select more than 1 image or file
I'm trying to upload multiple images using the Django REST Framework, the problem that I have is that when I render the form in HTML and I want to select the files it only lets me choose one instead of multiple. Normally in django in Forms this will be handle with the attribute Multiple = True and in HTML with the multipart. Here is my code: views.py class PhotoList(APIView): renderer_classes = [TemplateHTMLRenderer] template_name = 'upload.html' parser_classes = (FormParser, MultiPartParser) def get(self, request, format=None): photo = get_object_or_404(Session) serializer = SessionSerializer(photo) return Response({'serializer': serializer, 'photo': photo}) # return Response(data=serializer.data, status=status.HTTP_200_OK) def post(self, request, format=None): photo = get_object_or_404(Session) serializer = SessionSerializer(photo, data=request.data) if not serializer.is_valid(): return Response({'serializer': serializer, 'photo': photo}) serializer.save() return redirect('upload') serializer.py class SessionSerializer(serializers.ModelSerializer): class Meta: model = Session fields = ("name", "picture") models.py class Session(models.Model): name = models.CharField(max_length=50) picture = models.ImageField(upload_to='pictures') html {% extends 'base.html' %} {% load rest_framework %} {% block content %} <div class="container"> <div class="mt-2 pt-0"> <div class="bg-light border"> <div id="progress"> <form class="form-group pt-2 pl-1" method="POST" enctype="multipart/form-data"> {% csrf_token %} {% render_form serializer %} <button type="submit">Upload</button> </form> </div> </div> </div> </div> {% endblock %} not able to select more than one -
Django Forms - DateInput not populating from instance
I'm trying to set up an edit form for a Django model which includes a DateField. I've set this field as a forms.DateInput in forms.py. This works fine for creating a new instance of the model, but when I try to populate the form with an existing instance the DateInput field remains blank even though all of the other fields are populated correctly. If I revert to the default TextField input then the data is recalled correctly. I've also tried to set a format in the DateInput widget. models.py class Rider(models.Model): first_name = models.CharField(max_length=40) surname = models.CharField(max_length=40) MALE = 'M' FEMALE = 'F' GENDER_CHOICES = [ (MALE, 'Male'), (FEMALE, 'Female'), ] gender = models.CharField(max_length=1, choices=GENDER_CHOICES) dob = models.DateField("Date of Birth", auto_now = False, auto_now_add = False) club = models.CharField(max_length=50,blank=True, null=True) bc_number = models.IntegerField("British Cycling Membership Number", blank=True, null=True) linked_account = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1) views.py def rider_edit(request, pk): rider = get_object_or_404(Rider, pk=pk) if request.method == "POST": form = RiderForm(request.POST, prefix='rider', instance=rider) if form.is_valid(): rider = form.save(commit=False) rider.linked_account = request.user rider.save() return redirect('rider_list') else: form = RiderForm(prefix='rider', instance=rider) return render(request, 'riders/rider_new.html', {'riderform': form}) form.py from django import forms from .models import Rider, MedicalInfo class RiderForm(forms.ModelForm): class Meta: model = Rider fields = … -
Online mock exam using django and python
How to render the exam page like as shown in this image url and generate results for each user. url for image: https://drive.google.com/file/d/1YIkEWEXg6I7jazCJcx67NY_7nkWxMrOF/view?usp=sharing -
Perform some calculations using django form. Which framework?
I have an input form with couple of input fields mostly numerical. I have a python script which takes the input values then performs some medium calculations (arrays, loops, etc) and gives results. I would like to display results without a page refresh below the input form. Simplest example would be to display an average from the three input fields below when user clicks calculate button or instantly without even clicking. Could anybody point me to the right direction how this would be implemented? I don't know what's the best framework to use for this. Just Ajax or Angular? Perform calls on client side or server? -
How to open and read an attached pdf from an email in a django unit test?
I'd like to test that the correct information was added to a pdf and in a sent email. I'm using from django.core.mail import EmailMessage to create the message and attach the pdf. My unit test: class CommandTest(TestCase): def test_picklist_email_contains_pdf_with_material(self): response = self.client.get(reverse('retrieval:picklist')) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].subject, 'Picklist TEST') self.assertIsNotNone(mail.outbox[0].attachments) Right now I can see that a message is sent, that there are multiple attachments and I can see their subjects, but I can't read the actual attached files. The output when I print the first attachment shows the title and other info shown below: print(mail.outbox[0].attachments[0]) ('lsf1_picklist10/08/19 04:22 PM.pdf', b'%PDF-1.4\n%\x93\x8c\x8b\x9e ReportLab Generated PDF document http://www.reportlab.com\n1 0 obj\n<<\n/F1 2 0 R\n>>\nendobj\n2 0 obj\n<<\n/BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font\n>>\nendobj\n3 0 obj\n<<\n/Contents 7 0 R /MediaBox [ 0 0 612 792 ] /Parent 6 0 R /Resources <<\n/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]\n>> /Rotate 0 /Trans <<\n\n>> \n /Type /Page\n>>\nendobj\n4 0 obj\n<<\n/PageMode /UseNone /Pages 6 0 R /Type /Catalog\n>>\nendobj\n5 0 obj\n<<\n/Author (\\(anonymous\\)) /CreationDate (D:20191008162252+06\'00\') /Creator (\\(unspecified\\)) /Keywords () /ModDate (D:20191008162252+06\'00\') /Producer (ReportLab PDF Library - www.reportlab.com) \n /Subject (\\(unspecified\\)) /Title (\\(anonymous\\)) /Trapped /False\n>>\nendobj\n6 0 obj\n<<\n/Count 1 /Kids [ 3 0 R ] /Type /Pages\n>>\nendobj\n7 0 … -
Django QuerySet Filtering – Intersect Clause in Field Lookups?
Suppose I have the following models, where Questions and Choices have a many-to-many relationship. (To understand it better, consider a poll where each Question can have multiple Choices and each Choice can be associated to multiple Questions.) class Question(models.Model): question_text = models.CharField(max_length=200) choices = models.ManyToManyField('Choice') class Choice(models.Model): choice_text = models.CharField(max_length=200) Now suppose I have a QuerySet consisting of Choice objects, call it universe_choices. I want to filter all Question objects, to get only those Questions whose choices have at least one element in common with universe_choices. In other words, if at least one of a Question's choices is also in universe_choices, include that Question in the QuerySet returned from my filter. Ideally, I would do this with something equivalent to: Question.objects.filter(choices__intersection__exists=universe_choices) or Question.objects.filter(choices.intersection(universe_choices).exists()) But obviously neither the intersection() nor exists() methods exist in lookup-form, and you can't use them as-is in a filtering query. Is there a way to do this? The inefficient work-around of course is to loop through all Question objects, and check whether there is an intersection between each iteration's Question.choices object and universe_choices. -
How to write queryset to get N similar objects, but if they are less than N, to add to N (for example last created)?
I'm trying to get queryset of objects ordered by number of the same tags of particular object. This function returns queryset of objects that have at least one common tag: def get_similar_posts(post, n_posts): tag_ids = post.tags.values_list('id', flat=True) similar_posts = Post.objects.filter(tags__in=tag_ids).exclude(pk=post.pk) similar_posts = similar_posts.annotate(n_same_tags=models.Count('tags') similar_posts = similar_posts.order_by('-n_same_tags')[:n_posts] return similar_posts So I want to get exactly n_posts objects. But if number of objects with the same tags is less than n_posts, add more with last published objects. They all must be unique -
Store product URL for each retailer and product with Django models
I'm trying to create a database storing information for various products and retailers. I'm trying to capture information about all URLs that certain products can be found on retailers websites. In essence, think of a traditional price checker website. There is a product page that shows all the URLs of the product stocked by various retailers. It's probably a rather easy solution but I'm having issues wrapping my head around it. I'm not sure where should I capture the URL of certain product for each retailer. I believe URLs should be stored in the Product model which would require some kind of dictionary to hold information about retailer and product URL sold by those retailers. class Manufacturer(models.Model): manufacturers = models.CharField(max_length=10,choices=manufacturer_list,default='30') country = models.CharField(max_length=10,choices=country_list,default='30') class Retailers(models.Model): retailer_name = models.CharField(max_length=10,choices=retailer_list,default='30') retailer_website = models.URLField(max_length=250) retailer_page = models.URLField(max_length=250) country = models.CharField(max_length=255) class Product(models.Model): name = models.CharField(max_length=255) price = models.DecimalField(max_digits=4,decimal_places=2) product_image_url = models.URLField(max_length=250) product_manufacturer_url = models.URLField(max_length=250) product_size = models.CharField(max_length=10,choices=bottle_sizes,default='30') manufacturer = models.ForeignKey(Manufacturer,on_delete=models.CASCADE) reatailers = models.ManyToManyField(Retailers) Hope that makes sense, Mat -
How can I enable postgis on a Kubernetes executor under gitlab-runner?
I'm trying to set up a CI flow for a Django application which relies on postgis with a Kubernetes executor under the runner. In trying to do so, I've hit several kinds of problem: Trying to use postgres as a service obviously isn't sufficient, but it fails sanely, reporting that /usr/share/postgresql/9.6/extensions/postgis.control can't be found. At this point, that's expected -- but I'm including it here because it serves as proof that the Django/PostgreSQL connection works fine, since the failure occurs when trying to CREATE EXTENSION 'postgis' from a database bootstrap script. Adding a before_script step to apt install -y postgis* postgresql-9.6-postgis-scripts as recommended by an older answer on SO also fails in the same way. Because this is a k8s executor, I'm suspecting that this doesn't install postgis on the actual postgres host, resulting in the error. Adding a find /usr postgis.control step confirms that the file exists on the test runner container. I've also tried using the mdillon/postgis container often referenced as a solution to this, but no dice there: using localhost as the database host in the Django app (which both works for plain postgres as well as being recommended by the docs for the k8s executor type) … -
Django: Create user Active Directory from formulary
I new in Django and i want to know if exist any way to create a user in active directory from any formulary created in a web in django THanks all! Example Form -
ManyToMany field constraints in Django
This is a general database question that is not specific to Django. Since I'm using Django, I am asking it in this context. Suppose I have three models: class ModelA(models.Model) name = models.CharField(max_length=255) class ModelB(models.Model) a = models.ForeignKey(ModelA, on_delete=models.CASCADE) class ModelC(models.Model) a = models.ForeignKey(ModelA, on_delete=models.CASCADE) bs = models.ManyToManyField(ModelB, blank=True) I would like ModelC to have a link to many ModelBs. I would like there to be a constraint that only allows ModelC to have a ModelB if they share a common ModelA. Is there a way to architect this properly at the database level or should this be done logically in other parts of the system? -
Django: Object.objects.get returns me `Jquery Datepicker widget`
urls.py: from django.urls import path from . import views urlpatterns = [ path('<int:pk>/', views.show_object, name='show-object') views.py: def show_object(request, pk): testt = 2 objj = Object.objects.get(id=pk) pdb.set_trace() So I found pdb to debug with, but when I open console in debug mode (via pdb) and type objj it returns me <Object: Jquery Datepicker widget, create new date and getTime method?> if I type testt it returns me 2, I'm confused. -
class Meta VS form fields in Django
I'm learning Django forms from this example. When I run my server I get django.core.exceptions.ImproperlyConfigured: Creating a ModelForm without either the 'fields' attribute or the 'exclude' attribute is prohibited (solved here). Using class Meta everything works. Explain pliese could I use these both aproaches with Django==2.2.6 and pros and cons of them. -
How to pass custom url parameter for each Search button of raw_id_fields in django-admin
I have models class Product(models.Model): number = models.CharField(_('OEM/Part number'), max_length=128,) .... class Orderitem(models.Model): searchstring = models.CharField(_('OEM/Part number'), max_length=128, blank=True, default='',) product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) order = models.ForeignKey(Order, on_delete=models.CASCADE,) .... class Order(models.Model): .... And admins @admin.register(Product) class ProductAdmin(admin.ModelAdmin): list_display = ('number', .....) search_fields = ('number',) class OrderitemInline(admin.TabularInline): model = Orderitem fields = ('searchstring', 'product', .....) readonly_fields = ('searchstring',) raw_id_fields = ["product"] def get_formset(self, request, obj=None, **kwargs): form = super().get_formset(request, obj, **kwargs) field = form.form.base_fields['product'].widget.rel.limit_choices_to = {'q': '11111111'} return form @admin.register(Orderdiscuss) class OrderdiscussAdmin(admin.ModelAdmin): list_display = (....) inlines = [ OrderdiscussItemInline, ] ..... How can I replace "11111111" from field = form.form.base_fields['product'].widget.rel.limit_choices_to = {'q': '11111111'} to each Orderitem's "searchstring" field, to have raw_id_fields urls like: http://localhost:8003/admincp/catalog/product/?q=searchstring1 http://localhost:8003/admincp/catalog/product/?q=searchstring2 and other, so I can view only related records in Popup window? Thanks a lot! -
How do I alter my API request based on a field from the user?
What I would like is an API request that gives me data based on a field from the User. i.e. If the User is premium, give all of the data, otherwise, give a subset of that data. This is easy enough, as shown in the DRF filtering documentation: class PurchaseList(generics.ListAPIView): serializer_class = PurchaseSerializer def get_queryset(self): """ This view should return a list of all the purchases for the currently authenticated user. """ user = self.request.user return Purchase.objects.filter(purchaser=user) The problem: I currently have it set up so anyone trying to access the API needs a Token. But, I'd like a 'Guest' user (someone who is not logged in) to still be able to see some data from my API. I am using these Django Rest Framework settings: REST_FRAMEWORK = { "TEST_REQUEST_DEFAULT_FORMAT": "json", 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), }