Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the best way to build API in python?
I'm trying to build API in python and i wondering what is the best way to do that. I consider: -django-rest-framework -graphene-django -aiohttp and I want to know what are pros and cons of using each of them and what is the best option in 2020 -
How to change 'name' in edit row in Django Admin?
How to make a different name for the model only in this line. It is necessary that in other places there is also an Author and Authors, and it was in this one that it was possible to change to something else. -
Time constraint in Django
I have a time constraint for creating something in Django. Consider the constraints: Constraint 1: Timings: the user will give the timings varying from 5:00 AM to 4:59 AM. Constraint 2: End - Time cannot be after 4:59 am of the next day. Cases: Case 1: creating slots from 2 am - 4 am should work fine. Case 2: Presently, The code what I have written works incorrectly for case: Start_time = 8:00 End_time = 6:00 Here, in front-end, the start_time = 8:00 means morning and end_time = 6:00 means the next day morning and violates our Constraint No:2. Case 3: When someone gives start_time = 5:00 and end_time = 2:00, we need to add the next day in end_time. The Code I have written is as below: start_time = request.POST.get('start_time') end_time = request.POST.get('end_time') dateTimeA = datetime.datetime.strptime(start_time, '%H:%M') dateTimeB = datetime.datetime.strptime(end_time, '%H:%M') dateTimeDifference = dateTimeB - dateTimeA dateTimeDifferenceInHours = dateTimeDifference.total_seconds() / 3600 if dateTimeDifferenceInHours <= 0: dateTimeB += datetime.timedelta(days=1) dateTimeDifference = dateTimeB - dateTimeA dateTimeDifferenceInHours = dateTimeDifference.total_seconds() / 3600 The Front-End Looks as below(The code is written in HTML): So, if someone can please help with the improvements in the code I have written so, that all my above cases … -
Pass js variable to django change admin view
Is it possible to pass js variable to custom change_form_template? I've override changeform_view to add this variable to template def changeform_view(self, request, object_id=None, form_url='', extra_context=None): extra_context = extra_context or {} extra_context['var_name'] = request.build_absolute_uri(f'<url>/{object_id}/') return super().changeform_view(request, object_id, form_url, extra_context) Then I need somehow to declare it in my template -
Change default constraint for PositiveSmallInteregField
i want to change constraint that SmallPositiveIntegerField produces in Db during migration: last_watched_episode smallint constraint archives_seasonmodel_last_watched_episode_check check (last_watched_episode >= 0), I want to change check (last_watched_episode >= 0) to check (last_watched_episode >= 1). Do you know where is the souce code of this field in Django, that is in charge for making constraints? I need it in oredr to create mixin for this field. Thank you. -
How to make a request to local URL as part of automated tests?
I'm writing an automated test in Django to check that a webhook is working on the application. The test sends a bunch of JSON to the webhook and will check that the call has been logged in the database. The problem I'm hitting however is that the test calls the http://localhost URL and the data is thus saved in my local dev database and not in the temporary database created by the test. So I now have no way to check the call has been received. Whats the right solution for this? from django.test import TestCase import requests from monzo.models import Transaction, RequestLog class WebhookChecks(TestCase): fixtures = ['db.json', ] def test_simple_expense(self): my_json = '{"type": "transaction.created", REMOVED FOR SECURITY }' url = 'http://localhost/some_url/webhook/' headers = {'Content-Type': 'application/json'} r = requests.post(url, data=my_json, headers=headers) if not "200" in str(r): print("Something didn't work out. Error: "+str(r)) self.assertTrue("200" in str(r)) -
How to properly filter nulls_last on one_to_many field?
I'm trying to filter and order objects by existance of a related model with forcing nulls as last. Example models: class ModelA(models.Model): name = models.CharField(max_length=255) ... class ModelB(models.Model): model_a = models.ForeignKey(ModelA, related_name=model_b) date = models.DateField() time = models.TimeField() ... Now, I need to filter ModelA by some kwargs (normal operations), but I also need to order ModelA by nearest ModelB date and time (in future, not past) ascending or descending WITH A SINGLE QUERY PARAM and also NULLS need to be placed last regardless of ascending or descending order. I already came to a conclusion that I need to overwrite default QuerySet order_by: class ModelAQuerySet(models.QuerySet): def order_by(self, *field_names): if 'model_a_date' in field_names or '-model_a_date' in field_names: field_names = list(field_names) if 'model_a_date' in field_names: field_names.remove('model_a_date') return super().order_by( 'model_b__date', 'model_b_time', *field_names ) else: field_names.remove('-model_a_date') return super().order_by( '-model_b__date', '-model_b__time', *field_names ) else: return super().order_by(*field_names) It works fine when I'm ordering descending ('-model_a_date'), since NULLS are last, but I'm having a hard time placing nulls last in ascending order. I already tried: return super().order_by( F('model_b').asc(nulls_last=True), 'model_b__date', 'model_b__time', *field_names ) #### return super().order_by( F('model_b').asc(nulls_last=True) ).order_by( 'model_b__date', 'model_b_time', *field_names ) #### return super().order_by( 'model_b__date', 'model_b_time', *field_names ).order_by( F('model_b').asc(nulls_last=True), ) but that does not work at all. … -
Whatsapp bot with Twilio and Chatterbot not working properly
I have a Whatsapp bot using Twilio and Django server. For conversational replies, I have used ChatterBot package. The problem is it is giving the same message coming to it via sender. To begin testing, connect to your sandbox by sending a WhatsApp message from your device to +14155238886 with code join drove-provide You will see that the chatterbot is giving the same message and is not working properly. Please help me. This is Callback URL from Twilio and its working fine https://whats-app-bot-99.herokuapp.com/sms/ from twilio.twiml.messaging_response import MessagingResponse from django.views.decorators.csrf import csrf_exempt from chatterbot import ChatBot from chatterbot.trainers import ChatterBotCorpusTrainer chatbot = ChatBot( 'Ron Obvious', trainer='chatterbot.trainers.ChatterBotCorpusTrainer' ) trainer = ChatterBotCorpusTrainer(chatbot) # Train based on the english corpus #Already trained and it's supposed to be persistent #trainer.train("chatterbot.corpus.english") def home(request): return HttpResponse("Hello World!!") @csrf_exempt def sms_reply(request): """Respond to incoming calls with a simple text message.""" # Fetch the message if request.method=='POST': msg = request.POST.get('Body') phone_no = request.POST.get('From') reply = chatbot.get_response(msg).text # Create reply resp = MessagingResponse() resp.message(str(reply)) return HttpResponse(str(resp)) -
How to restore postgres database backup that is in my host system using Docker config from django-cookiecutter?
How to restore Postgres database backup .sql file that is in my host system using Docker config from django-cookiecutter? Where to copy file and what commend run? -
Django:Uploaded images not showing in Heroku
I have deployed my app on Heroku and added some images through the admin panel. In my page the images are not showing. The database is working fine so I dont think theres anything wrong there. media and static urls in settings: STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media_root') urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('', include('management_app.urls')) ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I guess the media_root file is not being created in heroku. I had to run python manage.py collectstatic manually for the static files to load. What should I do about this? -
Django+React rest-auth
I am using the rest-auth module to enable user authentication on my web app. Though I am facing some difficulties in fetching details about the user. The Django-rest-framework return a key when I post my username and password, while that's enough for logging in I also want to fetch additional details like user.is_staff, user.username and user.email. I tried to use Token serializer, but I am not sure if I am doing it right. ** settings.py ** REST_AUTH_SERIALIZERS = { 'TOKEN_SERIALIZER': '## How to define the path to my serializer ##', } ** serializers.py ** from rest_framework import serializers from lms.models.post_models import Post from django.contrib.auth.models import User from rest_auth.models import TokenModel class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'email') class TokenSerializer(serializers.ModelSerializer): user = UserSerializer() class Meta: model = TokenModel fields = ('key', 'user') Please tell what piece is missing or if any piece is incorrect. Also, please help me figure out the part between ## ##. Thank you! -
How to restart a port 8080 in port 8080, 8081, 8082 in apache on Centos 7?
i want restart one port in multiple port of apache in Centos 7, how i can do this? thank you. -
Django - set a model CharField value to the name of a field from another model
I have a model when I want to field_name to be the name of any field from another model. I wrote this code: from providers.models import Organisation FIELD_CHOICES = [(x.name,x.verbose_name) for x in Organisation._meta.get_fields() ] class Score (models.Model): field_name = models.CharField(max_length=101, choices=FIELD_CHOICES) When I run makemigrations I get django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. This is the complete traceback: Traceback (most recent call last): File "./src/manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/henry/Documents/Sites/Development/autumna-dev/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/henry/Documents/Sites/Development/autumna-dev/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/home/henry/Documents/Sites/Development/autumna-dev/env/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/henry/Documents/Sites/Development/autumna-dev/env/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/home/henry/Documents/Sites/Development/autumna-dev/env/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/home/henry/Documents/Sites/Development/autumna-dev/env/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/henry/Documents/Sites/Development/autumna-dev/autumna/src/scoring/models.py", line 7, in <module> FIELD_CHOICES = [(x.name,x.verbose_name) for x in Organisation._meta.get_fields() ] File "/home/henry/Documents/Sites/Development/autumna-dev/env/lib/python3.6/site-packages/django/db/models/options.py", line 733, in get_fields return self._get_fields(include_parents=include_parents, include_hidden=include_hidden) File "/home/henry/Documents/Sites/Development/autumna-dev/env/lib/python3.6/site-packages/django/db/models/options.py", line 793, in _get_fields all_fields = self._relation_tree File "/home/henry/Documents/Sites/Development/autumna-dev/env/lib/python3.6/site-packages/django/utils/functional.py", line 37, in __get__ res = instance.__dict__[self.name] … -
How to add an element without changing the height of the card or disturbing position of other elements
How do I add an element(image) at the end without changing the height of the card, with card height set to auto is there any way to solve this? any help is appreciated, Thanks! .card { width: 540px; height: auto; border: 1px solid #707070; } .field2 { font-family: inherit; padding-top: 20px; padding-bottom: 25px; display: flex; justify-content: space-between; } .log_in_instead { padding-left: 60px; } .create { padding-right: 70px; } #img101 { position: relative; left: 490px; top: -150px; } <div class="card"> <div class="field2"> <span class="log_in_instead"> <a href="#">Log in instead</a> </span> <span class="create"><button id="create_button" type="submit">Create</button</span> </div> <span><img src="{% static 'main/images/img101.svg' %}" id="img101"></span> </div> This is what it should look like: [1]: https://i.stack.imgur.com/jkPg2.png This is what it looks like: [2]: https://i.stack.imgur.com/w1ROu.png -
How to put an if statement outside the functions in Django Views, Python
I have 3 functions. Each of them has the same line of code: if request.method == "POST" and 'url' in request.POST: Here are the functions: def checkurl(request): if request.method == "POST" and 'url' in request.POST: url = request.POST.get('url', '') url_response = "" if not url.startswith('http://') and not url.startswith('https://'): url_get = "http://" + url url_response = requests.get(url_get, headers=headers, allow_redirects=False) url_status_code = url_response.status_code if url_status_code == 200: url = url_get return url else: url = "https://" + url return url return url def netloc(request): url = checkurl(request) global url_scheme global url_port global url_netloc global url_path if request.method == "POST" and 'url' in request.POST: url_parsed = urlparse(url) url_scheme = url_parsed.scheme url_port = url_parsed.port url_netloc = url_parsed.netloc if url_netloc.startswith('www.'): url_netloc = url_netloc.replace('www.', '') if url_netloc.endswith('/'): url_netloc = url_netloc.replace('/', '') return url_scheme, url_port, url_netloc def tests(request): if request.method == "POST" and 'url' in request.POST: url = checkurl(request) netloc(request) var = { 'url':url, 'url_scheme':url_scheme, 'url_port':url_port, 'url_netloc':url_netloc, } return render(request, 'apptests/shots.html', var) else: return render(request, 'apptests/shots.html') I do not want to repeat the same line of code in each function and want to remove it and put it aside before these 3 functions. But I cannot do it Please help -
adding html links to different fields: Django
I have a question if i have 3-4 different post/section in html which i uploaded through admin panel but all this posts/sections have different html pages so how can i link each post/section with their specific html page and is there a field in django model which helps in uploading videos?? posts.Html <div class="blog_list"> <h1 class="blog_heading"> Top 10 Family Holiday Destination</h1><br><br> {% for postv in postv %} <h2 class="blog_location">{{ postv.locationv }}</h2><br> <img class="blog_img" src="{{ postv.imgv.url }}"><br> <p class="blog_details article-content">{{ postv.detailv }}</p><br><br> {% endfor %} </div> models.py class vacation(models.Model): locationv = models.CharField(max_length=100) imgv = models.ImageField(upload_to='locations') detailv = models.TextField() def __str__(self): return self.locationv views.py class top10_vacation(ListView): model = vacation template_name = 'shop/vacation.html' context_object_name = 'postv' -
How do I submit a form without page reload using Ajax
I'm learning Ajax on how I can submit a comment form without page reload. I'm using Django, I have list of posts in homepage each with comment form. When I submit a comment it is not saving in database and also it doesn't display in browser. When I check on Chrome console, I got an error 2 elements with non-unique id. from django.http import JsonResponse from django.template.loader import render_to_string def home(request): all_images = Post.objects.filter(poster_profile=request.user) if request.method == 'POST': post_id = request.POST.get("post_comment") post_obj = Post.objects.get(pk=post_id) form = CommentForm(request.POST) if form.is_valid(): comment=form.save(commit=False) comment.user=request.user comment.commented_image=post_obj comment.save() else: form=CommentForm() context = {'all_images':all_images, 'form':form} if request.is_ajax(): html=render_to_string('ajax_feeds_comment.html', context, request=request) return render(request, 'home.html', context) #home.html {% for post in all_images %} <img src="{{ post.image.url }}"> {% for comment in post.comments.all %} <p>{{ comment.comment_post }}</p> {% endfor %} <div class="reload-form"> {% include "ajax_feeds_comments.html" %} </div> {% endfor %} #ajax_feeds_comments.html <form method="POST" class="feeds-comment" action="."> {% csrf_token %} <input type="hidden" value="{{post.id}}" name="post_comment"> <textarea name="comment_post" class="form-control" id="id_comment_post{{post.id}}"></textarea> <button type="submit" class="btn btn-primary">submit</button> </form> <script> $(document).on('submit', 'feeds-comment', function(event){ event.preventDefault(); console.log($(this).serialize()); $.ajax({ type: 'POST', url: $(this).attr('action'), data: $(this).serialize(), dataType: 'json', success: function(response){ $('.reload-form').html(response['form']); }, error: function(rs, e) { console.log(rs,responseText); }, }); }); </script> -
Django: dropdown toggle javascript does not work well
I have the following sidebar in my django: <a class="sidebar-heading d-flex justify-content-between align-items-center px-3 mt-4 mb-1" href="#firstSubmenu" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle">Performance Monitoring<span data-feather="plus-circle"></span></a> <ul class="collapse list-unstyled" id="firstSubmenu"> <li> <a class="nav-link" href="#"> <span data-feather="monitor"></span> Dashboard</a> </li> <a class="sidebar-heading d-flex justify-content-between align-items-center px-3 mt-4 mb-1" href="#secondSubmenu" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle">Performance Monitoring<span data-feather="plus-circle"></span></a> <ul class="collapse list-unstyled" id="secondSubmenu"> <li> <a class="nav-link" href="#"> <span data-feather="monitor"></span> Dashboard</a> </li> And the following script to allow me to keep open the dropdown button when change url $("#firstSubmenu").on('shown.bs.collapse', function(){ // Save in sessionStorage here }); $("#secondSubmenu").on('shown.bs.collapse', function(){ // Save in sessionStorage here }); $("#firstSubmenu").on('hidden.bs.collapse', function(){ // Save in sessionStorage here }); $("#secondSubmenu").on('hidden.bs.collapse', function(){ // Save in sessionStorage here }); $("#firstSubmenu").collapse("show"); $("#secondSubmenu").collapse("show"); But, for example, If I keep close the first submenu and open the second one, if I update the url both submenu are opened. Whre is the error/s? -
Django Admin Classes that Override formfield_for_dbfield - Error
I have a bunch of FlatPages on my django website and would like to translate their content in different languages from the Admin using the django-modeltranslations pacakge. Here is my code: class TinyMCEFlatPageAdmin(FlatPageAdmin): def formfield_for_dbfield(self, db_field, **kwargs): if db_field.name.startswith('content'): return db_field.formfield(widget=TinyMCE(attrs={'cols': 80, 'rows': 30},)) return super().formfield_for_dbfield(db_field, **kwargs) Basically, I created a TinyMCEFlatPageAdmin class from the default one FlatPageAdmin to display the Flatpage content in HTML on the admin site. As far as the translation is concerned, i added the following code: class MyTranslatedFlatPageAdmin(TinyMCEFlatPageAdmin, TabbedTranslationAdmin): def formfield_for_dbfield(self, db_field, **kwargs): field = super().formfield_for_dbfield(db_field, **kwargs) self.patch_translation_field(db_field, field, **kwargs) return field I have then registered the new MyTranslatedFlatPageAdmin class: admin.site.unregister(FlatPage) admin.site.register(FlatPage, MyTranslatedFlatPageAdmin) When i log in to the flatpage content page i receive the following error: formfield_for_dbfield() takes 2 positional arguments but 3 were given I am struggling to find out why as everything seems to be correct to me. Thanks in advance for your help -
How to select for update postgresql in node js
I'm generally using django, and for operations with ordered concurrency I use next code with transaction.atomic(): try: player = Player.objects.select_for_update().get( id=player.id, player_online=False) except: return bad_response("Unknown error") player.player_socket = socket_id player.save() # Even here it will wait until "with" finished if player.extra_security: print("Ask for password action") else: pass So in this code I get player by criteria and while code inside "with transaction.atomic():" All other queries will WAIT, not returned with error. How can I reproduce such flow in node_js + postgresql (or MongoDb) I have found some solutions but, they not fit, because if object is locked they'll return an error (for mongo db) -
Is there a way to hide autodoc of exceptions and save methods?
I'm documenting a huge Django project and would like to have an option to hide autogenerated Django stuff like below. Is it something I have to "deal with" or is there a setting I haven't found yet? I document with: .. automodule:: module.models :members: and get things like below, which would be good if I had those overriden, but they're not: exception DoesNotExist exception MultipleObjectsReturned save(*args, **kwargs):... -
request.post redirecting to get in django development server
from rest_framework.authentication import BasicAuthentication from rest_framework.permissions import IsAuthenticated class TestApiView(APIView): authentication_classes = [BasicAuthentication] permission_classes = [IsAuthenticated] def post(self, *args, **kwargs): return Response({'method': 'post'}) def get(self, *args, **kwargs): return Response({'method': 'get'}) The view is accessable in the url http://127.0.0.1:8000/test/ and working as expected in browser I am calling the api from python shell import requests from requests.auth import HTTPBasicAuth url = 'http://127.0.0.1:8000/test/' my_auth = HTTPBasicAuth('<my-user-name>', '<password>') r=requests.post(url, auth=my_auth) print(r.json()) {'method': 'get'} The get method is called instead of post in the django development server. I want to make it work in django development server. Its working perfect in my nginx-gunicorn-django server Any help appreciated. -
Django TypeError objects is not iterable in Templates
I have two models one is club details and the other is player structure. so my plan is to based on the club iteration which has values like'test', 'odi', 'listA' i need to represent its respective player structure in my Django template. models.py class Clubstate(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class PlayerStructure(models.Model): clubstate = models.ForeignKey('Clubstate', on_delete=models.CASCADE, related_name='clubstate') country = models.ForeignKey('TeamStructure', on_delete=models.CASCADE, null=True, related_name='identifier1') firstname = models.CharField(max_length=255) lastname = models.CharField(max_length=255) imageUri = models.ImageField(upload_to='images/', verbose_name='image') JerseyNumber = models.IntegerField() def __str__(self): return self.firstname + self.lastname In views.py I'm using DetailView to represent the data. class PlayerStatistics(DetailView): context_object_name = 'Clubstate_details' model = models.Clubstate template_name = 'CricketDetails/playerstatistics_details.html' Template html <div class="jumbotron"> <div class="container"> <div class="row"> {% for club in Clubstate_details %} <h1>{{club.name</h1> {% endfor %} </div> </div> </div> My thought, logic is like {% for club in clubs %} {{club.name}} {{club.player_structure.firstname}} {{club.player_structure.lastname}} {% endfor%} So that for indivdual club i get its respective player structure. I get TypeError: 'Clubstate' object is not iterable error. Hope that makes sense... -
Error Unknown command: 'mycommand' in django management command
I am a beginner and I want Multiple arguments with values to custom management command, I am using following code def add_arguments(self, parser): parser.add_argument('--str_arg1', nargs='+') parser.add_argument('--int_arg2', nargs='+', type=int) when I run manage.py mycommand but I am getting an error F:\tb\sun>manage.py mycommand Unknown command: 'mycommand' Type 'manage.py help' for usage. My path is management/ commands/ __init__.py mucommand.py __init__.py -
trying to create a second forms.py on my Django app to post on the same page
I have one forms.py set up to post onto my Django application successfully. I would like to set up a second forms.py which posts onto the same page but i cannot get it to work. The form comes up but it does not post. Here is my forms.py, the first one is the successful one: ''' from django import forms from . import models class CreatePost(forms.ModelForm): class Meta: model = models.Post fields = ['title', 'body','reverse_around_the_corner','speed_limit','watching_mirrors','centre_of_the_road','slug'] class CreateLearnerPost(forms.ModelForm): class Meta: model = models.LearnerPost fields = ['title', 'body', 'author', 'slug'] ''' Here is my views py, the LearnerPost view is the one i'm trying to create: ''' rom django.shortcuts import render, redirect from .models import Post, LearnerPost from django.contrib.auth.decorators import login_required from . import forms def PostList(request): posts = Post.objects.all().order_by('date') learner_posts = LearnerPost.objects.all().order_by('date') return render(request, 'logbook_index.html', {'posts':posts}, {'learner_posts':learner_posts}) def PostDetail(request, slug): post = Post.objects.get(slug=slug) return render(request, 'post_detail.html', {'post':post}) def LearnerPostDetail(request, slug): learner_post = LearnerPost.objects.get(slug=slug) return render(request, 'learner_post_detail.html', {'learner_post':learner_post}) def PostCreate(request): if request.method == 'POST': form = forms.CreatePost(request.POST, request.FILES) if form.is_valid(): instance = form.save(commit=False) instance.author = request.user instance.save() return redirect('/logbook/') else: form = forms.CreatePost() return render(request, 'post_create.html', {'form':form}) def LearnerPostCreate(request): if request.method == 'POST': form = forms.CreateLearnerPost(request.POST, request.FILES) if form.is_valid(): instance = form.save(commit=False) …