Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do you change django widget select attrs?
I'm trying to add new attributes to this ChoiceField so with help of ddslick() it should display images instead of text, but I'm unable to do so, I've tried declaring it explicitly before and after the meta class or simply as an normal widget, but without success, neither the generated <select> or <option> tags changed any of it's attributes, I was wondering if there's anything else that I can try. class MemoryForm(ModelForm): cover_image=(ChoiceField(widget=Select(attrs={'class': 'asdf'}))) class Meta: model = Memory fields = [ "title", "description", "date", "location", "accurate_date", "accurate_month", "accurate_day", "cover_image", ] labels = {"title": "", "description": "", "date": "", "location": ""} widgets = { "title": TextInput( attrs={"placeholder": _("Enter a title"), "class": "only-bottom"} ), "description": TextInput( attrs={ "placeholder": _("Add a description (optional)"), "class": "only-bottom", } ), "location": TextInput( attrs={"placeholder": _("Enter a location"), "class": "only-bottom"} ), "date": HiddenInput(), "accurate_date": HiddenInput(), "accurate_month": HiddenInput(), "accurate_day": HiddenInput(), "cover_image" : Select( attrs={"data-imagesrc": "/static/media/images/cherryimage/e2e4a952-e949-4b97-8597-eebd9bd445d5.jpg"} ), } -
Which is best method to deploy django site on production server?
In how many different ways I can deploy django web app? Can you explain any one method in detail? -
Django forms request
My Django application has two models. Which are Vehicle and Offer. So users can submit offers for vehicles. When submitting an offer I want to capture user_id and vehicle_id with the form. views.py def your_view(request): if request.method == 'POST': offer_form = Offerform(request.POST) if offer_form.is_valid(): instance = offer_form.save(commit=False) instance.user = request.user instance.vehicle = ? instance.save() messages.success(request, 'Offer submitted successfully') return redirect('vehicles') models.py class Offer(models.Model): name = models.CharField(max_length=90, blank=False) email = models.EmailField(max_length=90, blank=False) vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE, default=None) user = models.ForeignKey(User, on_delete=models.CASCADE, default=None) I can get the user with reqeust.user but how to get the vehicle_id that the user submits their offers to? -
Few ids in urlspattern
I am making a API with REST Framework. I can't find out how to create an urlspattern that got 2 id's from main model and primary model. Models: class Diary(models.Model): title = models.CharField(max_length=100, null=True) data = models.CharField(max_length=100, null=True) class DiaryRecord(models.Model): diaryID = models.ForeignKey(Diary, on_delete=models.CASCADE) data = models.CharField(max_length=25, null=True) Sample: path('api/diary/<int:firstID>/record-update/<int:secondID>/', views.defName) #firstId is id of Diary(Main model). Second id is DiaryRecord id. So i need to show a records, that belong to Diary. -
Django view decorator exception does not prevent view execution
A docorator that is suppose to send a 403 page let the rest of the view execute. request-token library provides a view decorator. If provided token is expired an exception is raised. Documentation says if such exception is raised, 403 response is send. When token is expired, decorator do raise an exception but the rest of the view is still executed and no 403 response is send. @require_POST @use_request_token(scope="my_scope") def my_view(request): print('after raised') # this code is executed return JsonResponse({ 'status': 'everything is fine !!!'}) # Wrong ! raise ExpiredSignatureError('Signature has expired') jwt.exceptions.ExpiredSignatureError: Signature has expired after raised Is this behavior normal ? How can I prevent view being executed if an exception is send by decorator ? -
Django form with fields and Ajax dependent Dropdown list from 4 different models
I want to insert data to the DB tables using Django ModelForm, the form is populated from 4 different Models. My Models: Region: name, District: name and region foreign key, Address: street, address, and district foreign key, Property: name, staff_manager(User model foreign key), and address foreign key. (All models' fields are set not to be blank) My forms: PropertyForm: fields = ['name', 'staff_manager'], AddressForm: fields = ['street', 'address'], for Region and District fields, I've used a dependent dropdown list with the help of Json, Ajax and Js, where districts will be shown depending on a selected region. My Challenge/Objective: I want to be able to simultaneously create a Property, and Address (insert it's street, address & district_id ---> which will be selected depending on region choosen from the form), all from a single form. My Models: Region & District Models, Address & Property Models My Form: ModelForm, Form HTML, Form-Frontend My Views: View, Region & District Json View Dependent Dropdown list Ajax & Js: Region Ajax Javascript Any help, insight or different perspectives of achieving my objective will be greatly appreciated. Thanks -
Overriding simple-jwt's TokenObtainPairSerializer to implement 2FA
I am currently trying to implement 2FA in my Django Application. The first thing I've done is to modify the Meta class in the UserSerializer class to add two fields enabled (indicates if 2FA is enabled for a user) and secret_key (the key to generate OTP, that is shared to the user when he enables 2FA). To minimally modify the login flow, I've modified the form that is sent to generate the access tokens to include a new field "otp". The user can fill it or not, and the backend will check if the user has 2FA enabled, and if yes, if the OTP is correct. Without 2FA, the login is simply a POST request with body {"username": usr, "password": pwd}. This has become a POST request with body {"username": usr, "password": pwd, "otp": otp}. If a user user hasn't enabled 2FA, he can simply leave the opt field blank. My urls.py looks like this: path("api/token/", TokenObtainPairView.as_view(), name="token_obtain_pair") My idea is to override TokenObtainPairView to adapt to the new request. From what I've found, I have to change the validate method, but I don't really have a clue as to how to do that. I probably would have to get … -
How do we forward a InMemoryFile in request.files to other External APIs in Django
if "files" not in request.FILES: return Response({"sucess" : False, "code": 500, "message" : "Please select file and then click upload"}) if "documentCategoryUuid" not in request.data: return Response({"sucess" : False, "code": 500, "message" : "Please select document category"}) files = request.FILES.getlist('files') try: documentCategory = DocumentCategories.objects.get(documentCategoryUuid=request.data["documentCategoryUuid"]) except Exception as e: return Response({"sucess" : False, "code": 500, "message" : repr(e)}) for upload_file in files: documentName = upload_file.name.replace(" ", "_") -
Django m2m_changed signal, post_add is called automatically after post_remove
I want to remove user from moderatos, when it is removed from users field. but when i called instance.moderators.remove(*pk_set) it is removed and then added again by post_add signal. works in this way users.pre_remove > users.post_remove > moderators.pre_remove > moderators.post_remove > moderators.pre_add > moderators.post_add the last two (pre_add, post_add) are getting called unnecessarily I am using Django admin page for these operations. Model : class Tank(models.Model): device = models.OneToOneField(Device, on_delete=models.SET_DEFAULT, related_name="tank", default=1) users = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="tanks", blank=True) hidden_for_users = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name="hidden_tanks", blank=True) admins = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="tanks_of_admin", blank=True) moderators = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="tanks_of_moderator", blank=True) name = models.CharField(max_length=40) Signals : @receiver(m2m_changed, sender=Tank.users.through) def on_tank_users_change(instance, action,pk_set, **_): if action == 'post_remove': instance.moderators.remove(*pk_set) -
Ignore all current migrations and start from current model state WITHOUT deleting the migration files/history
Preface: Migrating from Oracle to Postgres with a VERY large, VERY old Django app. Need the ability to start a new db from the current state of my models, ignoring 5+ years of migrations, BUT without deleting any of the migration files. -
Django test returns 404 despite of correct URL
I am using this tutorial for learning Django Test. On running the following error: ➜ DjangoSimpleIsBetter python manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). F...... ====================================================================== FAIL: test_board_topics_view_contains_link_back_to_homepage (boards.tests.BoardTopicsTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/X/Data/Development/PetProjects/DjangoSimpleIsBetter/boards/tests.py", line 47, in test_board_topics_view_contains_link_back_to_homepage self.assertContains(response, 'href="{0}"'.format(homepage_url)) File "/Users/X/Data/anaconda3/lib/python3.7/site-packages/django/test/testcases.py", line 462, in assertContains response, text, status_code, msg_prefix, html) File "/Users/X/Data/anaconda3/lib/python3.7/site-packages/django/test/testcases.py", line 434, in _assert_contains " (expected %d)" % (response.status_code, status_code) AssertionError: 404 != 200 : Couldn't retrieve content: Response code was 404 (expected 200) ---------------------------------------------------------------------- Ran 7 tests in 0.068s FAILED (failures=1) Destroying test database for alias 'default'... Below is the Test code: class BoardTopicsTests(TestCase): def test_board_topics_view_contains_link_back_to_homepage(self): board_topics_url = reverse('board_topics', kwargs={'id': 1}) response = self.client.get(board_topics_url) homepage_url = reverse('home') self.assertContains(response, 'href="{0}"'.format(homepage_url)) urls.py from django.conf.urls import url from django.contrib import admin from django.urls import path from boards import views urlpatterns = [ path('admin/', admin.site.urls), url(r'^$', views.home, name='home'), url(r'^boards/(?P<id>\d+)/$', views.board_topics, name='board_topics') -
Django3 Like Ajax Button Book By Antonio Mele
It works but when press like button it coun 2099 instead of 1, after refresh it turn 1..when unlike same problem happend...It counts correctly after refresh....before refresh it count 2099 or 3011 random number I tried some solution from stackoverflow but it didn't give me much better result.. Ajax: {% block domready %} $('a.like').click(function(e){ e.preventDefault(); $.post('{% url "images:like" %}', { id: $(this).data('id'), action: $(this).data('action') }, function(data){ if (data['status'] == 'ok') { var previous_action = $('a.like').data('action'); // toggle data-action $('a.like').data('action', previous_action == 'like' ? 'unlike' : 'like'); // toggle link text $('a.like').text(previous_action == 'like' ? 'Unlike' : 'Like'); // update total likes var previous_likes = parseInt($('span.count .total').text()); $('span.count .total').text(previous_action == 'like' ? previous_likes + 1 : previous_likes - 1); } } ); }); {% endblock %} HTML: {% with total_likes=image.users_like.count users_like=image.users_like.all %} <div class="image-info"> <div> <span class="count"> <span class="total">{{ total_likes }}</span> like{{ total_likes|pluralize }} </span> <span class="count"> {{ total_views }} view{{ total_views|pluralize }} </span> <a href="#" data-id="{{ image.id }}" data-action="{% if request.user in users_like %}un{% endif %}like" class="like button"> {% if request.user not in users_like %} Like {% else %} Unlike {% endif %} </a> </div> {{ image.description|linebreaks }} </div> <div class="image-likes"> {% for user in users_like %} <div> <img src="{{ … -
SQL DATA BASE QUERY
City Id Name 1 Delhi 2 Noida 3 Gurugram Parameter Id Name 1 Health 2 Education 3 Employment Rating Id Rating City_Id Param_Id Quarter Year Value_Date 1 7.5 1 1 Q1 2017 2017-02-15 2 6.3 1 1 Q1 2017 2017-02-13 3 6.9 1 1 Q1 2017 2017-02-20 4 8.2 1 1 Q2 2017 2017-04-05 5 5.5 1 1 Q2 2018 2017-12-13 6 7.6 1 1 Q3 2017 2017-08-20 7 4.5 2 1 Q1 2017 2017-02-17 8 5.3 2 1 Q1 2017 2017-02-14 9 6.9 2 1 Q1 2017 2017-02-25 10 7.2 2 1 Q2 2017 2017-08-05 11 8.5 2 1 Q2 2018 2017-12-13 12 9.6 2 1 Q3 2017 2017-08-20 13 3.5 3 1 Q2 2018 2017-12-14 14 4.6 3 1 Q4 2017 2017-08-17 15 5.5 3 1 Q2 2018 2017-12-20 16 7.6 3 1 Q3 2017 2017-08-15 17 7.5 3 1 Q2 2018 2017-12-18 18 8.6 3 1 Q3 2017 2017-08-24 19 7.5 1 2 Q1 2020 2018-05-25 20 6.3 2 2 Q3 2018 2018-17-13 21 6.9 3 3 Q2 2019 2019-06-20 I want to fetch the data from the Rating Table. I have a list of city ids, parameter ids, Quarter and Year. For Example city_id = [1,2,3], … -
Django: "AppRegistryNotReady: Apps aren't loaded yet" when deploying to Heroku
I'm consistently running into an error when deploying to production(Heroku), but the app works fine on my localhost. I see that many other people have this issue but none of the solutions work for me. One important note is that I do not call django.setup(), because when I do I get another error (auth.User model not found), but according to the Django docs you should not have to call that when running the app on a web server (as I am). I've been really stuck on this so would appreciate any help anyone can give. The error is: File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/registry.py", line 136, in check_apps_ready 2021-03-26T10:33:44.756357+00:00 app[web.1]: raise AppRegistryNotReady("Apps aren't loaded yet.") 2021-03-26T10:33:44.756413+00:00 app[web.1]: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I'm on Django 3.1.7, and looked at my requirements.txt and i believe my apps are up to date. Below is my code: Procfile release: python manage.py migrate web: daphne django_project.asgi:application --port $PORT --bind 0.0.0.0 -v2 worker: python manage.py runworker channels --settings=django_project.settings -v2 blog/models.py print('~~~\n\nvery top in blog/models.py\n\n~~~') from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from datetime import datetime, timedelta # we're inheriting from the models.Model class Post(models.Model): title = models.CharField(max_length=100) # character field … -
Cleaning up file based variables 00:01 ERROR: Job failed: exit code 1
When I am trying to commit changes to gitlab for continuous integrations i am facing this error Cleaning up file based variables 00:01 ERROR: Job failed: exit code 1 I am running 2 stages building and testing at the moment here is my script for testing - pytest -p no:warnings --cov=. - flake8 . - black --check --exclude=migrations . - isort . --check-only He is trowing this error when he went trough black and is supposed to start isort. And what is interesting is when i am trying to run isort in the terminal his response is UserWarning: Likely recursive symlink detected to /usr/src/app/env/lib warn(f"Likely recursive symlink detected to {resolved_path}") Skipped 1 files I am stuck with this for a while, so any help will be appreciated. tanks in advance -
Django Unittest how to adjust client.post to set data in request.META
I am trying to test a view by posting data to the view, but the view uses a key/value from request.META. How do I adjust my client.post to ensure the request.META data is populated ? The following example isn't working! Example from unittest: with mock.patch("......") as gt: header = {'SOME_SIGNATURE': 'BLAH'} gt.side_effect = ValueError response = self.client.post('/webhook/', data={'input': 'hi'}, content_type='application/json', follow=False, secure=False, extra=header) self.assertEqual(response.status_code, 400) Code from the view: def my_webhook_view(request): # Extract Data from Webhook payload = request.body # THIS LINE CAUSES MY UNITTESTS TO FAIL sig_header = request.META['HTTP_SOME_SIGNATURE'] ...... -
How to update select option from Jquery Ajax successful data
When I click the button I am getting console ouptpur correctly ; but my options are not getting updated. Please help as I new to Ajax,Jquery and Django. I spent more than a week to fix the issues. But no result. Your correction is very much require. Thanks My model is: class Post(models.Model): post_heading = models.CharField(max_length=200) post_text = models.TextField() def __str__(self): return self.post_heading my view is: def getmydata(request): # get the provinces for given country from the # database excluding null and blank values if request.method == "GET" : data = list(Post.objects.all().values()) return JsonResponse({"data": data}) my html template is: <div > <select name="car_maker" id="car_maker"> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="fiat">Fiat</option> <option value="audi">Audi</option> </select> </div> <div class="postacct"> <p>>{{ acct.post_heading }}</p>> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <script type="text/javascript"> $('.clickme').click(function(){ let catid; {#catid = $(this).attr("data-catid");#} catid='nil' $.ajax( { type: "GET", url: "/getmydata", data: { post_id: catid, 'csrfmiddlewaretoken': '{{csrf_token}}' }, success: function (data) { console.log(data); $("#car_maker option").remove(); $.each(data.rows, function (index, item) { //jQuery way of iterating through a collection $("#car_maker option").append($('<option>') .text(item.label) .attr('value', item.value)); }) } })}) </script> </body> </html> from ajax i getting the console output: (index):54 {data: Array(2)} data: Array(2)s 0: {id: 1, post_heading: "2", post_text: "two"} 1: {id: 2, post_heading: "1", post_text: "one"} … -
Does Django Rest Framework execute query for SerializerMethodField
I have following Django Rest Framework Serializer: from rest_framework.serializers import SerializerMethodField from posts.api.serializers import CommentSerializer class PostSerializer(ModelSerializer): comments = SerializerMethodField() class Meta: model = Post fields = ('id', 'title', 'comments') def get_comments(self, obj): return CommentSerializer(obj.comments.all(), many=True).data And I have following View: from rest_framework.views import APIView from rest_framework.responses import Response from posts.models import Post class PostsAPIView(APIView): def get(request): posts = Post.objects.all() serializer = PostSerializer(posts, many=True) return Response(serializer.data, status=200) So, My question is, when my serializer is working to prepare JSON of posts, for getting comments of each post, it executes a database query or not? For example, if I have 10 posts, is 11 database queries executed in this view? (1 query to get posts and 10 queries to get comments of each post in serializer). -
Discord - Send messages from a channel to my website in real time
I currently have a python/django platform and a discord community. On my discord server there is a channel "announcements". I would just like that when a message is published in this channel, it goes up to my website in real time. This is in order to convert it into a notification. Currently I managed to upload the messages from the channel to my site in a simple way but not in real time: def discord_get_last_message_id(): message_id = 0 try: message_id = Notification.objects.latest('id').discord_message_id except: pass return message_id def get_channel_messages(): #load last id discord message in DB last_message_id = discord_get_last_message_id() #Base route route = "/channels/"+ DISCORD_CHANNEL_ANNONCES_ID +"/messages" #if first time to DB, load just one item if last_message_id == 0: add = "?limit=1" else: add = "?after="+last_message_id route = route + add data,error_message = request_discord('GET',route) print(data) def request_discord(method,url_access,body={}): data ='' #Call token error_message = '' access_token = discord_get_token() #Call request headers = {'Authorization': access_token} body = body if method=="GET": result = requests.get(DISCORD_BASE_URI + url_access, headers=headers) else: result = requests.post(DISCORD_BASE_URI + url_access, headers=headers,data=body) #Check result if result.status_code != 200 and result.status_code != 201: error_message = "Impossible de d'obtenir un resultat erreur: " + str(result.status_code) else: data = result.json() return data,error_message def discord_get_token(): return … -
Python, Django: Editing inlineformset_factory
inside my app I'm using an inlineformset_factory and right know it's working fine! But when displaying it inside my template the Labels are always staying right above the input-field. Is there any way to display them side-by-side or even move the label as some sort of placeholder inside the input-field? views.py formset = inlineformset_factory(Model_A, Model_B, can_delete=False, extra=0, fields=('fields_01', 'fields_02', 'fields_03')) template.html <form method="post"> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} {{ form }} {% endfor %} <button type="submit">Save</button> </form> Thanks for all your help and have a great weekende! -
Django API throws CORS error when visitor behind proxy
I have a web service built in React that uses a back-end API in Django. I am currently struggling because we have an enterprise customer that is trying to signup but he is getting a CORS error. The surprising thing is that we don't even have CORS enabled on the Django API (ALLOWED_HOSTS is not set) so I don't know why the API is returning this error. The only thing I know is that they're behind a proxy. I am trying to replicate this behavior but when I put myself behind a proxy it still works perfectly... Any idea on what is causing the issue? -
Trying to create a function in Django
Can someone help me please ?! The function should filter some Products with their brands if arguments given if not it should return all products . def return_products(*products): pass -
Is there a way not to remove data from test database between each test
I use the "python manage.py test" for running my tests. I have several tests in my repo and have data dependency between the tests. I have the below structure. Class ABC(APITestCase): def setUp() def tearDown() def test_a() def test_b() Is there any way to not delete the data between each test.(Data should present in test DB when moving from test_a and test b) -
'poll_extras' is not a registered tag library. But I already registered one
This is my customize poll_extras.py file from django import template register = template.Library() def titless(value): """convert a string to upper case""" return value.title() register.filter('titless', titless) I have created this file in (templatetags>> this dir contain init.py file and poll_extras.py file also this dir is inside my poll app ) then I used this tags in one html file (named >> poll.html) here is poll.html few line {% extends 'base.html' %} {% load poll_extras %} {% block content %} <h2>{{"vote vage" | titless}}</h2> <h3>{{question.title}}</h3> ..... Now i am getting this error 'poll_extras' is not a registered tag library. but i did register here is tree if helpful +---ems | +---static | | \---css | | styles.css | | | \---templates | | base.html | | | +---auth | | login.html | | success.html | | | +---employee | | add.html | | delete.html | | detail.html | | edit.html | | home.html | | | \---polls | detail.html | index.html | poll.html | \---polls | admin.py | apps.py | context_processors.py | models.py | tests.py | urls.py | views.py | __init__.py | +---migrations | 0001_initial.py | 0002_auto_20210324_1407.py | 0003_answer.py | __init__.py | \---templatetags poll_extras.py __init__.py -
Django create QR code (Segno) and save to S3
I am seeking to create a QR code upon completion of a profile creation form for a user, and saving the QR image to a FileField. The FileField is also used for a profile_image field which already saves the image from the form to S3. I would like to do the same for the QR code (saving to S3 bucket). Using Segno I am able to generate the QR code. How am I able to create an image of it and save it to S3 via the models.py FileField? My code is as follows for the models.py and views.py files. Any help is appreciated. models.py class Profile(models.Model): def profile_path(instance, filename): return 'profile/{0}/{1}'.format(instance.profile_unique, filename) def qrcode_path(instance, filename): return 'profile/{0}/{1}'.format(instance.profile_unique, filename) #unique profile identification (alphanumeric string to be used on path for qrcode and profile image) profile_unique = models.CharField(max_length=50, default=0) #profile image filefield profile_image = models.FileField(upload_to=profile_path, default='') #qr code filefield qr_code = models.FileField(upload_to=qrcode_path, default='') views.py def add_profile(request): user = request.user userprofile = user.userprofile form = ProfileForm(request.POST or None, request.FILES or None) if form.is_valid(): profile = form.save(commit=False) profile.profile_user_id = user.id profile.profile_unique = get_random_string(8) #segno qr = segno.make_qr('test') qr.save('example.png', scale=4) profile.qr_code = qr profile.save()