Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
is django good for future career [closed]
is Django is good for a future career. actually, I want to become a full-stack developer please guide me -
AllValuesFilter shows data from other than the user, even when provided a queryset (Django-filters)
I'm trying to apply a AllValuesFilter to filter on a tag-field, such that the user can filter on the tag the given user has provided. I want only the logged-in user to be able to see its own tag. Right now I have the following: #filters.py import django_filters class Filter(django_filters.FilterSet): #zip(NICK_NAME_CHOICES,NICK_NAME_CHOICES) tag = django_filters.AllValuesFilter(field_name = "tag", label="Tag") and in my view.py from .filters import Filter def my_view(request): user = request.user user_products = MyModel.objects.filter(user=user).all() #Products added by the user filter = Filter(request.GET,queryset = user_products) . . context = {"filter":filter} return render(request,"my_html.html",context = context) the issue is that the choice-menu shows tags created by all users, and not just the one logged in. I thought the queryset was to avoid exactly this behaviour? -
DRF serialization - many-to-many field with through
How to serialize data from many-to-many field with through parameter? I have 3 models: class Ingredient(models.Model): name = models.CharField( max_length=200, ) measurement_unit = models.CharField( max_length=200, ) class Recipe(models.Model): name = models.CharField( max_length=200, ) ingredients = models.ManyToManyField( Ingredient, through='RecipeIngredientsDetails', ) class RecipeIngredientsDetails(models.Model): recipe = models.ForeignKey( Recipe, on_delete=models.CASCADE, ) ingredient = models.ForeignKey( Ingredient, on_delete=models.CASCADE, ) amount = models.FloatField() My serializers: class IngredientSerializer(ModelSerializer): # amount = ??? class Meta: model = Ingredient fields = ["id", "name", "amount", "measurement_unit"] class RecipeSerializer(ModelSerializer): class Meta: model = Recipe fields = ["name", "ingredients"] depth = 1 Now, I get: { "name": "Nice title", "ingredients": [ { "id": 1, "name": "salt", "measurement_unit": "g" }, { "id": 2, "name": "sugar", "measurement_unit": "g" } ] } I need amount-value in every ingredient. How can I implement it? -
Send a file as response to a post request
i m using django drf and react native, i m sending an image from the frontend and expecting to recieve a file as a response containing the OCR result of the image, However i haven't been able to acheive that i m used HttpResponseRedirect to redirect to the file url but i couldn't really figure out how to do it so i decided to currently return a json response with the file url still getting nothing: from processing.models import Uploads from rest_framework import viewsets from rest_framework.response import Response from django.http import HttpResponse , JsonResponse, response from .serializers import UploadSerializer from django.shortcuts import render from django.http import HttpResponseRedirect from digitize.models import File # Create your views here. class UploadView(viewsets.ModelViewSet): queryset=Uploads.objects.all() serializer_class=UploadSerializer def methodes(self,request,*args,**kwargs): if request.method=='POST': serializer=UploadSerializer(data=request.data) if serializer.is_valid(): serializer.save() data=File.objects.filter(id=str(File.objects.latest('created_at'))) file_data=data.values('file') response = JsonResponse(file_data, headers={ 'Content-Type': 'application/json',}) #'Content-Disposition': 'attachment; filename="foo.txt"', }) return(response) return HttpResponse({'message':'error'},status=400) elif request.methode=='GET': images=Uploads.objects.all() serializers=UploadSerializer(images,many=True) return JsonResponse(serializers.data,safe=False) -
Django overwrite validate MultipleChoiceField and remove queryset required
i'm tring to make a custom MultipleChoiceField but i have 2 problems 1st seems i can't overwrite validate function... when i try it print("i'm here") never come in my console even when that field triggers invalid_choice error class OdsTaggerlMultipleChoiceField(forms.ModelMultipleChoiceField): required=False def label_from_instance(self, obj): return obj.tag def __init__(self, *args, **kwargs): super(OdsTaggerlMultipleChoiceField, self).__init__(*args, **kwargs) self.to_field_name="tag" self.widget.attrs['class'] = 'odstagger' def validate(self, value): #azione cattiva valida la qualunque if self.required and len(value) < 1: raise forms.ValidationError(self.error_messages['required'], code='required') print("i'm here") 2nd problem is about queryset it's required to use that field, but i think resolving 1ts problem i can just use a empty choices list tags = OdsTaggerlMultipleChoiceField(queryset=Tag.objects.all()) do you know how resolve that? -
Django: how to update a user profile
I'm currently creating a workout application/blog using Django. What I'd like to do is every time the user enters in a new blog post, the program should look at the exercise fields and update their user profile with the max values for various lifts (deadlift, bench press, etc). I'm quite new to Django and it hasn't quite clicked on how models can interact with each other in this way I have the Profile class in user\models, which is the area I want to update. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') max_squat = models.FloatField(default=0.0) max_bench = models.FloatField(default=0.0) max_deadlift = models.FloatField(default=0.0) max_ohp = models.FloatField(default=0.0) squat_reps = models.IntegerField(default=0) bench_reps = models.IntegerField(default=0) deadlift_reps = models.IntegerField(default=0) ohp_reps = models.IntegerField(default=0) Then I have the blog post class, which has the variables in which the user enters for each blog post class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() workout = models.CharField(max_length=100, choices=const.WORKOUTS, default='deadlift') weight = models.CharField(max_length=200) sets = models.IntegerField(default=0) reps = models.CharField(max_length=200) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) Tried something like this but no joy: profile = Profile() profile.max_deadlift = weight profile.save() Any help is appreciated. -
Calling related name models in query (Q) "Django"
I have profile model like : class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile") first_name = models.CharField(max_length=30, blank=True, null=True) last_name = models.CharField(max_length=30, blank=True, null=True) and I have a search view like : def users_search_view(request): query = request.GET.get('q') users = User.objects.filter(Q(email__icontains=query)|Q(username__icontains=query),is_superuser=False,is_staff=False) ctx = {'users':users, 'q':query} return render(request,"staff/users_search.html", ctx) I want to have search by first name and also last name from Profile model, in my search, How can I make something like Q(email__icontains=query) for related modals ? -
Why is django showing variable (DateTimeFIeld) as None, even though it exists in SqLite?
I'm brand new to django and sqlLite have the problem that the value from a variable exists in SqlLite but it doesn't exist in django, using the following code: @api_view(['GET']) def predmetiSedamDana(request): p=Podaci.objects.select_related("id_predmeta","id_sedmice","id_semestra").all() p_json=[] for i in p: p_json.append({'broj_sedmice': i.id_sedmice.broj_sedmice,'naziv': i.id_predmeta.naziv,'broj_prisutnih': i.broj_prisutnih, 'pocetak_termina': i.id_predmeta.pocetak_termina,'kraj_termina': i.id_predmeta.kraj_termina, 'pocetak_semestra': i.id_semestra.pocetak_semestra,'dan': i.id_predmeta.dan,'vrsta': i.id_predmeta.vrsta.vrsta}) print(i.id_predmeta.dan) r=json.dumps(p_json, indent=1, cls=DjangoJSONEncoder) return HttpResponse(r) All the data that I got exists, except for i.id_predmeta.dan which is none, but in SqLite the value from i.id_predmeta.dan exists. SqlLite Django But if I put in SqlLite console, the following query update podaci_predmet set dan=datetime() where id=1; and rerunning the following function it returns a date. SqlLite after running update query Does anyone else know why this keeps happening, is there any other way to fix it! Any tip is useful, and thank you in advance! -
How to resolve multiple querysets in graphene.Union?
I want to create a graphene.Union type of multiple existing types. I am able to resolve it but it is not in my required format. Schema from graphene_django import DjangoObjectType class ageType(DjangoObjectType): class Meta: model = age class ethnicityType(DjangoObjectType): class Meta: model = ethnicity class combinedType(graphene.Union): class Meta: types = (ageType, ethnicityType) class Query(graphene.ObjectType): defaultPicker = graphene.List(combinedType) def resolve_defaultPicker(self, info): items = [] age_q = age.objects.all() items.extend(age_q) ethnicity_q = ethnicity.objects.all() items.extend(ethnicity_q) return items The query I am using in the graphql admin: { defaultPicker{ ... on ageType{ id age } ... on ethnicityType{ id ethnicity } } } I want to get a output like this: { "data": { "defaultPicker": [ 'ageType': [{ "id": "2", "ethnicity": "American", "ethnicityFr": "Test" }], 'ethnicityType': [{ "id": "1", "familyPlans": "3 kids", "familyPlansFr": "3 enfants" }], ] } } I tried many things but couldn't find a way to resolve it. -
currentTime of audio not changing in js for django input
I have an input range slider <input type="range" min="0" max="100" value="0" id="duration_slider" onchange="change_duration()" > I take my audio file from HTML <audio id = "mysong"> <source src = "{{song.song.url}}" type = "audio/mp3"> </audio> So, I want to change the currentTime of the audio on changing the slider (seeking). For this I have written so far let slider = document.querySelector('#duration_slider'); var mysong = document.getElementById('mysong'); function change_duration(){ mysong.currentTime = mysong.duration * (slider.value / 100); console.log(mysong.duration * (slider.value / 100)); console.log(mysong.currentTime); } And to update the slider as the music progresses, I have function range_slider(){ let position = 0; if(!isNaN(mysong.duration)){ slider_position = mysong.currentTime * (100 / mysong.duration); slider.value = slider_position; } if(mysong.ended){ play.innerHTML = '<i class="fa fa-play" aria-hidden="true"></i>'; } } From console, I can see that the value of mysong.currentTime is not changing and always returns to 0. Eg of a value on console 40.22376 and 0 respectively. And every time I try to seek the slider, the song restarts. Edit: The code seems to work fine if I directly take audio input from HTML. But not when I use song from django. -
Django Mixin, Python Inheritance behaviour - Returning old values for multiple classes
I wanted to clarify a behavior in python Here's a snippet written in django from django.shortcuts import render from django.views.generic import CreateView, UpdateView, TemplateView from testapp.models import TestCategory # Create your views here. class xMixin: someVal = {} def get_someval(self): return self.urlVal def get_value(self): return get_someval() class TestCategoryCreateView(xMixin, TemplateView): model = TestCategory template_name = "test_cat.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["urlv"] = self.get_value() return context class TestCategoryUpdateView(xMixin, TemplateView): model = TestCategory template_name = "test_cat.html" def get_someval(self): urlval = super().get_someval() urlval['123'] = 'abc' return urlval def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["urlv"] = self.get_value() return context I was expecting the context["urlv"] getting their respective values.. for TestCategoryUpdateView, it should be { '123': 'abc' } and for TestCategoryCreateView, it should be {} But, when i do the following steps, it results differently Visit create view url -> urlv is {} Visit update view url -> urlv is { '123' : 'abc' } Visit create view url again -> urlv is { '123' : 'abc' } Visit create view url anytime from this point -> urlv is { '123' : 'abc' } What would be a good way to avoid this behaviour ? -
To calculate the number of days between two specified days in Django?
I'm a student studying Django. I want to calculate the number of days between the two specified dates. Currently, View has specified two variables and attempted a subtraction operation, but the following error is being output: Could not parse the remainder: ' - today' from 'product.due_date|date:"Ymd" - today' How should I solve this problem? I would appreciate it if you could give me an answer. Attached is models.py and View.py below. models.py def product_detail(request, id, product_slug=None): current_category = None categories = Category.objects.all() products = Product.objects.all() product = get_object_or_404(Product, product_code=id, slug=product_slug) designated_object = Designated.objects.filter(rep_price='True') element_object = Element.objects.all() value_object = Value.objects.all() today = DateFormat(datetime.now()).format('Ymd') return render(request, 'zeronine/detail.html', {'product':product, 'products':products, 'current_category': current_category, 'categories':categories, 'designated_object': designated_object, 'element_object':element_object, 'value_object':value_object, 'today':today}) views.py class Product(models.Model): product_code = models.AutoField(primary_key=True) username = models.ForeignKey(Member, on_delete=models.CASCADE, db_column='username') category_code = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, related_name='products') name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True, unique=False, allow_unicode=True) image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True) benefit = models.TextField() detail = models.TextField() target_price = models.IntegerField() start_date = models.DateField() due_date = models.DateField() Created as {product.due_date|date:"Ymd" - today}}. -
Change text color when clicking Nav-link
I am a student learning Django. The code I wrote is as follows, but when I run it, the text becomes bold only when I select the text margin, and when I click the text, there is no change in the text. I want the text to be bold when I click on it. What should I do? I'd appreciate it if you could tell me how. code : <style> .menu-wrap li{ display: inline-block; padding: 10px;} .menu-wrap li.selected{ color:green; font-weight: 600; } </style> <ul class="menu-wrap"> <li class="nav-link"><a href="#">link1</a></li> <li class="nav-link"><a href="#">link2</a></li> <li class="nav-link"><a href="#">link3</a></li> <li class="nav-link"><a href="#">link4</a></li> </ul> <script> const menuWrap = document.querySelector('.menu-wrap'); function select(ulEl, aEl){ Array.from(ulEl.children).forEach( v => v.classList.remove('selected') ) if(aEl) aEl.classList.add('selected'); } menuWrap.addEventListener('click', e => { const selected = e.target; select(menuWrap, selected); }) </script> -
asynchronus form submission django
I'm using ajax to submit a form, and it's working. But it's not working asynchronously. When I'm trying to upload files it uploaded successfully and then the page loads again. I want it to make asynchronously. In addition, I want to make a progress bar too. But things not working as I expected. my forms.py from django import forms from .models import Comment from .models import post class UploadForm(forms.ModelForm): class Meta: model = post fields = ('image', 'video', 'content',) my views.py def django_image_and_file_upload_ajax(request): if request.method == 'POST': form = UploadForm(request.POST, request.FILES) if form.is_valid(): form.instance.author = request.user form.save() return JsonResponse({'error': False, 'message': 'Uploaded Successfully'}) else: return JsonResponse({'error': True, 'errors': form.errors}) else: form = UploadForm() return render(request, 'blog/upload.html', {'form': form}) and my upload.html {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <main> <div class="container"> <div class="row"> <div class="col-md-8 my-5"> <div class="content-section" style="padding:10px 20px"> <form enctype="multipart/form-data" id="id_ajax_upload_form" method="POST" novalidate=""> <fieldset class="form-group"> {% csrf_token %} <legend class="border-bottom mb-4"><i class="fas fa-feather-alt text-muted mr-2"></i>Create a post</legend> {{ form.as_p }} </fieldset> <div class="form-group"> <input type="submit" /> </div> </form> </div> </div> </div> </div> </main> {% endblock content %} <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script type="text/javascript"> // form upload $('#id_ajax_upload_form').submit(function(e){ e.preventDefault(); $form = $(this) var formData = new … -
Windows IIS Server stops Django processes after 2 minutes
I have django project that provides a IP Camera streaming and recording system that is using Python OpenCV so it needs to run processes for a long time, maybe one hour or more. However, the Windows IIS Server stops the processes after about 2 minutes. Is There any way to prevent IIS from doing that? -
How To Put Javascript In A Django View
I have a small piece of javascript that I want to put in my django view (to be ran in the web server, not the client's computer). I know how to put in into a template, but I don't know how to have it run on the server's (in this case heroku). -
Why do I get heroku error : App not compatible with buildpack
So I'm trying to deploy my Django project with heroku. I have created an app and connected by git repo. However when I try to deploy, I get this error : App not compatible with buildpack. So the possible cause is that the git repo that is connected is not exactly the root folder of my Django project, since I have both React (for FE) and Django (for BE). Hence the repo contains two directories inside. Please see the repo itself (link) Now I think the reason why I'm getting the error above is because I've connected repo "/bookcake", not "bookcake/synergy_django" which is the exact root folder of my Django project. How so I deal with this error? Thank you very much. -
Django Template System
I want to create beautiful modern Front-end UIs for my web app. I have a small exposure to Django. Django is perfect for the backend I am building so that's confirmed. The issue is that whether the Django template system flexible enough to create front-end UIs like below? -
Django TypeError while trying to list objects in html
I want to make manually create form for a model but when I try to call object.all() method it gives me TypeError error in return. def addPatient(request): con = Intensivecare_Form.objects.all() context = {'items': con, 'title': 'Items'} if request.method == 'POST': patient = Patient(name=request.POST.get("fname"), data=request.POST.get( "lname"), Intensivecare_Form=request.POST.get("cform")) try: patient.full_clean() patient.save() except ValidationError as e: # Do something based on the errors contained in e.message_dict. # Display them to a user, or handle them programmatically. return HttpResponse("Your form is wrong, try again") return render(request, context, 'AddPatient.html') I couldn't do to return model data for html. -
Unhash encrypted text in Python [duplicate]
I have these codes to hash a string. import hashlib test = "TESSTTT HASHHHING STRING" test1 = hashlib.sha256(test.encode('utf-8')) hashed = test1.hexdigest() result: dba883d794567f6fb740abe0e4abb2fe3e3a960b47e8b66f2aa7902a2d5b2960 the result will be inserted in the database so I am trying to get it there and then decrypt it but I dunno how to decrypt it. -
Django sqlite to postgres database migration
I have a quite large db of 750MB which I need to migrate from sqlite to postgres. As, the db is quite large I am facing some issues that some of the previous questions on the same topic did not had. Few days ago, I have migrated one sqlite db of size 30MB without any issues with loaddata and dumpdata commands. But for this large db, one of my app throws Database image is malformed error when running command dumpdata. Another of my app dumps successfully but does not load. I have seen the with -v 3 verbose flag that the objects are not even processed. To be precise, while running the loaddata command data from json file is processed first to check duplicate primary key and other model constraints then those data are used to create model objects. But for this app, data are not processed in the first place. Apart from this two commands there are some other methods that does the migration. But, the schema is completely changed in those way which I don't desire to do. Moreover I have faced issue DurationField becomes a string after migration and I couldn't typecast those fields. Bigint becomes int … -
Django - How to display user's profile picture with a message after its sent?
I have a live chat application and I'm trying to display a profile picture with the message after its sent with Javascript. Here is my code... Models.py - here is my Message and Profile model class Message(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) room = models.CharField(max_length = 255) content = models.TextField() date_added = models.DateTimeField(auto_now_add = True) class Meta: ordering = ('date_added', ) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.png', upload_to='profile_pics') 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) Consumers.py class ChatRoomConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name print(self.room_group_name) await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] username = text_data_json['username'] room = text_data_json['room'] await self.save_message(username, room, message) await self.channel_layer.group_send( self.room_group_name, { 'type': 'chatroom_message', 'message': message, 'username': username, } ) async def chatroom_message(self, event): message = event['message'] username = event['username'] await self.send(text_data=json.dumps({ 'message': message, 'username': username, })) @sync_to_async def save_message(self, username, room, message): user = User.objects.get(username = username) Message.objects.create(author = user, room = room, content = message) pass And … -
Only the last item has the text in an ajax call
I'm having a hard time solving this problem. here's the code: const postBox = document.querySelector('#posts') const getUser = function(id, val) { $.ajax({ type: 'GET', url: `/api/user/${id}`, success: function(response){ val.innerHTML = `Posted by: ${response.username}` }, error: function(error){ console.log(error) } }) } const getPosts = () => { $.ajax({ type: 'GET', url: '/api/posts/', success: function(response){ console.log(response) response.forEach(el => { postBox.innerHTML += ` <div class="card mb-2"> <div class="card-body"> <h5 class="card-title">${el.title}</h5> <p class="card-text">${el.body}</p> <p class="card-text">${el.date}</p> </div> <div class="card-footer"> <p class="card-text" id='author${el.id}'></p> </div> </div> ` const authorBox = document.querySelector(`#author${el.id}`) console.log(authorBox) getUser(el.author, authorBox) }) }, error: function(error){ console.log('error') }, }) } getPosts() Only the last item has the "Posted by author" I can't seem to figure out why only the last item has it. Even when I inspect it, it has the "Posted by author" inner html and inner text but it's not showing it. here's the output: Test 1 Test 1 2021-07-12 Test 2 Test 2 2021-07-12 Test 3 Test 3 2021-07-12 Test 4 Test 4 2021-07-12 Posted by: kyrios How do I make sure that all of the authorBox has their inner html changed? -
Django MultipleChoiceField rendering each item without li tag / or render them with bootstrap
i have this code on my forms.py to create multiple choice field but it always render as ul/li someinput = forms.MultipleChoiceField(required=False, widget=forms.CheckboxSelectMultiple( attrs={'class': 'form-check-input'}), choices=Courtintroductiondetail.TypeOfCourt.choices) but when i render them with bootstrap classes it do nothing somehow i think it is because the li tag the form.someinput in template creates so how i render them without li tag or render them like bootstrap checkbox -
users can not login by custom login model django
i am going to use a dual authentication system (email, username). when i create users by "createsuperuser" users can login but when i create users inside admin panel of django user can not login and also i noticed the user's password which is made in admin panel is not hashed in DB! backend.py: class EmailBackend(backends.ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): if username is None: username = kwargs.get(UserModel.USERNAME_FIELD) try: user = UserModel.objects.get(Q(username__iexact=username) | Q(email__iexact=username)) except UserModel.DoesNotExist: UserModel().set_password(password) else: if user.check_password(password) and self.user_can_authenticate(user): return user return super().authenticate(request, username, password, **kwargs) models.py from django.db import models from django.contrib.auth.models import AbstractUser from django.utils.translation import ugettext_lazy as _ class User(AbstractUser): email = models.EmailField(_('email address'), unique=True, null=False, blank=False) def __str__(self): return self.email