Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Workaround for dictsort-ing by model method as of Django 4.0.1
It helps to read the release notes. After three hours of debugging, I finally found out that my code stopped working in Django 4.0.1 due to the removed functionality to use model method for dictsort-ing. It is documented in the release notes: CVE-2021-45116: In order to avoid [potential information disclosure], dictsort now works with a restricted resolution logic, that will not call methods, nor allow indexing on dictionaries. Now I wonder what to do. I need to sort my list by a value that is not stored in the database but is calculated based on a value in the database. Is it a bad practice? What is a better one? Unfortunately, the generally very helpful documentation is silent about it so far. -
Putting an ImageField inside a JSONField in Django
I have a jsonfield inside of a django model which is supposed to hold some other fields alongside an ImageField. How can I store the data of the image inside that JSONField and put the image inside the media directory and have it called when I want to use it inside of my template like a regular imagefield. Please note that the image have already been saved inside the media folder but I have the name of the file which i want to put inside the jsonfield -
Start telegram bot on django project
I'm developing a djnago project and want to connect a telegram bot to it. I'm using python-telegram-bot but do not know how to start the bot when the django server starts. from django.apps import AppConfig from .telegramBot import updater class SocialMediaConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'memefinder' def ready(self) -> None: updater.start_polling() pass I added this code to the apps.py file of one the project's app but it's not working. I got this error message evrytime I run the project telegram.error.Conflict: Conflict: terminated by other getUpdates request; make sure that only one bot instance is running and this the code of telegramBot.py file. it's very simple code. from telegram import Update, ForceReply from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext updater = Updater("TOKEN") dispatcher = updater.dispatcher def start(update: Update, context: CallbackContext) -> None: """Send a message when the command /start is issued.""" user = update.effective_user update.message.reply_markdown_v2( fr'Hi {user.mention_markdown_v2()}\!', reply_markup=ForceReply(selective=True), ) dispatcher.add_handler(CommandHandler("start", start)) -
Django REST API don't see a URL
I think I have an import problem. After learning through all the tutorials and was able to get up to this point. I just want to see my database with .objects.all(). The problem is the code 404 where it can't see "receipts.url" makemigrate and migrate is all done without any issues. server was running with access to admin. I am getting this problem, but I have it all mapped out. Please help and thanks again. "Page not found (404) Request Method: GET Request URL: http://localhost:8000/receipts/ Using the URLconf defined in project.urls, Django tried these URL patterns, in this order: admin/ receipts/ [name='all'] The current path, receipts/, didn’t match any of these." My project name is "project", my app name is "receipts". "project", "receipts" and "manage.py" all are in the same level. I can see my database in the admin page, and as well as Mongodb compass. Here are all of my files: project/settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'receipts', 'rest_framework', ] project/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('receipts/', include('receipts.urls')), ] receipts/urls.py from django.urls import path from . import views from .views import CustomersViews urlpatterns = [ path(" … -
Django Staff Member Required Decorator does Infinite Loop if access denied
I am using the Django staff_member_required decorator to protect an admin area of the site. I am using it like this @staff_member_required(login_url=reverse_lazy('account_login')) def kommando_home(request): # business logic return render(request, 'kommando/home.html', context) I am using the custom login so users do not see the Django login page if they hit the URL. However, if a user who does not have staff permision logs in, it just results in this: I can add a redirect parameter to the decorator but that always redirects the user to the url provided even if the user has permission. I tried looking into customizing the decorator but I do not see any way to check if permission denied is raised. -
Remove plain HTML text withing a div
How can I remove the 'Currently' in the HTML withouting deleting other texts <div class="group if-description-margin"> Currently: <--- Remove this text <a href="/media/images/header-dots.png">images/header-dots.png</a> <input type="checkbox" name="profile_picture-clear" id="profile_picture-clear_id"> <input type="file" name="profile_picture" accept="image/*" id="id_profile_picture"> <p> But don't remove this </p> <label for="id_profile_picture">Profile Picture</label> </div> -
How to get Objects ID
I am trying to get the ID of Options however I do not now what I can do to get it? I am new to Django - I have got the question ID through a parameter however I am not trying to pass another parameter. Is there a filter or get command that can be used? I am trying to edit an existing option however it doesn't know which option it is looking for as there is more than one. The only way to identify is through its ID Model class Option(models.Model): OptionID = models.AutoField(primary_key=True, unique=True) OptionText = models.CharField(max_length=256, null=True) QuestionsID = models.ForeignKey(Question, on_delete=models.CASCADE) def __str__(self): return str(self.OptionID) View @login_required(login_url='loginPage') def question_editOption(request, id): question = Question.objects.get(QuestionsID = id) options = Option.objects.filter(QuestionsID = question) current_user = request.user c = current_user.userID if current_user.is_admin: if request.method == 'POST': edited = request.POST.get('Q') if request.POST['Q']: obj = Option.objects.filter(QuestionsID = id, ).update(OptionText = edited) messages.success(request, "Edited") return redirect('dashboardAdmin') # elif not request.POST['Q']: # obj = Question.objects.filter(QuestionsID = id).update(QuestionText = oldVal) # messages.error("Question Is Null!") # return redirect('question/edit/<int:id>/') else: messages.error("User is not admin") return redirect('dashboardPage') context = {'question' : question, 'options' : options} return render(request, 'editOption.html', context) HTML <!DOCTYPE html> <html> <head> <title>Admin Panel</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" … -
How to override data returned by self.get_serializer() in DRF?
Got mixin view (CreateAPIView, ModelViewSet) in my DRF project. In list() method I do return all of the instances of my model. def list(self, request): queryset = self.get_queryset() serializer = self.get_serializer(queryset, many=True) return Response(serializer.data, status=status.HTTP_200_OK) I need to override self.get_serializer() to modify the data a bit (add some stuff) and then access it via serializer.data I was trying to accomplish it via overriding init method of my serializer class but it did not work. Is there any another way? -
Rest API: Why is object doesn't findable in 'create' function?
For example, here is my all data : IMG1 My viewset : class CardCheckViewSet(viewsets.ModelViewSet): serializer_class = CardCheckSerializer queryset = CardCheck.objects.all() def create(self, request): for obj in CardCheck.objects.all(): print(obj) return super().create(request) And here is the data after I post something in it: IMG2 There should be 4 objects but this is what I got printed : CardCheck object (30) CardCheck object (34) CardCheck object (44) There is not the posted data as you see. Why is that data doesnt appears in here? What can I do about it? -
Django give a field default value = pk
I'm trying to give a field in Django a default value = value of pk, is this possible ? I've found an old question about giving a field default = value of another field but it doesn't really help when working with pk value : How do I set default field value to value of other field in a Django model? Basicly is something like this possible using pk instead of "name" variable ? : class MyModel(models.Model): name = models.CharField(max_length=50) fullname = models.CharField(max_length=100,default=name) def clean(self): self.fullname=name Thanks. -
What comes first OOA and OOD or Database design in Django? Would the answer change if
My first question, so please let me know if I'm doing something wrong. I'm studying OOA and OOD, GoF patterns, even reading some examples of Fowler OO "patterns"... But I was missing database design, and many other questions came up with the perssistence topic: schema, would it normalize, would it scale? If I'm going to develop an app that manages and Inventory of products, What should be the propper way to start with it in terms of design? OOD first or Dabase design first? Would the answer change if I'm using Django or Flask? I know maybe I've been failing at doing things properly in the past for so long that I've developed reflexes to answer to myself questions like this ones. I usually developed the database schema first and then relied on ORM. But I made many mistakes that way, some related to bad OOD and solid principles. In the other hand, I'm worried that if I use the OOA and OOD approach first, I could end up making wrong choices in the schema, like for example bad use of EAV (Entity-Attribue-Value model). The answer to some other similar questions like mine were just to do what fits best … -
Pass an object into Ajax
This is a two part question. The first part is being able to send an array of objects within an object into ajax to send to python(django framework). let object = { "value1": 1, "value2": 2, "arrOfObject": [ { "value3": 3, "value4": 4, }, { "value3": 5, "value4": 6 }] } let formData = $("form").serialize(); data = formData + '&' + jQuery.param(object) $.ajax({ url: "someurl", method: 'post', data: data }) The second question is the passing where arrOfObject is actually coming for django to begin with. Passing along the data before the template was rendered and being sent to another function. Of course the way that I have it right now is using the template tags to build the array of objects but was wondering if I can take the data passed in without any other iteration of the data. I would like to avoid something like let arrOfObjects = [] {% for data in object %} let data_object = { "value3": '{{ data.value3 }}', "value4": '{{ data.value4 }}' } arrOfObjects,push(data_object); {% endfor %} -
Django Rest Framework combine field and non field errors
I have a model serializer for changing the email and password. class ChangeEmailSerializer(ModelSerializer): class Meta: model = CustomUser fields = ['email', 'password'] def update(self, instance, validated_data): instance.email = validated_data.get('email') return super().save_instance(instance) How do I combine the a field error from EmailField with a non field error from the validate function used to check the user password? -
How to disable and modify password validation in Django
I want the end-user to set the password like a numeric pin of min & max length to 6 characters while registration. e,g: 234123 Yes, this can be insecure but the project needs to do it with 6 digit pin. As AUTH_PASSWORD_VALIDATORS doesn't allow to do it. AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 'OPTIONS': { 'min_length': 9, } }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] So how to disable and modify password validation in Django. Without changing the AUTHENTICATION_BACKENDS If we have to change the AUTHENTICATION_BACKENDS, then how to achieve it. -
How do I fix Permission Error (errno 13) Permission Denied
When I try to open the website using http://localhost:8000/admin/ i get the Permission denied error. This is what i get: [Errno 13] Permission denied: 'C:\\Users\\gvast\\OneDrive\\Documents\\learning_log\\learning_logs\\templates\\learning_logs\\index.html' Exception Location: C:\Users\gvast\OneDrive\Documents\learning_log\ll_env\lib\site-packages\django\template\loaders\filesystem.py, line 23, in get_contents -
Filter Query with Django-Filter but Return Custom JSON
I want to be able to pass a query via an endpoint (such as /api/generate-team/?rarity=Gold), have that filter a queryset and then return custom JSON based on some calculations that occur. Essentially, the query will contain filtered data from the PlayerProfile model. Data from the PlayerProfile's is then calculated and a custom JSON response is returned. I already have a FilterSet built for another view that contains that exact same filters we need, so I'd like to reuse it. Here is a condensed version of the filter (this filter works great with the other view I'm using it for): class PlayerProfileFilter(django_filters.FilterSet): rarity = CharInFilter(field_name='rarity', lookup_expr='in') card_id = CharInFilter(field_name='card_id', lookup_expr='in') max_overall = django_filters.CharFilter(field_name='overall', lookup_expr='lte') ... class Meta: model = PlayerProfile This is what I'm trying to do with the view: class GenerateRosterView(some-kinda-viewset): queryset = PlayerProfile.objects.all() filter_backends = (django_filters.DjangoFilterBackend, filters.SearchFilter,) filterset_class = PlayerProfileFilter def do_some_calculations_to_filtered_query_set(): doSomething(queryset) return {"calculations": 1} I'm having issues passing a filtered query to a function and returning a custom JSON response. -
None instead of empty Object instance?
I'm trying to create Secret Santa web site using Python Django. Issue I have is when there's odd number of participants. I'm using Django's built in User model and pairing its instances as matches for the game. In case of odd number, there will be a participant without match. Is there any way to store None in case of empty instance without raising ValueError? Here's my code: models.py class Participants (models.Model): giver = models.OneToOneField(User, on_delete=models.CASCADE, null = True, blank = True, related_name = "giver") receiver = models.OneToOneField(User, on_delete=models.CASCADE, null = True, blank = True, related_name = "receiver") def __str__(self): return self.receiver.username views.py def matchPairs(request): participants = User.objects.all().exclude(is_superuser=True) participants_names = [p.id for p in participants] i = 0 Givers = [] Receivers = [] if request.method == "POST": [givers, receivers] = pairs_generator.generate_match(participants_names) while i < len(receivers): if givers[i] == None: Givers.append(None) else: Givers.append(User.objects.filter(pk = givers[i])) Receivers.append(User.objects.filter(pk = receivers[i])) Participants.objects.create(giver = Givers[i], receiver = Receivers[i]) messages.success(request, "Matching successful! Here's the list.") return redirect('participants') else: messages.error(request, "Woops. Something went wrong. Please try again.") return redirect('participants') generate_match.py def generate_match(participants_names): givers = [] receivers = [] flag = None random.shuffle(participants_names) i = 0 while i < len(participants_names): if (is_even(participants_names)): print(f'{participants_names[i]} exchanges gifts with {participants_names[i + … -
Django Hyperlinks
How can I make a hyperlink go back to /articles/testing rather than staying as /categoryview/demo/articles/testing. The code I am using to create the hyperlink is View /categoryview/demo is the path of the current page. Thanks for your help. -
django - filter problem for self compare of model
in django via python 3, i want my drivers can join to a live request of customer that radius of cover defined by our customer. i have these code: pnt = GEOSGeometry('SRID=4326;POINT(%s %s)' % (supply.data['gpsCoordinate']['coordinates'][0], supply.data['gpsCoordinate']['coordinates'][1])) demands = DemandModel.objects.annotate( distance=Distance('gpsCoordinate', pnt), ).filter(distance__lte=D(km=DemandModel.allowedDistance), locationType = location.locationType, demandType = location.supplyType ).exclude(userProfile = location.userProfile) i need driver location checked by user allowedDistance and if lower than rage, added. so my problem is in km=DemandModel.allowedDistance. that not work and get these error: float() argument must be a string or a number, not 'DeferredAttribute' anyone can guide me? -
DRF - Custom serializer - prefill data by request.user
I have a model: class Income(...): user = ForeignKey(User....) # not null type = ... amount = ... And a special non-model serializer that should (besides other things) create Income objects for this user. class WelcomeWizardSerializer(serializers.Serializer): applicant = serializers.HiddenField(default=serializers.CurrentUserDefault()) applicant_incomes = IncomeSerializer(many=True, required=True) Obviously, I need to tell IncomeSerializer to use applicant as user. Otherwise WelcomeWizardSerializer returns errors: {'applicant_incomes': [{'user': [ErrorDetail(string='Toto pole je povinné.', code='required')]}, {'user': [ErrorDetail(string='Toto pole je povinné.', code='required')]}]} How can I do that? @action(['POST'], detail=False, url_path='from-welcome-wizard') def from_welcome_wizard(self, request, pk=None): serializer = WelcomeWizardSerializer(context={'request':request}, data=request.data) if serializer.is_valid(): # not valid serializer.save() I know I should get applicant (as I don't want to use CurrentUserDefault in IncomeSerializer) and add it to the data['incomes'] objects but I don't know where/when is the right place/time. -
MultiValueDictKeyError in Django REST APIView POST request
I am trying to write a POST request for a game API and am passing some data from the GET request and some through this POST request. However, I keep getting the following error: MultiValueDictKeyError 'gameround' What am I doing wrong here? 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.GET['gameround'] random_resource = request.GET['resource'] created = datetime.now() score = 0 origin = '' name = request.POST['name'] language = request.POST['language'] user_input_tag = Tag.objects.create(name=name, language=language) tag_serializer = TagSerializer(user_input_tag) if Tagging.objects.all().filter(tag=user_input_tag).exists(): # if tagging like this exists, save tagging anyway and leave tag unchanged score += 5 user_input_tagging = Tagging.objects.create(user_id=current_user_id, gameround=gameround, resource=random_resource, tag=user_input_tag, created=created, score=score, origin=origin) tagging_serializer = TaggingSerializer(user_input_tagging) return Response({'tag and ': tag_serializer.data}, {'tagging': tagging_serializer.data}) elif not Tagging.objects.all().filter(tag=user_input_tag).exists(): # save tagging otherwise and del tag? user_input_tagging = Tagging.objects.create(user_id=current_user_id, gameround=gameround, resource=random_resource, tag=user_input_tag, created=created, score=score, origin=origin) user_input_tagging.save() tagging_serializer = TaggingSerializer(user_input_tagging) return Response({'tagging only': tagging_serializer.data}) -
cant get the tag of a post displayed django
I've built a blog kinda app and there is a location section. I can add a location for a post when I create it (with django taggit) and when I search for it let's say Paris http://127.0.0.1:8000/tag/paris/ it shows me all the posts that have that tag. the thing i couldn't add is that on my homepage right next to the username I want to show the location that post has and when I click it I want to see the other posts that have that tag, so if post1 has the tag of Paris i'll click on it and it'll show me http://127.0.0.1:8000/tag/paris/ I've tried this just to show the tag the post has location:<strong> {{post.tags}} </strong></a>--> but it says location: blog.Post.None btw http://127.0.0.1:8000/tag/paris/ and all other tags work. I can see all the posts that have that tag when I search this in the search bar. I just can't seem to put the link to it anywhere. i'll try to put just the relevant parts of the code. home.html {% for post in posts %} <a class="mr-2" href="{% url 'user-posts' post.author.username %}">{{ post.author }}</a> location:<strong> {{post.tags}} </strong></a>--> {% endfor %} views.py class TagIndexView(ListView): model = Post paginate_by = … -
Redirect back to detailview
I have a detail view which displays details from one model. But on the detail view I also have a button which leads to a create view, which creates an object in another model. I want to redirect back the user to the detail view they was on before they created the object after they have created their object. I have tried this piece of code in the create view. def get_success_url(self): return reverse_lazy('article-detail', kwargs={'pk': self.object.pk})' The problem however, is that this does not find the right primary key of a specific article. -
JavaScript console.error redirect to file in Daphne Django application
I am using systemd (on Debian) to launch a shell script (as me as a user): startup.sh: #/bin/bash daphne -b '0.0.0.0' -p 8000 cartsProject.asgi:application 2> /tmp/log.out In my Python (Django) application I need to output to stdout and have it show up on the screen (tty1), which is working fine. The problem is that the JavaScript console.error() messages are also showing up on the screen even though I am redirecting stderr when launching Daphne. Is there an easy way to have the JavaScript stderr also redirect to a file? (could be the same or a different file than /tmp/log.out) -
Django poetry cannot find version of desired pylib
I am working on a Django application (python 3.8.12, Django 3.1) that is set up with poetry. The application is Dockerized. In my pyproject.toml file, I add a pylib (It happens with any lib, for example with django-mirage-field) django-mirage-field = "^1.3.0" And I get the error "... which doesn't match any versions, version solving failed". I can successfully install the specified version with pip install .... Any ideas? For the record, I don't have much Django experience so this might something very trivial, but I have not been able to resolve this yet :)