Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
foreign key showing undefined django ajax
in this scenario when put the name of foreign key in p tag with js, it is showing undefined but its getting the inpuput as the proper user but not not able to show it because it is saying undefined js code $(document).ready(function(){ // $('#submit').onclick(function(){ // $('#message').val='' // }) $(document).on('submit','#post_form',function(e){ e.preventDefault(); $.ajax({ type: 'POST', url:"{% url 'create' %}", data:{ message: $('#message').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), }, success:function(){ window.location = url; } }); }); setInterval(function() { $.ajax({ type:'GET', url:"{% url 'comments' %}", success:function(response){ $('.display').empty(); for(var key in response.comments){ this is where it shows undefined, is there any way to convert it to string console.log(response.comments[key].user); var temp = "<div class='message_area'><p id='messagetext'>"+response.comments[key].message+"</p></div>" $(".display").append(temp); } }, error:function(response){ console.log("no data found") } }); }, 500); }); views.py def create(request): if request.method == "POST": author = request.user message = request.POST['message'] message = comments(user=author,message=message) message.save() models class comments(models.Model): userId = models.AutoField(primary_key=True) user = models.ForeignKey(User,on_delete=models.CASCADE) message = models.CharField(max_length=100,blank=False) date = models.TimeField(auto_now_add=True) def __str__(self): return f'{self.user} comments' -
Which is First and All?
I read the Django documentation, but I'm not sure if I'm doing it right. What I want to do: I want to get all the user's posts through his id, because it will be a platform that will have profiles of users of various types. I did it this way to return the user's posts: user = Post.objects.filter(user=id).all() But I saw that there is another way to do it, so I was seeing it on facebook groups. users = Post.objects.filter(user=id).first() Which of the two ways are correct to be done? OBS: I want to return all user posts! -
Overlap in drop down button in HTML code using JQUERY
Drop Down1: Work County1: INDIA Work State1: Drop Down2: Work County2: INDIA Work State2: CHN I have coded drop down logic. Scenario1: selected Country1 India and state as chennai. Scenario2: Selected country2 USA and state is TX. Scenario3: Selected country 2 as India and state is Chennai.But it impacted the drop down 1 by making the state as blank. My doubt is drop down1 and drop down 2 should be independent of each other but scenario3 stated above occurs. My code snippet is below. <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> $(document).ready(function() { var $select1=$('#select1'), $select2=$('#select2') $options=$select2.find('option'); $select1.on('change',function() { $select2.html($options.filter('[value="'+this.value+'"]')); }).trigger('change'); } ); </script> <script> $(document).ready(function() { var $select3=$('#select3'), $select4=$('#select4') $options=$select4.find('option'); $select3.on('change',function() { $select4.html($options.filter('[value="'+this.value+'"]')); }).trigger('change'); } ); </script> <title>Page Title</title> </head> <body> <tr> <td><label for="appt">Work County1:</label></td> <td><select id="select1"> <option selected disabled="true" value="">------</option> <option value="1">INDIA </option> <option value="2">USA </option> </select><br></td> <td><label for="appt">Work State1:</label></td> <td><select id="select2"> <option selected disabled="true" value="">------</option> <option value=1>CHN</option> <option value=2>TX</option> </select><br></td> </tr> <br><br><br><br> <tr> <td><label for="appt">Work County2:</label></td> <td><select id="select3"> <option selected disabled="true" value="">------</option> <option value="1">INDIA </option> <option value="2">USA </option> </select><br></td> <td><label for="appt">Work State2:</label></td> <td><select id="select4"> <option selected disabled="true" value="">------</option> <option value=1>CHN</option> <option value=2>TX</option> </select><br></td> </tr> </body> </html> -
How can i use filepond javascript library in Django template?
Intro: I have Django web app where users are allowed to create posts. Each post has multiple images that are associated with that post. What I want to do: I want to use Filepond javascript library for remove, add more and previews of selected images. The issue: The code below is working ok without filepond library but if i try to use filepond library the form is submitting only title input without files. views.py class NewsCreateView(CreateView): form_class = FileForm template_name = 'create.html' success_url = '/' def form_valid(self, form): post = form.save(commit=False) post.author = self.request.user post.save() for f in self.request.FILES.getlist('filepond'): FileModel.objects.create(post=post, file=f) return super().form_valid(form) create.html <link href="https://unpkg.com/filepond/dist/filepond.css" rel="stylesheet"> <link href="https://unpkg.com/filepond-plugin-image-preview/dist/filepond-plugin-image-preview.css" rel="stylesheet"> <div class="content"> <div class="row"> <div class="col-md-12"> <div class="hpanel" style="margin-top: 10px;"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <input type="text" id="id_title" name="title" class="form-control"> <input type="file" id="id_file" name="file" multiple="true"> </div> <button class=" btn btn-success btn-block" type="submit">Submit</button> </form> </div> </div> </div> </div> <script src="https://unpkg.com/filepond-plugin-image-preview/dist/filepond-plugin-image-preview.min.js"></script> <script src="https://unpkg.com/filepond/dist/filepond.min.js"></script> <script> FilePond.registerPlugin( FilePondPluginImagePreview ); FilePond.create( document.querySelector('input[type="file"]') ); </script> -
Djando Class Based Views InlineFormSet_Factory not saving The Extra Feilds
I need a support here I am trying to use inlineformset_fatory It is rendered in template and (Post) form is submitted and saved .. but fields in formset is NOT SAVED Forms.py ImageFormSet = forms.modelformset_factory(ExtraPostImages, fields=('extra_images_image',), extra=3) Models.py class Post(models.Model): title = models.CharField(max_length=150) slug = models.SlugField(max_length=150, null=True, blank=True) content = models.TextField() class ExtraPostImages(models.Model): extra_images_post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='extra_post_images') extra_images_image = models.ImageField(upload_to=post_images_upload, blank=True) Views.py class PostCreateView(LoginRequiredMixin, View): template_name = "blog/Post_Create.html" form_class = PostCreateForm def get(self, request, *args, **kwargs): Image_FormSet = ImageFormSet() return render(request, self.template_name, { "form": self.form_class, "ExtraFormSet": Image_FormSet, }) def post(self, request, *args, **kwargs): ExtraFormSet = ImageFormSet(self.request.POST or None, self.request.FILES or None) form = self.form_class(request.POST, request.FILES) if form.is_valid() and ExtraFormSet.is_valid(): post = form.save(commit=False) post.author = request.user post.save() form.save_m2m() for f in ExtraFormSet: try: photos = ExtraPostImages(post=post, extra_images_image=f.clean_data['extra_images_image']) photos.save() except Exception as e: break messages.success(request, "Your post has been saved successfully.") return redirect(reverse("detail-post", kwargs={"slug": post.slug})) else: ExtraFormSet = ImageFormSet(queryset=ExtraPostImages.objects.none()) form = PostCreateForm messages.error( request, "An error occurred when saving your post.Please try again") return render(request, self.template_name, { "form": form, "ExtraFormSet": ExtraFormSet, }) Templates.html <form id='create-new-project' method="POST" enctype="multipart/form-data" class="my-ajax-form" data-url="{% url 'create-post' %}"> {% csrf_token %} {{ form.media }} {{ form|crispy }} {{ ExtraFormSet.management_form }} {{ ExtraFormSet.as_table }} <input class="btn btn-secondary mt-4" … -
How can i delete a single comment for a user inside of a post in Django
I'm trying to add a delete button for a single comment of current user inside a post. I tried the function below in my views.py , but it comes back as error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/comments/15/delete/ Raised by: feed.views.comment_delete Any ideas what I'm doing wrong ? views.py @login_required def comment_delete(request, pk): comment = get_object_or_404(Comments, pk=pk) if request.user.id == comment.username_id: Comments.objects.get(pk=pk).delete() messages.error(request, f'Comment Deleted') return redirect('post-detail', pk=pk) models.py class Post(models.Model): description = models.TextField(max_length=255) pic = models.ImageField(upload_to='path/to/img', blank=True) date_posted = models.DateTimeField(default=timezone.now) user_name = models.ForeignKey(User, on_delete=models.CASCADE) tags = models.CharField(max_length=100, blank=True) def __str__(self): return self.description def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) class Comments(models.Model): post = models.ForeignKey(Post, related_name='details', on_delete=models.CASCADE) username = models.ForeignKey(User, related_name='details', on_delete=models.CASCADE) comment = models.CharField(max_length=255) comment_date = models.DateTimeField(default=timezone.now) post_detail.html <h4 class="comment_text">Comments</h4> <div class="row"> <div class="col-xl-9 col-md-10 m-auto order-xl-2 mb-0 mb-xl-0"> {% if post.details.all %} <div class="card card-signin my-0"> {% for detail in post.details.all %} <div class="card-body"> <a href="{{ detail.username.profile.get_absolute_url }}"> <img src="{{ detail.username.profile.image.url }}" class="rounded-circle" width="30" height="30" alt=""> </a> <a class="text-dark" href="{{ detail.username.profile.get_absolute_url }}"><b>{{ detail.username }}</b></a> <a class="comment_delete" href="{% url "comment-delete" user.id %}">delete</a> <br><small>{{ detail.comment_date }}</small><br><br> <p class="card-text text-dark">{{ detail.comment }}</p> </div> <hr class="my-1"> {% endfor %} </div> {% else %} <p>No comments to show!</p> {% endif … -
How can I do to test a graphql api using django?
I would like to do unittest with that : import graphene from graphene_django import DjangoObjectType from myApp import Player class PlayerType(DjangoObjectType): class Meta: model=Player class Query(graphene.ObjectType): player=graphene.List(PlayerType, playersearch=graphene.String()) def resolve_player(self, info, value=None): return Player.objects.get(name=value) I mean especially the resolve_player() function but I have no idea how to do that ... Could you help me please ? Thank you very much ! -
Add new ports like 8081 in cloudflare
I have two Django project running on port 8080 and 8081 with named domain name abc.com Now we added our website to Cloudflare so abc.com with new IP with port 8080 is working fine But, on port 8081 we can access it via the only original_host_ip and not the domainname.com i.e abc.com:8080 WORKING a.b.c.d:8081 WORKING I tested it via Test-NetConnection a.b.c.d -port 8081 Test-NetConnection abc.com -port 8081 abc.com:8081 NOTWORKING ->Remote address cloudflare a.b.c.d:8081 WORKING ->Remote address a.b.c.d So I thought it is maybe due to the firewall of Cloudflare that it is not accepting port 8081 So I want to know how to add a new port to Cloudflare like port 8081. -
How is Django makemigrations triggered for changes to a custom model field?
I have a custom model field defined as: class PriceField(models.DecimalField): def __init__(self, *args, **kwargs): kwargs['max_digits'] = 30 kwargs['decimal_places'] = 20 super().__init__(*args, **kwargs) I want to change it so that it is also nullable/blankable so I add: class PriceField(models.DecimalField): def __init__(self, *args, **kwargs): kwargs['max_digits'] = 30 kwargs['decimal_places'] = 20 kwargs['null'] = True kwargs['blank'] = True super().__init__(*args, **kwargs) However, having made this addition and running makemigrations, no new migrations are created. Having read the documentation at https://docs.djangoproject.com/en/3.1/howto/custom-model-fields/#field-deconstruction I thought that the problem might be the lack of a deconstruct() method, but even after adding one as seems to be described in the docs (which I read as being to delete the kwargs you override in the init method): def deconstruct(self): name, path, args, kwargs = super().deconstruct() del kwargs['max_digits'] del kwargs['decimal_places'] del kwargs['null'] del kwargs['blank'] return name, path, args, kwargs ...it still doesn't create any migrations to make the field nullable/blankable. Can anyone tell me what I'm missing? -
How to render a string/dict in views.py with gettext_lazy before sending to rendering in Django
I am currently looking for a possibility to render a string using elements that need to be translated and using gettext_lazy. Lets assume following: My dict data: from django.utils.translation import gettext_lazy as _ data = { "name": _("Invoice"), } I want to pass this data to requests to do an API call, like this. response = requests.post('https://someapi.com/call', headers=settings.AUTH_HEADERS, json=data) If I do this, I get an error, as the gettext_lazy is only proxy at this point. Grateful for any hint. -
Why does my django webserver stop after trying to send password reset mail
The problem: I am setting up the "forgot password" functionality for my website but whenever it is triggered the webserver shuts down. (when I hit the "submit" it waits for a while and then exits the program, then I have to "runserver" again) The URLS: path('reset_password/', auth_views.PasswordResetView.as_view(), name="reset_password"), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(), name="password_reset_done"), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name="password_reset_confirm"), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(), name="password_reset_complete"), Settings setup: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = '*******@gmail.com' EMAIL_HOST_PASSWORD = *******' Here are the logs, I tried to read them but I got no idea how to fix this error. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\base.py", line 850, in resolve_lookup (bit, current)) # missing attribute django.template.base.VariableDoesNotExist: Failed lookup for key [is_nav_sidebar_enabled] in [{'True': True, 'False': False, 'None': None}, {'csrf_token': <SimpleLazyObject: <function csrf..get_val at 0x00000285F295D488>>, 'request': <WSGIRequest: GET '/reset_password/'>, 'user': <SimpleLazyObject: <function AuthenticationMiddleware.process_request.. at 0x00000285F2B482F0>>, 'perms': <django.contrib.auth.context_processors.PermWrapper object at 0x00000285F2A4EE10>, 'messages': <django.contrib.messages.storage.fallback.FallbackStorage object at 0x00000285F2B200F0>, 'DEFAULT_MESSAGE_LEVELS': {'DEBUG': 10, 'INFO': 20, 'SUCCESS': 25, 'WARNING': 30, 'ERROR': 40}}, {}, {'form': , 'view': <django.contrib.auth.views.PasswordResetView object at 0x00000285F2B201D0>, 'title': 'Password reset', 'LANGUAGE_CODE': 'en-us', 'LANGUAGE_BIDI': False}] "GET /reset_password/ HTTP/1.1" 200 1903 File C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\conf\locale\en\formats.py first seen with mtime 1603131647.8355522 File C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\conf\locale\en_init.py … -
Django 3.1.5 and Channels 3.0.3 websocket problem
I am migrating an app to Django 3.1.5 and channels 3.0.3 and I am having problems with websockets getting disconnected around 2 seconds after being connected. This is my consumer and it gets connected but a few seconds later, it disconnects without triggering the disconnect from channels.generic.websocket import JsonWebsocketConsumer from django.utils import timezone from asgiref.sync import async_to_sync class SystemConsumer(JsonWebsocketConsumer): groups = ["WSbroadcast","WSsystemAPP"] def connect(self): self.accept() print('Websocket accepted: ' + str(self.scope)) def disconnect(self, close_code): # Called when the socket closes print('Websocket disconnected: ' + str(close_code)) Can anyone tell me what can it be failing here?? I guess if the websocket connects, the routing and all the stuff is OK, but it disconnects without any advise... Thanks!! -
Working with one-to-many model relationship in templates (Django)
I have two models which have a one-to-many relationship: class Book(models.Model): title= models.CharField(max_length=200) description = models.TextField() source = models.TextField() source_site = models.TextField() def __str__(self): return self.title class Chapter(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE) chtitle = models.CharField(max_length = 100) chtitletext = models.CharField(max_length = 200) def __str__(self): return self.chtitle And I am trying to use this in my templates for specific books: <!-- Placing header with book title is finished! --> <script> $(document).ready(function () { var headerText = '{{books.1.title}}' placeHeader(headerText); }); </script> {% block chapterheader %} <script> //var chHeader = '{{chapters.0.chtitle}}' + '<br>' + '{{chapters.0.chtitletext}}'; var chHeader = '{{books.1.chapters.0.chtitle}}' + '<br>' + '{{books.1.chapters.0.chtitletext}}'; placeChapterHeader(chHeader); </script> {% endblock%} The commented out line in block chapterheader works fine in terms of displaying it. But I need to send a value that has chapter info for a particular book. -
Declare queryset only in modelviewset methods Django rest
Hey I have a view like this class ProjectShareView(viewsets.ModelViewSet): queryset = ShareProject.objects.all() serializer_class = ShareProjectSerializer def post(self, request, *args, **kwargs): project = Project.objects.get(id=kwargs['project_id']) ... def get(self, request, *args, **kwargs): share_project = ShareProject.objects.filter(project=kwargs['project_id']) ... def delete(self, request, *args, **kwargs): share_projects = ShareProject.objects.filter(project=kwargs['project_id']) ... I use a separate queryset for each method. How can I remove the queryset of the class, without it, an error appears, and leave it only in methods. Or i can use queryset.objects.none () for this? -
connecting devices with my django web application using TCP IP
I'm trying to connect couple of devices with my django web app using TCP IP and i'm new in django so my question is what is the best way to do that, i've seen some suggestion about using twisted but the thing that when i've tried to use twisted but every time a run the server i got this error (twisted.internet.error.CannotListenError: Couldn't listen on any:8015: [WinError 10048] Only one usage of each socket address (protocol/network address/port) is normally permitted.) (the twisted application works good but when i add it to django i got that error, and i tried to use a diffrent pores for the django app) -
Reading data from Javascript Promise
I'm using the django framework and I'm trying to get the data from a Javascript Promise as follows: Js file console.log("working"); $("#username").keyup(function(event){ let user=event.target.value fetch("/login/userValidation/",{ body:JSON.stringify({username:user}), method:"POST" }).then((res)=>{ console.log(res.json()); }); }); Py file (views.py) from django.contrib.auth.models import User from django.http import JsonResponse as jresp from django.views import View import json class userValidation(View): def post(self,req): data=json.loads(req.body) user=data['username'] print(user) if(user.isalnum()): if(User.objects.filter(username=user)): print("Username not available") return jresp({"user_status":"Username not available, try something else"}) else: print("Username Valid") return jresp({"user_status":"Username Valid"}) else: print("Please enter alphanumeric characters only") return jresp({"user_status":"Please enter alphanumeric characters only"}) Fetch() is posting the data from the client side to the server and the server is receiving the data just fine, as I have checked by printing out the data in the backend. However, the JsonResponse that is being returned to the client is showing undefined instead of the actual data - I'm not able to get the required data from the promise, using response.json() under the subsequent then() function. Anything I'm missing out? Please help. -
My reply button is not working in django.. please someone help me how to make working reply button in comments of django
My comment section is working fine but I don't know why my reply button is not working.. please can you go through my code and help me to find out error... I think it is a logical error. 1.Views.py from django.shortcuts import render, get_object_or_404, redirect from datasecurity.models import Post, Comment from django.urls import reverse from django.http import HttpResponseRedirect from django.contrib.auth.decorators import login_required from django.contrib import messages from django.contrib.auth.models import User from .forms import CommentForm # Create your views here. @login_required def likes(request, pk): post=get_object_or_404(Post, pk=pk) post.likes.add(request.user) return HttpResponseRedirect(reverse('datasecurity:datasecurity')) def datasecurity(request): allPosts= Post.objects.all() context={'allPosts': allPosts} return render(request, 'datasecurity/data.html',context=context) def blogHome(request, slug): post=Post.objects.filter(slug=slug).first() cf = CommentForm(request.POST or None) comments = Comment.objects.filter(post=post).order_by('sno') if request.method == 'POST': if cf.is_valid(): content = request.POST.get('content') comments = Comment.objects.create(post = post, user = request.user, content = content) comments.save() return HttpResponseRedirect(reverse('datasecurity:datasecurity')) else: cf = CommentForm() parentSno= request.POST.get('parentSno') if parentSno=="": comment=Comment(comment= comment, user=user, post=post) comment.save() else: parent= BlogComment.objects.get(sno=parentSno) comment=Comment(comment= comment, user=user, post=post , parent=parent) comment.save() context={'post':post, 'comments':comments,'comment_form':cf, 'user': request.user} return render(request, "datasecurity/blogHome.html", context) 2.models.py from django.db import models from ckeditor.fields import RichTextField from django.contrib.auth.models import User from django.utils.timezone import now # Create your models here. class Post(models.Model): sno=models.AutoField(primary_key=True) title=models.CharField(max_length=255) author=models.CharField(max_length=14) slug=models.CharField(max_length=130) timeStamp=models.DateTimeField(blank=True) content=RichTextField(blank=True, null=True) img = models.ImageField(blank=True, null=True, upload_to="dataimage/") likes … -
How to get the correct path for a django script
Here is my arborescence V1 : project/ ---AppUser/ ------models.py, view.Py etc ... ---project/ ------settings.py, manage.py etc ... myscript.py here my script works perfectly : import sys import os import django sys.path.append("../../../project") os.environ["DJANGO_SETTINGS_MODULE"] = "project.settings" django.setup() from AppUser.models import Subscription maps = Subscription.objects.get(uuid="1234565") print(maps) It works fine, i launch it from the root of the project ... But when i want to put my script in a script folder : V2 : project/ ---AppUser/ ------models.py, view.py etc ... ---project/ ------settings.py, manage.py etc ... ---script/ ------myscript.py Here is my script : import sys import os import django sys.path.append("../../../../project") os.environ["DJANGO_SETTINGS_MODULE"] = "project.settings" django.setup() from AppUser.models import Subscription maps = Subscription.objects.get(uuid="123") print(maps) and when i am in script/ and i do a python3 script.Py I have a : Traceback (most recent call last): File "myscript.py", line 12, in <module> from AppUser.models import Subscription ModuleNotFoundError: No module named 'AppUser' error How to be in script and not having this error ? The django.setup() seems to works fine. -
Why does my python anywhere show me 'install worked successfuly' page instead of the web app that i created
so i created a simple blog, tried deploying with heroku(it just told me application error), so now i tried with python everywhere. It didn't give me any errors but it acts as if my app is empty, it shows that page that u see when you firstly make a django app that is still emptythat's this page It says i see that page because DEBUG=True, but no it's off in my settings .It also says that this is because i have no configured URL's but i did configure URL's and they worked in localhost, but now i don't know why it doesn't work Please can someone help me check my SETTINGS.py and urls.py files. Thank you This is the repository containing my code https://github.com/GamerDTK/tishas-lifestyle I have a feeling the problem is from how i included the url of the app 'blog' to the main app. But it looks correct to me -
Getting AnonymousUser instead of real username authenticated when calling request.user
I am working on a form to create custom questions for a questionnaire. Both logged-in users and not logged-in ones can create questions (I am using default Django user authentication models and features). What I want to do is: when saving a question in the database, its attribute user can be saved as well, being user a field of Question model, as showed in models.py: class Question(models.Model): filepath = models.CharField(max_length=255, null=True, blank=True) slug = models.CharField(max_length=255, null=True, blank=True) order = models.CharField(max_length=255, null=True, blank=True) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, blank=True) user = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True) def __str__(self): return "{}".format(self.id) I am logged in as an admin user, so I have and id and username, but I can not get yet the Question saved with the (admin) username but AnonymousUser. In views.py file: class QuestionViewSet(generics.GenericAPIView): serializer_class = QuestionSerializer permission_classes = [AllowAny] @csrf_exempt def post(self, request, *args, **kwargs): data = request.data if request.user.is_authenticated: question = Question(user=request.user) else: question = Question() question.save() return JsonResponse(data={"success": True}, status=200) In serializers.py file (I am not using a model serializer but a generic one because I need to save several values from several models in only one post request): class QuestionSerializer(serializers.Serializer): title = serializers.CharField() description = serializers.CharField() categories … -
Django show save buttons for nlineModelAdmin not the main ModelAdmin?
I am not giving users the permissions to change the main modelAdmin. However I am allowing them to add a record to the InlineModelAdmin. Unforutnately the save button does not show. I tried overriding the method: def has_change_permission(self, request, obj=None): '''Show the save button''' return True That shows the save button but now gives the user permission to change the main model. It seems that this context variable has_editable_inline_admin_formsets in django/contrib/admin/templatetags/admin_modify.py is set to false. Even though the inline formset is editable. After a deeper dive it looks as though this section of code on line 1486 of django/contrib/admin/options.py overrides everything to false if you cannot edit the parent. if can_edit_parent: has_add_permission = inline.has_add_permission(request, obj) has_change_permission = inline.has_change_permission(request, obj) has_delete_permission = inline.has_delete_permission(request, obj) else: # Disable all edit-permissions, and overide formset settings. has_add_permission = has_change_permission = has_delete_permission = False formset.extra = formset.max_num = 0 So what should I do to allow for adding and deleting of the inline - I assume all that needs to be done is override the template in templates/admin/app_name/model_name_change_form.html and change this row to always show save: {% block submit_buttons_bottom %}{% submit_row %}{% endblock %} to: {% block submit_buttons_bottom %} {% submit_row %} <input type="submit" value="Save" … -
Is Django Apache or Nginx
I have made a project in the framework Django and I am setting up SSL encryption so it gets https instead of http and removes the safety sign in browsers. In the installation process of Certbot I am asked which software it is running. Django is sadly not an option. I've heard that Django often gets under the category Apache or Nginx, but I am not sure which one my Django project is. It is an Ubuntu server. https://certbot.eff.org/ https://letsencrypt.org/getting-started/#with-shell-access -
When I run code in Docker I get a Django error [Errno 2]. When running locally everything works. Why?
I don't know what's going on. A script run by Django works fine, but not through Docker and Django. An error is returned: Pic Errno 2 No such file or directory Below is the code of the function with the error and the code of the Dockerfile. ''' def mediainfo(filepath): Original code: prober = get_prober_name() command_args = [ "-v", "quiet", "-show_format", "-show_streams", filepath ] command = [prober, '-of', 'old'] + command_args Modified code: command = f"ffprobe -v error -show_format -show_streams -select_streams v:0 {filepath}" The rest of the functions: res = Popen(command, stdout=PIPE) output = res.communicate()[0].decode("utf-8") if res.returncode != 0: output = Popen(command, stdout=PIPE).communicate()[0].decode("utf-8") rgx = re.compile(r"(?:(?P<inner_dict>.*?):)?(?P<key>.*?)\=(?P<value>.*?)$") info = {} if sys.platform == 'win32': output = output.replace("\r", "") for line in output.split("\n"): # print(line) mobj = rgx.match(line) if mobj: # print(mobj.groups()) inner_dict, key, value = mobj.groups() if inner_dict: try: info[inner_dict] except KeyError: info[inner_dict] = {} info[inner_dict][key] = value else: info[key] = value return info ''' Code of the Dockerfile ''' FROM python:3.7 as base EXPOSE 80 WORKDIR /app COPY . /app ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 RUN pip install --upgrade pip RUN echo 'deb http://deb.debian.org/debian buster-backports main contrib non-free' >> /etc/apt/sources.list RUN apt-get update RUN apt-get -y install ffmpeg RUN apt-get update … -
Duplicate key error when saving a new object
I'm creating a new object with a form and when I hit the save button I got this error: IntegrityError at /department/add duplicate key value violates unique constraint "feedback_department_pkey" DETAIL: Key (id)=(1) already exists. Although, I have 18 records in this table in the database, but I can't figure out why is trying to start saving from the first id. my views.py: # Add new department def department_add(request): form = DepartmentEditForm() if request.method == "POST": print('Printing POST', request.POST) form = DepartmentEditForm(request.POST) if form.is_valid(): form.save() return redirect('feedback:department') return render(request, 'departmentadd.html', {'form': form}) my models.py: class Department(models.Model): name = models.CharField(max_length=100) title_bg = models.CharField(max_length=50) title_en = models.CharField(max_length=50) title_de = models.CharField(max_length=50) def __str__(self): return self.name urls.py path('department/add', views.department_add, name="departmentadd"), and forms.py: class DepartmentEditForm(forms.ModelForm): class Meta: model = Department #fields = '__all__' fields = [ 'name', 'title_bg', 'title_en', 'title_de', ] widgets = { 'name': forms.TextInput(attrs={'class': 'form-control'}), 'title_bg': forms.TextInput(attrs={'class': 'form-control'}), 'title_en': forms.TextInput(attrs={'class': 'form-control'}), 'title_de': forms.TextInput(attrs={'class': 'form-control'}), } Can someone say what I'm missing here? Thanks a lot! -
Django logging still prints out stacktrace
For some reason instead of just printing out the error message with logging it prints the stack trace to the console followed by the message: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'standard': { 'format': '[%(asctime)s] p%(process)s {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s', }, }, 'handlers': { 'default': { 'level': env.str('LOGGING_LEVEL'), 'class': 'logging.StreamHandler', 'formatter': 'standard', }, }, 'loggers': { 'default': { 'handlers': ['default'], 'level': env.str('LOGGING_LEVEL'), 'propagate': True }, } } from logging import getLogger log = getLogger('default') def test(): try: raise Exception('This is a test exception') except Exception as error: log.error(str(error)) output: $ python manage.py custom_test_command # calls test method ... raise Exception('This is a test exception') Exception: This is a test exception [2021-02-08 16:27:40,299] p21052 {<console>:4} ERROR - This is a test exception