Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
How to combine two querysets from two models? Django Rest Framework
I have two models class Answer(models.Model): answer = models.TextField() created_at = models.DateTimeField(editable=False, default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) user = models.ForeignKey('users.CustomUser', on_delete=models.PROTECT) question = models.ForeignKey('Question', on_delete=models.PROTECT) number_of_points = models.IntegerField(default=0) moderate_status = models.BooleanField(default=False) and class Question(models.Model): question_subject = models.TextField() question_text = models.TextField(default=None, null=True, blank=True) slug = models.SlugField(max_length=128, unique=True, null=False, editable=False) created_at = models.DateTimeField(editable=False, default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) user = models.ForeignKey('users.CustomUser', on_delete=models.PROTECT) animal = models.ForeignKey('animals.Animal', on_delete=models.PROTECT) serializers.py class QuestionDetailSerializer(serializers.ModelSerializer): answers = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = Question fields = '__all__' views.py class QuestionsDetailView(generics.ListAPIView): queryset = Question.objects.all() serializer_class = QuestionsSerializer def get_queryset(self): return super().get_queryset().filter( id=self.kwargs['pk'] ) url.py path('questions/<int:pk>', QuestionsDetailView.as_view()), And i want to combine 2 queryset, one being already that filters the question by pk provided in the url, and the other queryset i'd like to give is Answer.objects.all().filter(question__id='pk'). Essentially i want to show all the questions with answers to a particular question. -
How do I auto create pages for each element with Wagtail?
I'm learning Wagtail, and I'm struggling to understand auto page creation. Say I have a website where users can fill a form to become a "fan". I have a page where all the fan names are listed, e.g. fanlist = Fan.objects.order_by( "-timestamp") When a user submits the form and becomes a fan, they are added to the page with the fan list. Now I want to be able to create a page for each fan, so that the names in the fan list page link to a page for that specific fan. How can I do this programmatically and dynamically, so that each time a new fan signs up, the websites auto creates a page for this fan? -
How to execute custom function when I'm clicking on object in django admin?
I want to create function, that will be execute every time when Admin click on this object in Django Admin. Do you have some ideas? My function is trivial, I have just override save, but I want to execute this function without saving object: def save(self, *args, **kwargs): if self.corp_goal: print('We have corporate goal!') for i in self.corp_goal.all(): if i.corp_factor_rate: print('we have rated goal!') print('Corporate goal {} : factor {}'.format(i.corp_goal_title, i.corp_factor_rate * i.corp_factor_weight)) else: print('we dont have rated goal') else: print('we dont have asigned goals') -
Django edit the owner of Object
When an object is called via URL, I want to change the owner(user) of the object. The owner in my case is a ForeignKey. I tried it with something like this, which of course doesn't work def ChangeField(request, title_id): user_title = Field.objects.filter(id=title_id, user=request.user) if user_title: user_title.user = 'Admin' user_title.save() else: return redirect('https://example.com') return HttpResponseRedirect('/another') When the user of object ID 11 for example calls the URL /11, I want to change the owner of object 11 to the superuser, I mey case the superuser is called 'Admin' Models File class Field(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, default=None, null=True, on_delete=models.CASCADE, ) .... -
Serving user uploaded images in development
I have a Profile model that should allow a user to upload a profile image. In the browser the form where I allow a user to edit their profile displays the "Browse Images" input field, but upon submission the image is not saved and no "media/" directory is created, though the rest of the fields update properly. models.py: from django.db import models from django.contrib.auth.models import User from django.conf import settings class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) date_of_birth = models.DateField(blank=True, null = True) photo = models.ImageField(upload_to='users/%Y/%m/%d/', blank = True) forms.py: from django import forms from django.contrib.auth.models import User from .models import Profile class UserEditForm(forms.ModelForm): class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email') class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ('date_of_birth', 'photo') views.py: from django.shortcuts import render from .forms import UserEditForm, ProfileForm def edit(request): if request.method == 'POST': user_edit_form = UserEditForm(request.POST, instance=request.user) profile_edit_form = ProfileForm(data = request.POST,files = request.FILES, instance=request.user.profile) if user_edit_form.is_valid() and profile_edit_form.is_valid(): user_edit_form.save() profile_edit_form.save() else: user_edit_form = UserEditForm(instance = request.user) profile_edit_form = ProfileForm(instance = request.user.profile) return render(request, 'account/edit.html', {'user_edit_form':user_edit_form, 'profile_edit_form': profile_edit_form}) the template: <h2>Edit Your Profile</h2> <form class="" action="." method="post"> {{user_edit_form.as_p}} {{profile_edit_form.as_p}} {% csrf_token %} <input type="submit" name="" value="Change Profile"> </form> as for image specific … -
How to access a field inside a nested Serializer and make post request work?
I am working on a POST request where first a Tag is saved and then a Tagging - these are text labels relating to a picture (Resource). These are the two serializers: serializers.py class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = ('name', 'language') def create(self, validated_data): tag_data = validated_data.pop('tag') Tag.objects.create(**tag_data) return tag_data def to_representation(self, data): data = super().to_representation(data) return data class TaggingSerializer(serializers.ModelSerializer): tag_id = serializers.PrimaryKeyRelatedField(queryset=Tag.objects.all(), required=False, source='tag', write_only=False) # tag = TagSerializer(required=False, write_only=False).data.get('name') resource_id = serializers.PrimaryKeyRelatedField(queryset=Resource.objects.all(), required=True, source='resource', write_only=False) gameround_id = serializers.PrimaryKeyRelatedField(queryset=Gameround.objects.all(), required=False, source='gameround', write_only=False) user_id = serializers.PrimaryKeyRelatedField(queryset=CustomUser.objects.all(), required=False, source='user', write_only=False) class Meta: model = Tagging fields = ('id', 'user_id', 'gameround_id', 'resource_id', 'tag_id', 'created', 'score', 'origin') depth = 1 def create(self, validated_data): """Create and return a new tagging""" tagging = Tagging( user=validated_data.get("user"), gameround=validated_data.get("gameround"), resource=validated_data.get("resource"), tag=validated_data.get("tag"), created=datetime.now(), score=validated_data.get("score"), origin=validated_data.get("origin") ) tagging.save() return tagging def to_representation(self, data): data = super().to_representation(data) return data This is the post request in the view: views.py def post(self, request, *args, **kwargs): if not isinstance(request.user, CustomUser): current_user_id = 1 else: current_user_id = request.user.pk gameround = request.data.get('gameround', '') random_resource = request.data.get('resource', '') created = datetime.now() score = 0 origin = '' name = request.data.get('name', '') language = request.data.get('language', '') tag_serializer = TagSerializer(data=request.data) tagging_serializer = TaggingSerializer(data=request.data) if Tag.objects.all().filter(name=name, language=language).exists(): … -
Online pricing/ordering web with django: display/show a button aftern form submitted
I am working on a online pricing/ordering web. after user input some required data and click "get price", the form is submitted and the page will show the price at the bottom of the page (currently achieved as shown in below demo code). Next, I want the page also display a button called "order now" on the right side of the price. If user click it, the page will navigate to another page where user can input more data for order information, and also auto-display the price and other already inputed data shown in the previous page. Main html: <html> <body> <form method="POST" hx-post="{% url 'blog:post_list' %}" hx-target="#num_1" hx-target="#num_2" hx-target="#result"> {% csrf_token %} <div> <label>num_1:</label> <input type="text" name="num_1" value="" placeholder="Enter value" /> </div> <div> <label>num_2:</label> <input type="text" name="num_2" value="" placeholder="Enter value" /> </div> <br /> <div id="num_1">{{ num_1 }}</div> <br /> <div id="num_2">{{ num_2 }}</div> <br /> <div id="result">{{ result }}</div> <br> <button type="submit">Submit</button> </form> <script src="https://unpkg.com/htmx.org@1.6.1"></script> </body> </html> Child html: <div> <label>first_number:</label> <span id="num_1"> {{ num_1 }} </span> </div> <div> <label>second_number:</label> <span id="num_2"> {{ num_2 }} </span> </div> <div> <label>calculation_result:</label> <span id="result"> {{ result }} </span> </div> view.py: def post_list(request): result = "" num1 = "" num2 = "" … -
How to show a django form for many to many with through field?
I have created 3 model: class PropertyExtra(models.Model): type = models.CharField(choices=ExtrasType.choices, max_length=7) property_type = models.IntegerField(choices=PropertyType.choices) title = models.CharField(max_length=100) identifier = models.CharField(max_length=20, unique=True) class Property(models.Model): extras = models.ManyToManyField(PropertyExtra, through="PropertyExtraData") class PropertyExtraData(models.Model): value = models.CharField(blank=True, null=False, max_length=300) property_extra = models.ForeignKey(PropertyExtra, on_delete=models.CASCADE) property = models.ForeignKey(Property, on_delete=models.CASCADE) In PropertyExtra an admin user can add items like Electricity, Gas, Central Heating, etc. Some values will be boolean and some int which depends on the ExtrasType enum in the PropertyExtra. The specific value per property will be saved within the PropertyExtraData.value. Currently I'm have a form wizard to create a new Property using django-formtools and I'd like one of the steps to include a form that shows all the available PropertyExtras for a specific property_type. Basically if I have the above mentioned Electricity, Gas, Central Heating records in PropertyExtra - for a specific property_type I want to render 3 checkboxes where the user can mark them. Preferably would like to use ModelForm or ModelFormSet in order to simplify editing and saving but it's not possible - I'm looking for suggestions or 3rd party packages.