Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python unit test got error on INSTALLED_APPS settings not configured
With PyCharm IDE, we have a unit test importing the models module of the Django project for testing. While expecting a happy pass, the test always hit en error saying: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings. Configure() before accessing settings.. We are new to this part of the Python unit test, so we highly appreciate any hints or suggestions. The unit test: from applicationapp import models ... class TestElastic(TestCase): def test_parse_request(self): # expecting happy pass # # self. Fail() return The full error trace: /data/app-py3/venv3.7/bin/python /var/lib/snapd/snap/pycharm-professional/327/plugins/python/helpers/pycharm/_jb_unittest_runner.py --target test_elastic.TestElastic Testing started at 2:07 PM ... Launching unittests with arguments python -m unittest test_elastic.TestElastic in /data/app-py3/APPLICATION/tests Traceback (most recent call last): File "/var/lib/snapd/snap/pycharm-professional/327/plugins/python/helpers/pycharm/_jb_unittest_runner.py", line 35, in <module> sys.exit(main(argv=args, module=None, testRunner=unittestpy.TeamcityTestRunner, buffer=not JB_DISABLE_BUFFERING)) File "/usr/local/lib/python3.7/unittest/main.py", line 100, in __init__ self.parseArgs(argv) File "/usr/local/lib/python3.7/unittest/main.py", line 147, in parseArgs self.createTests() File "/usr/local/lib/python3.7/unittest/main.py", line 159, in createTests self.module) File "/usr/local/lib/python3.7/unittest/loader.py", line 220, in loadTestsFromNames suites = [self.loadTestsFromName(name, module) for name in names] File "/usr/local/lib/python3.7/unittest/loader.py", line 220, in <listcomp> suites = [self.loadTestsFromName(name, module) for name in names] File "/usr/local/lib/python3.7/unittest/loader.py", line 154, in loadTestsFromName module = __import__(module_name) File "/data/app-py3/APPLICATION/tests/test_elastic.py", line 6, in <module> from applicationapp.soap.elastic … -
How to Run a Pyomo Optimization Problem in a Django-Heroku App?
I have been trying to deploy a Django app that use the python optimization package 'pyomo' https://pyomo.readthedocs.io/en/stable/index.html It works locally, but not when deployed to heroku. In production, it is not able to find the uploaded executable for the solver. From the logs: 2023-05-30T19:49:36.256914+00:00 app[web.1]: RuntimeError: Attempting to use an unavailable solver. 2023-05-30T19:49:36.256915+00:00 app[web.1]: 2023-05-30T19:49:36.256915+00:00 app[web.1]: The SolverFactory was unable to create the solver "HIGHS" 2023-05-30T19:49:36.256915+00:00 app[web.1]: and returned an UnknownSolver object. This error is raised at the point 2023-05-30T19:49:36.256915+00:00 app[web.1]: where the UnknownSolver object was used as if it were valid (by calling 2023-05-30T19:49:36.256915+00:00 app[web.1]: method "solve"). 2023-05-30T19:49:36.256915+00:00 app[web.1]: 2023-05-30T19:49:36.256916+00:00 app[web.1]: The original solver was created with the following parameters: 2023-05-30T19:49:36.256916+00:00 app[web.1]: executable: /app/number_generator/executables/highs 2023-05-30T19:49:36.256916+00:00 app[web.1]: type: HIGHS 2023-05-30T19:49:36.256916+00:00 app[web.1]: _args: () 2023-05-30T19:49:36.256916+00:00 app[web.1]: options: {} 2023-05-30T19:49:36.257340+00:00 app[web.1]: 10.1.20.80 - - [30/May/2023:19:49:36 +0000] "POST /opttool/ HTTP/1.1" 500 145 "https://simple-esa.herokuapp.com/opttool/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36" 2023-05-30T19:49:36.257469+00:00 heroku[router]: at=info method=POST path="/opttool/" host=simple-esa.herokuapp.com request_id=73e964ec-dfca-487b-8b8c-319d01ce55f0 fwd="2.106.20.24" dyno=web.1 connect=0ms service=11075ms status=500 bytes=445 protocol=https I have three suspicions: I messed up my path to the executable You can't upload .exe files to heroku. Would there be another way to create a small optimization problem on a django-heroku app … -
Nginx refuses to connect to Django container in Lightsail
I have 2 images that I am uploading to aws lightsail. If I upload the django one it works without any issue, but trying to add to it Nginx has not been possible as Nginx cannot connect to django. I get this error: [30/may/2023:16:13:38] 2023/05/30 16:13:38 [error] 30#30: *71 connect() failed (111: Connection refused) while connecting to upstream, client: 172.26.45.36, server: localhost, request: "GET / HTTP/1.1", upstream: "http://172.26.18.131:8000/", host: "172.26.2.175" [30/may/2023:16:13:38] 172.26.45.36 - - [30/May/2023:16:13:38 +0000] "GET / HTTP/1.1" 502 157 "-" "ELB-HealthChecker/2.0" "-" this is my nginx.conf file: server { listen 80; server_name localhost; location /static/ { root /jp/static; } location / { proxy_pass http://myservice.service.local:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } when I check django, it seems just fine: [30/may/2023:16:12:24] 129 static files copied to '/jp/static'. [30/may/2023:16:12:26] Operations to perform: [30/may/2023:16:12:26] Apply all migrations: admin, auth, contenttypes, myprofile, sessions [30/may/2023:16:12:26] Running migrations: [30/may/2023:16:12:26] No migrations to apply. [30/may/2023:16:12:27] [2023-05-30 16:12:27 +0000] [9] [INFO] Starting gunicorn 20.1.0 [30/may/2023:16:12:27] [2023-05-30 16:12:27 +0000] [9] [INFO] Listening at: http://0.0.0.0:8000 (9) [30/may/2023:16:12:27] [2023-05-30 16:12:27 +0000] [9] [INFO] Using worker: sync [30/may/2023:16:12:27] [2023-05-30 16:12:27 +0000] [10] [INFO] Booting worker with pid: 10 This is my docker-compose file version: '3' services: … -
django-report-builder throws unauthorized error when I try it add a report as admin user
I am trying to implement report-builder for my django application. I have followed https://django-report-builder.readthedocs.io/en/latest/quickstart/ for the setup. From the admin console I can see reports section but when I try to add one I get Unauthorized error. Attaching screenshot for your reference Thanks in advance!!! I tried checking user permissions though I am admin user. I expect it to redirect once after I click on save and build report button on reports page. -
The django modal window don't stay with content inside
I'm really lost here. I build the django model window and when i start to write the content inside, everything it's out from the modal window. I have no idea what's going on. Click here to see the image The modal code <div id="modal_window_new_register" class="modal_window_new_register" > <div class="new_register_modal"> <button class="close" id="close">X</button> </div> Test Test Test Test Test </div> The model css code /* Modal window */ .modal_window_new_register{ width: 100vw; height: 100vh; position: absolute; top: 0; left: 0; background-color: #00000080; display: none; align-items: center; justify-content: center; z-index: 9999; overflow: auto; } .new_register_modal{ width: 40%; min-width: 450px; height: 95vh; background-color: #ffff; padding: 20px; border-radius: 10px; } .close{ position: absolute; top: -5px; right: -5px; width: 30px; height: 30px; border-radius: 50%; border: 0; background-color: #ffffff96; font-size: 20; cursor: pointer; } .modal_window_new_register.open_new_register_modal{ display: flex; } -
Understanding Nginx Logging: Does $request_time include Django backend response time?
I am checking the performance and response times of a web-app and the parties involved in it. I have a question regarding the logging that nginx makes of api rest requests to the backend of the web-app (React-Django). Nginx has the ability to log the $request_time to /var/log/nginx/access.log when serving a request from the backend. The question is: does it contain within that time in seconds the time that the Django backend takes to respond to the request? This is not clear to me from reading the documentation Nginx log_format. In what I tested, django responds to a request in 30 ms and Nginx logs that request as served in 33 ms. Do those 33 ms contain the 30 ms that django takes or are they separate? or are they only referring to the handling that Nginx can do (i.e. manage the request in a queue if there is a lot of service demand)? Thanks in advance! -
How can I retrieve a Django model element by name, regardless of text case?
How can i get element by name despite of text register. for example in my models i have element with user_name equal to "hello world" and i want get this element. So i write: User.objects.get(user_name=name) It's working if name equal to "hello world", but if name equal to "Hello World" or "hElLO wOrLD" then it's not working. I can use name.lower() but if user_name from models equal to "HELLO WORLD" then it's not working again. -
Issue with "delete" functionality in Django admin inline formset
I'm experiencing an issue with the "delete" functionality in my Django admin inline formset. I have a custom template for rendering the formset, and I've added a element with the class "delete" to allow users to delete rows. However, the delete functionality doesn't seem to be working as expected. tabular.html {% load i18n admin_urls static admin_modify %} <div class="js-inline-admin-formset inline-group" id="{{ inline_admin_formset.formset.prefix }}-group" data-inline-type="tabular" data-inline-formset="{{ inline_admin_formset.inline_formset_data }}"> <!-- ... --> <table class="table table-centered table-nowrap mb-0 rounded inline"> <thead class="thead-light"> <tr> <th class="original"></th> <!-- ... --> {% if inline_admin_formset.formset.can_delete and inline_admin_formset.has_delete_permission %} <th>{% translate "Delete?" %}</th> {% endif %} </tr> </thead> <tbody> {% for inline_admin_form in inline_admin_formset %} <!-- ... --> <tr class="form-row {% if inline_admin_form.original or inline_admin_form.show_url %}has_original{% endif %}{% if forloop.last and inline_admin_formset.has_add_permission %}empty-form{% endif %}" id="{{ inline_admin_formset.formset.prefix }}-{% if not forloop.last %}{{ forloop.counter0 }}{% else %}empty{% endif %}"> <td class="original"> <!-- ... --> </td> <!-- ... --> {% if inline_admin_formset.formset.can_delete and inline_admin_formset.has_delete_permission %} <td class="delete"> {% if inline_admin_form.original %} {{ inline_admin_form.deletion_field.field }} {% endif %} </td> {% endif %} </tr> {% endfor %} </tbody> </table> <!-- ... --> </div> Image Preview of the issue I suspect that there might be missing JavaScript or CSS code that handles the … -
Field 'id' expected a number but got <QueryDict
This is a common error on stack overflow but I cannot draw similarities with their errors and mine. A number is expected in the id column of the database(automatically made by django) but a query dict was put in instead Model: class Price(models.Model): HourlyPrice = MoneyField(default_currency="GBP",max_digits=19,decimal_places=3,null=True,blank=False) # price per hour DailyPrice = MoneyField(default_currency="GBP",max_digits=19,decimal_places=2,null=True,blank=True)# price per day WeeklyPrice = MoneyField(default_currency="GBP",max_digits=19,decimal_places=2,null=True,blank=True)# price per week MonthlyPrice = MoneyField(default_currency="GBP",max_digits=19,decimal_places=2,null=True,blank=True)# price per month View: def test(request): if request.method == 'POST': form = Price(request.POST) form.save() return render(request,'app/index.html', { 'title':'Home Page', 'year':datetime.now().year, } ) else: form = TestPrice(request.GET) context = { 'form': form, } return render(request,'app/test.html',context) Template: {% extends "app/layout.html" %} {% block content %} <form method="post" action=""> {% csrf_token %} <table> {{form}} </table> <button type="submit">Submit</button> </form> {% endblock %} Thank you for your time -
How to replace filter and .distinct() with another filter and .first() when subquery returns no result in Django Python?
I've got a subquery who returning some data depending of a specific filter. This specific filter sometime return null result but what I want is to catch the first() result without specific filter if no result return with. date_filter = Q(start_date__lte=OuterRef('object_start_date'), end_date__gte=OuterRef('object_start_date')) | \ Q(start_date__lte=OuterRef('object_start_date'), end_date=None) The query where i use this filter data_subquery = Object.objects.filter(date_filter).filter(user=OuterRef('user')).distinct() This subquery is used here next : main_subquery = Main.annotate(role=Subquery(data_subquery.values('role__name')[:1])) I've to anonymized data but the goal is to understand the need .... The filter subquery *datefilter *should be used if data_subquery return something ... else I don't need this filter and want to replace .disctinct() by .first() THanks for your help :) I've got a function to return specific data depending on user and date given in parameters ... or first one ... but I don't know how to use function into subquery ;) I tried to add : if len(data_subquery) == 0: data_subquery = Object.objects.filter(user=OuterRef('user')).filter() But it can't work with subquery :( -
poetry's 'run' stopped working claiming manage.py is missing
I have been using the run command for a year to perform all kinds of admin work, in this precise manner (i.e. with a dot): poetry run ./manage.py runserver and suddenly it no longer works, saying: $ poetry run ./manage.py runserver Command not found: ./manage.py But the file is there, and is executable: $ file manage.py manage.py: Python script, ASCII text executable witha proper #! /usr/bin/env python I know there's another way, namely: $ poetry shell followed by $ ./manage.py runserver but I feel a little stupid having to work around it =) I have recreated the virtual environment, but to no avail. The problem must be somewhere else, is my shell is missing something or poetry's setup? I did reinstall the system after all, but that wasn't a first time of so doing.. Thank you for your time! -
how to filter dropdown values based on the value of other dropdown in django
I have 2 models main_category and sub_category, in the sub_category model, it has a name and Foreign key of the main_category it belongs to. and I have 3rd model which is 'record' and it has main_category and sub_category as a Foreign key. what I need is when selecting the main category from the drop-down in the 'record' form it should filter the values in the sub_category dropdown so that it shows only the values that have the selected main category here are the models class MainCategory(models.Model): name = models.CharField(max_length=100, unique=True) activity_status = models.BooleanField() def __str__(self): return self.name class SubCategory(models.Model): name = models.CharField(max_length=100) main_category = models.ForeignKey(MainCategory, on_delete=models.CASCADE) activity_status = models.BooleanField() def __str__(self): return self.name class Record(models.Model): RECORD_TYPES = [ ('income', 'Income'), ('expense', 'Expense'), ('transfer', 'Transfer'), ] DELETED_CATEGORY = 'Deleted category' date = models.DateField(default=timezone.now) category = models.ForeignKey(MainCategory, on_delete=models.SET(DELETED_CATEGORY), default=1) subcategory = models.ForeignKey(SubCategory, on_delete=models.SET(DELETED_CATEGORY)) type = models.CharField(max_length=10, choices=RECORD_TYPES) amount = models.DecimalField(max_digits=10, decimal_places=2, validators=[MinValueValidator(0)]) account = models.ForeignKey(Account, on_delete=models.CASCADE) notes = models.TextField(blank=True) transfer_ops = models.ForeignKey(TransferOperation, on_delete=models.CASCADE, null=True, blank=True) activity_status = models.BooleanField() def __str__(self): return f"{self.date} - {self.type}: {self.amount}" and here is the view class CreateRecordView(CreateView): model = Record form_class = RecordForm template_name = 'create_record.html' success_url = reverse_lazy('home') def get_form(self, form_class=None): form = super().get_form(form_class) form.fields['subcategory'].queryset = … -
Why are my media files not being served in Django application with nginx?
I have a problem with my Django application which is deployed using gunicorn and nginx. I have a model for storing images in my sqlite database. class Image(models.Model): image_file = models.ImageField(upload_to="fucking_scraper/files/item_photos") item = models.ForeignKey(Item, on_delete=models.CASCADE) Here is my urls.py file urlpatterns = [ path("admin/", admin.site.urls), path("", include("fucking_scraper.urls")), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and here are parts of settings.py file, related to serving files BASE_DIR = Path(__file__).resolve().parent.parent MEDIA_URL = "/media/" MEDIA_ROOT = "" STATIC_URL = "static/" STATICFILES_DIRS = [os.path.join(BASE_DIR, "fucking_scraper", "static", "fucking_scraper"), os.path.join(BASE_DIR, "fucking_scraper", "files", "item_photos")] STATIC_ROOT = os.path.join(BASE_DIR, 'static/') On a deployed website images are not displayed. I assume there is a problem with nginx configuration because before deployment it was working correctly in a debug mode. Here is how it looks like: server { listen [::]:80; server_name fwebsite.org; location /static/ { root /home/django/fwebsite.org; } location /media/ { root /home/django/fwebsite.org/fucking_scraper/files/item_photos/; } location / { include proxy_params; proxy_pass http://unix:/home/django/fwebsite.org/fucking_website.sock; } } I tried setting up location /media/ following instructions found on the internet but it didn't work for me and I am currently stuck. -
Unable to post array in form data from react-select to django rest framework
I am building an app using React/Django and using DRF and Form data to post data from React forms to Django model. I was using React select that contains multi selections as I want to send data to manytomany field in Django models.py: class classification(models.Model): theclass = models.CharField(max_length=200) def __str__ (self): return self.theclass @property def classification_dictionary(self): return {'label':self.theclass , 'value': self.id} class book(models.Model): name = models.CharField(max_length=499) bookClassification = models.ManyToManyField('classification', blank=True) def __str__ (self): return self.name serializers.py: class BookSerializer(serializers.ModelSerializer): bookClassification = serializers.SlugRelatedField( many=True, read_only = True, slug_field='classification_dictionary' ) class Meta: model = book fields = '__all__' views.py (theapi): class BookFormViewSet(APIView): permission_classes = [AllowAny] authentication_classes = [TokenAuthentication] parser_classes = [MultiPartParser, FormParser, JSONParser] @csrf_exempt def post(self, request, format=None): serializer = BookFormSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data,status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) This is for the backend and the following is for the React frontend part: import React from "react"; import Select from 'react-select'; import axios from "axios"; import { useForm, Controller } from "react-hook-form"; import { TextField, Checkbox } from "@material-ui/core"; export default function BookForm(){ const [classificationOptions, setClassificationOptions] = React.useState([]) const [entryClass, setEntryClass] =React.useState([]) React.useEffect (function(){ fetch('/classification') .then(res => res.json()) .then(data => { data.map(theclass => { let newClass = {value: `${theclass.id}`, label: `${theclass.theclass}`} setClassificationOptions(oldArray => … -
Flutter Exception "type 'String' is not a subtype of type 'int' of 'index'" when fetching filtered api data
I'm making an Android app with local Django Restful Api. I have 2 models in database, that are nested together, ShowsModel and DirectorModel. This is basically how my JSON looks like with GET function. [ { "id": 1, "name": "Shows name", "annotation": "Some long text", "image": "/media/images/poster.jpg" "director": { "id": 2, "name": "First name", "surname": "Last name", "image": "/media/images/portrait.jpg" }, }, ] I need to filter shows by director id and display them. I changed up views.py in my Django, and added some functions, like check_director = self.request.query_params.get('check_director', None) if check_director: queryset = queryset.filter(director=check_director) serializer = ShowsSerializer(queryset, many=True) return Response(serializer.data) It works, now I have this key parameter check_director, and when I add value 1, it shows only that data, which contains director with id 1. Now, the problem is in Flutter. I have director detail page, that requires id, which it gets from another screen. I use this function to get data from DirectorsModel in Django Api. Future<void> getDirectorInfo() async { directorModel = await APIHandler.getDirectorsById(id: widget.id); setState(() {}); } It works, no problem. But how do I fetch data from ShowsModel? I'm trying this function for api: static Future<ShowsModel> getShowsByDirector({required String director}) async { try { var uri = … -
How do I fix these makemigrations errors?
When I try to run makemigrations it shows this error, what does it mean and how can I fix it? $ py manage.py makemigrations Traceback (most recent call last): File "C:\Users\ninie\estoque\manage.py", line 22, in <module> main() File "C:\Users\ninie\estoque\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\ninie\PycharmProjects\pythonProject1\venv\lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "C:\Users\ninie\PycharmProjects\pythonProject1\venv\lib\site-packages\django\core\management\__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\ninie\PycharmProjects\pythonProject1\venv\lib\site-packages\django\core\management\base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\ninie\PycharmProjects\pythonProject1\venv\lib\site-packages\django\core\management\base.py", line 453, in execute self.check() File "C:\Users\ninie\PycharmProjects\pythonProject1\venv\lib\site-packages\django\core\management\base.py", line 485, in check all_issues = checks.run_checks( File "C:\Users\ninie\PycharmProjects\pythonProject1\venv\lib\site-packages\django\core\checks\registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\ninie\PycharmProjects\pythonProject1\venv\lib\site-packages\django\core\checks\caches.py", line 17, in check_default_cache_is_configured if DEFAULT_CACHE_ALIAS not in settings.CACHES: File "C:\Users\ninie\PycharmProjects\pythonProject1\venv\lib\site-packages\django\conf\__init__.py", line 102, in __getattr__ self._setup(name) File "C:\Users\ninie\PycharmProjects\pythonProject1\venv\lib\site-packages\django\conf\__init__.py", line 89, in _setup self._wrapped = Settings(settings_module) File "C:\Users\ninie\PycharmProjects\pythonProject1\venv\lib\site-packages\django\conf\__init__.py", line 234, in __init__ raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: The ALLOWED_HOSTS setting must be a list or a tuple. It was supposed to make the migration, create tables and a file called 0001_initial.py I tried to change manage.py and settings.py, and tried to start my project from scratch but it didn't work -
How to show image link while uploading in Django?
#How to show image link while uploading in Django? This is the models.py class TopicModel(models.Model): topic_image = models.ImageField(upload_to = 'topic',blank = True,null = True) sub_catagory = models.ForeignKey(SubCatagoryModel,on_delete=CASCADE,blank = True,null = True) title = models.CharField(max_length=250) author = models.CharField(max_length=25) date_created = models.DateField(default=datetime.today) read_times = models.BigIntegerField(default=0,null=True,blank=True) blog_post = RichTextField(blank = True,null=True) def __str__(self) : return self.title class ImageModel(models.Model): image = models.ImageField(blank = True,null = True,upload_to='topic') alter = models.CharField(max_length=25,blank = True,null = True) topic = models.ForeignKey(TopicModel,on_delete=models.CASCADE) def image_link(self): return self.image.path def __str__(self) : return self.alter This is the admin.py @admin.register(ImageModel) class ImageAdmin(admin.ModelAdmin): list_display = ("image","alter","image_link") class ImageItemInline(admin.TabularInline): model= ImageModel extra = 0 @admin.register(TopicModel) class TopicAdmin(admin.ModelAdmin): list_display = ("title","author","date_created","sub_catagory","read_times") autocomplete_fields = ("sub_catagory",) search_fields = ("title",) readonly_fields = ("read_times",) inlines = [ImageItemInline] This is my admin page. When i wanna add an image in rich text editor how i will get the image link which i used in TabularInline. Is there any way to get the link from here? please suggest me some way. I have no idea how to do that on django admin. -
Hi everyone, can anyone help me?
I am coding a django project in the registration form I code in html I have 2 buttons submit and submit OTP I want when I click the send OTP button, the program will execute the send_OTP function I have coded in the view.py file, and when I click submit, I will proceed to checkOTP and register. Thanks a lot -
How to build an NFC-based smart employee in/out management system with Django?
I am working on building an employee in/out management system that utilizes NFC tags for clock-in and clock-out operations. I want to implement this system using Django, but I'm unsure about the specific steps involved. I have come across some tutorials that demonstrate similar implementations using Google Sheets example The Best Employee Timesheet using NFCs and NFC-Based Employee Time Logging System. However, I would like to integrate the system with my Django application and sync the employee database with the data stored on the NFC tags. Now I'm particularly interested in the following areas: Communication between Django app and NFC tag: I'm unsure about how to establish communication between my Django application and the NFC tags. What libraries or technologies should I use? Are there any Django-specific considerations to keep in mind? Database synchronization with NFC tag data: I want to ensure that the employee database in my Django application stays synchronized with the data stored on the NFC tags. How can I achieve this synchronization? Are there any best practices or recommended approaches? If anyone has experience with building an NFC-based employee in/out management system using Django or has insights into the specific steps I outlined, I would greatly … -
Django model constraint at least one field from two is not null or empty
I added a constraint to the model but seems that it has no impact because I'm still able to create a model instance without supplying any of the fields. Please help me to enforce the constraint to check is at least one field from two is not null or empty. Fields: class Fruit(models.Model): name1 = models.CharField(max_length=255, blank=True, null=True name2 = models.CharField(max_length=255, blank=True, null=True) class Meta: constraints = [ models.CheckConstraint( check=( Q(name1__isnull=False) | Q(name2__isnull=False) | ~Q(name1__exact='') | ~Q(name2__exact='') ), name='color_names_not_null_or_empty' ) ] Django v4 Postgres v15 -
Django IntegrityError UNIQUE constraint failed even when trying to login into Admin panel
I've searched across a similar topics but did't find a solution for my particular case. I have a User extended model and additionally UserProfile to extend and store some user's information. UserProfile has a OneToOne relation to User model. I've a User model save method overridden to instantly create a UserProfile object on User object created. But whenever I create a new User instance IntegrityError UNIQUE constraint failed: accounts_userprofile.user_id raises even though both instances created successfully (User and UserProfile). After user created (even superuser) whenever I try to login into Django Admin I got the same IntegrityError UNIQUE constraint failed: accounts_userprofile.user_id. I've tried : To apply migrations (just in case); To delete database completely and repeat everything from a scratch; I know theres is a way to change OneToOne relation to ForeignKey but I like to keep this kind of relation if there is another solution. models.py: class UserManager(BaseUserManager): def create_user(self, email, password, **kwargs): if not email: raise ValueError("Please, provide a correct email.") email = self.normalize_email(email) user = self.model(email=email, **kwargs) user.set_password(password) user.save() return user def create_superuser(self, email, password, **kwargs): kwargs.setdefault('is_staff', True) kwargs.setdefault('is_superuser', True) kwargs.setdefault('is_active', True) if not kwargs.get('is_staff'): raise ValueError("Superuser must have 'is_staff' value set to True") if not kwargs.get('is_superuser'): … -
Unable to generate downloadable PDF file from Django website hosted in apache
Im encountering an issue in generating a PDF file from a hosted django website. The website is hosted in apache thorough cpanel python web app. The website is basically a dashboard of all user submissions with a download button at the side. Once you click on the button, a dialog box will pop-up, prompting you to download the pdf file with user submission details. I followed this tutorial to get it to work: https://docs.djangoproject.com/en/4.2/howto/outputting-pdf/ I added some more code to it using pypdf and reportlab to handle the details from the database and add them to a pdf file to output it. The code works fine on my local computer, but when deployed to my hosting site, it returns a generic error response on my console and an uncommon error-like message saying io.UnsupportedOperation: fileno on my webapp stderr.log file. How my project is set up is that I have a javascript function that makes a GET request to a django function to generate the pdf file on the browser. Here are my code. javascript: function downloadPDF(id, date) { const csrftoken = getCookie('csrftoken'); $.ajax({ url: `/generate-pdf/${id}`, method: 'GET', headers: { 'X-CSRFToken': csrftoken, }, mode: 'same-origin', xhrFields: { responseType: 'blob' // Specify … -
How can I send both file and json data in a single request in Django using Requests library on the client side?
I need to send json data and file to my api in django. In the client side i use requests and i will share that code below. I tried this code but it gave "django.http.request.RawPostDataException: You cannot access body after reading from request's data stream". Hope you can help. client side: import requests my_json={ #some json data } file = {"file": open("sample.txt", "rb")} response = requests.post( "http://127.0.0.1:8000/API/upload-file", data=my_json, files=file ) print(response.text) endpoint in views.py def get_file(request): if request.method == "POST": uploaded_file = request.FILES["file"] json_data = json.loads(request.body) print(json_data) print(uploaded_file.filename) -
'QuerySet' object has no attribute 'items' when using HTMX get
I'm using htmx and django-filter and i want to change with hx-get and hx-target another select options but instead i got an error 'QuerySet' object has no attribute 'items' and i dont know how to fix that template.html {% render_field form.open_point_object class='form-select' hx-get='/customer/qsCategory/' hx-target='#id_category_choice' %} {% render_field form.category_choice|add_class:'form-control' %} urls.py path('customer/qsCategory/', qsCategory, name='qsCategory'), filters.py def qsCategory(request): object = request.GET.get('open_point_object') if object: return OpenPointList.objects.filter(open_point_object=object).values_list('category', flat=True).distinct() return OpenPointList.objects.values_list('category', flat=True).distinct() class OpenPointFilter(django_filters.FilterSet): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.filters['category_choice'].extra['choices'] = [ (category, category) for category in qsCategory(request=self.request) ] -
nb:i know cart models is not store any information about user , i try it but it ended with some error
Title: User Cart Data Not Persisting Across Logins in Django E-commerce Project Question: I am developing an e-commerce project using Django, and I have encountered an issue with persisting user cart data across login sessions. When a user logs in and adds products to their cart, the cart items are not visible when the user logs in again at a later time. I am unsure how to resolve this problem and would appreciate some guidance. cart view def cart_details(request,tot=0,count=0,cart_items=None,ct_items=None): try: ct=cartlist.objects.get(cart_id=c_id(request)) ct_items=items.objects.filter(cart=ct,active=True) for i in ct_items: tot += (i.prod.price*i.quan) count += i.quan except ObjectDoesNotExist: return HttpResponse("<script> alert('Empty Cart');window.location='/';</script>") return render(request,'cart.html',{'ci':ct_items,'t':tot,'cn':count}) def c_id(request): ct_id=request.session.session_key if not ct_id: ct_id=request.session.create() return ct_id def add_cart(request,product_id): prod=products.objects.get(id=product_id) try: ct=cartlist.objects.get(cart_id=c_id(request)) except cartlist.DoesNotExist: ct=cartlist.objects.create(cart_id=c_id(request)) ct.save() try: c_items=items.objects.get(prod=prod,cart=ct) if c_items.quan < c_items.prod.stock: c_items.quan+=1 c_items.save() except items.DoesNotExist: c_items=items.objects.create(prod=prod,quan=1,cart=ct) c_items.save() return redirect('cartDetails') def min_cart(request,product_id): ct=cartlist.objects.get(cart_id=c_id(request)) prod=get_object_or_404(products,id=product_id) c_items=items.objects.get(prod=prod,cart=ct) if c_items.quan>1: c_items.quan-=1 c_items.save() else: c_items.delete() return redirect('cartDetails') def cart_delete(request,product_id): ct=cartlist.objects.get(cart_id=c_id(request)) prod=get_object_or_404(products,id=product_id) c_items=items.objects.get(prod=prod,cart=ct) c_items.delete() return redirect('cartDetails') cart models class cartlist(models.Model): cart_id=models.CharField(max_length=250,unique=True) date_added=models.DateTimeField(auto_now_add=True) def __str__(self): return self.cart_id class items(models.Model): prod=models.ForeignKey(products,on_delete=models.CASCADE) #here class/tale product from shop is act as a foreign key so we can fetch the values ... cart=models.ForeignKey(cartlist,on_delete=models.CASCADE) quan=models.IntegerField() active=models.BooleanField(default=True) def __str__(self): return str(self.prod) login def register(request): if request.method == "POST": first_name = …