Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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', ), } -
How to link memo to all users in group
I have a simple model called Memos that looks like this: class Memo(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_time = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) Now if I want to create a table so that I have a sender and receiver I could change author to sender and then add a receiver with a foreignkey to link it to the receiving party. Problem is that I have "groups" of employees with specific permissions (using Django groups and permissions) in which each user of the group needs to receive these memos separately and mark as read. To mark as read I simply planned on adding a models.BooleanField(default=False) then switch it to True when user visits that page. So my question is how to allow group(s) to be selected as a receiver then each user in the receiver group have their own Memo assigned to them so that they can mark as read/unread? -
How to require login for homepage in wagtail
I am trying to figure out a way for when someone reaches the website that if they are not authenticated it redirects them to the login screen. I am using WagTail 2.6.2. The home app does not have a views.py to require the class for a login. Any suggestions or documentation out there to do this would be great. -
Object of type Decimal is not JSON serializable error in Django
I am following 'Django 2 by Example' book to create a ecommerce website in Django. But I am getting 'Object of type Decimal is not JSON serializable' when I am trying to save order id in the request.session in the following line. request.session['order_id'] = order.id def order_create(request): cart = Cart(request) if request.method == 'POST': form = OrderCreateForm(request.POST) if form.is_valid(): order = form.save() for item in cart: OrderItem.objects.create( order=order, product=item['product'], price=item['price'], quantity=item['quantity']) # cart.clear() order_created.delay(order.id) request.session['order_id'] = order.id return redirect(reverse('payment:process')) else: form = OrderCreateForm() return render(request, 'orders/order/create.html', {'cart': cart, 'form': form}) -
Django - TypeError: load_stations() missing 1 required positional argument: 'request'?
I'm trying to create dependent dropdowns and when I tried compiling I got this error File "C:\...\operations\urls.py", line 13, in <module> path('ajax/load-stations/', views.load_stations(), name='ajax_load_stations'), TypeError: load_stations() missing 1 required positional argument: 'request' My current code associated with this part is views.py class EnterExitArea(CreateView): template_name = "operations/enter_exit_area.html" form_class = WarehouseForm success_url = reverse_lazy('enter_exit_area') def form_valid(self, form): form.submit_time() return super().form_valid(form) def load_stations(request): work_area_id = request.GET.get('work_area') stations = StationNumber.objects.filter(work_area_id=work_area_id).order_by('name') return render(request, 'operations/station_number_dropdown_list_options.html', {'stations': stations}) and my urls is urls.py urlpatterns = [ url(r'enter-exit-area/$', EnterExitArea.as_view(), name='enter_exit_area'), path('ajax/load-stations/', views.load_stations(), name='ajax_load_stations'), ] What could be causing this error?