Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TemplateSyntaxError at /cart/ Invalid filter: 'mul' Reques
TemplateSyntaxError at /cart/ Invalid filter: 'mul' Request Method: GET Request URL: http://127.0.0.1:8000/cart/ Django Version: 5.0.6 Exception Type: TemplateSyntaxError Exception Value: Invalid filter: 'mul' Exception Location: C:\Users\denni\Desktop\Foods1\venv\Lib\site-packages\django\template\base.py, line 603, in find_filter Raised during: Foodies.views.view_cart Python Executable: C:\Users\denni\Desktop\Foods1\venv\Scripts\python.exe Python Version: 3.11.7 Python Path: ['C:\Users\denni\Desktop\Foods1\Foods', 'C:\Users\denni\AppData\Local\Programs\Python\Python311\python311.zip', 'C:\Users\denni\AppData\Local\Programs\Python\Python311\DLLs', 'C:\Users\denni\AppData\Local\Programs\Python\Python311\Lib', 'C:\Users\denni\AppData\Local\Programs\Python\Python311', 'C:\Users\denni\Desktop\Foods1\venv', 'C:\Users\denni\Desktop\Foods1\venv\Lib\site-packages'] Server time: Mon, 13 May 2024 11:01:44 +0000 Error during template rendering I want after click on buy now it should give me result -
Issue concercing cookie setting in django on browser, works fine on postman
I am experiencing an issue, I am using django 5 for my backend and nuxt 3 for my frontend. I have this view in django: @action(detail=False, methods=['POST']) def login(self,request): username = request.data['username'] password = request.data['password'] user = authenticate(request,username=username, password=password) if user is not None: login(request,user) sessionid = request.session.session_key return Response({'message': "Logged in!", 'sessionid': sessionid}) else: return Response({'message': "Invalid credentials provided",'username': username, 'password': password}, status=status.HTTP_400_BAD_REQUEST) And when I do a post request with the proper credentials on postman, I get a 200 OK response, with the cookies being set. On the frontend I also get a 200 OK response and the set_cookie response headers for both the sessionid and csrftoken are there. However in all subsequent requests, the request cookies tab is empty and there is no 'cookie' header. I had solved this issue, at least I thought and was able to get the sessionid cookie to be set after changing some of it's settings. However the csrftoken was still not being set despite me giving it the same settings. During the process of trying to get the csrftoken to work, the sessionid stopped being set. I tried reverting it's settings back to how it were, that didn't work so I … -
Count the number of users following a ticker in django
I need to get the top stock tickers followed by users, the issue is when two users or more follow the same ticker, it get repeated when using the query Tickers.objects.annotate(followers=Count('users')).order_by('followers') as shown here: In this example, the ticker FDCFF needs to be the top ticker since two users are following it, instead it gets repeated and its not being shown as the top followed ticker. Models.py class Tickers(models.Model): symbol = models.CharField(max_length=100) name = models.CharField(max_length=100) users = models.ManyToManyField(User, related_name='tickers') views.py def index(request): tickers = Tickers.objects.annotate(followers=Count('users')).order_by('followers') context = { 'tickers': tickers, } return render(request, 'main_index.html', context=context) -
Access to ForeignKey fields of another model
I have project in Django Rest Framework where I need get access from Project to ProjectTemplate. But between I have Department model, so I can only connect with Department via ForeignKey. There is some solution how I can handle this? from django.db import models class ProjectTemplate(models.Model): name = models.CharField(max_length=125) desc = models.TextField() def __str__(self): return self.name class Department(models.Model): name = models.CharField(max_length=125) desc = models.TextField project_template = models.ForeignKey(ProjectTemplate, on_delete=models.SET_NULL, related_name='departments', null=True, blank=True, unique=True) def __str__(self): return self.name class Project(models.Model): name = models.CharField(max_length=125) desc = models.TextField() is_visible = models.BooleanField(default=True) project_temp = models.ForeignKey(Department, to_field='name', on_delete=models.SET_NULL, null=True, blank=True) def __str__(self): return self.name -
How properly configure Entity Attribute Value pattern in django?
I have a product model: class Product(models.Model): title = models.CharField(max_length=255) description = models.TextField(null=True, blank=True) category = models.ForeignKey('Category', on_delete=models.CASCADE) price = models.FloatField() discount = models.IntegerField() # stands for percentage count = models.IntegerField() priority = models.IntegerField(default=0) brand = models.ForeignKey('Brand', on_delete=models.SET_NULL, null=True, blank=True) tags = models.ManyToManyField(Tag, blank=True) def __str__(self): return self.title Now I want to implement entity attribute value pattern as different products can have different specifications. I understood the traditional way of EAV. But I read in wikipedia as postgresql has jsonb column type and this allows performance improvements by factors of a thousand or more over traditional EAV table designs. My database in postgresql. So what is the best practice to implement EAV (or dynamic set relationship with attributes)? Should I just add like: class ProductVariant(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) specifications = models.JSONField() And also I want to handle price and count (in stock) differently for each variant, let's say there are 10 shoes with size 10 and color red which price is 100 dollars and 2 shoes with size 9 and color blue which price is 120 dollars. -
Programming Error in MySQL LOAD DATA statement when using ENCLOSED BY
I am trying to run a SQL statement using cursor.execute LOAD DATA LOCAL INFILE '/home/ubuntu/test.csv' INTO TABLE app_data CHARACTER SET UTF8MB4 FIELDS TERMINATED BY ',' ENCLOSED BY "" LINES TERMINATED BY '\r\n' This runs using mysql command line but the ENCLOSED BY raises a ProgrammingError / OperationalError. Any help/pointers appreciated. I have already tried variations such as ENCLOSED BY '"'. -
How to start a Django Celery Shared task using redis-cli
i have a Celery task defined in django application as below from celery import shared_task @shared_task def save_notification(notification): print("Received notif", notification) for testing purpose in django container i type following command to start celery worker celery -A hello_django worker --loglevel=INFO it starts as expected and tasks is discovered, now the important thing i need to start the task using some arguments. So for testing i am using below command. redis-cli -n 0 RPUSH celery "{\"task\":\"notifications.tasks.save_notification\", \"args\":[\"I am notification\"]}" Commands publishes successfully and print some integer but on worker side it crashes and following error occurs [2024-05-13 13:03:55,610: CRITICAL/MainProcess] Unrecoverable error: KeyError('properties') Traceback (most recent call last): File "/usr/local/lib/python3.12/site-packages/celery/worker/worker.py", line 202, in start self.blueprint.start(self) File "/usr/local/lib/python3.12/site-packages/celery/bootsteps.py", line 116, in start step.start(parent) File "/usr/local/lib/python3.12/site-packages/celery/bootsteps.py", line 365, in start return self.obj.start() ^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/celery/worker/consumer/consumer.py", line 340, in start blueprint.start(self) File "/usr/local/lib/python3.12/site-packages/celery/bootsteps.py", line 116, in start step.start(parent) File "/usr/local/lib/python3.12/site-packages/celery/worker/consumer/consumer.py", line 742, in start c.loop(*c.loop_args()) File "/usr/local/lib/python3.12/site-packages/celery/worker/loops.py", line 97, in asynloop next(loop) File "/usr/local/lib/python3.12/site-packages/kombu/asynchronous/hub.py", line 373, in create_loop cb(*cbargs) File "/usr/local/lib/python3.12/site-packages/kombu/transport/redis.py", line 1344, in on_readable self.cycle.on_readable(fileno) File "/usr/local/lib/python3.12/site-packages/kombu/transport/redis.py", line 569, in on_readable chan.handlers[type]() File "/usr/local/lib/python3.12/site-packages/kombu/transport/redis.py", line 974, in _brpop_read self.connection._deliver(loads(bytes_to_str(item)), dest) File "/usr/local/lib/python3.12/site-packages/kombu/transport/virtual/base.py", line 1017, in _deliver callback(message) File "/usr/local/lib/python3.12/site-packages/kombu/transport/virtual/base.py", line 636, in _callback message … -
I created a django project to retrive the transaction data from database by verifying the user. But i am getting error like"AnonymousUser"
veiw.py this is views code def view_transaction(request): print(request.user) user_transactions = Transactions.objects.filter(user_account = request.user) return render(request,'transactions.html',{'user_transactions':user_transactions}) is the above code correct or not, i think when it check wheather user login is not present here. models.py class User(models.Model): name = models.CharField(max_length=45) phone = models.CharField(max_length=45) account_number = models.CharField(max_length=45,primary_key=True,blank=False,unique=True) user_id = models.CharField(max_length=45,unique=True) password = models.CharField(max_length=45) confirm_password = models.CharField(max_length=45) class Transactions(models.Model): transaction_number = models.AutoField(primary_key=True) user_account = models.ForeignKey(User,on_delete=models.CASCADE) date_of_transaction = models.DateField() transaction_type = models.CharField(max_length=20, choices=TRANSACTION_TYPES) transaction_medium = models.CharField(max_length=20, choices=TRANSACTION_MEDIUM) transaction_amount = models.DecimalField(max_digits=10,decimal_places=2) when i login using userid and password ,it shows some details about customer. I want transaction details in transactions.html,but i didn't get any, instead i got error like anonymous user. -
ProgrammingError: relation "users_customuser" does not exist
I have created a custom user as follows: from django.db import models from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): email = models.EmailField(unique=True) USERNAME_FIELD="email" REQUIRED_FIELDS=["username"] def __str__(self) -> str: return self.email I have defined the model in my settings.py file as follows AUTH_USER_MODEL = "users.CustomUser" when I run the migrate command I get the above error I have tried running python manage.py migrate users --fake but the error still persists Internal Server Error: /api/register/ Traceback (most recent call last): File "/usr/local/lib/python3.11/site-packages/django/db/backends/utils.py", line 105, in _execute return self.cursor.execute(sql, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ psycopg2.errors.UndefinedTable: relation "users_customuser" does not exist LINE 1: SELECT 1 AS "a" FROM "users_customuser" WHERE "users_customu... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/local/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/views/decorators/csrf.py", line 65, in _view_wrapper return view_func(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/views/generic/base.py", line 104, in view return self.dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/usr/local/lib/python3.11/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/usr/local/lib/python3.11/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) … -
SimpleListFilter and M2M fields as JSON
My setup contains Product information that come from a JSON field and are linked to a Page in a m2m relation (Page like in a catalogue). class Page(models.Model): ... products = models.ManyToManyField(Product, related_name="%(class)s_name", related_query_name="product_page_qs", blank=True) class Product(models.Model): ... number = models.PositiveIntegerField() data = models.JSONField() I created a SimpleListFilter with text search to get a list of all pages that contain a given product (works just fine): class PageProductSearch(admin.SimpleListFilter): title = "product" parameter_name = "product" template = "search_filter.html" def lookups(self, request, model_admin): return ((None, None),) def choices(self, changelist): super().choices(changelist) return (*self.lookup_choices,) def queryset(self, request, queryset): value = self.value() if value: return queryset.filter(products=value) My problem here is, that I have to know the product.id in order to search for products. How can I extend my queryset filtering to search for a key in the jsonField? I tried: queryset.filter(products__contain=value) but got django.core.exceptions.FieldError: Unsupported lookup 'contain' for ForeignKey or join on the field not permitted. This might be because I am on SQLite. using Q and regex: queryset.filter(Q(data__regex=r'"name":.*"test"')) but this always leads to empty querysets. I liked the regex idea tough, because it is insensitive to data elements that might not contain the key name. -
Greets. Please help serve Media (Pro pics) on Website https://djangocareershifterswebsite.onrender.com. I have tried nGinx, deploy & redner docs.
All funtionality works except my profile pics being uploaded. So nginx just did not serve as the bucket, I have Linux machine and terminal on windows. I have PostgreSQL running on PG Admin 4. It shows my DB. Here is a link to my website. https://djangocareershifterswebsite.onrender.com. I deleted all my 6 of my failed deploy branches, I did deploy but still no profile pic. Here is my Github. https://github.com/GJprocode/DjangoCareerShiftersWebsite.main for production. https://github.com/GJprocode/DjangoCareerShiftersWebsite/tree/DeployV1 for deploy. Please provide setting.py for deploy( Import os to generate key and so on, getting data parse form sqlite db to postgreSQL etc.) Render.com Yaml file, and the.build file is static. Environmental variables. ALthough this method uses teh blue print tab. Thanks so much, or advise what works for you!! Then my website is complete. Last little bit. The functionality of my webiste worked with sqlite 3, admin and registering user and all collect static.css as per my website. Except serving media static. Thats it. Tried all the routes. PLease check mt deploy branch settings.py, render.yaml and advise how you did it. Thanks. -
NLTK package is not working in production but working in development
I have created a web-app using Django. I this web-app I want to add functionality to extract phrases from content. My code is working fine in development but not working in production. Using nltk package I have created a function which gives returns a list of phrases from content. below is my code: import nltk from typing import List def extract_phrases(content: str) -> List: # Tokenize text into sentences sentences = nltk.sent_tokenize(content) # Initialize list to store phrases phrases = set() # Iterate through each sentence for sentence in sentences: # Tokenize sentence into words words = nltk.word_tokenize(sentence) # Get part-of-speech tags for words pos_tags = nltk.pos_tag(words) # Initialize list to store phrases in current sentence current_phrase = [] # Iterate through each word and its part-of-speech tag for word, pos_tag in pos_tags: # If the word is a noun or an adjective, add it to the current phrase if pos_tag.startswith("NN") or pos_tag.startswith("JJ"): current_phrase.append(word) # If the word is not a noun or adjective and the current phrase is not empty, # add the current phrase to the list of phrases and reset it elif current_phrase: phrases.add(" ".join(current_phrase)) current_phrase = [] # Add the last phrase from the current sentence … -
Retrieve user data infos after authentification using OAuth 2.0
How can I retrieve user data information after authentication using Django and Google OAuth2 ? HTML <button> <a href="{% provider_login_url "google" %}"> <div class="connexion-type"> <div class="connexion-type-svg"> <svg xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" width="100" height="100" viewBox="0 0 48 48"> <!-- SVG paths --> </svg> </div> <div class="connexion-type-content">Login via Gmail</div> </div> </a> </button> </div> ** Django View:** @login_required def redirect_google_provider(request): print("Access to redirect_google_provider") if 'code' in request.GET: # Extract the authorization code code = request.GET['code'] # Debug print(f"Code is: {code}") # Exchange the authorization code for an access token token_url = 'https://oauth2.googleapis.com/token' client_id = 'YOUR_GOOGLE_CLIENT_ID' client_secret = 'YOUR_GOOGLE_CLIENT_SECRET' redirect_uri = 'YOUR_REDIRECT_URI' data = { 'code': code, 'client_id': client_id, 'client_secret': client_secret, 'redirect_uri': redirect_uri, 'grant_type': 'authorization_code', } response = requests.post(token_url, data=data) token_data = response.json() access_token = token_data.get('access_token') # Retrieve user information from Google API if access_token: user_info_url = 'https://www.googleapis.com/oauth2/v3/userinfo' headers = {'Authorization': f'Bearer {access_token}'} user_info_response = requests.get(user_info_url, headers=headers) user_info = user_info_response.json() email = user_info.get('email') # Check if the user exists in the system if email: user, created = User.objects.get_or_create(username=email, email=email) if created: # New user, save additional information if needed user.save() # Log the user in login(request, user) return HttpResponseRedirect('/home/') # Redirect to home page after successful login # If code is not present or user … -
I am using dart to develop a e-commerce flutter app , so in here when am trying build edit profile page , i need to pass token from login page
So I am using rest api as back end , I am unable to edit so I found that the token needs to be passed , from login to this change-profile api , so that the user can succesfully edit his or her details . Future updateProfile() async { String url = "http://167.71.232.83:8000/myprofile/${userId}/"; // Build the query parameters with updated user information Map<String, String> queryParams = { "email": _emailController.text, "password": passwordController.text, "repassword": repasswordController.text, "firstname": firstname.text, "lastname": lastname.text, "phonenumber": phonenumber.text, "state": state.text, "city": city.text, "Zip": zip.text, "mailing": _value.toString(), "referred_by": selectedItem, "flag": "business", "businessname": businesscontroller.text, }; String queryString = Uri(queryParameters: queryParams).query; url += '?' + queryString; try { final response = await http.put( Uri.parse(url), headers: { "Content-Type": "application/json", "User-Agent": "PostmanRuntime/7.28.4", "Accept": "*/*", "Accept-Encoding": "gzip, deflate, br", "Connection": "keep-alive", }, ); var data = jsonDecode(response.body); print(url); print(response.statusCode); print(data); if (response.statusCode == 200) { // Success _showSuccessDialog(); // Navigate to the next page or perform any other actions Navigator.push( context, MaterialPageRoute( builder: (_) => BottomPage(), ), ); } else { // Error _showErrorDialog('Failed to update profile. Please try again.'); } print(response.body); } catch (e) { print('Error updating profile: $e'); _showErrorDialog('Failed to update profile. Please try again.'); } } I attached the code snippet above … -
Error in importing latest DeepSpeechModel: CreateModel failed with 'Failed to initialize memory mapped model.' (0x3000)
Thanks for your time checking my post. In my Django project I created an API which is supposed be to trigged in view function where it runs the most recent deepspeech version (DeepSpeech: v0.9.3-0). Even though there is no problem with the backend and the request I sent from Insomnia is received from the server, and I have the latest TF version installed, I encounter the error below: linux@linux:~/docs/PROJECT$ cd /home/linux/docs/PROJECT ; /usr/bin/env /home/linux/docs/PROJECT/env_/bin/python /home/linux/.vscode/extensions/ms-python.debugpy-2024.6.0-linux-x64/bundled/libs/debugpy/adapter/../../debugpy/launcher 60057 -- /home/linux/docs/PROJECT/PROJECT/manage.py runserver 8001 Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). May 13, 2024 - 03:49:36 Django version 4.2.13, using settings 'PROJECT.settings' Starting development server at http://127.0.0.1:8001/ Quit the server with CONTROL-C. TensorFlow: v2.3.0-6-g23ad988 DeepSpeech: v0.9.3-0-gf2e9c85 ERROR: Model provided has model identifier 'u/3�', should be 'TFL3' Error at reading model file PROJECT/files/deep_speech_models/deepspeech-0.9.3-models.pbmm Error initializing DeepSpeech model: CreateModel failed with 'Failed to initialize memory mapped model.' (0x3000) Below is the relevant part of my view function code where the error occurs: class ModifyNarrativeAPIView(APIView): permission_classes = [permissions.IsAuthenticated] def post(self, request, *args, **kwargs): voice_files = paths.saved_sound_files ear = Ear(DEEPSPEECH_MODEL_PATH, DEEPSPEECH_SCORER_PATH) for voice_file in voice_files: text = ear.convert_voice_to_text(voice_file) ... Thanks again. -
Is there a less bloated alternative to GDAL and GeoDjango?
I am writing an API in Django and need to filter posts by a search radius and later on will need live tracking like on Uber. I am wondering if there is an easier way to query for posts and filter them based on a search radius defined by the user and their location. Wondering how a program like AutoTrader would do this. Dealing with the installation process for GDAL is a complete pain for Windows and my docker image. I know there are ways to install a pre-built wheel and blah blah blah but I'm looking for a streamlined approach that is as simple as throwing it into my requirements and won't be a nuisance after each release. -
How to create different sizetables for each type of clothing?
Im making shop on django and cant realize how to solve the problem: I got class Product(class for clothes) and i need to create another class for Sizes of different categories of clothes, for example: Shoes will got - 9US, 10US, 11US... Shirts will got - XS, S, M, L... etc. How can i create that type of class?? My Product class: class Product(models.Model): class ModerationStatuses(models.TextChoices): DRAFT = 'DR', _('черновик') ON_MODERATION = 'MD', _('На модерации') APPROVED = 'AP', _('Одобрено') REJECTED = 'RJ', _('Отклонено') class ConditionStatuses(models.TextChoices): NEW = 'NEW', _('New') USED = 'USD', _('Used') VERY_WORN = 'VW', _('Very worn') NOT_SPECIFIED = 'NS', _('Not specified') title = models.CharField(max_length=100) price = models.DecimalField(max_digits=6, decimal_places=2) quantity = models.IntegerField() city = ... style = models.ForeignKey(Style, related_name='category_products', on_delete=models.CASCADE, null=True, blank=True) category = models.ForeignKey(Category, related_name='style_products', on_delete=models.CASCADE, null=True, blank=True) address = models.CharField(max_length=250) description = models.TextField() brand = models.CharField(max_length=150) published = models.BooleanField(default=False, null=False) modification = models.OneToOneField('self', on_delete=models.CASCADE, null=True, blank=True, help_text='When editing an approved item a modification is created. This ' 'modification is sent for moderation and, after approval, replaces ' 'the original position.') is_modification = models.BooleanField(default=False) moderation_status = models.CharField(choices=ModerationStatuses.choices, default=ModerationStatuses.DRAFT, null=False, max_length= 2) condition = models.CharField(choices=ConditionStatuses.choices, default=ConditionStatuses.NEW, null=False, max_length=3) posted_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title I literally cant find … -
Custom MultiInput Model Field in Django
I'm trying to create a custom field for volume made up of 4 parts (length, width, height and units). I'm thinking that extending the models.JSONField class makes the most sense. Here is what I have so far. inventory/models.py from django.db import models from tpt.fields import VolumeField class Measurement(models.Model): volumne = VolumeField() tpt/fields.py from django.db import models from tpt import forms class VolumeField(models.JSONField): description = 'Package volume field in 3 dimensions' def __init__(self, length=None, width=None, height=None, units=None, *args, **kwargs): self.widget_args = { "length": length, "width": width, "height": height, "unit_choices": units, } super(VolumeField, self).__init__(*args, **kwargs) def formfield(self, **kwargs): defaults = {"form_class": forms.VolumeWidgetField} defaults.update(kwargs) defaults.update(self.widget_args) return super(VolumeField, self).formfield(**defaults) tpt/forms.py import json from django import forms class VolumeWidget(forms.widgets.MultiWidget): def __init__(self, attrs=None): widgets = [forms.NumberInput(), forms.NumberInput(), forms.NumberInput(), forms.TextInput()] super(VolumeWidget, self).__init__(widgets, attrs) def decompress(self, value): if value: return json.loads(value) else: return [0, 0, 0, ''] class VolumeWidgetField(forms.fields.MultiValueField): widget = VolumeWidget def __init__(self, *args, **kwargs): list_fields = [forms.fields.CharField(max_length=8), forms.fields.CharField(max_length=8), forms.fields.CharField(max_length=8), forms.fields.CharField(max_length=4)] super(VolumeWidgetField, self).__init__(list_fields, *args, **kwargs) def compress(self, values): return json.dumps(values) I'm able to run the server but when I try and add a new entry to the Measurement Model in Admin I get this error: [13/May/2024 11:57:59] "GET /admin/inventory/measurement/ HTTP/1.1" 200 12250 Internal Server Error: /admin/inventory/measurement/add/ Traceback … -
End of year project using Django, React and MySQL (beginner)
I'm a first year programming student so I apologize for sounding a bit ignorant on this topic, I'm still learning, but I need help. I'm working on making a web app for my end of year project. I'm gonna be using Django for backend, MySQL for storing data, React, html and css for frontend. I have 2 months to make this project so I'm currently speed running learning react and django rn. I am watching tutorials on how to link all these technologies together and it's quite confusing, can someone help and give me a simple explanation or some good resources that I can use please? Also the most important part of my question is where do I start? do I start with frontend or backend? I thought about making the frontend first, creating templates and all, and then linking it to Django and MySQL. I need professional advice though, any help would be much appreciated :) I just got started so I haven't done much. I just made a mockup template for starters, that's it, but I'm gonna start coding after I grasp the conceps I mentioned. I'm familiar with html and css and python(this will mostly help me … -
TestDriven.io: Docker Not Installing Pytest Requirements For Django API course project
I'm on the Django REST Framework portion of the course. Aside from the entrypoint, everything else is working. so I am leaving it as commented out for now. Here is the structure: Here is the Dockerfile: # pull official base image FROM python:3.11.2-slim-buster # set working directory WORKDIR /usr/src/TestDrivenIO # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # updated # install system dependencies RUN apt-get update \ && apt-get -y install netcat gcc postgresql \ && apt-get clean # install dependencies RUN pip install --upgrade pip COPY requirements.txt . RUN pip install -r requirements.txt # # new # # copy entrypoint.sh # COPY ./entrypoint.sh /usr/src/TestDrivenIO/entrypoint.sh # RUN chmod +x /usr/src/TestDrivenIO/entrypoint.sh # # add app # COPY . . # # new # # run entrypoint.sh # ENTRYPOINT ["/usr/src/TestDrivenIO/entrypoint.sh"] Entrypoint file: #!/bin/sh # continues until "Connection to movies-db port 5432 [tcp/postgresql] succeeded!" returned if [ "$DATABASE" = "postgres" ] then echo "Waiting for postgres..." while ! nc -z $SQL_HOST $SQL_PORT; do sleep 0.1 done echo "PostgreSQL started" fi python manage.py flush --no-input python manage.py migrate exec "$@" Requirements file in the TDD-Django/TestDrivenIO/requirements.txt file: Django==4.1.7 djangorestframework==3.14.0 psycopg2-binary==2.9.5 pytest-django==4.5.2 pytest==7.2.2 Requirements file in the TDD-Django/requirements.txt file (copied from other in case … -
how to get info from image before uploading it to db using django
i have a view that uploads image to db i need to get face_encoding tbefore uploading it to db any ideas how to do that this is my view def index(request): if request.method=='POST': form = ImageForm(request.POST,request.FILES) if form.is_valid(): form.save() return HttpResponse(type(ImageForm)) else: return HttpResponse("error") context={'form':ImageForm()} template=loader.get_template("core/index.html") return HttpResponse(template.render(context,request)) i want to use face_recognition library -
Django: Facing Issues in accessing DB and Instantiating object on app load
I want to load data from db and store it in an object and access that object from anywhere in the Django project. Preferably using the conventional settings.GlobalSettings where settings are the django.conf. I have a function that should run while the app starts. How can I achieve that and is it possible? I have been trying different implementations and getting errors like AttributeError: 'Settings' object has no attribute 'GlobalSettings' django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I was trying to call that function as a post_migrate signal in the apps.py. also, I was calling the settings class using from django.conf import settings and added my GlobalSettings in it and tried to load but nothing worked. I am fairly new to this, any help would be appreciated. -
Getting error 500 while accepting image from client to server
I have html code that takes image from user as an input and i am trying to send it to server side when i click button process for processing in Django but i am hetting error 500 in console. On server side i want to read that image and allign it and apply ocr on it Code for html is: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Image Processing</title> </head> <body> <h1>Image Processing</h1> <form id="image-upload-form" method="post" enctype="multipart/form-data"> {% csrf_token%} <input type="file" id="image-upload" name="image" accept="image/*"> <button type="submit">Upload Image</button> </form> <div id="result"></div> </body> </html> Code for server side python: # views.py from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt import numpy as np import cv2 import imutils import pytesseract import base64 pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe' def order_points(pts): rect = np.zeros((4, 2), dtype="float32") s = pts.sum(axis=1) rect[0] = pts[np.argmin(s)] rect[2] = pts[np.argmax(s)] diff = np.diff(pts, axis=1) rect[1] = pts[np.argmin(diff)] rect[3] = pts[np.argmax(diff)] return rect def four_point_transform(image, pts): rect = order_points(pts) (tl, tr, br, bl) = rect maxWidth = max(int(np.sqrt(((br[0] - bl[0]) * 2) + ((br[1] - bl[1]) * 2))), int(np.sqrt(((tr[0] - tl[0]) * 2) + ((tr[1] - tl[1]) * 2)))) maxHeight = max(int(np.sqrt(((tr[0] - br[0]) * 2) + ((tr[1] - br[1]) * 2))), … -
How do I add a new entry to my many to many related table in Django?
I have two models Course and Educators. Course has 3 fields course_name, course_educators and course_past_educators which link Educators to Courses by many to many. I want to write a function so that whenever a new entry is added to course_educators that entry will be copied over to course_past_educators. #models.py #code for Educators model class Educators(models.Model): educator_name=models.CharField(max_length=20,default=None) educator_img = models.ImageField(upload_to='educators_img',default=None) #code for Courses model class Course(models.Model): course_name = models.CharField(max_length=100) course_educators=models.ManyToManyField(Educators, related_name='current_educators', default=None, blank=True) course_past_educators=models.ManyToManyField(Educators, related_name='past_educators', default=None, blank=True) #views.py #This is the function I wrote so that entries into course_past_educators are automatically added when course_educators is added with another entry. @receiver(m2m_changed, sender=Course.course_educators.through) def create_past_educator_on_add(sender, instance, action, reverse, model, pk_set, **kwargs): if action == 'post_add' and reverse is False: currentEducators=instance.course_educators.all() for currentEducator in currentEducators: instance.course_past_educators.add(currentEducator) I use Django admin panel to add the educators yet, educators are not being added to course_past_educators. How do I fix this issue? -
Validation Error Placement for a list editable field
I have enabled list editable on one of my django admin to allow user update the min and max value. I have set a validation in place to make sure that min is not greater than max. The validation works as expected. However, I am not really happy with the way the message is displayed. So currently as seeing in the screenshot, the error message appears right above the field which messes up the alignment of the table. The column with error becomes wider than the others and it's not even highlighted with red. What I am trying to achieve instead is to show the error on the top of the page like Please correct the errors below. Min value cannot be greater than max value .... and simply have the errored field highlighted with red border. what is the best way to achieve this? I tried overriding the is_valid function in my CustomModelForm but I can't add the messages there since I don't have access to the request object. Anything I tried to pass the request object was in vain. class CustomModelForm(forms.ModelForm): class Meta: model = MyModel fields = '__all__' def is_valid(self): if 'min_quantity' in self._errors: # messages.error(self.request, self._errors["min_quantity"]) …