Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Models - Filter third model, based on two connected models?
How Can StoreDefaultAudience be improved? John's Store - Audiences: Audience A, Audience B, Audience C Nicole's Store - Audiences: Audience D, Audience E for StoreDefaultAudience John's Store should only be able to choose Audience A, Audience B, Audience C as a default audience for StoreDefaultAudience Nicole's Store should only be able to choose Audience D, Audience E as a default audience class Store(models.Model): store_name = models.CharField(max_length=50) class Audience(models.Model): audience_name = models.CharField(max_length=50) store = models.ForeignKey(Store, on_delete=models.CASCADE) # only one StoreDefaultAudience should be allowed per Store # the default audiences should only be that stores audiences class StoreDefaultAudience(models.Model) default_audience = models.ForeignKey(Audience, on_delete=models.CASCADE, unique=True) store = models.ForeignKey(Store, on_delete=models.CASCADE, unique=True) -
Can i merge photos in python with pillow?
I want to create a website like redbubble Can i use python to programming it? I want to use pilow, django. Is it possible with this tools? I searched for it and didnt find any answer. I tried a little but I am not sure that it can be possible or not Best regards -
Django blog - printing only last few posts and load more on clicking a button
I have a really simple Django blog application. https://example.com/ returns a template (index.html) which looks something like this: {% extends "base.html" %} {% block content %} <style> ... </style> ... <div class="container"> {% for post in post_list %} <div class="..."> <h2>{{ post.title }}</h2> <p>{{ post.content | slice:"300" }}</p> </div> {% endfor %} </div> ... <button onlick="morePosts()"></button> ... {% endblock %} and https://example.com/post_slug returns the full post What I need to do now, is to limit the for loop to print only first 5 posts in the post_list and to print more when function morePosts() is called. In my views.py there's a simple class PostList class PostList(generic.ListView): queryset = Post.objects.filter(status=1).order_by('-created_on') template_name = 'index.html' -
Define an abstract model with generic signals in a Django project
I am creating an abstract model that allows me to inherit signals that execute basic methods. Abstract model class SignalModel(models.Model): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) models.signals.post_save.connect(self.post_save_signal, sender=self.__class__, dispatch_uid='post_save_{}_signal'.format(self.__class__.__name__.lower())) # @classmethod # def __init_subclass__(cls, **kwargs): # super().__init_subclass__(**kwargs) # models.signals.post_save.connect(self.post_save_signal, # weak=False, # sender=cls, # dispatch_uid='post_save_{}_signal'.format(cls.__name__.lower())) class Meta: abstract = True def post_save_signal(self, sender, update_fields, created, instance, **kwargs): print('_post_save_signal') if <condition1>: self.condition1() ... def condition1(self): ... User model class User(SignalModel): email = .... ... When I do user = User.objects.first() user.save() I hope to see the result # _post_save_field_signal but nothing happends. I have tried to override __init__ or __init_subclass__. but nothing works. I think that the signal does not connect with the model. I do not know to do it. Thanks! :D -
Hi, I have builted a blog with django. How can I obtain all posts published in the last hour with a queryset?
That's my idea but obviously doesn't work.... Thanks def PostUltimaOra(request): PostsLastHour = Post.objects.filter(pub_date__time__range=(datetime.time.now, datetime.time(now- 1h))) return render(request, 'blog/numeroposts.html', {'PostsLastHour': PostsLastHour}) -
Create a field with conditions
I'm a beginner in django rest framework. I am wondring if there is a way to create a field from a GET. For example if "count" == 0, create a field named "available" : "out_of_stock" else "available [ { "id": 1, "count": 10, }, { "id": 2, "count": 0, } ] -
Can I use django templating language with inside .vue file?
I would like to use Vue CLI for my existing Django project. The setup works, as in I can, in the future - if I want to, separate backend (API Django) and frontend (Vue CLI). One problem is, since it's an existing project, many templates/htmls are using Django templating language, such as: {% load static %} {% load fruit_tags %} {% load i18n %} {% load l10n %} .... {% if not request.user.is_authenticated %} {% endif %} .... etc ... My questions: Is there a way to use Django templating language inside .vue files? What would be the best practice for this scenario? I am currently using npm installation approach and it's working (using html with Django template; not .vue). Shall I just keep on doing it like this, and use the CLI (new frontend folder) for upcoming features? Thank you in advance! -
how to calculate number of clicks on embeded video
I am embedding some videos on my Django site and I want to calculate how many users viewed that video. I think of one solution which is "how many times the user clicks on (generated automatically) viewers will be updated" with the help of jQuery, but it doesn't work as expected. This is my template: {% load static %} {% load embed_video_tags %} <!DOCTYPE html> <html lang="en"> <head> </head> <body> <h4>User: {{user}}</h4> <div class="row"> <div class="container"> {% for v in videos %} <div class="col s12 l6"> {% video v.video 'tiny' %} <div class="info"> <h5 id="view"><span><i class="material-icons">visibility</i></span> 0</h5> </div> </div> {% endfor %} </div> </div> </body> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <script src="{% static 'js/main.js' %}"></script> </html> Views.py: ... @login_required(login_url='login') def index(request): videos = item.objects.all() user = request.user.username return render(request, 'video/index.html', context={'videos': videos, 'user': user}) If you have any better solution please suggest to me that also. -
setting cookie in the middleware
please I need to set cookies country for the user, if it is his first time visit the site, check the following code, I depend on the code on call function class CountrySelectionMiddleware(MiddlewareMixin): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # to check if the browser supports cookies or not # if request.session.test_cookie_worked(): # request.session.delete_test_cookie() country = request.COOKIES.get('country', None) expiry_date = request.session.get_expiry_date() if request.user.is_authenticated and request.user.username: account = Account.objects.filter(username=request.user.username) if account.exists() and country and account.country != country: account.first().update(country=country) elif not request.user.is_authenticated: if country is None or expiry_date < timezone.now(): if request.path != reverse('membership:choose_country'): return HttpResponseRedirect(reverse('membership:choose_country')) # response.set_cookie('country', country, max_age=settings.SESSION_COOKIE_AGE) response = self.get_response(request) country = request.POST.get('country', None) #if country: #response.set_cookie('country', country, max_age=settings.SESSION_COOKIE_AGE) return response the request.POST always return None -
Does elastic beanstack support latest python version?
In EB document it says Django 2.2 is incompatible with the Elastic Beanstalk Python 3.6 platform. The latest compatible version is Django 2.1.https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html But another document says EB support latest python versions, don't they contradict each other ? I wish to try Django 2.2 stable version hosting. https://docs.aws.amazon.com/elasticbeanstalk/latest/platforms/platforms-supported.html#platforms-supported.python -
django rest framework many to many field not working
I need your help regarding something weird. I have the following models: class Profile(models.Model): first_name = models.CharField(max_length=20, default="") last_name = models.CharField(max_length=20, default="") email = models.EmailField(max_length=50, unique=True, default="") image = models.ImageField(null=True, blank=True, upload_to=profile_image_upload_path) class Skill(models.Model): profiles = models.ManyToManyField(Profile, blank=True) name = models.CharField(max_length=30) image = models.ImageField(upload_to=skill_image_upload_path) is_tech_skill = models.BooleanField(default=True) and the following serializer: class SkillSerializer(serializers.ModelSerializer): profiles = serializers.PrimaryKeyRelatedField(queryset=Profile.objects.all(), many=True) class Meta: model=Skill fields=['name', 'image', 'is_tech_skill', 'expertise'] class ProfileSerializer(serializers.ModelSerializer): skill_list = SkillSerializer(read_only=True, many=True,) class Meta: model = Profile fields = ('first_name', 'last_name', 'email', 'image', 'skill_list') depth = 2 when I do GET request for the profile I do not see any skills: enter image description here I added two skills to this profile from django admin panel. Thanks a lot in advance! -
Unable to create related model within forloop
I'm attempting to create a related model within a forloop, but I'm getting the following error: Cannot assign "False": "GoogleProfile.userprofile" must be a "UserProfile" instance. Any thoughts as to how to get this working? my code is below for column in csv.reader(io_string, delimiter=',', quotechar="|"): _, created = UserProfile.objects.update_or_create( busname=column[0], ) google_profile = GoogleProfile.objects.create( userprofile=created, longitude=column[1], latitude=column[2], ) Thanks for your help! -
How To Pass a Dictionary Of Labels and Values into jQuery Autocomplete
I am trying to pass in a dictionary of Labels and Values into my template so that I can use the autocomplete on one of my fields with jQuery. The problem is that my dictionary is not being passed in correctly. I have a Django model Question that has a question and a slug. I want to pass both of these into my template so that when someone clicks on the question text, I can redirect them to the url/slug of that question. Question.html <input id="search-bar" name="question" type="text" class="form-control" placeholder="Find your next question..." aria-label="Find your next question..."> <div class="input-group-append"> <button id="search-question-button" class="btn" type="submit">Search</button> </div> <script> $(function () { $("[name='question']").autocomplete({ source: "{% url 'questions' slug=question.slug %}", select: function (event, ui) { window.location.href = ui.item.value; console.log(ui.item); } }); }); </script> Views.py if 'term' in request.GET: qs = current_questions.filter(question__istartswith=request.GET.get('term')) qs_dict = dict() for question in qs: qs_dict['label'] = question.question qs_dict['value'] = question.slug print(qs_dict) return JsonResponse(qs_dict, safe=False) In my django project console I am printing this dictionary and it seems to be printing correctly {'label': "Blah blah blah", 'value': 'blah-blah-blah'} However, when I inspect my site using chrome I see that the label and value are the same and my dictionary did not get … -
django-rest-framework datatables columns break table
Part 1 I had my datatable working with obj iteration but I am moving to DRF-datatables.. and although I got the example site running no problem the actual implementation on my end is kicking my butt. Basically, I got my whole weekend to show a table that seems to be loading data (as pagination is showing the proper info) but my rows are all blank: https://i.imgur.com/ImA23Zo.png Then I tried to add the "columns" section in the scripts and that breaks the whole table: https://i.imgur.com/ykwf58P.png Where am I going wrong? I'm also not getting any error messages so it's hard to debug datatables. Maybe Part 2.. Do I even need to go for DRF-datatables? My end goal is to be able to select multiple rows and then edit the trade for all those entries. Example of the end goal Select 3 trade Click dropdown somewhere at the top of the table Select Trade PK from that dropdown Click Save Table shows the latest data entry_list.html {% extends "dashboard/base.html" %} {% load i18n %} {% block content %} <!-- Page Heading --> <div class="d-sm-flex align-items-center justify-content-between mb-4"> <h2 class="text-gray-800">{% block title %}{% trans "Imported Entries" %}{% endblock %}</h2> <a role="button" class="btn btn-success" … -
two variables in front of update_or_create
I've come across the following line of code _, created = UserProfile.objects.update_or_create( What is the point of the "_"? Thanks! -
Django | getting circluar import error on ModelForm
I am using Form and FormModel in Django for one of my application. I created one Model as below models.py from django.db import models class ImageProcessor(models.Model): id_image = models.ImageField(upload_to="image_dir") I am using the form as below (forms.py) from django import forms from .models import ImageProcessor class ImageProcessorForm(forms.ModelForm): class Meta: model = ImageProcessor In terminal window I am getting below message, and I am pretty sure that it is because of from .models import ImageProcessor this import. ERROR message: django.core.exceptions.ImproperlyConfigured: The included URLconf 'img_site.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular i mport. -
Caddy server: Running a Django app behind a reverse proxy with docker-compose
I just discovered CaddyServer, and it looks super promising for running multiple applications on the same VPS with Docker. But I'm struggling to set my docker-compose.yml file(s) to work with external domains. I'll use gunicorn later in production, for now I'd just be happy to get the Django runserver to work. Here's my directory structure: caddy/ Caddyfile docker-compose.yml djangoApp/ docker-compose.yml Dockerfile config/ ... manage.py requirements.txt myghostapp/ This is caddy/Caddyfile { email john@gmail.com acme_ca https://acme-staging-v02.api.letsencrypt.org/directory } app1.example.com { reverse_proxy django:8000 } # app2.example.com { # reverse_proxy ghost:2368 # } app2.example.com is my intended second domain, which points to a ghost application. This one works when uncommented (I'm including it for reference). This is caddy/docker-compose (the reverse proxy) version: "3" networks: web: external: true services: caddy: image: caddy:2-alpine restart: unless-stopped ports: - "80:80" - "443:443" volumes: - /data/caddy/Caddyfile:/etc/caddy/Caddyfile networks: - web django: build: context: /data/djangoApp/ dockerfile: /data/djangoApp/Dockerfile restart: unless-stopped environment: - url=app1.example.com volumes: - /data/djangoApp:/app/ networks: - web # ghost: # image: ghost:3.22-alpine # restart: unless-stopped # environment: # - url=app2.example.com # volumes: # - /data/myghostapp:/var/lib/ghost/content # networks: # - web For now, it would be great to get the Django app working. In the djangoApp folder, I have a Dockerfile like … -
Is it possible to automatically run a function on django app thru settings.py?
I have this function on my views.py, I need to automatically runs it after I run python manage.py runserver a guy said that I must run that function it on settings.py. I tried it but I can't import the views & models to my settings.py (maybe because im noob?) so I can't do what he suggested. This is the process, I have a toggle button for enabling and disabling auto_sms function on my frontend javascript(vuejs). if I pick enable it will call the API endpoint of auto_sms thru axios. like do this in a while loop, check in every 30 mins then repeat until get executed then reset. wait for another condition to be valid. responses.count() if I pick disable it will call the API endpoint of disable_sms thru axios (I haven't started coding this yet). like if its detects that auto_sms is true then make it false. I want to ask, is my imagination for my application is possible to happen? @models.py class Rainfall(models.Model): level = models.CharField(max_length=10, blank=True, default='') amount = models.FloatField() timestamp = models.DateTimeField(auto_now_add=True) def update_level(self): if 0.1 <= self.amount < 2.5: return 'Light' elif 2.5 <= self.amount < 7.5: return 'Moderate' elif 7.5 < self.amount < 15: … -
Many to Many duplicate when saving entity with multiples words (ex. The government)
I got a question. I've a models with some M2M fields. My goal is to classify the text. After saving my text, my M2M starts classifying: create a new entry if it does not exist, add the entry if it already exists, But I got an issue: For simple word there is no duplicate but for multiple word (ex. Mr President or Christophe Colomb) I got an error with duplicate entry. class Categories(models.Model): name = models.CharField(max_length=20, unique=True) image_url = models.URLField(max_length=200,blank=True) slug = models.SlugField(editable=False) def save(self, *args,**kwargs): if not self.slug: self.slug = unique_slugify(self, slugify(self.name)) super(Categories, self).save(*args, **kwargs) def __str__(self): return self.name ... catego = models.ManyToManyField('Categories',blank=True, related_name='post_catego') In the save method I got this: for category in response.categories: current_category = Categories.objects.filter(name=category.name) current_post = get_object_or_404(Post, slug=self.slug) if current_category.count()<1: create_category = self.catego.create(name=category.name) current_post.catego.add(create_category) else: existed_category = Categories.objects.get(name=category.name) current_post.catego.add(existed_category) -
Why is my test function not activating the user?
I have a django email verification app that sends email with activation url that contains encoded user pk and a token, then when app recieves the correct data in a url it sets user.is_active boolean value to True. I've written a test that is supposed to create a user and send a get request with it's encoded pk and a token, but it fails to activate my user even though the url is correct (as you will be able to see below) views.py contains signup function and verification class based view. def signup(request): if request.method == 'POST': form = SignupForm(request.POST) if form.is_valid(): user = form.save(commit=False) raw_password = form.cleaned_data.get('password1') name = form.cleaned_data['name'] gender = form.cleaned_data['gender'] user.is_active = False user = User.objects.create(email=user.email, password=raw_password, name=name, gender=gender) user.set_password(raw_password) user.save() # Verification email_subject = 'Activate your followerr account' domain = get_current_site(request).domain user_id = urlsafe_base64_encode(force_bytes(user.pk)) link = reverse('activate', kwargs={ 'user_id': user_id, 'token': token_generator.make_token(user), }) activate_url = 'http://' + domain + link email_body = 'Hello ' + user.name + ' please use this link to verify your account\n' + activate_url email = EmailMessage( email_subject, email_body, 'noreply@domain.com', [user.email], ) email.send() return redirect('login') else: form = SignupForm() return render(request, 'signup.html', {'form': form}) class VerificationView(View): def get(self, request, user_id, token): … -
Django and React always Bad Request when submitting
I am developing a E-Prescription Web App using Django Rest Framework and Bootstrap-React. But I'm facing an error saying that POST http://127.0.0.1:8000/api/prescription-view/ 400 (Bad Request) How to fix this? Btw here's my codes: settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'prescribe_app', ] CORS_ORIGIN_ALLOW_ALL = True MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] views.py @api_view(['GET', 'POST']) def prescription_view(request): if request.method == 'GET': prescription = Prescription.objects.all() serializer = PrescriptionSerializerView(prescription, many=True) return Response(serializer.data) elif request.method == 'POST' : serializer = PrescriptionSerializerView(data=request.data) if serializer.is_valid(): serializer.save() else: content = {'Error': 'Invalid data'} return Response(content,status=status.HTTP_400_BAD_REQUEST) return Response(serializer.data) serializers.py class PrescriptionSerializerView(serializers.ModelSerializer): class Meta: model = Prescription fields = ['drug_name' , 'dosage' , 'route', 'frequency', 'amount_dispensed', 'no_of_refills'] Form.js import React from 'react'; import { Row, Card, Col, Table, Form, Button} from 'react-bootstrap'; class FormPage extends React.Component{ constructor(props){ super(props); this.state = { prescriptionList: [], activeItem: { id:null, drug_name:'', dosage:'', route:'', frequency:'', amount_dispensed:'', no_of_refills:'' }, editing:false, } this.viewPrescription = this.viewPrescription.bind(this) this.handleChange = this.handleChange.bind(this) this.handleSubmit = this.handleSubmit.bind(this) this.getCookie = this.getCookie.bind(this) // this.deleteItem = this.deleteItem.bind(this) // this.startEdit = this.startEdit.bind(this) // this.strikeUnstrike = this.strikeUnstrike.bind(this) }; getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for … -
How do I add Django to path
When I try the following command: django-admin startproject pyshop . It says this django-admin : The term 'django-admin' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 django-admin startproject pyshop . What can I do to get this to work? -
MS Azure Oryx Pre Build Command
Trying to add a Oryx Pre Build Command for apt-get package as per the documentation found here I added the command as an App Setting in the Azure App Service Portal, but when the project builds, it doesn't run the command. Did I place the command in the correct location? -
Django using pre_save to assign username to user if username was empty due to an error
I am trying to use pre_save signal to assign random username to any user if due to an error their username was empty (Social login or edit profile error). Currently, I have: @receiver(pre_save, sender=Profile) def set_username(sender, instance, **kwargs): if not instance.username: rand = random.getrandbits(64) username = "user" + str(rand) while Profile.objects.filter(username=username): rand = random.getrandbits(64) username = "user" + str(rand) instance.username = username Now I was wondering to be safer, how can I generally filter out profiles in my ProfileManager? Can I change the get_queryset() method? Since I read that isn't safe to do so. Or is my pre_save signal enough to make sure users will always have a username no matter what? -
Django Operational Error - problem with UserProfiles in All auth
I am trying to added extra User Profiles within all auth module. However I am still getting the error no such column: profiles_userprofile.default_house FORMS.PY from django import forms from .models import UserProfile class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile exclude = ('user',) def __init__(self, *args, **kwargs): """ Add placeholders and classes, remove auto-generated labels and set autofocus on first field """ super().__init__(*args, **kwargs) placeholders = { 'default_phone_number': 'Phone Number', 'default_postcode': 'Postal Code', 'default_town_or_city': 'Town or City', 'default_street_address1': 'Street Address 1', 'default_house': 'Street Address 2', 'default_home': 'Nr mieszkania', } self.fields['default_phone_number'].widget.attrs['autofocus'] = True for field in self.fields: if field != 'default_country': if self.fields[field].required: placeholder = f'{placeholders[field]} *' else: placeholder = placeholders[field] self.fields[field].widget.attrs['placeholder'] = placeholder self.fields[field].widget.attrs['class'] = 'border-black rounded-0 profile-form-input' self.fields[field].label = False MODELS.PY from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class UserProfile(models.Model): """ A user profile model for maintaining default delivery information and order history """ user = models.OneToOneField(User, on_delete=models.CASCADE) default_phone_number = models.CharField(max_length=20, null=True, blank=True) default_postcode = models.CharField(max_length=20, null=True, blank=True) default_town_or_city = models.CharField(max_length=40, null=True, blank=True) default_street_address1 = models.CharField(max_length=80, null=True, blank=True) default_house = models.IntegerField(null=True, blank=True) default_home = models.IntegerField(null=True, blank=True) def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_or_update_user_profile(sender, instance, created, **kwargs): """ Create or update …