Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to validate form field in django?
I want to make shure that the current value of the "bid" field is not less than current biggest bid. This is my form with a custom clean method. Form: class Place_A_Bid_Form(forms.Form): listing = forms.CharField(widget=forms.TextInput(attrs={"type":"hidden"})) bid = forms.IntegerField(widget=forms.NumberInput(attrs={"class":"form-control"}), min_value=1) def clean_bid(self, biggestBid): bid = self.cleaned_data["bid"] if bid < biggestBid: raise ValidationError("""New bid shouldn't be less than starting bid, or if any bids have been placed then new bid should be greater than current biggest bid""") return bid View: def place_a_bid(request): if request.method == "POST": form = Place_A_Bid_Form(request.POST) user = User.objects.get(username=request.user.username) biggest_bid = Bid.objects.filter(user=user).aggregate(Max("amount")) if form.is_valid(): data = form.cleaned_data user_obj = User.objects.get(username=request.user.username) listing_obj = Listing.objects.get(title=data["listing"]) Bid.objects.update_or_create( user=user_obj, listing=listing_obj, amount=data["bid"] ) return redirect(listing_obj) In view I am extracting current value that I am going to compare to, and I can't figure out how to pass this value to my form field's clean method. Or maybe I'm doing this wrong? So how to do properly this sort of validation? -
How to use Q objcts in annotate tortoise
So simply i have my models Announcement, User, FavoriteAnnouncement class FavoriteAnnouncement(CoreModel): user = fields.ForeignKeyField('models.User', related_name='favorites') announcement = fields.ForeignKeyField( 'models.Announcement', related_name='favorites' ) i want to add an annotated field is_user_fav : Optional[bool] I found a soluition in django ( queryset = queryset.annotate(is_user_fav=ExpressionWrapper( Q(...), output_field=BooleanField(), ),) ) How can i do a similar thing in TortoiseORM ? -
How can I GET the parameters from URL in django
I'm trying to send a parameter by URL and trying to use it in a listview. But I cant GET it in my view. I know I'm doing some stupid mistake, but can't find it. This is the link I'm using in my template: <a class="dropdown-item" href="{% url 'listarmateriales' tipolista='metales' %}">Ver metales This is my url.py: path('listarmateriales/<tipolista>',listarmateriales.as_view(), name='listarmateriales'), And this is where I try to get the "tipolista" in my views.py: class listarmateriales(ListView): template_name = 'materiales/materialeslist.html' def get_queryset(self): if self.request.GET.get('tipolista') is not None: lista=Materiales.objects.all() tipolista=self.request.GET.get('tipolista' '') if tipolista=='metales': Do whatever... else: I have tried some different sintaxis, but the result is always the same, I cant read "tipolista", I have spent a lot of time with this, too much. I know it must be something easy, but, I'm new at this. Thanks in advance -
Call a Django Model class in a plain class as an Instance
I am trying to call a Django model class in a plain class as an Instance, I want to reference some of it's methods : For example I tried this : class Sample(models.Model): title = models.CharField( max_length=40, unique=True, null=True, blank=True) description = models.CharField(max_length=40, unique=True, null=True, blank=True) Then in a plain class below is where I want to access the Model as an instance : class Generator: def __init__(self): self.instance = Sample() I have tried this, though I get this error : mypackage.models.RelatedObjectDoesNotExist Whats the correct way of accessing the model class as an Instance in another class. -
Missing fields of nested serializer
I am using DRF's ModelSerializer and Nested relationships. The issue is that in nested modelserializer, some of the fields defined on, and visible on listing the nested serializer do not show up when listing the parent. Models: class customer(models.Model): cstid = models.AutoField(primary_key=True, unique=True) name = models.CharField(max_length=35, blank=False) ...SNIPPED class Meta: unique_together = ["name", "mobile", "linkedclinic"] ordering = ['name'] def __str__(self): return self.name class Procedure(models.Model): procid = models.AutoField(primary_key=True, unique=True) timestr = models.DateTimeField(default=timezone.now) template = models.ForeignKey( ProcedureTemplate, on_delete=models.CASCADE, blank=True, null=True) clinic = models.ForeignKey(Clinic, on_delete=models.CASCADE) doctor = models.ForeignKey( doctor, on_delete=models.SET_NULL, blank=True, null=True) customer = models.ForeignKey( customer, on_delete=models.CASCADE, null=False, related_name='procedures') def __str__(self): return f'{self.template} for {self.customer} on {self.timestr}' def eventtime(self): class_date = timezone.localtime(self.timestr) return class_date.strftime("%d-%m-%Y %I:%M %p") Serializers: class FindingSerializer(serializers.ModelSerializer): class Meta: model = Finding depth = 1 fields = [ 'fid', 'fieldheading', 'value', 'linkedprocedure', ] class ProcedureSerializer(serializers.ModelSerializer): finding_proc = FindingSerializer(many=True, read_only=True) class Meta: model = Procedure depth = 2 fields = [ 'procid', 'timestr', 'template', 'clinic', 'doctor', 'customer', 'eventtime', 'finding_proc', ] class customerSerializer(ConvertNoneToStringSerializerMixin, serializers.ModelSerializer): def get_unique_together_validators(self): """Overriding method to disable unique together checks""" return [] class Meta: model = customer depth = 3 biovar_data = Biovariable_dataSerializer( read_only=True, many=True) # many=True is required procedures = ProcedureSerializer( read_only=True, many=True) # many=True is required # allergies … -
Can't filter a field in a translation model of parler app for django
I'm trying to filter a model of images by a certain category. It was all funtioning until I implement the parler app and modify the model to be a tranlated model. Now I can't make the filter work. This are my models: from parler.models import TranslatableModel, TranslatedFields from django.db import models class Categoria(TranslatableModel): translations = TranslatedFields( nombre=models.CharField(max_length=200, null=False, blank=False), ) def __str__(self): return self.nombre class Imagenes(TranslatableModel): translations = TranslatedFields( imagen=models.ImageField(null=False, blank=False), carrusel = models.BooleanField(default=False), nombre=models.CharField(max_length=50, null=False, blank=False), descripcion=models.TextField(max_length=200, null=True, blank=True), fecha_publicacion=models.DateField(), categoria=models.ForeignKey(Categoria, on_delete=models.SET_NULL, null=True, blank=True), ) def __str__(self): return self.nombre This is the view: def gallery(request): category = request.GET.get('category') if category == None: imagenes = Imagenes.objects.all() else: imagenes = Imagenes.objects.filter(translations__categoria=category) categorias = Categoria.objects.all() context = { 'categorias': categorias, 'imagenes': imagenes, } return render(request, 'images/gallery.html', context) And the part of the HTML: {% for cate in categorias %} <a class="dropdown-item" href=" {% url 'gallery' %}?category={{cate.nombre}}">{{cate.nombre}}</a> {% endfor %} When I try this code I get this error: ValueError at /es/gallery/ Field 'id' expected a number but got 'My_Category'. I also try with this line in my view: imagenes = Imagenes.objects.filter(translations__categoria__nombre=category) and get this error: FieldError at /es/gallery/ Related Field got invalid lookup: nombre Every help and suggestion will be apreciated. Thanks -
How to send "time" when sending a message with django channels
I'm a beginner with django-channels working on a chat app. I want the "timestamp" to be shown instantly when a message is sent the room, it only works when I refresh the page as the timestamp gets saved with the models. I tried playing arround with consumers.py and the js code but was not able to send the "timestamp" instantly with the message. * models.py: class Message(models.Model): username = models.CharField(max_length=100) room = models.CharField(max_length=100) content = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) consumers.py: class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from web socket async def receive(self, text_data): data = json.loads(text_data) message = data['message'] username = data['username'] room = data['room'] await self.save_message(username, room, message) # Send message to room group await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message, 'username': username } ) # Receive message from room group async def chat_message(self, event): message = event['message'] username = event['username'] # Send message to WebSocket await self.send(text_data=json.dumps({ 'message': message, 'username': username })) @sync_to_async def save_message(self, username, room, message): Message.objects.create(username=username, room=room, content=message html/js: {{ room_name|json_script:"json-roomname" }} … -
How do I calculate age using Django with a class-based form, templates and gijgo datepicker?
I have read this post and I believe that mine in totally different; Django Datepicker calculate age I am using Django version 4.0.1. I am making use of the Gijgo datepicker to capture the date of birth of the person registering. In my base.html template I added this: <script src="https://unpkg.com/gijgo@1.9.13/js/gijgo.min.js" type="text/javascript"></script> <script>$('.dateinput').datepicker({ format: 'yyyy-mm-dd' });</script> In my register.html template I extends the base template. The form in the register template use a POST method. The code is: <form method="POST"> {% csrf_token %} {{ form|crispy }} With a submit button. The form I use is a class based form in my forms.py file. The code for that looks like this: from django import forms from django.contrib.auth.forms import UserCreationForm from datetime import date selection = [ ('yes', 'Yes'), ('no', 'No') ] class StudentApplicationForm(UserCreationForm): email = forms.EmailField() first_name = forms.CharField(max_length=70) last_name = forms.CharField(max_length=150) date_of_birth = forms.DateField() previous_experience = forms.CharField(widget=forms.RadioSelect(choices=selection)) terms_and_conditions = forms.CharField(widget=forms.CheckboxInput()) class Meta: model = User fields = [ 'first_name', 'last_name', 'date_of_birth', 'terms_and_conditions', 'previous_experience', 'username', 'email', 'password1', 'password2', ] def clean_email(self): email = self.cleaned_data.get('email') email_count = User.objects.filter(email=email).count() if email_count > 0: raise forms.ValidationError('This email is already in use. Please select a different email!') return email def calc_age(self): dob = self.cleaned_data.get('date_of_birth') raise forms.ValidationError(int(dob)) … -
Possible bug in Django in selecting a pandas DataFrame?
I am creating a Django project of which the code is rather complex. For that reason I split it into several files which are called from models.py. But because the code is complex I would like to run the code stand-alone to debug it. I have a simple piece of code that looks like this: print('DF:\n', df) selection = df[df[sel_crit] >= sel_val] print('SELECTION\n', selection) In the examples below: sel_crit is "Coverage" and sel_val is 0.1. The value of df is (first print statement): DF: cpu Status Coverage Distance Lyapunov FractDim Missers Uninteresting Coefficients 28 0.067678 1.0 0.107931 95.987910 NaN 0.569875 0.0 0.0 IQLHUFOFBKCJGUSQGPJPTPNUDPMTPAU 304 0.124464 1.0 0.107508 93.144860 0.032726 NaN 0.0 0.0 IUMOUMOGSHJIIPPPCNCCOJLHQFPZHPU 1241 0.123443 1.0 0.107392 82.698345 26.796081 0.999999 0.0 0.0 ILGDKLOSWHPJIPPPCTBITJLLQLPLCUM 117 0.123463 1.0 0.106203 80.419825 -0.862029 0.602059 0.0 0.0 ILJEHSNGNHGGIJJLFNJPOBAUDQALHUM 386 0.131001 1.0 0.102985 73.330918 -3.630947 NaN 0.0 0.0 INTDEKECMIQPLKELOBHJHLREUDGKAMG 1117 0.125086 1.0 0.096597 79.500703 -0.793354 0.371611 0.0 0.0 IKHRKQQPAEGLLCBFFPCQPROBUMLGCOH 797 0.123657 1.0 0.094546 97.020646 0.828907 1.204119 0.0 0.0 IGXYLPLFCHSPMHHDMFCREMMPAWPUFQL 356 0.126138 1.0 0.091071 88.329201 -0.361238 1.414972 0.0 0.0 IKKQLLHCNLGLLSHLEPIQCIGKKDHTFBH 675 0.123957 1.0 0.072746 103.955944 15.489624 1.531477 0.0 0.0 IQUAUIFLCCQPZKHYIGLOHMHSONMXCPW 182 0.123799 1.0 0.065901 63.458365 -0.523814 1.903088 0.0 0.0 ITMBUJLNUOMGTVNDPNJVOCNUDSMTMIU The results produced by the Djando runserver: … -
Django relay graphql order by created date
How to query a model as order by created date in django graphene-relay class CategoryNode(DjangoObjectType): class Meta: model = Category filter_fields = ['name', 'ingredients', 'created_at'] interfaces = (relay.Node, ) class Query(graphene.ObjectType): category = relay.Node.Field(CategoryNode) all_categories = DjangoFilterConnectionField(CategoryNode) -
Dynamic Model Django - similar repeated items
I am working on building a quote generation tool with django and trying to determine the best way to build the model(s). For example, a quote could have n number of different items to be worked on: driveway1, driveway2, sidewalk, wall, fence, etc, etc. Each of these different items will have a similar calculation: length x width or flat fee My initial thought was to build a model to house all of the items and the two calculations: class item(models.Model): item = models.CharField(max_length=250) length = models.FloatField(blank=True, null=True) width = models.FloatField(blank=True, null=True) flat_fee = models.FloatField(blank=True, null=True) Example Submissions: Form 1: driveway, 50,50, null Form 2: driveway, 60,40, null | sidewalk, 10, 10, null How could I store these two results without pre-defining the schema as it could change with every form submission? Is this a good use-case for NoSQL? -
Create a new model row with fields that are foreign keys
I feel like the way I'm creating instances of my models must be wrong/have too many steps. models.py: class Library(models.Model): name=models.CharField(max_length=40) address=models.CharField(max_length=30) postcode=models.CharField(max_length=30) class Bookshelf(models.Model): number=models.IntegerField(default=0) name=models.CharField(max_length=30) library=models.ForeignKey(Library, on_delete=models.CASCADE) I have created a library by doing: library = Library(name="town centre", address="main street", postcode = "N15" library.save() I now want to create a bookshelf for that library, but I'm not sure how to specify the library it belongs to. shelfie = Bookshelf(number=5, name="fiction", library = ???) I can get it to work by doing: selected_library = Library.objects.get(name="town centre") shelfie = Bookshelf(number=5, name="fiction", library = selected_library) But is this correct? When I have a view that needs to make an instance of something that has lots of foreign key/many-to-many relationships I end up with this list of assigning variables to database queries of various models so I can use them to create a single thing. -
dj_rest_auth uses 'access_token', 'refresh_token' whereas drf_simple_jwt uses 'access', 'token' - how to make it work together?
I'm using dj-rest-auth. To use jwt I also installed django-rest-framework-simplejwt. The problem is that the first one uses token names like this: access_token refresh_token whereas the second one uses access refresh But they are supposed to be working together. For example, in dj-rest-auth docs, they say I should use auth/token/refresh which works but it takes refresh and returns access. How to make it work together - to use the same names for tokens? -
Using the results from a query in BOTH the templates and the view
In Django, I need to query a table to get some details from the database. I need the results BOTH in the views and in ALL of my templates. Is there a way to only run this query once? Here is my current setup if I don't use a context processor: def collect_important_information(): return SomeModel.objects.filter(parameter=abc) def homepage(request): information = collect_important_information() if information: do something context = {"information": information} return render(request, "index.html", context) def second_page(request): information = collect_important_information() if information: do something else context = {"information": information} return render(request, "second.html", context) def third_page(request): information = collect_important_information() if not information: do something context = {"information": information} return render(request, "third.html", context) def fourth_page(request): information = collect_important_information() context = {"information": information} return render(request, "third.html", context) There is a lot of replication here. I can reduce that by using a context_processor to insert the "information" variable into each template. However, if I do that I have to run the database query twice for many of these requests. Once to obtain the database variables I need inside my views.py function (for some condition that takes place, independent from the template), and a second time in the context processor. Is there a way to somehow 'centralize' the … -
How to access postgres database and get data from it?
So... I've been working on a project with postgres database. It includes authenticaton system and stores user data to postgres database. Now I want to get data from database. For example emails of all users in database. settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': 5432 } } -
Not getting the desired output on the page after running code built in React and Django
I created 3 components in react and rendered them I used react router to route those components but even after routing them exactly the same as shown in this video https://youtu.be/YEmjBEDyVSY i was unable to get the desired text on the web page After running npm run dev i'm getting this warning: WARNING in DefinePlugin Conflicting values for 'process.env.NODE_ENV' -
database_sync_to_async not working in django channels consumers
This is my consumers file and I am using AsyncWebSocketConsumer. And Get details function is not working. enter image description heremgur.com/demrn.png Its Showing the error "django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async." If Anyone can help me solve this issue, It would be highly appreciated. Thanks -
ORA-00904: "2022-01-20": invalid identifier
I'm having a problem with the output of the Search Records Between Two Date Range From Database. Below is my code snippet: I await your help: def mostraDate(request): if request.method == "POST": fromDate = request.POST.get('fromDate') toDate = request.POST.get('toDate') cursor = Sms.objects.raw('select process_id, date_received,originator_msisdn, error_code from sms where date_replyed between "'+fromDate+'"and"'+toDate+'"') #cursor = Sms.objects.raw('''select process_id, date_received,originator_msisdn, error_code from sms where date_replyed between ''', [fromDate] ,'''and''' ,[fromDate]) return render(request, 'mostraDate.html', {"data": cursor}) else: displaydate= Sms.objects.order_by('date_received').reverse() paginator = Paginator(displaydate, 5) page = request.GET.get('page') displaydate = paginator.get_page(page) return render(request, 'mostraDate.html', {"data": displaydate}) -
Django rest framework view patching for unit test
here is my view that I want to test: class CityWeather(APIView): def get(self, request): city = request.GET.get('city', None) if city: city_weather = get_weather_data(city) if city_weather: return Response(city_weather, status=status.HTTP_200_OK) return Response({"error": "City was not found"}, status=status.HTTP_404_NOT_FOUND) so far here is my tests.py: class TestWeatherAPI(TestCase): def test_get_weather_data(self): with mock.patch('weather.utils.get_weather_data') as mock_get: response_data = { "current_temperature": "3.1°C", "current_pressure": 1033, "current_humidity": 86 } mock_get.get_weather_data.return_value = response_data response = self.client.get(reverse('get_city_weather'), {'city': 'London'}) self.assertEqual(response.status_code, 200) self.assertEqual(response.json(), response_data) As we can see, I want to patch only the get_weather_data in the view. How can I do this ? -
UnicodeDecodeError: skipped file requirements.txt in . (reason: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte)
I was installing gettext without any problem and suddenly I got this error: UnicodeDecodeError: skipped file requirements.txt in . (reason: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte) processing locale es What catches my attention is that this appears: processing locale es. That is to say that if it was installed? -
Python [Errno5] Input/output error when converting audio file
I wrote a video/audio converter using Python PyTube. The code for converting videos is working but the audio isnt. Im using moviepy to write the audiofile because it isnt possible with pytube alone. But now I have a error which I dont have normally. If I'm logged in into putty everything works but if I close the console this error appears: [Errno 5] Input/output error I googled it and it says that if the console can't print out messages (because putty is closed) this error appears. I just need the cause in my code for it. This is my code for the mp3 converting: if format == "3": yt = YouTube(videolink) downloads = MEDIA_ROOT + "/videos/" audio_file = yt.streams.filter(only_audio=True).first().download(downloads) base, ext = os.path.splitext(audio_file) clip = AudioFileClip(audio_file) clip.write_audiofile(base + uuid + ".mp3") clip.close() audioclip = clip.audio basename = os.path.basename(base + uuid + '.mp3') os.remove(base + '.mp4') new_video = Video( path = basename, link = videolink ) request.session['file'] = basename new_video.save() Ignore the database stuff with "new_video" this is just for my framework for database interaction. The important lines are this: clip = AudioFileClip(audio_file) clip.write_audiofile(base + uuid + ".mp3") clip.close() -
Django + Celery: How to run a task after subtasks from different scheduled Tasks are finished
I'm currently building a webapp with Django and Celery. I have one task (sometask) that adds an unknown number of other tasks(othertask) in a for loop to the queue. Now I don't understand how I can run another Task(task3) after sometask with all the subtasks are done. I understand that you can chain tasks for example, but if I chain othertask to sometask it will run before the subtasks are done. Could someone please give me some input on how to get it done the way I described? Example of my tasks.py @shared_task(bind = True) def sometask(self): for whatever: othertask.delay() return "done" @shared_task(bind = True) def othertask(self): pass @shared_task(bind = True) def task3(self): pass Celery.py: app.conf.beat_schedule = { 'weekly':{ 'task': 'webapp.tasks.sometask', 'schedule': crontab(minute=0, hour=23, day_of_week='sat'), } } -
Update a specific column of mysql table using django views
I have a mysql table with column id, username and token, where id and username is already given but token changes for every time. How to update it using django views.py I am giving username for identity but it add a new row in the table. -
How can I Annotate another annotate group by query in django
I have two querys Proyecto.objects.filter().order_by('tipo_proyecto') Proyecto.objects.values('tipo_proyecto').annotate(total=Sum('techo_presupuestario')) how can I make this in only one query, i want that the first query contains an annotate data that represents all sum techo_presupuestario depending of your tipo_proyecto is this posible? -
get request in django?
I have problem with django request.I dont know. I tried to do everything, but I got 'blog' object has no attribute 'get'. I want to do mini blog on my website,but it isnt working now. I would like to get all objects from database.(Sorry,If I did something wrong,I am beginner in django and tried to functions for my website) :) models.py from django.db import models # Create your models here. CHOOSE =[ ('Usual','Обычный тариф'), ('Premium','Премиум тариф'), ('Prise','Аукционный') ] class VDSTARIFS( models.Model): id = models.CharField(max_length=40, primary_key= True,serialize=True) name = models.CharField(max_length=20, verbose_name = 'Цены') choosen = models.CharField(max_length= 20, choices = CHOOSE, verbose_name = 'Тариф', help_text='Выбор тарифного плана.') title = models.CharField(max_length= 15) def __str__(self): return str(self.title) class blog(models.Model): id = models.CharField(max_length=40, primary_key= True,serialize=True) message = models.TextField( verbose_name= 'Сообщение блога') titleblog = models.CharField(max_length=50, verbose_name = 'Название') img = models.ImageField(upload_to = 'admin/', verbose_name= 'Картинка' ) def __str__(self): return str(self.titleblog) def get_all_objects(self): ##maybe I have troubles with it. queryset = self.__class__.objects.all() blog.html {% csrftoken %} {% for item in message %} {% endfor %} views.py from django.shortcuts import render from django.http import HttpResponse from django.shortcuts import render from django.http import HttpResponseRedirect import os from polls.models import VDSTARIFS from polls.models import blog from django.template.loader import render_to_string def …