Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django on Railway
I have fully tested on localhost Django app. When hosted on Railway I cannot login to app or admin. It is showing all migration ok, no database configuration errors, but when trying to login it is showing wrong user/password. Any ideas, please? Checked for errors but it is not showing any. -
Calculating functions with python / django
I'm building a python / django portfolio and i'm having a very hard time with one of my Gym / BMI calculator. I'm trying to have a user input their current Weight and Height, so they can have a BMI result that will be visible from the frontend, and then POST and saved from the Backend models. I just don't know how to include a .py class that i created that will allow the user to input those details from the models and have calculation done in the frontend from the input textfield. Please help...:-) ` from django.db import models # Create your models here. (<-- This is my Model, where i'll save the calculation) class BMI(models.Model): Name = models.CharField(max_length=50) Surname = models.CharField(max_length=50) Weight = models.IntegerField() Height = models.IntegerField() def __str__(self): return self.Name # Create your forms here. (<-- This is my form, where user will be inputting their Weight and Height) from django import forms from django.forms import ModelForm from . models import BMI class BMIForm(ModelForm): class Meta: model = BMI fields = ['Weight', 'Height'] ` from django.shortcuts import render from . models import BMI from . forms import BMIForm # Create your views here. def Home(request): BMIOutcome = … -
How can I acces to my AWS S3 bucket in django?
I am working for the first time with aws s3, where I have images to upload from the django admin, everything works perfect on localhost, but once deployed the images are uploaded but not displayed on the web My setting.py AWS_ACCESS_KEY_ID = 'my acceskey' AWS_SECRET_ACCESS_KEY = 'my secret key' AWS_STORAGE_BUCKET_NAME = 'mybucketname' AWS_DEFAULT_ACL = None AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} STATIC_LOCATION = 'static' PUBLIC_MEDIA_LOCATION = 'media' MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{PUBLIC_MEDIA_LOCATION}/' DEFAULT_FILE_STORAGE = 'portfolio.storages.MediaStore' My models class Project(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=200) link = models.CharField(max_length=250) another_link= models.CharField(max_length=250, null= True, blank=True) image = models.ImageField(upload_to='media/') My views def project(request): projects = Project.objects.all().order_by('-id').values() return render(request, "works.html", {"projects": projects}) My template {% for project in projects %} {% csrf_token %} <div class="row"> <div class="col-md-12 col-md-offset-1"> <div class="row"> <div class="col-xs-12 col-md-6"> <h3>{{project.name}}</h3> <p style=> {{project.description}} </p> <a href="{{project.link}}" target="_blank" class="btn btn-default">Source Code</a> <a href="{{project.another_link}}" target="_blank" class="btn btn-default">See Live</a> </div> <div class="col-xs-6 col-md-4"> <img src="{{project.image.url}}" width="360" height="200" > </div> </div> </div> </div> {% endfor %} In the Html not return a asw link, return this <img src="" width="360" height="200"> Images are loaded perfectly in the S3 bucket but are not displayed in the HTML. -
How to convert excel file to json in specific format
I need a specific JSON output from excel in order to insert data to my database. Right now, the input must come from an Excel table. This is the output I want [ { "model": "client.Restaurant", "pk": 1, "fields": { "name": "KOPITAN CLASSIC WHITE COFFEE", "description": "An ideal place for students and employees to release stress.", "location_lon": 100.481, "location_lat": 5.17818, "operating_hours_start": "10AM", "operating_hours_end": "10PM", "owner_id": 18, "image_url": "kopitanClassic.jpg" } } ] This is the output that I get from using online excel to json converter. [ { "name": "KOPITAN CLASSIC WHITE COFFEE", "description": "An ideal place for students and employees to release stress.", "location_lon": 100.481, "location_lat": 5.17818, "operating_hours_start": "10AM", "operating_hours_end": "10PM", "owner_id": 18, "image_url": "kopitanClassic.jpg" } ] -
how to set foreign by post method in django?
models.py class Courses(models.Model): course_name=models.CharField(max_length=50) course_price=models.IntegerField() class Exam(models.Model): exam_name=models.CharField(max_length=101) course=models.ForeignKey(Courses,on_delete=models.CASCADE,default='python') exam_time=models.DateTimeField() views.py def Examadd(request): mycourses = Courses.objects.all() context = {'mycourses': mycourses} if request.method == 'POST': newexam = request.POST.get('examname') course = request.POST.get('courses') examtime = request.POST.get('time') new = Exam.objects.create(exam_name=newexam,course=course,exam_time=examtime) new.save() messages.success(request, "Course created successfully") return redirect('Courselist') return render(request,'addexam.html',context addexam.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>Add New Exam</h1> <form method="post"> {% csrf_token %} <label>Examname:</label> <input type="text" name="examname"> <label>Course:</label> <select name="courses"> {% for i in mycourses %} <option value={{i.id}}>{{i.course_name}}</option> {% endfor %} </select> <label>Exam time and date:</label> <input type="text" name="examtime"> <button type="submit">Add</button> </form> </body> </html> I am doing a project elearning.I want a dropdown list with courses and pass its ids to Exam table.course id is a foreign key.I want to pass the courseid to course column in Exam table.By this code I gets error as,Cannot assign "'1'": "Exam.course" must be a "Courses" instance. -
How to save a wish icon checked after page refresh -Django
Trying to keep selected icon in product cards active after page refresh when the user refresh the page I want that the icon to remain a full heart and not an empty heart. How could I do that? views.py @login_required def add_wishlist (request): if request.is_ajax() and request.POST and 'attr_id' in request.POST: if request.user.is_authenticated: data = Wishlist.objects.filter(customer = request.user,product_id= int(request.POST['attr_id'])) if data.exists(): data.delete() else: Wishlist.objects.create(customer= request.user,product_id = request.POST['attr_id']) else: print("No Product is Found") return redirect("products:product_all") product_all.html <div id='alCarrito'class="like-container"> {% if product in wishlisted_list %} <span class="like heart " id="id" attr_id="{{product.id}}" action_url="{% url 'products:add_wishlist' %}"> <i class="fas fa-heart"></i> </span> {% else %} <span class="like" id="id" attr_id="{{product.id}}" action_url="{% url 'products:add_wishlist' %}"><i class="far fa-heart"></i></span> {% endif %} </div> wishlist.js $(document).ready(function(){ $(".like").click(function(){ var attr_id = $(this).attr('attr_id') var action_url = $(this).attr('action_url') var that = $(this) $.ajax({ url: action_url, type: "POST", data: {'attr_id': attr_id }, headers: { "X-CSRFToken": $.cookie("csrftoken") }, success: function (response) { console.log("Success") that.toggleClass("heart"); }, }); }); }); -
Django get_queryset has different signature for Admin and Generic views, how to prevent code duplication
I would like to write simple code to filter records in view based on request information (eg. organization the user belongs to). I started to implemented it as Mixin for Admin views. class OrganizationPermissionMixin: def get_queryset(self, request): query = super().get_queryset(request) if request.user.is_superuser: return query return query.filter( organization__in=request.user.organization_set.all() ) This works fine but when I tried to apply this Mixin on Generic views, I have a signature error as there is no request parameter passed to the get_queryset method: TypeError: OrganizationPermissionMixin.get_queryset() missing 1 required positional argument: 'request' If I adapt the Mixin to: class OrganizationPermissionMixin: def get_queryset(self): query = super().get_queryset() if self.request.user.is_superuser: return query return query.filter( organization__in=self.request.user.organization_set.all() ) It works for generic views such as ListView but now it indeed breaks for ModelAdmin view: OrganizationPermissionMixin.get_queryset() takes 1 positional argument but 2 were given This inconsistency in signature is somehow very frustrating because it requires to duplicate code simply because request passing mechanism is different between Generic and Admin views. My question is: how can I make this Mixin works both for Generic and Admin views. Is there something ready for that in Django? Is it normal it behaves like this or is it an unfortunate design choice? -
I am getting following error when try to upload Django project to Heroku
When I try to upload my Django project to Heroku I am getting following error Heroku Push error Could you please tell me what is the problem and how to resolve this Thank in advance tried to run push command multiple time change the python runtime in runtime.txt file switch to different Heroku instance -
nginx: [emerg] "http" directive is not allowed here in /etc/nginx/sites-enabled/default:22
whenever I tried to enter the code above in the Nginx config file I found this error.which is nginx: [emerg] "http" directive is not allowed here in /etc/nginx/sites-enabled/default:22. I tried in HTTP tag but can't solve it enter image description here -
django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY environment variable what you said in the previous question doesn't work
I can not run the project, I did what I was told in README.md as directed, but still gives an error. The Output is: Traceback (most recent call last): File "C:\Users\user\AppData\Roaming\Python\Python311\site-packages\environ\environ.py", line 403, in get_value value = self.ENVIRON[var_name] ~~~~~~~~~~~~^^^^^^^^^^ File "<frozen os>", line 678, in __getitem__ KeyError: 'SECRET_KEY' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\new-folder\manage.py", line 21, in <module> main() File "C:\new-folder\manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\user\AppData\Roaming\Python\Python311\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\user\AppData\Roaming\Python\Python311\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\user\AppData\Roaming\Python\Python311\site-packages\django\core\management\base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\user\AppData\Roaming\Python\Python311\site-packages\django\core\management\base.py", line 448, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Roaming\Python\Python311\site-packages\django\core\management\base.py", line 93, in wrapped saved_locale = translation.get_language() ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Roaming\Python\Python311\site-packages\django\utils\translation\__init__.py", line 210, in get_language return _trans.get_language() ^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Roaming\Python\Python311\site-packages\django\utils\translation\__init__.py", line 65, in __getattr__ if settings.USE_I18N: ^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Roaming\Python\Python311\site-packages\django\conf\__init__.py", line 92, in __getattr__ self._setup(name) File "C:\Users\user\AppData\Roaming\Python\Python311\site-packages\django\conf\__init__.py", line 79, in _setup self._wrapped = Settings(settings_module) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Roaming\Python\Python311\site-packages\django\conf\__init__.py", line 190, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\Python311\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked File … -
Django unique slug field for two or more models
I have such structure: class Category(models.Model): name = models.CharField(max_length=255, validators=[MinLengthValidator(3)]) parent = models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.CASCADE ) slug = models.SlugField(max_length=255, null=False, unique=True) class Product(models.Model): name = models.CharField(max_length=255, validators=[MinLengthValidator(3)]) to_category = models.ForeignKey(Category, on_delete=models.SET_NULL, blank=True, null=True, ) slug = models.SlugField(max_length=255, null=False, unique=True) I have created one category with slug "test". When I try to create new category with slug "test" I got warning message and it is Ok. But If I try to create product with slug "test" I dont have warning and this is not good in my case. Is there a solution or method to validate slug field for uniqueness with Product and Category model? -
PyCharm 2022.1.2 does not hit the debug breakpoint with Django
I can't get Python debugger to work on PyCharm 2022.1.2 with Django 4. When I set the breakpoint inside the view function and then call this view in the browser, nothing happens when started in debug mode... breakpoint_selected However breakpoint is hit when I set it for import. breakpoint_hit I have 2 configurations, one for Python and one for Django Server, both don't work. config1 config2 Went through numerous JetBrains tickets with people reporting similar problem but didn't find the solution there. Also tried creating second run configuration, for Python instead Django Server, but this also didn't help. -
How to prevent end users from editing a hidden input value in a Django social website
In a website having a "Comment" and "reply to a comment" system. After each comment in the template, There's a "Add a reply" form which have a hidden input to carry the comment pk on its value attribute. How to prevent the end user from editing that hidden input value ? And If this is not possible, What would be the correct approach ? -
button 'pay now!' not working for redirect to payment-done view in payment-braintree and django
I am writing an online store based on the Django 3 By Example 3rd Edition book. I encountered a problem with the book's codes in the payment section, I searched the internet and updated some of the codes, but I still have a problem! After filling out the debit card form, when I click on the "pay now!" button, I am not redirected to the Don page! Thank you for your guidance. process.html {% extends "shop/base.html" %} {% block title %} Pay by credit card {% endblock %} {% block sidenavigation %} {% endblock %} {% block content %} Pay by credit card <form method="post" autocomplete="off"> {% if braintree_error %} <div class="alert alert-danger fade in"> <button class="close" data-dismiss="alert">&times;</button> {{ braintree_error|safe }} </div> {% endif %} <div class="braintree-notifications"></div> <div id="braintree-dropin"></div> <input style="background-color: #0783ca" id="submit-button" class="btn btn-success btn-lg btn-block" type="button" value="Pay now!"/> </form> <script> var braintree_client_token = "{{ client_token}}"; var button = document.querySelector('#submit-button'); braintree.dropin.create({ authorization: "{{client_token}}", container: '#braintree-dropin', card: { cardholderName: { required: false } } }, function (createErr, instance) { button.addEventListener('click', function () { instance.requestPaymentMethod(function (err, payload) { $.ajax({ type: 'POST', url: '{% url "payment:process" %}', data: { 'paymentMethodNonce': payload.nonce, 'csrfmiddlewaretoken': '{{ csrf_token }}' } }).done(function (result) { //do accordingly }); … -
Update user profile with user uuid
I want to update user profile passing user uuid as kwarg. Here is the url: path("profile/update/<uuid:pk>", UpdateProfile.as_view(), name="update_profile"), However, after I try to update my profile, it gives me an error. Here is my view: class UpdateProfile(LoginRequiredMixin, UpdateView): model = Profile user_type_fields = { "Buyer": ["photo", "first_name", "last_name", "city"], "Celler": ["photo", "name", "city", "address"], } def get(self, request, *args, **kwargs): print(kwargs) self.fields = self.user_type_fields[get_user_model().objects.get(pk=kwargs["pk"]).type] return super().get(request, *args, **kwargs) And here is the error itself: Page not found (404) No profile found matching the query As I understand, django tries to find profile with uuid as in url, doesn't find it and returns me this error. However, if I change model in my view to user, it wouldn't be able to find fields as they belong to profile model. The only working option was to pass profile id as kwarg, but I don`t find it preferrable due to security reasons. Could someone give me an advice on how to update profile with user uuid in kwargs? Thanks in advance! -
Authenticate serverless API against Django user pool
I would like to move an API from Django server on ec2 to serverless (AWS API gateway + Lambda) because of better scalability. I need authentication/authorization for this API against my Django user pool, but that would mean polling Django server because of auth.. and I am back where I was regarding scalability. What would be my option to deal with it in a scalable (lambda like scalable) way? I was thinking about creating Cognito user pool and duplicate users from Django there. Is there a better option? -
Django IntegrityError: UNIQUE constraint failed: pu_limity.zakazka_id
I am getting following error, when I try to import csv file and save data to database: IntegrityError at /limity/limity_csv_import UNIQUE constraint failed: pu_limity.zakazka_id models.py class Limity(models.Model): zakazka = models.ForeignKey(Zakazky, on_delete=models.CASCADE) p_el = models.DecimalField("E/L", decimal_places=2, max_digits=4, null=True, blank=True) p_ml = models.DecimalField("M/L", max_digits=6, decimal_places=4, null=True, blank=True) p_prispevek = models.DecimalField("Příspěvek", max_digits=10, decimal_places=2, null=True, blank=True) p_pu = models.DecimalField("PU", max_digits=10, decimal_places=2, null=True, blank=True) aktualizace = models.DateTimeField(auto_now=True, null=True) @classmethod def create_from_csv_line(cls, line): l = Limity() try: l.zakazka = Zakazky.objects.get(kod=line["Zakazka"]) except Zakazky.DoesNotExist: print(line["Zakazka"]) l.zakazka, _ = Zakazky.objects.get_or_create(kod=line["Zakazka"]) except: print(line["Zakazka"]) l.p_el = line["EL"] l.p_ml = line["ML"] l.p_prispevek = line["Prispevek"] l.p_pu = line["PU"] l.save() views.py class LimityCSVImportView(LoginRequiredMixin, SuccessMessageMixin, FormView): template_name = "limity/limity_csv_import.html" form_class = LimityCSVForm def test_func(self): return self.request.user.is_superuser def post(self, request, *args, **kwargs): form: LimityCSVForm = LimityCSVForm(request.POST, request.FILES) if form.is_valid(): csv_file = form.cleaned_data["uploaded_file"] decoded_file = csv_file.read().decode('utf-8-sig') io_string = io.StringIO(decoded_file) reader = csv.DictReader(io_string, delimiter=",", skipinitialspace=True) record_count = 0 for line in reader: Limity.create_from_csv_line(line=line) record_count += 1 context = self.get_context_data() my_text = ' nových limitů vloženo.' messages.success(request, str(record_count) + my_text) return render(request, self.template_name, context) else: return self.form_invalid(form) Error arises when data from form saved at line l.save() I red some answers for this error and I tried in @classmethod: el = (line["EL"]) if not el: l.p_el = 0 else: … -
Enabling browser link for django in visual studio 2022
Is it possible to enable browser link for django website in VS2022 ? Im using default template for building Django website in vs and its kinda annoying for every change to stop and start the project again and again. i know i can do this if i use the console and run "Python manage.py runserver" but i want to use VS2022 debug engines too. if i use Python manage.py runserver and change the code it will refresh browser for me. -
Can't authenticate a user in Django rest framework
im trying to get data of an authenticated user using token, im using postman to send a get request and get the data i need but im reciveing a response "detail": "Authentication credentials were not provided." this is the view ` class ReceiveMessagesView(viewsets.ModelViewSet): serializer_class = MessageSerializer permission_classes = [permissions.IsAuthenticated] http_method_names = ['get', 'post'] def get_queryset(self): user = self.request.user queryset = Message.objects.filter(receiver=user) return queryset` settings REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } In the postman request im sending in Authorizaion the key as "Token" and value as the user i want data about's token tried to send an authorized get request and recived authorized user's data -
pytest parametrize I am getting TypeError: missing required positional arguments
I'm trying to use pytest.mark.parametrize import pytest from rest_framework.test import APITransactionTestCase class TestBulkImport(APITransactionTestCase) @pytest.mark.parametrize('data, expected_response', [ ( {'body': 'data;to;validate'}, {'body': ['error response']} ), ]) def test_bulk_import_validations(self, data, expected_response): response = self.client.post(reverse('path:to:url'), data=data) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertEqual(response.json(), expected_response) I'm running the testcase using following command: pytest path/to/test/file::TestBulkImport::test_bulk_import_validations I'm getting following error: def _callTestMethod(self, method): > method() E TypeError: test_bulk_import_validations() missing 2 required positional arguments: 'data' and 'expected_response' -
developer of django
i am a developer . #inclue.life i am a developer . #inclue.life -
django project ,runserver wsgi working but asgi server configure but still not wroking
setting.py setting.py asgi.py routing.py consumers.py runserver asgi not show django project asgi server not work pls tell me how to solution this problem -
Django Rest how to save current user when creating an new blog?
When I am creating an blog post I also want to automatically save the current user without selecting the user manually as a blog author. here is my code: models.py: class Blog(models.Model): author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) blog_title = models.CharField(max_length=200, unique=True) serializers.py class BlogSerializer(serializers.ModelSerializer): class Meta: model = Blog views.py class BlogViewSet(viewsets.ModelViewSet): queryset = Blog.objects.all().order_by('-id') serializer_class = BlogSerializer pagination_class = BlogPagination lookup_field = 'blog_slug' def get_permissions(self): if self.action == 'retrieve': permission_classes = [IsOwnerOrReadOnly] elif self.action == 'list': permission_classes = [IsOwnerOrReadOnly] else: permission_classes = [IsOwnerOrReadOnly & IsAuthorGroup] return [permission() for permission in permission_classes] -
Point of Sales System Using python
Point of Sales System Using python. Guys, I need your experience to develop my POS system. These are my question. Please share your opinion about this question. This is my basic idea about this POS system. I am trying to create a POS system for a shop with various items such as supermarkets and electronic items. It means that has multiple types of products in this shop. I need to add stock management also this software not only that it is necessary to add expiration dates to some categories of products as well (My idea is to send an alert to shop owners about expired that products). Among these features, I need to add a thermal printer and a barcode reader as well. And also I need to generate some sales reports as well with the net profit. These are my questions. I decided to use python to create my POS system. Is that language ok for that software? If it is ok, If I try to implement it as a stand-alone application, which is the most suitable GUI builder for that? (Ex: PyQt, Tkinter, Kivy). Is that ok to use Django for this ? Based on my basic idea … -
How to safely add an additional fee for additional services in an online store?
I have an online car rental store built on Python Flask. My problem is that: When choosing a car, the customer goes to the checkout page, where he can choose additional services, for example: GPS navigator, child seats and other services. The cost of some services depends on the number of rental days, for example, for a Gps navigator, the cost of 1 day is $ 5. The question is, how can I safely get the cost of these additional services from the FrontEnd and add to the cost of the car received from the BackEnd side I am trying to safely connect the cost of renting a car with the cost of additional services, some of which depend on the number of rental days.My task is to implement this system as safely as possible, but I do not know how it can be done