Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Does WSGI behave dynamicly?
I remember when I save my files in PHP language, it didn't need to restart or reload apache web server. In Python, specialy Django, If I use django webserver with runserver command,it needs to restart django if I change my files. Question is, if I use WSGI in server, Does it behave such as php or runserver command? -
How to remove , while using Django {% for in %}
Trying to stop a comma being used on last item in loop, I want to seperate everything with a , but not the last thing as it is closing with a ] bracket. series: [{`enter code here` {% for service in availability.getSortedServices %} name: '{{ service }}', data: [12908, 5948, 8105, 11248, 8989, 11816, 18274, 18111] }, <----------------------------------------------------------------------how can i stop Django/Script stop this for last item on list, i want comma in all items except at end of last {% endfor %} ] -
I am not able to pass dynamic data in html file
I want to render my database information into HTML pages. I have used the way of passing dynamic data from databases. But, it's not working. I am seeing an empty page as a result. -
Mock decorator in django test
I want to test below code in view.py: class A(view): @has_access def get(request): ..... but I couldn't mock @has_access with patch('pathtouse.has_access').start() and even I tried with patch('pathtouse.has_access') as has_access how can I mock @has_access? I don't want execute decorator when I test A.get() -
How can I connect my buttons with two URLs in django?
I'm trying to connect a template that has two buttons with other two templates. The first button sends you to a login form and the second to a register one. I want to know how to modify my HTML template for it to do this. paginaPrincipal.html {% extends "base.html" %} {% block titulo %} PAGINA PRINCIPAL {% endblock %} {%block contenido %} <p>Tengo una cuenta</p> <p><button>Iniciar Sesion</button></p> <p>No tengo una cuenta</p> <p><button>Registrarse</button></p> {% endblock %} urls.py path('principal/', views.intro, name='pagina_principal'), path('registro/', views.registro_usuario, name='registro_usuario'), path('login/', views.login_view, name="login"), I want to connect those two button tags with login and registro urls, I guess I have to use the a tags but I don't know how to do this. Help is much appreciated -
Paginating a filtered queryset
I'm trying to implement a dynamic filter form in my web application for an e-commerce website, the filter works fine, but getting to paginate it is the issue, once the set is filtered, and i to click next page, it runs through the whole function again and the filtered set is overridden by Product.objects.all() def explore(request): categories = Category.objects.all() product_list = Product.objects.all().order_by('-Name') if request.GET: name = request.GET.get('name') brand = request.GET.get('brand') price = request.GET.get('price') colour = request.GET.get('colour') size = request.GET.get('size') if is_valid(name): product_list = product_list.filter(Name__icontains=name) if is_valid(brand): product_list = product_list.filter(Brand__icontains=brand) if is_valid(price): product_list = product_list.filter(Price__lte=price) if is_valid(colour): product_list = product_list.filter(variations__product_variations__value__icontains=colour).distinct() if is_valid(size): product_list = product_list.filter(variations__productvariation__value__icontains=size).distinct() paginator = Paginator(product_list, 2) # Show 25 products per page page = request.GET.get('page') products = paginator.get_page(page) else: paginator = Paginator(product_list, 25) # Show 25 products per page page = request.GET.get('page') products = paginator.get_page(page) context = {'categories':categories, 'products':products} if request.GET: if is_valid(name): context.update({'name':request.GET['name']}) if is_valid(brand): context.update({'brand':request.GET['brand']}) if is_valid(price): context.update({'price':request.GET['price']}) if is_valid(colour): context.update({'colour':request.GET['colour']}) if is_valid(size): context.update({'size':request.GET['size']}) return render(request, 'commercial/explore.html', context) -
Issues with Gunicon and Docker alpine-fat Image
I'm having a strange issue regarding Gunicorn installation for a Django project. My Dockerfile extends FROM openresty/openresty:alpine-fat as follows: FROM openresty/openresty:alpine-fat # VERSIONS ENV ALPINE_VERSION=3.8 \ PYTHON_VERSION=3.8.0 # PATHS ENV PYTHON_PATH=/usr/local/bin/ \ PATH="/usr/local/lib/python$PYTHON_VERSION/bin/:/usr/local/lib/pyenv/versions/$PYTHON_VERSION/bin:${PATH}" \ # These are always installed. # * dumb-init: a proper init system for containers, to reap zombie children # * musl: standard C library # * lib6-compat: compatibility libraries for glibc # * linux-headers: commonly needed, and an unusual package name from Alpine. # * build-base: used so we include the basic development packages (gcc) # * bash: so we can access /bin/bash # * git: to ease up clones of repos # * ca-certificates: for SSL verification during Pip and easy_install PACKAGES="\ dumb-init \ musl \ libc6-compat \ linux-headers \ build-base \ bash \ git \ ca-certificates \ libssl1.0 \ libffi-dev \ tzdata \ postgresql \ postgresql-dev \ " \ # PACKAGES needed to built python PYTHON_BUILD_PACKAGES="\ bzip2-dev \ coreutils \ dpkg-dev dpkg \ expat-dev \ findutils \ gcc \ gdbm-dev \ libc-dev \ libffi-dev \ libnsl-dev \ libtirpc-dev \ linux-headers \ make \ ncurses-dev \ libressl-dev \ pax-utils \ readline-dev \ sqlite-dev \ tcl-dev \ tk \ tk-dev \ util-linux-dev \ xz-dev \ zlib-dev … -
What is the best practice to dynamically change content in django cms template depends on country/endpoint
I'm looking for the very best practice to change some content on the site in the header depends on the endpoint in site url. I'm using django cms to generate html templates with a content. I have aside tag with some content written in german with german adress. If user from Brasil visits my website I want to use the adress of an office that is not placed in Germany but in Brasil - so a pure translation is not the way. I'm using python 3+, django cms. I'm new into django cms, and dunno if there is any preffered option. -
my form just loads but I can't edit it . Its Profile create form
This is my models . I have created abstract user instead of django built in user . I have also added image field from django.db import models from django.contrib.auth.models import AbstractUser from django.utils.translation import gettext_lazy as _ from PIL import Image class User(AbstractUser): ROLES = (('0','Admin'),('1','Reporter'),('2','Guest')) role = models.CharField(choices=ROLES, default='2', max_length= 1) email = models.EmailField(_('email address'), unique=True) REQUIRED_FIELDS = ('email',) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) dob = models.DateField(null= True, blank = True) address = models.CharField(max_length=100, blank=True) image = models.ImageField(default='default.jpg', upload_to='profile_pic') def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) This is my signals . i have created so that I can have instant Profile after I register from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from accounts.models import Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() this is my view.. I have done function based view.. this view contains 2 forms one for profile and other for username and firstname @login_required def profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance= … -
Blockquote Not working in CKEditor (Django)
I'm working on a project and I'm using CKEditor. After struggles, most features work but blockquote is not working. I work on the editor itself but when I display on template it's not. see screen shorts on templates after printing the field its gone Here is how I added it -
IntegrityError: duplicate key value violates unique constraint
I created a model in a django app and populated the data into the table from pgadmin but now when I am trying to create a record from the app it throws this integrity error: duplicate key value violates unique constraint "packsapp_foo_pkey" DETAIL: Key (id)=(4) already exists. Here's the models.py class foo(models.Model): a = models.CharField(max_length=500, default=0) b = models.EmailField(max_length=500, default=0) c = models.CharField(max_length=500, default=0) d = models.CharField(max_length=500, default=0) Do I always have to insert data from the app itself ? -
How to use 2 models within a serializer in Django REST API?
I just started using the Django Rest Framework recently and was wondering how to use 2 models within a single serializer. I have a custom model named 'Profile' and am also using a default Django model 'User'. With these two tables, I planned to use nested representations. Finally, in order to test the RegisterAPI, I wanted to create data using the POSTMAN tool but currently, it's not working as expected. This is what I had done so far: models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) company = models.CharField(max_length=100, blank=True, null=True) address = models.TextField() views.py: class RegisterAPI(APIView): permission_classes = [AllowAny] def post(self, request, format=None): serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() content = { 'result': 'Thanks for registering!' } return Response(content, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers.py: from rest_framework import serializers from myapp.models import Profile from django.contrib.auth.models import User class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ['company', 'address'] class UserSerializer(serializers.ModelSerializer): profile = ProfileSerializer(many = True) class Meta: model = User fields = ['username', 'email', 'password', 'profile'] def create(self, validated_data): profile_data = validated_data.pop('profile') password = validated_data.pop('password', None) # instance = self.Meta.model(**validated_data) user = User.objects.create(**validated_data) if password is not None: user.set_password(password) user.save() Profile.objects.create(user = user, **profile_data) return user Within POSTMAN, I … -
Is there any way to get selected values from ManyToManyField before save in Django Model
I've a model with many-to-many field. And I want to pre-process the values that will be selected on the many-to-many field. I need help from the experts. Thanks in advance. I've already tried to solve according to my scenario. But it's not working what I want. My code is given below: class Product(models.Model): sku = models.CharField(max_length=50, null=True, blank=True, verbose_name='sku'.upper()) title = models.CharField(max_length=50, null=False, blank=False, verbose_name='title'.title()) slug = models.SlugField(null=True, blank=True) category = models.ManyToManyField(Category, null=True, blank=True) ..... def save(self, *args, **kwargs): selected_categories = self.category.all() ...... -
Django - Optional cleaner GET parameters in URL?
I'm trying to set up an object filter bar on my template. This consists of a few <select> dropdowns. I plan on then sending those back to my view by reloading the URL but with GET requests. So my question has two parts: 1) Is there a way to make GET parameters optional with django? For example can I have mysite.com which gives me the default view and also mysite.com/name/age which filters by name and age parameters? 2) As per the above example. Say I want to filter by 5 or 6 parameters, or maybe miss some out. How do I do that so I'm not having a giant URL like mysite.come/name/age/occupation/birthday/bankbalance? -
Django ORM qeury for last 7 days day by day
This is my models: class Sales(models.Model): title = models.TextField() created_at = models.DateTimeField(auto_now_add=True) I am trying to get last 7 days data like i want to see how many sales occurred in last Friday, Saturday,Monday, etc date. Only for the last 7 days but it should appear day by day, like: friday: 40 mondey:80 widnesday: 88 etc date I am not getting how to achive this... I have tried like this below: some_day_last_week = timezone.now().date() - timedelta(days=7) sales_by_day = Campaign.objects.filter( created_at__gte=some_day_last_week, ).values( 'created_at__date' ).annotate( created_count=Count('created_at__date') ) Can anyone help me in this case? -
How to run periodic tasks immediately on django?
I have method that I want to run. I am using celery. This line is above my method : @periodic_task(run_every=crontab(minute='1')) How do I run this task locally? -
Django set relation between two models fields
I need to create relation between two model fields (without using ForeignKey method), for example: class Client(models.Model): login = models.CharField(max_length=100, blank=True, null=True) class StatClient(models.Model): client_login = models.CharField(max_length=100, blank=True, null=True) The relation need to by 1 to 1. I mean login need to by equal to client_login in another model and vice versa. To make this work i can overwrite for each model save() method: def save(self, *args, **kwargs): from * import StatClient data = StatClient(client_login=login) data.save() super().save(*args, **kwargs) Problem is when the data is changed based on php code direct in mysql. Then Django is not aware of any changes have been made! In this case one option is to monitor all data every 1 second but this can't be done because of performance. Is there any solution to do this without touching php code? -
What is Python function call with 'or None' as argument
I have been following this Django tutorial on youtube and they use this class call there: form = ContactForm(request.POST or None) What is (request.POST or None) part? I have never seen anyone do this and I am unable to formulate my question clearly enough for google to understand. How does 'or None' work? When is this used? What is the alternative way to call this class? -
You are trying to add a non-nullable field 'password' to user without a default; we can't do that
I am building a custom User class in django to use in creating a signup application and I keep on getting the error above every time I try to makemigrations.As far as I can see, my code is per django documentation here.I also have AUTH_USER_MODEL correctly placed in my settings configurations. Here's my models.py # from __future__ import unicode_literals from django.contrib.auth.models import AbstractUser from django.contrib.auth.base_user import BaseUserManager from django.db import models from django.utils.translation import ugettext_lazy as _ from django.core.validators import RegexValidator class UserManager(BaseUserManager): """Define a model manager for User model with no username field.""" use_in_migrations = True def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) if password: user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): """Create and save a regular User with the given email and password.""" extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): """Create and save a SuperUser with the given email and password.""" extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have … -
Django confirmation with sweetalert before post
I have a problem with submit buttons in Django 2. In the beginning, I had two buttons. One button accepts something, another redirect to form with choose changes. Template: <form action="event\" method="post" id="systemForm"> {% csrf_token %} <button type="submit" name="akcept" value={{zami.id}} form="systemForm" class="akceptacja" data-toggle="tooltip" data-html="true" data-placement="top" title="<b>Tooltip</b> on top">Akceptacja</button> <button type="submit" name="system" value={{zami.id}} form="systemForm" class="akceptacja"> Do poprawy</button></form> View: def event(request): if request.method == 'POST' and 'system' in request.POST: system = request.POST.get('system', None) zamowienie = Order.objects.filter(id=system) context = {'zamowienie': zamowienie} context['system'] = system sesja_zamowienie = context['system'] request.session['zamowienie'] = sesja_zamowienie elif request.method == 'POST' and 'akcept' in request.POST: akcept = request.POST.get('akcept', None) zamowienie = Order.objects.filter(id=akcept) for zami in zamowienie: zami.akcept = True zami.wyslane = True zami.save() numer_zamowienia = zami.numer_zamowienia pozycja_zamowienia = zami.pozycja_zlecenia nazwa_tow = zami.nazwa receiver_email = "email" if zami.rodzaj_zlecenia == "PART": wysylka_czesciowa(numer_zamowienia,pozycja_zamowienia, nazwa_tow, receiver_email) context={} return redirect('/') else: context={} return render(request, 'event.html', context) Now i would like to submit button after second confirm button from sweetalert js </script> <script type="text/javascript"> function JSalert(){ swal({ title: "TITLE", text: "Accept?", type: "warning", showCancelButton: true, cancelButtonColor: "#DD6B55", confirmButtonColor: "#5cdd55", confirmButtonText: "Accept", cancelButtonText: "Quit", closeOnConfirm: false, closeOnCancel: false }, function(isConfirm){ if (isConfirm) { swal("Accepted!", "Action ...", "success"); event.preventDefault(); return true; } else { swal("Cancel", "Cancel...", "error"); return … -
How to get value of upload file in Ckeditor?
I am new to ckeditor, and need some guideline from everyone. Currently i'm implementing a custom plugin with feature upload file or docs to editor. I successfully display the UI file field however i have problem in get back the file uploaded content after i press green button 'OK'. Image below is my UI, Click ME to view ME Below are my code, CKEDITOR.dialog.add('attachFileDialog', function (editor) { return { title: 'Attach File', minWidth: 400, minHeight: 150, contents: [ { id: 'tab-attach-file', label: 'Attach File', elements: [ { type: 'text', id: 'filename', label: 'File Name', }, { type: 'hbox', className: 'hbox-v-bottom', widths: ['75%', '25%'], children: [ { type: 'file', id: 'upload', label: 'Select a file', }, { type: 'fileButton', id: 'fileId', label: 'Upload file', 'for': ['tab-attach-file', 'upload'], filebrowser: { onSelect: function (fileUrl, data) { alert('Successfully uploaded: ' + fileUrl); } } }, ] }, ] }, ], Next part is, I have added file browser plugin into ckeditor and this, filebrowserBrowseUrl: 'aapx/static/lib/ckeditor_4.13.0_full/fileupload.js', filebrowserUploadUrl: 'aapx/static/lib/ckeditor_4.13.0_full/fileupload.js', However, i have no idea what to write in the js file. Any good sample or guidelines. Deeply apologise for my bad english and noobness. And Thank You. -
Maximum number of database queries per view
I am currently working on a view that has multiple database queries in it (currently 10 but in the end it will be most likely 50 or more) -> My aim is to built a html page with a large table for monthly reporting purposes with all kind of data from the database (kind of a dashboard). My question 1: Is my approach of putting 50 or more queriesin a view sensible or will it make the page loading time very slow. If it is not sensible, what is the best practice to built a view with a lot of data from various sources (Eg. build only a few large queries that somehow chain together multiple smaller queries (in order to query the database less often) and then separate and slice and dice the data from the queryset via python? My question 2: Does it make any difference in efficiency whether I design my queries like this: data = Testdata3.objects.all() data1 = data.filter(key__regex=r'abc123$').order_by('date').values('date','performance') data2 = data.filter(key__regex=r'def456$').order_by('date').values('date','performance') data3 = data.filter(key__regex=r'ghi789').order_by('date').values('date','performance') or like this: data1 = Testdata3.objects.filter(key__regex=r'abc123$').order_by('date').values('date','performance') data2 = Testdata3.objects.filter(key__regex=r'def456$').order_by('date').values('date','performance') data3 = Testdata3.objects.filter(key__regex=r'ghi789').order_by('date').values('date','performance') My assumption would be that the first way is more efficient since I hit the database only once and … -
Is there an entity relationship diagram of Django default authentication database models?
The Django 2.2 default authentication uses User objects (username, password, email, first_name, last_name). However it's not clear to me how users are related to Django 2.2 default permissions and Django 2.2 groups. Is there an entity relationship diagram of the default, means a typical default database models in the docs or somewhere else? -
Django, how to write SQL or ORM to sum something?
I want to count something like this: input list: AAA female 1 AAA female 2 BBB male 2 BBB male 1 AAA male 1 output list: AAA male 1 AAA female 3 BBB male 3 Sorry, my english is not good, thanks for everyone who help me. -
How to filter for all in Model.objects.filter?
I'm wanting to set up a database table filter for my django template. The way I've done it is using Javascript in my template to send back the selected item in a select tag back to my view as a POST request. I have an "All" option in my drop down box which allows for no filter to be applied, but I'm not sure what to do with this. My plan was to filter the output by using Model.objects.filter(variable1 = {select}option1, etc, etc). But is there a way to write variable1 = all or variable1 = *?