Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Favicon not displaying when deployed
I have deployed a Django website on Pythonanywhere. The favicon worked on my local server but not on my Pythonanywhere site. The code in my base.html is <link rel="stylesheet" type="text/css" href="{% static 'fixtureapp/style.css' %}"> <link href="{% static 'images/scc.ico?' %}" rel="icon" type="image/x-icon" /> I've shown the stylesheet link as this is working so static is set up ok. iamges/scc.ico is in the same static file. I get the error 2021-03-10 14:52:43,422: Not Found: /favicon.ico -
How to restrict users logged in via Saml in Django
I have developed a website using Django and integrated saml sso. So whoever login to "https://testing.com/saml2.login" , they will redirected to saml2 , verified and request will be sent to "https://testing.com/home". However, I want to restrict only allowed users should be shown the webpage. Note: I can do this via Django admin's users, groups. But this login is happening via saml sso. Could you please suggest me a way on how to achieve it ? Thanks in advance. Flow diagram -
multiple delete in in genericview
I have a template in my django app that displays several checkboxes. When some of these are checked I want to delete the entries. Normaly I pass the key to the generic function to delete one. But I don't know how to pass several selected keys, any idea? views.py: class PDelete(DeleteView): template_name='kammem/delete.html' model=Person success_url=reverse_lazy('pe path('pdelete/<int:pk>/',DeleteView.as_view(model=Person,\ success_url=reverse_lazy('personer'),template_name='kammem/delete.html')), rsoner') def get_context_data(self,**kwargs): mod=self.request.kwargs['model'] context=super().get_context_data(**kwargs) context['model']=self.kwargs['model'] return mod persl.html: (there is a {% for l in pl %} but it can't be displayed correctly) <tr> <td><div class="form-check"> <input class="form-check-input" type="checkbox "value="" id="checked"> <label class="form-check-label" for="checked"> </label> </div> </div> </td> <td><a href="pupdate/{{l.pk}}"><i class="bi bi-pencil-square"></i></a></td> <td><a href="pdelete/{{l.pk}}"><i class="bi bi-trash"></i></a></td> <td>{{l.pk}}</td> <td><a href="detail/{{l.padress.pk}}">{{l.fname}}</a></td> <td>{{l.lname}}</td> <td>{{l.mobil}}</td> <td>{{l.mail}}</td> <td>{{l.padress}}</td> </tr> ursl.py path('pdelete/<int:pk>/',DeleteView.as_view(model=Person,\ success_url=reverse_lazy('personer'),template_name='kammem/delete.html')), -
How to return value to view after select item from dropdown list in django
`def store_list(request): displaystores=stores.objects.all() if request.POST: store_pk_list = request.POST.getlist('stores', None) print(request.POST.getlist('stores.unit_key', None)) selected_store_obj_list = stores.objects.filter(pk__in=store_pk_list) print(selected_store_obj_list) return render(request,'storelist.html',{'stores':displaystores}) -
How to pass pass/reference a dictionary in a request
I have made an API call with the function below that I am testing on Postman. It takes in an id(dictionary) and deletes the doctor with that id. So the solution works as it is.Problem is , the id is hard coded - id = {"id": 11} .How do I reference it so that I can feed it in postman instead of hard coding? I have tried using id = request.GET.get("id") and adding it as a parameter but it didn't work for me.Any assistance will be highly appreciated Views.py class DoctorBillingPayments(GenericAPIView): authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] @classmethod @encryption_check def delete(self, request, *args, **kwargs): id = {"id": 11} try: result = {} auth = cc_authenticate() res = deleteDoctor(auth["key"],id) result = res return Response(result, status=status.HTTP_200_OK) except Exception as e: error = getattr(e, "message", repr(e)) result["errors"] = error result["status"] = "error" return Response(result, status=status.HTTP_400_BAD_REQUEST) api_service.py def deleteDoctor(auth, data): try: headers = { "Authorization": f'Token {auth}' } url = f'{CC_URL}/doctors/' print(url) res = requests.delete(url, json=data, headers=headers) return res.json() except ConnectionError as err: print("connection exception occurred") print(err) return err -
Can't access js file in Amazon S3
I have a website running on Django. Trying to measure its performance with Django-Debug-Toolbar. I have installed it properly, run collectstatic and the script is now in my static folder in Amazon S3 bucket. When I reload the website, I don't see the panel triggered. Looking at console tells me GET https://hull2hull-bucket.s3.amazonaws.com/debug_toolbar/js/utils.js net::ERR_ABORTED 403 (Forbidden) My S3 bucket is private, but Django obviously has access to it. Some other javascripts in static folder are running fine, but not this one. I have even tried to make the whole bucket public for a while, but I was still getting 403. I've added my localhost to CORS. What's wrong with my setup? Amazon documentation is vast, but not very helpful here. -
How to add a new dependency in requirements.txt file?
I cloned a djangox repo to my local device I founded a requirements.txt file that contains some dependencies I wanna add a rest framework ( adding a new dependency ) to this file how could I do that, please ?! p.s: I usually use poetry that deals with pyproject.tomal but for using docker, I wanna use this one. -
How to pass a variable from python file to html file in django?
I want to show a variable value in webpage from the ml model connected by django -
null value in column "comment_id" of relation "blog_comment" violates not-null constraint
When attempting to create an application for comments in my Django blog, I get the "null value in column "comment_id" of relation "blog_comment" violates not-null constraint" error listed above. For the view of the page, I am using a Detail View with a FormMixin. I am not sure why I am getting this error. Any assistance is appreciated. The full error message IntegrityError at /post/7/ null value in column "comment_id" of relation "blog_comment" violates not-null constraint DETAIL: Failing row contains (6, dafsdfa, sdfasdfasdf, sdfadfa, 2021-03-10 15:03:11.283567+00, null). views.py class DetailPostView(FormMixin, DetailView): model = Post template_name = "blog/post_detail.html" context_object_name = "posts" form_class = CommentForm def form_valid(self, form): form.save() return super().form_valid(form) def post(self, request, *args, **kwargs): form = self.get_form() self.object = self.get_object() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def get_success_url(self): return reverse("post-detail", kwargs={"pk": self.object.pk}) Models.py class Comment(models.Model): comment = models.ForeignKey(Post, on_delete=models.CASCADE) title = models.CharField(max_length=200) content = models.TextField() author = models.CharField(max_length=50) created_on = models.DateTimeField(auto_now_add=True) Forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment labels = {"author": "Author", "title": "Title", "content": "Comment"} fields = ["author", "title", "content"] -
Deploying Django on Amazon Elastic Beanstalk
I'm trying to deploy Django on EB but here's my issue: The deployment goes well, and I can migrate and create a superuser from the .config file in the .ebextensions directory. The only thing is, the Django server doesn't start by itself, and I have to python manage.py runserver via SSH to get it working. Which brings up another issue: when the EC2 instance shuts down, the Django server stops too and is not restarted at the next instantiation. Here's my .config file: container_commands: 01_migrate: command: "source /var/app/venv/staging-LQM1lest/bin/activate && export $(sudo cat /opt/elasticbeanstalk/deployment/env | xargs) && cd /var/app/staging/my_project_name && python manage.py migrate --noinput" leader_only: true 02_createsu: command: "source /var/app/venv/staging-LQM1lest/bin/activate && export $(sudo cat /opt/elasticbeanstalk/deployment/env | xargs) && cd /var/app/staging/my_project_name && python manage.py createsu" leader_only: true option_settings: "aws:elasticbeanstalk:application:environment": DJANGO_SETTINGS_MODULE: "monga.settings" "aws:elasticbeanstalk:container:python": WSGIPath: /var/app/current/my_project_name/my_project_name/wsgi.py NumProcesses: 3 NumThreads: 20 I even tried to add the following without success (it cannot even be deployed, probably because it gets stuck with the runserver command): 03_runserver: command: "source /var/app/venv/staging-LQM1lest/bin/activate && export $(sudo cat /opt/elasticbeanstalk/deployment/env | xargs) && cd /var/app/staging/my_project_name && python manage.py runserver" leader_only: true What should I do to get the Django server to run automatically? -
Risk of exposing an ID of entry in DRF framework
I'm building an API and I've started using the GenericAPIViews. In this example class InsertActivityChange(UpdateAPIView): authentication_classes = [] permission_classes = [] serializer_class = ActivitiesSerializer lookup_field = 'id' def get_queryset(self): return Activities.objects.filter(id=self.kwargs['id']) def put(self, request, *args, **kwargs): return self.update(request, *args, **kwargs) path('insertactivitychange/<int:id>', views.InsertActivityChange.as_view(), name='insertactivitychange'), I've used a generic class to do updates for an object. My concern is if I'm risking much by allowing the ID to be directly inputted after the URL. Obviously, I'd further mitigate the risk by properly configuring the authentication and permission class, so is the ID of the entry even a security risk? -
How to redirect to another view/page if the form is invalid
In the event that the form is not valid, how do I redirect the user to another page? def dothings(request): form = dumyForm(request.POST or None) if form.is_valid(): #do 123 else: # INSTEAD OF REINITIALIZING THE FORM LIKE THIS, I WANT TO REDIRECT TO ANOTHER PAGE form = form = dumyForm() return render(request,'dummy.html',{}) -
Venv not wrapping third-party libraries leading to module not found
I tried starting a Django project through python manage.py <folder_name> only to get the following stack trace: Traceback (most recent call last): File "C:\Users\User\PycharmProjects\pythonProject\web_projects\mysite\manage.py", line 12, in main from django.core.management import execute_from_command_line File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\django\core\management\__init__.py", line 12, in <module> from django.conf import settings File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\django\conf\__init__.py", line 19, in <module> from django.utils.deprecation import RemovedInDjango40Warning File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\django\utils\deprecation.py", line 5, in <module> from asgiref.sync import sync_to_async ModuleNotFoundError: No module named 'asgiref' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\User\PycharmProjects\pythonProject\web_projects\mysite\manage.py", line 23, in <module> main() File "C:\Users\User\PycharmProjects\pythonProject\web_projects\mysite\manage.py", line 14, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? The last line makes it evident what's missing but Django was already installed. First time, it wasn't included in the venv folder but even after including it through primitive copy-paste mechanism it didn't execute. How can it be resolved? -
How can I display form instance?
How can I pass the form with an actual filled profile informations (like ProfileUpdateForm(instance=x) in function views). I did it this way and have no idea how to pass an actual profile instance to the form class ProfileDetailView(FormMixin, DetailView): model = Profile context_object_name = 'profile' template_name = 'profiles/myprofile.html' form_class = ProfileUpdateForm def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): form.save() return super().form_valid(form) def get_success_url(self): return reverse_lazy('profiles:profile', kwargs={'pk': self.get_object().pk}) -
UNIQUE constraint failed: auth_user.username when creatin a django sign up form
I need to create sign up form manually and i can't so if you can help me it will be so kind from you :-) here it my code with VS code debugger -
Made a mistake. Didn't push the django migration file to github and there have been subsequent migrations. Now I don't know how to include that file
My changes were migrated to the prod database but I didn't include my migrations file in the pull request. Now on github, since migrations have been performed after mine, there is another migration file where mine should be, and then more after that. Not sure how to resolve this issue. -
Django built-in server cannot decode URL parameters
I'm not sure if this is a Django-specific issue but right now I see it in my project. Because browsers tend to cache favicon and I have changed them for my website, I came up with a trick to force anyone who have visited my site before to receive the new icons, adding "?" followed by some random characters to the image file name, so currently it is like this: <link rel="icon" type="image/png" sizes="32x32" href="{% static 'images/favicons/favicon-32x32.png?v=Gv6qnaoWO5' %}"> Now the issue is, the favicon is not loading and when I check the source I see this: <link rel="icon" type="image/png" sizes="32x32" href="/static/images/favicons/favicon-32x32.png%3Fv%3DGv6qnaoWO5"> and when I click on the above link, I get 404 error from django.views.static.serve. If I remove the "?" and rest of characters, everything works fine. If memory serves, this is normal encoding of special characters and the web server should decode it, but this is not happening on Django's built-in server. So, is there a fix for this, or I should wait until moving the site to production? -
Why doesn't DRF enforce non-empty field?
I am using a custom user model: from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): username = models.CharField(max_length=120, unique=True, blank=False, validators=[MinLengthValidator(6)]) email = models.EmailField('Email Address', unique=True) FCM_ID = models.CharField(max_length=300) I was hoping that I won't be allowed to create a user with blank email field, but for some reason, I can do so without any errors. User().save() successfully adds a user with all blank fields. The unique condition, however, is enforced as expected. Why is blank=False not enforced? Here's the custom user manager: from django.contrib.auth.base_user import BaseUserManager class CustomUserManager(BaseUserManager): def create_user(self, email, **kwargs): if not email: raise ValueError("The email must be set") email = self.normalize_email(email) user = self.model(email=email, **kwargs) user.save() return user def create_superuser(self, email, password, **kwargs): ... -
How do I use the {% url %} tag in a library app?
How do I use the {% url .. %} template tag in a "library" app to create a link to the library-app's own views? Given a site with mysite/urls.py: urlpatterns = [ url(r'^myapp/', include('myapp.urls', namespace='mysite')), ] and an app with myapp/urls.py: urlpatterns = [ url(r'^mylib/', include('mylib.urls', namespace='mylib')), ] and the library app with mylib/urls.py: urlpatterns = [ url(r'^commands/$', views.commands, name='list-commands'), url(r'^command-1/$', views.command_1, name='command-1'), ] where the views.commands view displays a template that should contain a link to /myapp/mylib/command-1/, ie. mylib/templates/mylib/list-commands.html <a href='{% url "command-1" %}'>command-1</a> It will of course work if I change it to: {% url "mysite:mylib:command-1" %} but the author of mylib doesn't know about neither mysite or myapp...? I have a feeling I've misunderstood something basic... -
Divide the SUM of two integers and return a Float in Python/Django
I've spent long time trying to return a Float result from the division of Sum(value1) and Sum(value2) Here's my code: kpiCapaTotal = reportKpiCeFilter.aggregate(kpiCapaTotal=Sum('operation_time') / Sum('load_time') * 100).get('kpiCapaTotal') It returns: 89,0 but the correct should be 89,3 I tried : kpiCapaTotal = reportKpiCeFilter.annotate(kpiCapaTotal=Sum('operation_time') / Cast(Sum('load_time'),FloatField()) * 100, output_field=FloatField()).get('kpiCapaTotal') It returns an error: "QuerySet.annotate() received non-expression(s): <django.db.models.fields.FloatField>." Also with aggregate: kpiCapaTotal = reportKpiCeFilter.aggregate(kpiCapaTotal=Sum('operation_time') / Cast(Sum('load_time'),FloatField()) * 100,output_field=FloatField()).get('kpiCapaTotal') Error: "QuerySet.aggregate() received non-expression(s): <django.db.models.fields.FloatField>." I'dont know how to divide the SUM of two integers and return a Float, do you have any idea? Python Version: 3.7 Djando Version: 2.1 -
Django call custom code based on model instance
I am working on a gamification framework in Django. I have a model Badge that describes a badge that users can obtain. I would like to associate to each and every badge a function that will basically run a query against my database and return True if the member can receive the badge or False otherwise. I was thinking of storing the function name as a CharField and use eval() but I was wondering if there would be a more Pythonic/Djangonic way to achieve this? -
Bootstrap 5 modal django - modal on separate html not opening from the base page
base.html when clicking on user profile icon, it should open login modal from another page on the base page. Now, instead of the modal raw html page opens with the content of login modal <a class="navbar-tool ms-1 ms-lg-0 me-n1 me-lg-2" href="{% url 'ecomapp:usersignin' %}" data-bs-target="#signin-modal" data-bs-remote= "{% url 'ecomapp:usersignin' %}" data-bs-toggle="modal"> <div class="navbar-tool-icon-box"><i class="navbar-tool-icon ci-user"></i></div> </a> login.html <div class="modal fade" id="signin-modal" tabindex="-1" role="dialog"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <!-- content --> </div> </div> </div> -
How to change data inside table django?
I have been creating clone of Twitter. User can register, login, write tweets. Tweet modal is here: class TweetModel(models.Model): text = models.TextField(max_length=300, blank=False) created_at = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True) username = models.CharField(max_length=100, blank=True) def __str__(self): return f'{self.username}: {self.text[0:15]}' Once user changes his/her username, I want to change username in the tweets they write also. How can I handle this? Thank you. -
MultiValueDictKeyError at /categories 'category'
Models.py #the category class class Category(models.Model): category = models.CharField(max_length=64) def __str__(self): return self.category class Listing(models.Model): title = models.CharField(max_length=64, default="") bid = models.ForeignKey(Bid, on_delete=models.CASCADE, related_name="listing", default=None,) description = models.TextField(default="") image_url = models.CharField(max_length=200, default="") date = models.DateTimeField(default=timezone.now) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="listings", default="") is_closed = models.BooleanField(default=False, blank=True, null=True) watchlist = models.ManyToManyField(User, blank=True, related_name="watching") owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="listing", null=False, blank=True, default="") def __str__(self): return self.title Views.py *This is where I think the problem is because i'm not very familiar with the methods, and this is where it points out the error. The choose_category page just gives you a form with the POST method to select the category and then I'm trying to submit the form to my category page. def choose_category(request): categories = Category.objects.filter() return render(request, "auctions/choose_category.html", { "categories":categories }) def categories(request): if request.method == "POST": categories = Category.objects.get(category=request.POST['category']) return render(request, "auctions/categories.html", { "categories": categories }) choose_category.html {% extends "auctions/layout.html" %} {% block body %} <form action="{% url 'categories' %}" method="post"> {% csrf_token %} <div class="form-group"> <label for="categories">Category</label> <select class="form-control" name="categories" id="categories"> {% for category in categories %} <option>{{category}}</option> {% endfor %} </select> </div> <input class="btn btn-primary" type="submit" value="Done"> </form> {% endblock %} categories.html % extends "auctions/layout.html" %} {% block body %} … -
set display to none if string is not translated
I am writing a translation program and I am trying to implement a functionality where, If the translation string in the .po file is empty ( msgstr "" ) the parent elements visibility will be set to none. As an example, if I have this template code: {% language target_language %} <td><p> {% translate Hello %} </p></td> {% endlanguage %} If the target languages po file should look like this: #: translation/forms.py:10 msgid "Hello" msgstr "" then I would like to set: {% language target_language %} <td style="display: none"><p> {% translate Hello %} </p></td> {% endlanguage %} How could I go about implementing this? I have worked myself through the Django internationalization but haven't found anything to point me in the right direction. I'm using Django 3.1 and Python 3.8. Best Regards Max