Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Autocomplete in Django from 2 different models
I designed the following search bar: And I started reading about a solution found here: https://stackoverflow.com/a/50613330/12323384 But what i want, is to be able to make the search bar look from 2 different models: Model1.objects.all() and Model2.objects.all() and when the user starts typing keywords, both results are being shown and the type is displayed next to the result (like Model1 or Model2). Kind of like when you are searching on LinkedIn and it displays the suggestions with their categories (People, Companies, etc...) Any idea on how to achieve that using one view and in the same search bar? -
Page Not Found Error trying to render form in django
I've been following the instructions here. This is the error it gives me, when i try to run it on localhost: Page not found (404) Request Method: GET Request URL: http://localhost:7000/account.html Using the URLconf defined in gettingstarted.urls, Django tried these URL patterns, in this order: [name='index'] [name='account'] db/ [name='db'] admin/ ^celery-progress/ The current path, account.html, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. This is what i have in my urls.py urlpatterns = [ path("", hello.views.index, name="index"), path("", hello.views.account, name="account"), path("db/", hello.views.db, name="db"), path("admin/", admin.site.urls), re_path(r'^celery-progress/', include('celery_progress.urls')) ] This is what i have in views.py def account(request): if request.method == 'POST': form = AccountForm(request.POST) if form.is_valid(): return HttpResponseRedirect('loading.html') else: form = Nameform() return render(request, 'account.html', {'form': form}) Finally this is the form itself(account.html): <form action="/account/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> I have the feeling i'm missing something really simple but i can't for the life of me see it. Any help would be greatly appreciated. -
Django, how to save User and model extended from User in 1 form?
I'm very new to Django so likely I'm missing something obvious here. I have a model 'Profile' that extends form Django's User model. This model is for storing extra settings for the user which should be decided when registering. So I have a register form that I want to use to save a User and a Profile. Currently the User is created and the User's Profile is created but the Profile is not populated with the POST data in the registration form. I'm using signals but I must be missing a crucial component somewhere. models.py class Profile(models.Model): BUTTON_SIZES = ( ('S', 'Small'), ('M', 'Medium'), ('L', 'Large'), ) COLOUR_OPTIONS = ( ('Def', 'Default'), ('Con', 'High Contrast'), ('Pro', 'Protanopia'), ('Deu', 'Deuteranopia'), ('Tri', 'Tritanopia'), ) user = models.OneToOneField(User, on_delete=models.CASCADE) teacher = models.BooleanField(default=False) button_size = models.CharField(max_length=1, choices=BUTTON_SIZES) colours = models.CharField(max_length=3, choices=COLOUR_OPTIONS) group = models.ForeignKey(Class, on_delete=models.SET_NULL, null=True, blank=True) def __str__(self): return f'{self.user.username} Profile' forms.py class UserRegisterForm(UserCreationForm): BUTTON_SIZES = ( ('S', 'Small'), ('M', 'Medium'), ('L', 'Large'), ) COLOUR_OPTIONS = ( ('Def', 'Default'), ('Con', 'High Contrast'), ('Pro', 'Protanopia'), ('Deu', 'Deuteranopia'), ('Tri', 'Tritanopia'), ) button_size = forms.ChoiceField(choices=BUTTON_SIZES) teacher = forms.BooleanField(required=False) colours = forms.ChoiceField(choices=COLOUR_OPTIONS) # added to UserRegisterForm after creating Class model group = forms.ModelChoiceField(queryset=Class.objects.all(),required=False) class Meta: model = … -
obj.save() reverts changes in Django
I have a model like: class product(): title = models.CharField("name", max_length=20) exist_flag = models.BooleanField('flag', default=True) in a view I use this function: def my_view(product): print(product.exist_flag) product.exist_flag = False print(product.exist_flag) product.save(['exist_flag']) print(product.exist_flag) it prints: True False True why obj.save() reverts the exist_flag field? how can I fix it to save correctly? -
Please guide how to use pk_of_user_without_token in django rest_framework. I am getting error in using this
from django.contrib.auth.models import User from rest_framework.authtoken.models import Token user = User.objects.get(pk=pk_of_user_without_token) Image clearly showing code and error -
Saving multiple instances of the form in django
Unable to store multiple instances of the form in Django after submitting automatically redirect to success URL that is home.html I wanted to build signup form that consists of three forms first form is basic login info, second form can have multiple instances of the single form where user can add more form or remove it. and third form if nested from where user also can add from or remove it. all these in under single submit button. I'm doing right or is there any proper solution or method for that. The first Form that is sign up for user is submitted successfully but the second form(vendor material) is not getting saved third form I'm working on it view.py class VendorSingUp2(View): VendorMaterialSet = formset_factory(VendorMaterialForm) template_name = "singup2.html" def get(self, request, *args, **kwargs): context = { 'vendormaterials': self.VendorMaterialSet(), 'vendor': VendorSignUpForm() } return render(request, self.template_name, context) def post(self, request, *args, **kwargs): vendor = VendorSignUpForm(self.request.POST) vendormaterials = self.VendorMaterialSet(self.request.POST) if vendor.is_valid() & vendormaterials.is_valid(): self.user = vendor.save() self.vendordata = Vendor.objects.get(user=self.user) for vm in vendormaterials: vm.instance = self.vendordata vm.save() print("success") return redirect('home') else: print("invalid") return render(request, self.template_name, {'vendor': vendor, 'vendormaterials': self.VendorMaterialSet(self.request.POST)}) signup2.html {% extends 'base.html' %} {% load static %} {% block content %} <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> … -
How to migrate django app without specifying each app name?
I am migrating django model by using makemigrations. Ex :- python manage.py makemigrations But it is not migrating some apps. Ex:- app1, app2 etc. Ex :- python manage.py makemigrations app1 Now, I want to migrate all apps without specifying each app name. i.e when i run command python manage.py makemigration, then i need to migrate all the apps. I have already specified all apps in settings.py INSTALLED_APPS. -
How to timeout a connection after certain time period, say 15s is over
I am trying to implement a connection timeout for any connection that exceeds 15s even if the connection is active. We are facing an issue with multipart image upload where some image randomly takes over a minute to upload, sometimes a couple of minutes. The same image takes less than a second to upload in the subsequent requests. We are uploading the image from an IoT device. As we have limited access to the device, we are unable to implement the timeout on the device end, and therefore have to do it at the server-side. I am using Nginx, gunicorn and django. Also, I have already tried implementing these settings: For nginx : #To have them timeout after just 1s keepalive_timeout 1; proxy_connect_timeout 1; proxy_send_timeout 1; proxy_read_timeout 1; send_timeout 1; For Gunicorn : --timeout 1 With these settings, I expected to close any connection that went over 1s. However, the request is completing even if it takes 5 mins. Going through the internet, I could only find answers and tutorials for increasing the timeout, with these same settings, so I thought the reverse was also true. Seems like that is not the case. Can anyone help me with this? -
How to declare a time-based alphanumerical id field with predefined aplphabetic part (Django model)
I am developing an app in Django. I wanted to insert in my model an auto-incrementing alphanumerical unique ID field, having, by default, a fixed alphabetical part and an auto-incrementing numerical part. But I also want the availability to change, from admin section, this id to another alphanumerical one, with a different alphanumerical and numerical part. I tryed to implement this, but it turned out that trying to implement such a field and making it the autofield of the model generates problems in my database. So I am changing my aim: now I want to implement a time-based alphanumerical unique field with predefined aplphabetic part. Please note: I don't want to overwrite the django default id field, I just want to include in my model a field that gets as default value a unique customized alphanumerical value. Here is what I did, in my models.py: def return_timestamped_id(): prefix = "ITCH" import time this_time = time.time() this_time = this_time *10000000 this_time = int(this_time) timestamp = str(this_time) default_value = prefix + timestamp return(default_value) class object_example(models.Model): name = models.CharField(max_length=256, blank=True, null=True) Id_generated = models.CharField(max_length=256, blank=False, null=False, unique=True, default=return_timestamped_id()) The problem is that, as I add objects to this model from the admin section, … -
How to add/push data if we have EmbeddedField without using admin page(i.e using python code)
How to add/push data if we have embedded-field without using admin page(i.e using python code) -
NoReverseMatch at ...... in django
I am working on a blog site where you can search for posts by using searching with keywords (basically a normal searchbar). I have imported Q from django.db.models The view I created: def search(request): queryset = Article.objects.all() query = request.GET.get('q') if query: queryset = queryset.filter( Q(title__icontains=query) | Q(overview__icontains=query) ).distinct() context = { 'queryset': queryset, } return render(request, 'search_results.html', context) The urlpattern: path('search/', search, name='search-results'), The form itself: <form action="{% url 'search' %}" class="search-form">{% csrf_token %} <button type="submit" class="submit"><i class="icon-search"></i></button> <div class="form-group"> <span class="icon icon-search"></span> <input type="text" class="form-control" name="q" placeholder="Type a keyword and hit enter"> </div> </form> When I want to access the page to which I have put this form in, it says: Reverse for 'search' not found. 'search' is not a valid view function or pattern name. Below it also shows this: 1 <!DOCTYPE html> 2 <html lang="en"> 3 4 {% include 'head.html' %} 5 6 <body> 7 8 {% include 'header.html' %} 9 10 {% block content %} I have tried adding/removing csrf_token and the submit button, but the result is always the same. Please help! -
Django Create Class From Multiple Functions
I have several functions in my utils.py file that my views use to calculate trade stats. Below I added just 3 but there are 8 and soon there will be several more. The way I currently have it set up works but it's very inefficient. You can see each function starts from the beginning and calls other functions that set similar variables. What is the proper way to turn this into a class? Is this even the right approach? utils.py | multiple functions def max_amount_function (pk): trade = get_object_or_404(Trade, pk=pk) entries_buy = Entry.objects.filter(trade=trade, entry_type="entry") max_amount_function = entries_buy.aggregate(max_amount_function=Sum('amount'))['max_amount_function'] if max_amount_function is None: return 0 else: return max_amount_function def fees_function (pk): trade = get_object_or_404(Trade, pk=pk) entries = Entry.objects.filter(trade=trade) fees_function = entries.aggregate(fees_function=Sum('fee'))['fees_function'] return fees_function def entry_cpu_function (pk): if max_amount_function(pk) > 0: trade = get_object_or_404(Trade, pk=pk) entries_buy = Entry.objects.filter(trade=trade, entry_type="entry") entry_cpu_function = entries_buy.annotate( s=F('amount') * F('price') ).aggregate( entry_cpu_function=ExpressionWrapper( Sum( Cast('s', output_field=models.FloatField()) ) / Sum('amount'), output_field=models.FloatField() ) )['entry_cpu_function'] return entry_cpu_function else: return 0 utils.py | one class class TradeStats: trade = get_object_or_404(Trade) entries_buy = Entry.objects.filter(trade=trade, entry_type="entry") def __init__(self): pass def max_amount_functio(pk): pass def fees_function(pk): pass def entry_cpu_function(self): pass -
Custom plugin TextField Django CMS
I am trying to implement my custom CMS plugin with a TextField and would like to have all the text styling options provided by the CKEditor but when I add a TextField or CharField in my models it creates a simple text input field. class Something(CMSPlugin): text = models.TextField(max_length=512) image = models.ImageField() Anybody an idea what I have to add so the styling options for text are available in the frontend editor? Also thought about overriding one of the existing Plugins but this doesnt seem to be the right path. -
How to use Django "empty_forms" correctly to dynamically add new formsets : Select Widget's failure
I am using Django modelformset_factory for one of my models where I am creating a number records in a single page. Two of the form fields are select widgets and the rest of the fields are simple text/number inputs. With the initial number of rows the records get created perfectly. To add extra rows dynamically I have adapted the solution from here. New rows of empty forms are getting generated as expected. However, when a new row is added, the select boxes are generating a list of FK (available) choices, instead of drop downs which are otherwise being generated for the original set of forms. On changing the .Select widget to a .TextInput, the dynamically added rows display now such issue (and I can create new records using the formsets, including, using those added dynamically by manually inputting the values for the fields). My question is: What could make the select widgets to fail as they exhibit here? Note: Images added to demonstrate what exactly is happening. Original Rows New Rows Added (The highlighted object is the FK field value which is getting displayed here, instead of a .Select widget!!) -
How to execute psql interactive in its docker container?
I want to run a query in Postgres interactive shell. I'm using a docker container for this purpose as the following: Here is the relevant piece of docker-compose: db_of_ivms: image: postgres:10 restart: unless-stopped ports: - 5432:5432 container_name: db_of_ivms environment: POSTGRES_PASSWORD: xxx POSTGRES_USER: ivms_usr POSTGRES_DB: ivms_db Nevertheless, I'm dealing with this error: docker exec -it -u 0 db_of_ivms bash # psql psql: FATAL: role "root" does not exist -
Get the username with django profileserializer
I developed api with django. I created a code structure like below. How do I get the user's first_name and last_name in class ProfileSerializer? that is, with ProfileSerializer, I want to get information such as the user's name, surname, id number `` from django.contrib.auth.models import User from django.contrib.auth.password_validation import validate_password from rest_framework.serializers import ModelSerializer, Serializer from rest_framework import serializers from account.models import Profile class ProfileSerializer(ModelSerializer): class Meta: model = Profile fields = ('id', 'userKey', 'phone', 'email', 'address', 'userState') class UserSerializer(ModelSerializer): profile = ProfileSerializer() class Meta: model = User fields = ('id', 'first_name', 'last_name', 'profile') def update(self, instance, validated_data): profile = validated_data.pop('profile') profile_serializer = ProfileSerializer(instance=instance.profile, data=profile) profile_serializer.is_valid(raise_exception=True) profile_serializer.save() return super(UserSerializer, self).update(instance, validated_data) `` -
Django ORM: How to use count method inside values_list method?
To simplify things, I need to perform this query: select state,count(*) from Airports group by state order by count(*) desc And the desired return from my query is a dictionary like this: { 'state1': value1, 'state2': value2, 'state3': value3, ... 'staten': valuen, } I did some research and seems I need to use aggregate and annotate but I'm kinda lost in how to perform this with values_list(). Can I use count inside it like this? Airport.objects.values_list('state', Airport.objects.count()).annotate('state').order_by(-Airport.objects.count()) -
docker compose up generate (2005, "Unknown MySQL server host 'db' (-2)") error
Hi all i'm trying to dockerize a django application with a connexion to the database. when i run docker compose up i get this error when the dockerfile is making migrations django.db.utils.OperationalError: (2005, "Unknown MySQL server host 'db' (-2)") ERROR: Service 'web' failed to build: The command '/bin/sh -c python manage.py makemigrations' returned a non-zero code: 1 here is my Dockerfile FROM python:3.6 ENV PYTHONUNBUFFERED 1 RUN mkdir /SFP_ingestion WORKDIR /SFP_ingestion COPY . /SFP_ingestion RUN pip install -r requirements.txt RUN python generatemodel.py RUN python generateapp.py RUN python manage.py makemigrations RUN python manage.py migrate RUN python manage.py migrate easyaudit CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] and here is my docker-compose.yml services: db: image: mysql restart: always command: --default-authentication-plugin=mysql_native_password --mysqlx=0 environment: - MYSQL_HOST=localhost - MYSQL_PORT=3306 # cannot change this port to other number - MYSQL_DATABASE=sfp # name you want for the database - MYSQL_USER=root # change to whatever username you want - MYSQL_PASSWORD=password #change to the password you want for user - MYSQL_ROOT_PASSWORD=password #change to good root password ports: - "3306:3306" expose: - "3306" volumes: - "./db:/var/lib/mysql" web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/SFP_ingestion restart: always ports: - "8000:8000" depends_on: - db -
django url tag with dynamic app_label
i'm trying to create a dynamic url tag for my class based listview. it's needed for a delete button on every list item it loops over. the issue is that I use this template in multiple apps and want to reuse it. what currently works: [filename.html] {% for file in object_list %} <tr> <td>{{file.name}} </td> <td>{{file.regExpFilename}}</td> <form class="delete-form" method="POST" action="{% url 'MyApp1:filenames_delete' pk=file.stream %}"> <button type="submit" value="delete" class="btn-delete" onclick="return confirm('Are you sure to delete {{file.stream}} {{file.regExpFile}}?')"> Delete </button> But I want to remove the 'MyApp' to make it reusable for multiple apps. Many Thanks, -
install django on suse linux enterprise server 11
I use SUSE Linux enterprise server 11 and try to install Django but these package not found on ZYPPER or YAST second question i want to know if i want to install SUSE Linux enterprise server 12 or 15 after using the registration code on the site then the time of it is ended i didn't want to buy activation code what happen is this close system ? -
No post found matching the query
class PostDetailView(DetailView): model = Post template_name = 'blog/post_detail.html' path('post//', PostDetailView.as_view(), name='post-detail') when i go to 127.0.0.1:8000/post/1, it says No post found matching the query enter image description here -
errors in django tests
im trying to run the following test but im not sure why its not working since when tests are ran a test db is created and that means that the newly created item gets an id of 1 but im still getting an error that no object matches the query model from django.db import models # Create your models here. class Post(models.Model): text = models.TextField() def __str__(self): return self.text[:50] tests from django.test import TestCase from .models import Post # Create your tests here. class PostModelTest(TestCase): def setup(self): post = Post.objects.create(text="just a test") def test_text_content(self): post = Post.objects.get(id=1) expected_obect_name = f'{post.text}' self.assertEqual(expected_obect_name, 'just a test') here's the error -
what is mean by "Apply all migrations: admin, auth, authentication, contenttypes, sessions, sites" in Django Python 2.2 migrate command?
I am trying to migrate all the models in my Django project to a database, after migration, There are many tables missing in the database, but when I run python manage.py migrate there is no migration to apply, and what is this Operations to perform, and what exactly mean by Apply all migrations: adming, auth, authentication, contenttypes, sessions, sites ? -
Drop-down list in table rows django
How to display in the table rows a drop-down list whose data is taken from the database? At the moment, I just show the value from the database, and there is no drop-down list, although I specified the ModelChoiceField. My code: models.py class Technology(models.Model): technology_name = models.CharField(max_length=255, null=True) def __str__(self): return '%s' % (self.technology_name) class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.PROTECT) order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='order_items') qty = models.PositiveIntegerField(default=1) price = models.DecimalField(default=0.00, decimal_places=2, max_digits=20) technology_id = models.ForeignKey(Technology, on_delete=models.PROTECT, null=True) view.py class OrderUpdateView(UpdateView): model = Order template_name = 'order_update.html' form_class = OrderEditForm def get_success_url(self): return reverse('update_order', kwargs={'pk': self.object.id}) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) instance = self.object qs_p = Product.objects.filter(active=True)[:12] products = ProductTable(qs_p) order_items = instance.order_items.all() context.update(locals()) return context forms.py class OrderItemTable(ModelForm): technology_id = forms.ModelChoiceField(queryset=Technology.objects.all(), empty_label='') class Meta: model = OrderItem fields = ['product', 'qty', 'technology_id'] order_update.html {% for item in order_items %} <tr> <td>{{ item.product }}</td> <td>{{ item.qty }}</td> <td>{{ item.technology_id }}</td> </tr> {% endfor %} -
Django - context - How to pass context to ALL views
Because I need to cycle through a model table to render the options/nav-links in the navbar, and the navbar is rendered on every page. Hence, I find myself passing in the same context to every class-based view and it's quite repetitive: class Xxx: ... def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['categories'] = Category.objects.get_categories_with_item() return context Is there a DRYer way to do this? Thanks!! PS. and also, is *args necessary in get_context_data method? I've seen code with it and code without