Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Azure shared image gallery using python SDK "GalleriesOperations"
I am trying to create shared image gallery and add existing image to it using "GalleriesOperations" in python SDK, but not sure of what argument to pass for "serializer" and "deserializer" and "config" parameter for GalleriesOperations(client, config, serializer, deserializer) I need some reference code example as I am new to azure. GalleriesOperations(client, config, serializer, deserializer) begin_create_or_update(resource_group_name: str, gallery_name: str, gallery: "_models.Gallery", **kwargs: Any) -> LROPoller['_models.Gallery'] Here is what i was trying , but for compute_client var, its not showing any "compute_client.config" to pass as an argument. compute_client = azure.mgmt.compute.ComputeManagementClient(credential, subscription_id) resource_group_name="xxxx",gallery_name='xxxxx', gallery='_models.Gallery', location='xxxx', tags=None, description=None, identifier="xxxx") -
Django constraint that IS NULL conditions of two columns must match
Consider the following model. class MyModel(models.Model): a = models.DateField(blank=True, default=None, null=True) b = models.DateField(blank=True, default=None, null=True) I'd like to require that both a and b are NULL, or both are NOT NULL. I can express this in raw DDL: ALTER TABLE "app_mymodel" ADD CONSTRAINT "both_or_none_null" CHECK ((a IS NULL) = (b IS NULL)); To get this through Django, I tried class Meta: constraints = [ models.CheckConstraint( check=Q(a__isnull=F('b__isnull')), name='both_or_none_null' ) ] Alas, this produces django.core.exceptions.FieldError: Joined field references are not permitted in this query when I try to apply the resulting migration. I have therefore resorted to the less succinct check=(Q(a__isnull=True) & Q(b__isnull=True)) | (Q(a__isnull=False) & Q(b__isnull=False)) which generates a correspondingly clunky DDL constraint. But my Django-foo is limited, so is there a way to express the original constraint correctly? -
'QuerySet' object has no attribute 'x'
I want to go to a users page and see the their photos, so I was trying to get the objects assigned to a foreign key, but I keep getting the error above AttributeError at /user/30/ 'QuerySet' object has no attribute 'file'. I feel like the problem is in my syntax, but I really have no clue why it can't read my Uploads file model object, but it's able to read my profile objects. views.py def profile_view(request, *args, **kwargs,): #users_id = kwargs.get("users_id") #img = Uploads.objects.filter(profile = users_id).order_by("-id") context = {} user_id = kwargs.get("user_id") try: profile = Profile.objects.get(user=user_id) img = profile.uploads_set.all() except: return HttpResponse("Something went wrong.") if profile and img: context['id'] = profile.id context['user'] = profile.user context['email'] = profile.email context['profile_picture'] = profile.profile_picture.url context['file'] = img.file.url return render(request, "main/profile_visit.html", context) models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, null = False, blank = True) first_name = models.CharField(max_length = 50, null = True, blank = True) last_name = models.CharField(max_length = 50, null = True, blank = True) phone = models.CharField(max_length = 50, null = True, blank = True) email = models.EmailField(max_length = 50, null = True, blank = True) bio = models.TextField(max_length = 300, null = True, blank = True) profile_picture = … -
django charfield not showing in admin panel
i create a model in django and register it in admin.py when i go to admin panel it shows the model but when i want to create object it doesn't show the charfields and i can just create the oject without any details this is my codes below view.py from django.shortcuts import render from django.http import HttpResponse from .models import Feature # Create your views here. def index(request): features = Feature.objects.all() return render(request, 'index.html', {'features' : features}) model.py from django.db import models # Create your models here. class Feature(models.Model): name: models.CharField(max_length=100) details: models.CharField(max_length=200) stting.py """ Django settings for myproject project. Generated by 'django-admin startproject' using Django 3.2.12. For more information on this file, see For the full list of settings and their values, see """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-dubzu2qq@tk9lk%d05a*@j1rd1hkr$v72eiga+*u7%v2d)19_5' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'livesync', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp' ] MIDDLEWARE … -
How can I call different Fields from one Django models to another fields of another Django Field?
I want to call MemberRegistration Model's 'fname' and 'regino' fields to TypeCharge Model (in 'serial' field), and 'fname' and 'presentaddress' fields to BankAccount Model (in 'accholder' field). I tried Foreign Key but it can only return one combination at a time due to def str(self). Thank You..! Here are my models: `class MemberRegistration(models.Model): regino = models.PositiveIntegerField(default=user_id) fname = models.CharField(max_length=200) presentaddress = models.CharField(max_length=500) def __str__(self): return str(self.regino) + " - " + self.fname class TypeCharge(models.Model): serial = models.ForeignKey(MemberRegistration, on_delete=models.CASCADE) chargename = models.CharField(max_length=200) class BankAccount(models.Model): accholder = models.ForeignKey(MemberRegistration, on_delete=models.CASCADE)` ``` -
How can I receive a list of dictionaries in djano?
Hello I am working on a djago project and I want to recieve a list of dictionaries just like this: [{1: 20}, {2:30}, {3: 50}, ......] here the key is the id of the productand value is price And the code below is just receiving a single dictionary like this {"id": 1, "price" : 20} I want to change it to something look like I mentioned above list_of_objects = [] try: id = int(request.payload.get("id")) price = int(request.payload.get("price")) list_of_objects.append({ "id" : id, "price" : price }) except ValueError: return response.bad_request("Invalid price, %s, should be in whole dollars" % price) I don't know how to do it Thanks -
Активировал venv, но все пакеты устанавливаются в общий питон [closed]
Установил venv, но при попытке установки пакетов, пишет, что они установлены. Проверяю через pip list, пишет все пакеты, которые установлены на стандартном pip. https://i.stack.imgur.com/pnGKv.png Скрин интерпретатора https://i.stack.imgur.com/ks6LP.png https://i.stack.imgur.com/hwp0C.png И скрин терминала https://i.stack.imgur.com/J0GEd.png Больше двух часов не могу решить проблему, помогите пожалуйста. -
'NoneType' object has no attribute 'json'
**Question ** 'NoneType' object has no attribute 'json' how to solve this error views.py from django.shortcuts import render from django.http import HttpResponse #from django.shortcuts import render import json import dotenv #from . models import Contect from flask import Flask, render_template, Response from rest_framework.response import Response # Create your views here. def home1(request): # get the list of todos response1 = request.GET.get('https://jsonplaceholder.typicode.com/todos/') # transfor the response to json objects todos = response1.json() return render(request, "main_app/home.html", {"todos": todos}) -
Make single CharField display as textarea inside a fieldset
I have a user model: class User(AbstractBaseUser): username = models.CharField(max_length=64, unique=True) email = models.EmailField(unique=True) about_me = models.CharField(max_length=140, blank=True) last_login = models.DateTimeField(auto_now_add=True) last_message_read_time = models.DateTimeField(auto_now_add=True) following = models.ManyToManyField("self",symmetrical=False) def save(self, *args, **kwargs): self.full_clean() return super().save(*args, **kwargs) def clean(self): obj = self parents = set() while obj is not None: if obj in parents: raise ValidationError('Cannot follow self', code='self_follow') parents.add(obj) obj = obj.parent and this admin form: class BlogUserAdmin(admin.ModelAdmin): fieldsets = [ (None, { 'fields': ['username', 'email', 'password'] }), ('Biography', { 'classes': ['collapse'], 'fields': ['about_me'] }), ('Follows', { 'classes': ['collapse'], 'fields': ['following'] }), ] admin.site.register(User, BlogUserAdmin) and it displays like this: imgur I want to make the "about me" a text area. I have viewed methods where you define the text area in forms.py but it seems that fieldsets do not support forms from that. I'm assuming this is not possible and that I will have to define my own form from scratch but perhaps there is some setting or method or class I have overlooked? -
Elasticsearch dsl
I need an multi match and suggestions in elasticsearch-dsl search1 = search.filter( 'nested', path='item_id', query=Q('match', item_id__code=categoryField.code) ) I tried multi_phrase and multi_phrase_prefix but not working ! -
update api not working in django rest framework
I have a simple update api which is not working properly. I tested the API in postman by sending only the key and data that needs to be updated but my frontend is sending whole formdata along with the data that are updated. It is working in my postman when I send only the key and the data that needs to be updated but when I send all the data with certain fields as empty string (""), it does not get updated. My models: class Lead(models.Model): title = models.CharField(max_length=5, choices=TITLES, blank=True) first_name = models.CharField(max_length=30) middle_name = models.CharField(max_length=30, blank=True) last_name = models.CharField(max_length=30) address = models.CharField(max_length=100, blank=True) city = models.CharField(max_length=50, blank=True) state = models.CharField(max_length=50, blank=True) country = models.CharField(max_length=30, default="nepal") phone = models.CharField(max_length=50, ) /........other fields................................/ My views: class LeadsView(APIView): permission_classes = [AllowAny] def put(self, request, pk=None, *args, **kwargs): print("iam put") id = pk abc = Lead.objects.get(id=id) serializer = LeadSerializer(abc,data=request.data) if serializer.is_valid(): serializer.save() return Response({ "message": " Leads has been updated", "data": serializer.data }, status=status.HTTP_200_OK) return Response(serializer.data) My serializers: class LeadSerializer(serializers.ModelSerializer): email= serializers.EmailField(required=False) phone = serializers.CharField(required=False) first_name = serializers.CharField(required=False) last_name = serializers.CharField(required=False) title = serializers.CharField(required=False) address = serializers.CharField(required=False) company_name = serializers.CharField(required=False) /.................same in other fields............../ class Meta: model = Lead fields = ['id','title','first_name','last_name','address','company_name', … -
How to upload images with AJAX in DJANGO
I have been using AJAX recently with DJANGO to send text data. It has been working smoothly and feels an easy method. But I cant understand and there no proper resource to learn to send images with AJAX and save to Django Database. HTML: <input type="file" id="fileInput-single" class="drop-zoon__file-input" accept="image/*"> JS: $(".add-prop").click(function() { var data = new FormData(); data.append("image", $("#fileInput-single")[0].files[0]) data.append("csrfmiddlewaretoken", $("input[name=csrfmiddlewaretoken]").val()) $.ajax({ method: "POST", url: "{% url 'upload-prop-images' %}", processData: false, contentType: false, mimeType: "multipart/form-data", data: data, success: function(data) { if (data.status == "Upload Done") { console.log("Uploading Done successfully") } } }) }); models.py class Property(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name='property_user') prop_images = models.ImageField(upload_to="prop_images") views.py def uploadPropImages(request): image = request.POST['image'] property_new = Property(user_id=request.user.id, prop_images=image) property_new.save() return JsonResponse({'status': 'Upload Done'}) urls.py urlpatterns = [ path('upload-prop-images/', views.uploadPropImages, name='upload-prop-images') ] There is one tutorial using the forms.py file but I don't want to create a forms.py file. -
How to backend filter exact field of model
I have model named Tittle and I wanted to filter its GET respond by the "genres->slug". I tried to use backend filter with filterset_fields = ("genres__slug",). But it is not doing what I thought. How can I filter it by the model Slug of the Genres? views.py class TitleViewSet(viewsets.ModelViewSet): queryset = Title.objects.all() permission_classes = (AdminModifyOrReadOnlyPermission,) pagination_class = LimitOffsetPagination filter_backends = (DjangoFilterBackend, ) filterset_fields = ('genres',) def get_serializer_class(self): if self.action == 'list' or self.action == 'retrieve': return ReadTitleSerializer return WriteTitleSerializer models.py class Title(models.Model): ... genres = models.ManyToManyField( Genre, through='GenreTitle', ) class Genre(models.Model): name = models.CharField( max_length=255, verbose_name='Название жанра' ) slug = models.SlugField( unique=True, verbose_name='Слаг жанра' ) def __str__(self) -> str: return self.slug class GenreTitle(models.Model): title_id = models.ForeignKey( Title, on_delete=models.CASCADE, related_name='genres_titles' ) genre_id = models.ForeignKey( Genre, on_delete=models.CASCADE, related_name='genres_title' ) -
how to use many to many field in django serializers and How o use related_name for that
class PamphletLocation(models.Model): pin_code = models.CharField(max_length=6) def __str__(self): return self.pin_code class PamphletCampaign(Campaign): PAMPHLET_SIZE_CHOICES = ( ('A4', 'A4'), ('A5', 'A5'), ) pamphlet_id = models.ForeignKey(ClientPamphletDesign, on_delete=models.CASCADE) size = models.CharField(max_length=3, choices=PAMPHLET_SIZE_CHOICES) pin_codes = models.ManyToManyField(PamphletLocation, related_name="pin_codes_str") class Meta: verbose_name = 'Campaign' class CreatePamphletCampaignSerializer(serializers.ModelSerializer): pin_codes_str = PamphletDistributionLocationListSerializer(read_only=True, many=True) class Meta: model = PamphletCampaign fields = ('id', 'name', 'quantity', 'file', 'sub_industry', 'amount', 'pamphlet_id', 'pin_codes_str') -
django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on 'localhost' ([Errno 99] Address not available)")
I have built a Django app along with Mariadb by referring to this https://www.javatpoint.com/django-crud-application And I'm trying to make a docker image for this app. I am completely new to Docker and I'm not able to figure out what I am doing wrong. This is my Dockerfile FROM python:3.9.10-alpine # set work directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install dependencies RUN pip install --upgrade pip COPY ./requirements.txt /usr/src/app RUN pip install -r requirements.txt # copy project COPY . /usr/src/app EXPOSE 8000 CMD python3 manage.py runserver This is my requirements.txt file asgiref==3.5.0 Django==4.0.2 protobuf==3.19.4 PyMySQL==1.0.2 six==1.16.0 sqlparse==0.4.2 The docker build is successful, but if I try to run the docker image, I get this error and I have no idea on what I'm supposed to do. Should I make a Docker compose file ? I don't know why that is used, as I said I'm completely new to Docker. Can someone please help me out ? -
How to pass some data from html to django view? Should I just try with javascript?
I'm rendering some questions about math from a Postgres database. Exercises have a field with correct answers; I'm passing it to view. I want to compare the answers the user sends through a form with correct answers. How could I pass the correct answers (as a list, for example) to a view to check how many are correct? Is there a way in Django ou I should use JavaScript? This is the views.py from django.shortcuts import render from questoes.models import Questao from .forms import CHOICES from django.forms import formset_factory # Create your views here. #I'd like to use this function to compare the answers. In this part I'm getting the responses from the form def get_respostas(request): form = CHOICES(request.POST) if request.method=='POST': form0 = request.POST['form-0-NUMS'] form1 = request.POST['form-1-NUMS'] form2 = request.POST['form-2-NUMS'] form3 = request.POST['form-3-NUMS'] form4 = request.POST['form-4-NUMS'] # Id like to test here. return render(request,"provas/teste.html") def prova(request): questoes = Questao.objects.order_by('?')[:5] gabarito = [] for q in questoes: gabarito.append(q.gabarito) form = CHOICES respostaFormSet = formset_factory(CHOICES, extra=5) if request.method=='POST': dados = { 'formset': formset, 'questoes': questoes, 'form':form(request.POST), 'gabarito':gabarito } return render(request,'provas/prova.html', dados) else: dados = { 'formset': formset, 'questoes': questoes, 'form':form, 'gabarito':gabarito } return render(request,'provas/prova.html', dados) this is the prova.html {% if questoes … -
How to sort related objects based on the timestamp of when we are associating the two objects?
i'm trying to sort objects based on the time when i associate the two objects. For example, i have these two models: class Album(models.Model): title = models.CharField(max_length=255) release_date = models.DateField() order = models.IntegerField(blank=True, null=True, help_text="The order of albums to be displayed.") class Artist(models.Model): name = models.CharField(max_length=255) stage_name = models.CharField(max_length=125) is_active = models.BooleanField(default=True) albums = models.ManyToManyField(Album, blank=True) I have an Album model, that have an order field to sort the priority of the album when we display it on the API. Now, of course it is working when i sort the albums based on the order field: artist = Artist.objects.get(id=76) album1 = Album.objects.create(title="Untitled Album", order=2) album2 = Album.objects.create(title="Magical Nights", order=1) artist.albums.add(album1, album2) albums = Album.objects.filter(artist=artist).order_by('order') print(albums) >> <QuerySet [<Album: Magical Nights>, <Album: Untitled Album>]> But when i have some albums with the same priority, i want to also sort the objects based on the timestamp of when i associate the item. Something like this: artist2 = Artist.objects.get(id=77) new_album1 = Album.objects.create(title="Sapphire Blue", order=1) new_album2 = Album.objects.create(title="Now We're Strangers", order=2) new_album3 = Album.objects.create(title="Fight For You", order=1) artist2.albums.add(new_album3) artist2.albums.add(new_album2) artist2.albums.add(new_album1) albums = Album.objects.filter(artist=artist2).order_by('order') print(albums) >> <QuerySet [<Album: Sapphire Blue>, <Album: Fight For You>, <Album: Now We're Strangers>]> My expected result is that when we … -
Django - NoReverseMatch Error even with correct parameters (no namespacing)
I'm trying to create an app that stores problems (specifically math problems), and displays them to the user. I haven't add much of the functionality that I want to yet, and as I'm fairly new to Django, I have been following along with the Django Tutorial project, and changing it according to my needs. However, I'm encountering a NoReverseMatch error even though I seem to be passing in the correct parameters. My code is below. models.py import imp from django.db import models from django.urls import reverse import uuid # Create your models here. class Source(models.Model): '''Model that represents the source of a problem (e.g. AMC, AIME, etc.)''' problem_source = models.CharField(max_length=20) problem_number = models.PositiveSmallIntegerField() def __str__(self): '''toString() method''' return f'{self.problem_source} #{self.problem_number}' class Topic(models.Model): '''Model that represents the topic of a problem (e.g. Intermediate Combo)''' problem_topic = models.CharField(max_length=50) problem_level = models.CharField(max_length=15) def __str__(self): return f'{self.problem_level} {self.problem_topic}' class Problem(models.Model): '''Model that represents each problem (e.g. AIME #1, AMC #11, etc.)''' id = models.UUIDField(primary_key=True, default=uuid.uuid4) source = models.OneToOneField(Source, on_delete=models.RESTRICT, null=True, unique=True) problem_text = models.TextField() topic = models.ManyToManyField(Topic) def __str__(self): """String for representing the Model object.""" return f'{self.source}' def get_absolute_url(self): """Returns the url to access a detail record for this book.""" return reverse('problem-detail', args=[str(self.id)]) urls.py … -
Django running timer
I'm trying to implement a running timer on a django app/website. Essentially I would like for someway to input let's say 5 min and then start and then a timer will start that will countdown to 0:00. Any help with where I can start? I've found some tutorials that have running timers but this is part of a project where I would like after the timer for a signal to be sent to a microcontroller (that's not important for this part). -
How to link HTML and CSS file using Django?
I am novice person to Django learning. I have tried with simple linking HTML and CSS files in Django by referring some sites and videos but it seems CSS file is not included. Though I tried multiple times I am not getting the background color which I put in CSS file. CSS file saved in static/css/style.css body{ background-color: violet; } HTML file saved in templates/bg.html {%load static%} <!<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title> BG </title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="{% static 'style.css' %}"> </head> <body> <h2 class="bg_class">BG Colour</h2> <p> Background Color is to be changed.<br> </p> <script src="" async defer></script> </body> </html> Also, I have configured the static file in settings.py file too. STATIC_URL = '/static/' STATIC_DIRS=[ os.path.join(BASE_DIR,'static') ] Instead of ‘violet’ background, I am still getting ‘white’ background. Kindly help me to fix this. -
How to upload an image to DriveHq using django?
Can any one give me the code for uploading an image through html file and using django for uploading that image to DriveHq. Thankyou so much... -
Django print statements/debug on hosted app pythonanywhere
I have a Django app working fine on the local server but when I host it on the pythonanywhere (It is a cloud-based python site), there are some issues with the rendering on the template. While I was coding on the local server, I used to use print statements to debug the functions in views.py, but how to use print statements for debugging if the site is deployed on the web because after hosting it on the pythonanywhere, I am unable to find where the output of the print statements goes to? Please suggest ay other way, if this is not feasible, to get the backend output after deploying the django web app. Thanks for the help. -
Use django, filter and get to the same id, but result data not same, why?
enter image description here just like this, I guess its beacause of caches, but i don't ensure, how should i do? thanks -
Is there any function to filter the field values based on another field value in django
model1 class Client(models.Model): client_name=models.CharField(max_length=20) company=models.CharField(max_length=200) finance_contact_email=models.EmailField(max_length=25,default=None) business_purpose=models.CharField(max_length=50,null=True,default=None) location=models.CharField(max_length=200) emergency_contact=models.CharField(max_length=200,null=True,default=None) website=models.URLField(max_length=200,null=True) comments=models.TextField(max_length=300,null=True, blank=True) start_Date = models.DateTimeField(max_length=10,null=True) end_Date=models.DateField(max_length=10,null=True) Model2 class Project(models.Model): project_name = models.CharField(max_length=20) client= models.ForeignKey(Client,on_delete=CASCADE,related_name="Client1",default=None) description=models.TextField() type=models.TextField() start_date = models.DateTimeField(max_length=10) end_date=models.DateTimeField(max_length=10) technical_contact_name = models.CharField(max_length=30) email=models.EmailField(max_length=254,default=None) phone = PhoneField(blank=True) delivery_head_contact_name=models.CharField(max_length=30) model3 class Job(models.Model): job_name=models.CharField(max_length=50) client=models.ForeignKey(Client,on_delete=CASCADE,related_name='client',default=None) project=models.ForeignKey(Project,on_delete=CASCADE,related_name='project',default=None) user=models.ForeignKey(User,on_delete=CASCADE,related_name='user',default=None) hours=models.TimeField(null=True) start_date = models.DateTimeField(max_length=10) end_date=models.DateTimeField(max_length=10) Actually I need to filter the values based on the clients in the Job model. For example we will be giving the project_name on the Project model based on selecting the specific clients. So we need a filter in the Job model like if we select the specific client in the field, it needs to display only the projects available for that client in the project field of Job model. Now it is displaying all the projects which are inputted. Please help me get this solved as I am new to django. -
How to add optional parameters in a django view keeping the same url
Let's say I have the following URL: http://127.0.0.1:8000/en/project_page/1/ and my urls.py: path( 'project_page/<int:pid>/', views.project_page, kwargs={'approvalid': None}, name='project_page' ), Generally speaking, the users will always access via http://127.0.0.1:8000/en/project_page/1/ , but in some cases I want to pass an optional parameter so that the page renders optional content. For example, if the user access: http://127.0.0.1:8000/en/project_page/1/somevalue I would like to see the content of somevalue in my view, like: def project_page(request, pid, somevalue): if somevalue: #do something here with the optional parameter else: #run the view normally Once we get the optional parameter, I want the url structure to be the original: http://127.0.0.1:8000/en/project_page/1/somevalue -> get the value of the optional parameter and get back to the original url -> http://127.0.0.1:8000/en/project_page/1/ What I've tried: I thought kwargs would do the trick, but I did something wrong. I found this from the official docs (Passing extra options to view functions) but it seems that I'm doing something wrong.