Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
wagtailmenus packages not working or rendering any thing in the template
I'm trying to access the wagtailmenus items {% load menu_tags %} {% load wagtailcore_tags %} <ul class="nav navbar-nav"> {% for item in menu_items %} {{ item.text }} {% endfor %} </ul> it is not displaying anything my home/models.py is class CustomFlatMenuItem(AbstractFlatMenuItem): """A custom menu item model to be used by ``wagtailmenus.FlatMenu``""" menu = ParentalKey( 'wagtailmenus.FlatMenu', on_delete=models.CASCADE, related_name="custom_menu_items", # important for step 3! ) image = models.ForeignKey( get_image_model_string(), blank=True, null=True, on_delete=models.SET_NULL, ) hover_description = models.CharField( max_length=250, blank=True ) # Also override the panels attribute, so that the new fields appear # in the admin interface panels = ( PageChooserPanel('link_page'), FieldPanel('link_url'), FieldPanel('url_append'), FieldPanel('link_text'), ImageChooserPanel('image'), FieldPanel('hover_description'), FieldPanel('allow_subnav'), ) and I added {% main_menu template="menu/main_menu.html" %} in the template that I want to view -
No installed app with label 'emp' Django and what i dont understand is that i did put the app in the installed apps
No installed app with label 'emp' Django and what i dont understand is that i did put the app in the installed apps this is the insstalled apps part -
What is the point of a Django Through Model?
I'm struggling to understand why I should use a relationship between 2 models w/ a "through" model vs just a model w/ foreign-keys to the 2 models. Here is some code: class Team(models.Model): name = models.CharField(max_length=100) class Person(models.Model): name = models.CharField(max_length=100) teams = models.ManyToManyField(Team, related_name="people", through="Membership") class Membership(models.Model): person = models.ForeignKey(Person, related_name="memberships") team = models.ForeignKey(Team, related_name="memberships") join_date = models.DateTimeField(auto_add_now=True) Given the above classes, I can do >>> bob = Person(name="Bob) >>> lakers = Team(name="Lakers") >>> bob.teams.add(lakers) And that will have the effect of creating a new Membershp instance linking "bob" and "lakers" w/ the correct "join_date". But I could also just do: >>> Membership.objects.get_or_create(person=bob, team=lakers) or even: >>> bob.memberships.add(lakers) And it would have the same effect, wouldn't it? So why should I bother having the "teams" m2m field from Person to Teams? Thanks -
Common Fields For Different Model in django rest framework
I am developing a system where I have created multiple types of users(seller, agent provider, buyer, etc) by extending the Django default user model (BaseUserManager). I need to create a common Address model which can be associated with all users. For example buyer, seller can be used the same address field but the data will be different & I need to post the user information and address field during the registration. I have tried the manytomanyfield but it's not working. Need an idea about the common model for all users. -
How to calculate fft using rest api in django, by using the csv file passed by the user using POST request
I have a code that take in post request from the server ie, a file and store it into my local drive. What I am looking to solve is to read the file uploaded and store it into the db.sqlite3 database, and pass a post request using rest api to perform fast fourier transform calculations on the csv data that the user upload. Using rest api only. I have created a api to get the file from the user, I am not able to find out a relavent solution regarding the issue, thanks for the help in advance. the csv file uploaded is this: time, amplitude, 0,0.73904, 0.02441,1.2372, 0.04883,1.0019, 0.07324,0.50924, 0.09766,-0.603, 0.12207,-1.6674, 0.14648,-1.5332, 0.1709,-0.85486, 0.19531,0.3971, 0.21973,1.3604, 0.24414,1.8384, 0.26855,1.7446, 0.29297,0.73904, 0.31738,-0.69308, 0.3418,-1.6969, 0.36621,-1.6215, 0.39063,-0.97252, 0.41504,-0.07721, 0.43945,0.78132, . . . There are 2549 lines in total Here is my model.py file from django.db import models class Files(models.Model): file = models.FileField(blank = False, null = False) remark = models.CharField(max_length = 50) timestamp = models.DateTimeField(auto_now_add=True) serializers file from rest_framework import serializers from . models import Files class FilesSerializer(serializers.ModelSerializer): class Meta(): model = Files fields = ('file', 'remark', 'timestamp') this is the view file from rest_framework.views import APIView from rest_framework.parsers import MultiPartParser, FormParser from rest_framework.response … -
Disable sentry logs
I have sentry in my django application. And sentry all the time print in the console [sentry] DEBUG: Discarding transaction because sampled = False [sentry] INFO: Discarded session update because of missing release How can I disable this messages and why they appers? This is how sentry is installed in django sentry_sdk.init( dsn=os.environ.get('SENTRY_DSN_PYTHON'), integrations=[DjangoIntegration(), CeleryIntegration()], debug=False ) -
Django rest create user if login not exists
My problem: I send post request from frontend, which consists of login and password. At backend (Django) I need to check if user with that login exists. And then send response back to frontend. I found different solutions, using different django rest decorators, but when i send post request, I get 500 error. serializers.py: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' views.py: class UserViewSet(viewsets.ModelViewSet): serializer_class = UserSerializer queryset = User.objects.all() And my js file, where I send post request: const register = () => { Axios.post('http://localhost:8000/api/users/', { login: loginReg, password: passwordReg, }).then((response) => { console.log(response); }) } -
Partially updating a model with BooleanFields with djangorestframework
I have a model like this class Status(models.Model): is_working = models.BooleanField( default=None, null=True ) is_at_home = models.BooleanField( default=None, null=True ) with the corresponding serializer class StatusSerializer(ModelSerializer): class Meta: model = Status fields = [ "is_working", "is_at_home" ] using the default ModelViewSet class StatusViewSet(viewsets.ModelViewSet): """ """ serializer_class = StatusSerializer queryset = Status.objects.all() Whenever I partially update a Status, by e.g calling the put method on the API, all other fields are reset to False instead of keeping their old value. Say, I have a Status that looks like this: { "id": 1, "is_working": null, "is_at_home": null, } If I call put using the following JSON: { "is_working": true } my data now looks like this { "id": 1, "is_working": true, "is_at_home": false <-- GOT UPDATED } I however, just want to update the is_working field, so that my desired result would be: { "id": 1, "is_working": true, "is_at_home": null } This probably has to do with the fact that HTML forms don't supply a value for unchecked fields. I, however, don't use any HTML forms as I'm purely consuming the API through JSON requests. Using the serializer as is, I'd need to perform an extra get request prior to updating the … -
Django ORM Query index usage on PSQL
Im a bit confused by the way how indexes are used when making Django ORM Queries. I have a PSQL Database with 12000 rows and a hash index on the column where I query against: SELECT * FROM numbertable WHERE number='77885'; With EXPLAIN ANALYZE of this query I can see a processing time of: Planning Time: 0.388 ms Execution Time: 0.203 ms When I do the equivalent Django ORM query like: numbertable.objects.filter(number='77885') in the Django shell_plus with --print-sql, I get an execution time which differs between 1,5 and 3 ms If I do an EXPLAIN ANALYZE on the SQL equivalent to the ORM query, which I got from the --print-sql, in the psql terminal SELECT "numbertable"."number", "numbertable"."id", FROM "numbertable" WHERE "numbertable"."number" = '77885' LIMIT 21; I get similar times to the first SQL Query: Planning Time: 0.428 ms Execution Time: 0.366 ms The Django model: from django.contrib.postgres.indexes import HashIndex class numbertable(models.Model): id = models.IntegerField(blank=True, null=True) number = models.CharField(max_length=5, blank=True, null=True, db_index=True) class Meta: managed = False db_table = 'numbertable' indexes = [ HashIndex(fields=['plz'], name='plz_town_index'), ] (the 'managed = False' comes from inspectdb which I had to use because I created the databasetable not through a django migration) I looked what … -
django admin - Separation by type in one model
users/models.py class User(AbstractBaseUser, PermissionsMixin): class Meta: verbose_name_plural = "user" user_nm = models.CharField(max_length=10) user_email = models.EmailField( unique=True) user_tel = models.CharField( max_length=11, validators=[validate_user_tel] ) user_ty = models.CharField(max_length=8) users/admin.py class UserAdmin(admin.ModelAdmin): list_display = [ "id", "user_nm", "user_ty", "user_tel", "user_email", "point_amt", "user_join_dts", ] There are two types of user models(user_ty) "P" and "G". at the admin I want to divide categories by users "P" and "G" types. Will it be possible? -
how to use slug to 'objects.filter' retrieve data through a many-to-many class
I'm new to django and coding, so in my head with this problem, i've got two directions that i have no idea if whether either will be the right solution. So I have in model.py three classes Recipe Ingredient and IngredientAmount where, Recipe has a ManyToManyField to connect to Ingredient and has SlugField to be picked up by my recipe_detail.html page using a Detail function-based-view. IngredientAmount acts as a 'through' class so to speak and has Recipe and Ingredient as a ForeignKey here is my model.py: class Recipe(models.Model): alphanumeric = RegexValidator( r'[a-zA-Z][a-zA-Z ]+', 'Only alphabet characters and spaces are allowed.') slug = models.SlugField(null=False, unique=True) title = models.CharField(max_length=30, null=True, validators=[alphanumeric]) description = models.TextField(max_length=200, null=True, blank=True) ingredients = models.ManyToManyField( 'Ingredient', through='IngredientAmount', related_name='recipes') def __str__(self): return self.title def get_absolute_url(self): return reverse('recipe:recipe_detail', kwargs={'slug': self.slug}) class Ingredient(models.Model): name = models.CharField(max_length=200, null=True) def __str__(self): return self.name class IngredientAmount(models.Model): SINGLE = 1 DOUBLE = 2 TRIPLE = 3 AMOUNT_CHOICES = ( (SINGLE, 'Single'), (DOUBLE, 'Double'), (TRIPLE, 'Triple'), ) recipe = models.ForeignKey( 'Recipe', related_name='ingredient_amounts', on_delete=models.SET_NULL, null=True) ingredient = models.ForeignKey( 'Ingredient', related_name='ingredient_amounts', on_delete=models.SET_NULL, null=True,blank=True) amount = models.IntegerField(choices=AMOUNT_CHOICES, default=SINGLE) def __str__(self): return f'Recipe = {self.recipe}, Ingredient = {self.ingredient}, Amount = {self.amount}' I can get my recipe_detail.html to show the {{ … -
Django Python , trying to get pk, from urls to automatically add to my form
I am trying to add value in my form, for task_catagory field. When my user login to a home page, he/she will have a link to the category, which he/she will select a certain type of category and redirect him to add post page. This is mine home.html page, this is working fine, when I click on selected category, it redirect me to my add_post.html page, and in my browser it is all sow displays cat.pk: <div id="Categories" class="row"> {% for cat in cat %} {% if user.is_authenticated %} <div class="card-body"> {% if user.user_type == user.KORISNIK %} <a class="btn btn-primary" href="{% url 'add_post' cat.pk%}"> {{ cat.category_title }}</a> {% endif %} </div> {% endif %} </div> I'm trying to add that pk of 5 127.0.0.1:5050/AddPost/5: to my task_category value in form: add_post.html page: {% if user.is_authenticated %} <div class="form-group"> <div class="form"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.media }} {{ form.as_p }} <h3>{{ post.postUser}}</h3> <button type="submit" class="btn">Post</button> <button type="button" class="btn btn-secondary"><a href="{% url 'home' %}"> Back to home page </a></button> </form> </div> </div> {% endif %} <script> var name ="{{ user.id }}"; document.getElementById("user").value = name; </script> I also try to get that pk by JavaScript as I did in user.id … -
Do we need to use on_delete argument in ManyToManyField in django?
While designing Models do we need to add on_delete attribute in Manytomanyfield in django just like the foreign key. -
Why am I getting an error at admin (django version 1.11) Incorrect Padding?
Receiving the following error while accessing admin through my website and I am not able to understand why this is occuring. -
Why are my bootstrap cards aligned on top of each other and not aligned side by side?
My bootstrap cards are not aligning side by side and I can't seem to find my mistake. I am using django and html. {% extends 'base.html' %} <div> {% block content %} <h1>Players<h1> {% for player in players %} <div class="row"> <div class="column"> <div class="card" style="width: 18rem;"> <img class="card-img-top" src="{{ player.image_url }}"> <div class="card-body"> <h5 class="card-title">{{ player.name }}</h5> <p class="card-text">{{ player.position }}</p> <a href="#" class="btn btn-primary">Know More!</a> </div> </div> </div> </div> {% endfor %} {% endblock %} </div> -
Site authorization (django) via session + cookies via a third-party API to an external server where login, password data is stored
I can not understand any need to write views in order to do so in the form of authorization by user and login through the api of a third-party service where users with passwords lie. I understand that you need to make a request on the APIs that are available and in post send the login and password. How to implement this in views and form -
Unable to Align the Label under other Label
Sorry I am very very new to CSS I am trying to align "Low" under "Work", but no luck. Could anyone suggest me. Please refer screenshot.enter image description here -
VSCode Django Virtualenvwrapper
Hi i have my django project with use Virtualenvwrapper. I use VSCode and works for me workon etc in terminal. I have 3 files settings to run project in local server and in VPS server. I remove from settings my SECRET_KEY and all files with codes to json files. and run project like this: workon env_name (env_name) workon my_project python manage.py runserver --settings setings.local2 and this works good with file like this: like this: from my_project.settings import * import json import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) with open('keys_my_project.json') as config_file: config = json.load(config_file) SECRET_KEY = config['SECRET_KEY'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': config['NAME'], 'USER': config['USER'], 'PASSWORD': config['PASSWORD'], 'HOST': config['HOST'], 'PORT': '5432', } } DEBUG = True ALLOWED_HOSTS = [] STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATIC_ROOT = os.path.join(BASE_DIR, 'static_root') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') and now i have a problem with using VSCode debbuger: { "name": "my_project django", "type": "python", "request": "launch", "program": "my_project/manage.py", "args": ["runserver --settings settings.local2"], "django": true } MY ERROR: Exception has occurred: ImproperlyConfigured The SECRET_KEY setting must not be empty. File "my_project\manage.py", line 18, in main execute_from_command_line(sys.argv) File "my_project\manage.py", line 22, in <module> main() why my VSCode debbuger dont read json in settings file ? -
User Session in Django
Problem: I would like to assign a bank statement for each user. Each user will log in using their username and password, and access their document. At the moment, one user can see the statement of all users. If I would like to assign a document for each user, is adding a ForeignKey to the model is enough? user = models.ForeignKey(User) models.py class BankStatement(models.Model): user = models.ForeignKey(User) name = models.CharField(max_length=20) date_created = models.DateTimeField(auto_now_add=True) last_updated = models.DateTimeField(auto_now=True) Many Thanks -
Django with Gunicorn Serves Only One Request at a Time
I have deployed my Django project to Google Cloud. It has a RAM of 1.7GB and 1 shared core, running on Ubuntu 20.0.4. I have used Nginx as reverse proxy and to serve static files and Gunicorn behind it to serve as WSGI handler. I have run some performance tests using Apache Bench. Now it seems that Gunicorn is serving only one request at a time. I had turned off Nginx and run Gunicorn in port 80 to see if Nginx was the bottleneck, and it wasn't. I have checked with python manage.py server and it serves 3.16 requests per second with nearly 316ms response time. The problem is when I run it with Gunicorn it shows almost the same result or sometimes even worse. I am developing an e-commerce website which performs database I/O. I have used gevent as worker class. I have run the following command- /var/www/grocery-app/g_env/bin/gunicorn grocery.wsgi --workers 3 --worker-class gevent --worker-connections 100 --bind 127.0.0.1:8000 Nginx reads the server from local port 8000. I have run the test from Apache Bench with 100 requests in 100 connections, 50 requests in 50 connections, 50 request in 10 connections. No matter what combination I choose the result always seems … -
How to add values from another model and export it to csv when selecting the School Object from django admin?
How do i add the values and field names of all books (author, year and grade) and teachers (full_name and subject) related to the School when trying to export to csv? Csv example: expecting something like fields for School in db = id, name, address, location, website, about_us, school_book_id fields for Books in db = id, author, year, grade fields for Teachers in db = id, full_name, subject admin.py the django admin is displaying correctly! class SchoolAdmin(admin.ModelAdmin, CsvAdminMixin): list_display = ("name", "address",) model = TechPartner inlines = [ SchoolBooks, SchoolTeachers ] actions = ["export_to_csv",] admin.site.register(School, SchoolAdmin) model.py class SchoolModel: name = models.TextField(verbose_name=_(u"name"), default="", blank=True) address = models.TextField( verbose_name=_(u"address"), default="", blank=True ) website = models.URLField(verbose_name=_(u"website"), blank=True, null=True) class Meta: abstract = True class School(SchoolModel): type = models.ManyToManyField( to=SchoolType, verbose_name=_(u"Type"), blank=True ) class Meta: verbose_name = _(u"school") mixins.py class CsvAdminMixin(object): def export_to_csv(self, request, queryset): meta = self.model._meta fields = meta.get_fields() field_names = [field.name for field in fields] resp = HttpResponse(content_type='text/csv') resp['Content-Disposition'] = 'attachment; filename={}.csv'.format( meta ) writer = csv.writer(resp) writer.writerow(field_names) for obj in queryset: writer.writerow([getattr(obj, field_name) for field_name in field_names ]) return resp export_csv.short_description = "CSV export selected items." when printing queryset: <QuerySet [{'id': UUID('2342342'), 'name': 'Austin High school', 'address': 'There', 'about_us': … -
How can get the data from the foreign key in django
I am trying to get the vendor information against the category id,means when someone select the category all vendor's information against the category should be display,but when i call the url it show the error ' Cannot use QuerySet for "VendorCategory": Use a QuerySet for "Vendor" '. how can i get the vendor information Model.py class Vendor(models.Model): name = models.CharField(max_length=30) address = models.CharField(max_length=40) Contact_No = models.IntegerField(unique=True) email = models.CharField(max_length=30, unique=True) def __str__(self): return self.name class VendorCategory(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE) View.py class All_Vendor(TemplateView): template_name = 'purchase/allVendor.html' def get(self, request, *args, **kwargs): categories = categoryModel.objects.all() categoryId = self.request.GET.get('SelectCategory') vendorselect = VendorCategory.objects.filter(category_id=categoryId) vendor_id = VendorCategory.objects.filter(vendor_id=vendorselect) vendors = vendorModel.objects.get(id=vendor_id) args = {'categories': categories, 'selectedCategory': categoryId, 'vendorselect': vendorselect, 'vendors': vendors} return render(request, self.template_name, args) Template {% block content%} <form method="get"> <label> <select name="SelectCategory"> <option disabled="disabled" selected> Select Category</option> {% for category in categories %} <option value={{ category.id }}> {{ category.name }} </option> {% endfor %} </select> </label> <input type="submit" value="Select"> </form> {% for vendor in vendorselect %} {{ vendor.id }} {% endfor %} {% endblock %} -
How do i access a function i defined in my django view, inside the template (for UTF Encoding)
I have installed django-simple-gravatar and added that in my installed apps in the project. Then i tried using it in my template as: {% load gravatar %} {% gravatar_url user.email 40 %} But i got the following error: Unicode-objects must be encoded before hashing So i made the "Profile" View Accordingly: def Profile(request, pk): template = 'events/profile.html' user = User.objects.get(id=pk) posts = Post.objects.filter(owner=user) liked_posts = Fav.objects.filter(user=user) def email_for_gravatar(self): return self.user.email.lower().encode("utf-8") ctx = {'user': user, 'posts': posts, 'liked_posts': liked_posts} return render(request, template, ctx) And This is how i am trying to access the "email_for_gravtar" function inside my template, i may be wrong here: {% gravatar_url user.profile.email_for_gravatar 40 %} But the error message is still the same. What am i doing wrong here? -
Can get_queryset return 403 or any custom response
I have no idea if This is the good way to do this. I have an endpoint, it should retrieve a specific instance of system. Before being worried about permissions my view lookeds like this: class SystemDetail(generics.RetrieveAPIView): """ Get a system detail """ queryset = System.objects.all() serializer_class = SystemSerializer I want to update this because I want user to be able to see only systems they own. So I update my view like so: class SystemDetail(generics.RetrieveAPIView): def get_queryset(self): user_groups = self.request.user.groups.all().values_list('name') if 'all_rights' not in user_groups[0]: if len(user_groups) == 1: # For now we say that 1 user is only in 1 group dealer_name: str = user_groups[0][0].capitalize() # Group name are creating progammatically, it is using the same enum than the dealer name on the system return System.objects.filter(dealer__name=dealer_name) else: raise AttributeError('User in 2 groups, endpoint can not manage it') else: return System.objects.all() """ Get a system detail """ serializer_class = SystemSerializer So basically it works, when I try to access a system that I should not be able to see I got this message: {"detail":"Not found."} but What I'd like is to set a custom message with a 403 status saying to the user he is trying to access a … -
I can't send form with attachment in Django
I have problem with forms. I have few on my site and they works but i have one form with attachment and when i press 'send' on site nothing happened (site is only refreshing). Thats do immediately so I supposed Django don't even try send this form. And second, how can I set format file for only jpg,png and pdf? forms.py class PayBackForm(forms.Form): subject = forms.CharField(required=True) signature_number = forms.CharField(required=True) email = forms.EmailField(required=False) file = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) message = forms.CharField(widget=forms.Textarea, required=False) views.py from aplikacja.settings import EMAIL_HOST_USER from .models import News from django.core.mail import send_mail, BadHeaderError from django.http import HttpResponse from django.shortcuts import render, redirect from .forms import ContactFormForDebtor, ContactFormForClient, PayBackForm from django.contrib import messages ... from django.core.mail import EmailMessage def splata(request): if request.method == 'GET': form = PayBackForm() else: form = PayBackForm(request.POST) if form.is_valid(): messages.success(request, 'Form submission successful') subject = form.cleaned_data['subject'] message = form.cleaned_data['message'] email = form.cleaned_data['email'] file = request.FILES['file'] try: mail = EmailMessage(subject, message, EMAIL_HOST_USER, [email]) mail.attach(file.name, file.read(), file.content_type) mail.send() return render(request, "splata.html", {'email_form': form, 'error_message': 'Sent email to %s'%email}) except BadHeaderError: return render(request, "splata.html", {'email_form': form, 'error_message': 'Either the attachment is too big or corrupt'}) return render(request, "splata.html", {'form': form}) html <form enctype="multipart/form-data" method="post"> {% csrf_token %} {% if …