Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Django template to Vue component
So I need to turn some of my templates to Vue components but I am currently using server-side rendering with Jinja how can I turn Jinja render into Vue? I am new to Vue.js so I apologies if that is a terrible question. -
Django Rest Framework - Doesn't appear to be paginating queryset correctly causing a long wait time before displaying on front end
I am experiencing an issue where it is taking upwards of 30 seconds to receive 25 items in a paginated response. This happens on original load of the page as well as any subsequent page requests via the datatables previous and next buttons. The model in question has roughly 600k records in it with the request to the api providing a query parameter to filter this by listing type (Letting or Sale). There are other filters applied to the queryset to ignore items that don't fall into the queue leaving 37k records on the Sales side and 90k on lettings that are returned. My model structue is as follows: class Listing(models.Model): date_added = models.DateField(verbose_name='Date Added', auto_now_add=True, auto_now=False) listing_id = models.CharField(max_length=15, blank=False, primary_key=True) portal = models.CharField(max_length=30, blank=False) url = models.URLField(max_length=200, blank=False) date = models.DateField(verbose_name='Listing Date', auto_now_add=False, auto_now=False, null=True, blank=True) listing_status = models.CharField(max_length=30, blank=False) outcode = models.ForeignKey( 'postcode_data.Outcode', blank=True, null=True, default=None, on_delete=models.CASCADE, related_name='+') sector = models.ForeignKey( 'postcode_data.Sector', blank=True, null=True, default=None, on_delete=models.CASCADE, related_name='+') address = models.CharField(max_length=200, blank=False) postcode = models.CharField(max_length=15, blank=False) description = models.TextField(blank=True) price = models.DecimalField(max_digits=9, decimal_places=1, default=Decimal(0.0)) property_type = models.CharField(max_length=30, blank=False) beds = models.PositiveIntegerField(default=0) baths = models.PositiveIntegerField(default=0) agent = models.CharField(max_length=150, blank=False) agent_company = models.CharField(max_length=100, blank=False) agent_branch = models.CharField(max_length=50, blank=False) available = … -
Django DeleteView Not Saving Changes
I'm using django DeleteView to delete user account. when i set the user's is_active property to False, it doesn't get saved in the database. it's still set to True here's my views.py from django.shortcuts import get_object_or_404 from django.urls import reverse_lazy from django.http import HttpResponseRedirect from django.views.generic.edit import DeleteView from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.messages.views import SuccessMessageMixin class DeleteAccount(LoginRequiredMixin, SuccessMessageMixin, DeleteView): """ DeleteAccount: view to delete user account """ model = User template_name = 'registration/delete_account.html' success_url = reverse_lazy('core:index') success_message = 'Account Successfully Deleted!' def form_valid(self, form): """ Delete account and logout current user """ account = self.get_object() # verify if user is the rightful owner of this account if not account.id == self.request.user.id: return HttpResponseRedirect(reverse_lazy('accounts:index')) account.is_active = False # DOESN'T GET SAVED account.save() # EVEN AFTER CALLING MODEL.SAVE() METHOD logout(self.request) return super().form_valid(form) def get_object(self): return get_object_or_404(User, pk = self.request.user.id) -
Manytomany relationship with through field doesn't show up in admin edit panel
I am trying to add new functionality to an existing project, where users can add multiple country locations with cities. Here are the models: class OfferCountries(models.Model): country = models.ForeignKey("Country", on_delete=models.CASCADE) cities = models.ManyToManyField("City", related_name="offer_cities", blank=True) offer = models.ForeignKey("Offer", related_name="offer_id",on_delete=models.CASCADE) class Offer(BaseModel): ... offer_country = models.ManyToManyField('Country', through='OfferCountries', related_name='offer_countries',blank=True) Now when I try to add a new Offer instance in admin there is no field of offer_country. Any ideas on how can I fix it? -
python: How can I import my own module? ModuleNotFoundError in python
I'm going to import my own module to my main.py. I made some python files in my scripts directory.(DataExtractor~KorTextPreProcessor) enter image description here I wrote my code like this... import DataExtractor import KoreTextPreprocessor and so on... Pycharm doesn't show me any errors, but my ec2 command errors... which says :: "No module named 'DataExtractor" << I want to import them all in main.py. Someone recommends to write this way from FileTransformer import method but it still shows error... how can I fix it? Maybe shoud I wrote somethin in my init.py? -
Invalid command 'PassengerPython', perhaps misspelled or defined by a module not included in the server configuration IN Django godaddy
Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator at webmaster@example.com to inform them of the time this error occurred, and the actions you performed just before this error. More information about this error may be available in the server error log. Additionally, a 500 Internal Server Error error was encountered while trying to use an ErrorDocument to handle the request. -
Using Django template tags and filters in javascript
I am building a search engine using Algolia in a client's Django project. In the html section of the template the client uses this line to format the date correctly. <span><em>posted</em> <strong>{{ dealer_announcement.publish_date|date:"F jS, Y" }}</strong></span> In the script on the template I define what each hit on the search engine should look like in a template like so. {% verbatim %} const hitTemplate = '' + '<span><em>posted</em> <strong>{{ publish_date }}</strong></span>' + '</div>' + ''; {% endverbatim %} This works fine, however the date is not formatted correctly so I tried to match the same format like so. {% verbatim %} const hitTemplate = '' + '<span><em>posted</em> <strong>{{ publish_date|date:"F jS, Y" }}</strong></span>' + '</div>' + ''; {% endverbatim %} but then nothing shows up. How can I use the same filters and tags within the script to have it match the original output.