Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django display any querry as html table
I want to display a simple query in my database as an HTML table. But i a missing something either in the template or general logic of data management in Django. First i am creating a model like that : class Book(models.Model): title = models.CharField(max_length=128, unique =True) quantity = models.IntegerField(default=1) Then making a view with a context containing both the column's names of the query and the query object such as : def books(request): context = {"rows":Book.objects.all(),"fields" : Book._meta.get_fields()} return render(request,"blog/books.html",context) Finally i am trying to iterate over the value of the query in my template so i can put them in a HTML table: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Our Books</title> </head> <body> <table border="1"> <thead> <tr> {% for field in fields %} <th>{{ field.verbose_name }}</th> {% endfor %} </tr> </thead> <tbody> {% for row in rows %} <tr> {% for field in fields %} <td>{{ row[field] }}</td> {% endfor %} </tr> {% endfor %} </tbody> </table> </body> </html> Adding the header of the table works fine but this part is not working : {% for row in rows %} <tr> {% for field in fields %} <td>{{ row[field] }}</td> {% endfor %} </tr> {% endfor %} … -
Django Admin Search - returning duplicates when search_field includes many-to-many
I'm receiving multiple duplicate objects when using Django Admin search. I have two models involved. Organisation and OrgAlias(Organisation Alias). Each Organisation may have multiple aliases and each alias may be attached to multiple Organisations. The models: class OrgAlias(models.Model): name = models.CharField(max_length=255,unique=True) def __str__(self): return self.name class Organisation(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) aliases = models.ManyToManyField(OrgAlias) ... My Django Admin class: class OrganisationAdmin(admin.ModelAdmin): search_fields = ['aliases__name'] ... I've tried overriding the ModelAdmin get_search_results function with various strategies. e.g. def get_search_results(self, request, queryset, search_term): queryset, use_distinct = super().get_search_results(request, queryset, search_term) queryset = queryset.distinct() return queryset, use_distinct The result is always the same. If I have 3 aliases attached to and organisation. The organisation will appear 3 times in the search results. Similar queries work fine in the shell. It's just in django admin the problem appears. Is there a simple fix or workaround for this? -
Why is my Jquery autocomplete not working on my search bar?
I have a search bar that should be visible in all my pages in django, however the autocomplete is not working. my bse.html has the following: <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css"> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> this is my search bar: <div class="sbar "> <div class="row-search "> <div class="col-6"> <form action="{% url 'search' %}" method="get"> <div class="input-size input-group mb-3"> <input type="text" name="q" id="searchBox" class="form-control" placeholder="Search..."> <button class="btn btn-primary" type="submit">Search</button> <div id="search-suggestions-dropdown"></div> <!-- Add this line --> </div> </form> </div> </div> </div> this is my script inside my base.html: <script> $(document).ready(function(){ $('#searchBox').autocomplete({ source: function(request, response) { console.log("Making AJAX request with query:", request.term); $.ajax({ url: "{% url 'search' %}", dataType: 'json', data: { 'q': request.term }, success: function(data) { console.log("Received data:", data); var suggestions = []; data.forEach(function(item) { suggestions.push({ label: item.label, value: item.value }); }); response(suggestions); } }); }, minLength: 2, select: function(event, ui) { console.log("Selected item:", ui.item); window.location.href = ui.item.value; } }); }); </script> this is from my views.py: class SearchView(View): def get(self, request, *args, **kwargs): query = request.GET.get('q') print("Received query:", query) # Print the received query if query: infos = Info.objects.filter(Q(firstName__icontains=query) | Q( middleName__icontains=query) | Q(lastName__icontains=query)) files = Files.objects.filter(fileName__icontains=query) results = list(infos.values('firstName', 'middleName', 'lastName', 'orphanID')) + list(files.values('fileName', 'fileID')) results = [ { 'label': … -
Insert the row to the Queryset manually
I have objects and filter, which get the label value pair from database. results = (m.Drawing.objects. annotate(label=F('update_user__name'),value=F('update_user')). values('label','value'). annotate(dcount=Count('update_user__name')). order_by()) print(results) serializer = s.SearchChoiceSerializer(instance=results, many=True) Results is like this,print(results) <SafeDeleteQueryset [{'label': 'admin', 'value': 1, 'dcount': 13}, {'label': 'demouser1', 'value': 2, 'dcount': 13}]> Now, I want to insert this {'label':'myuser', 'value':2,'dcount':23} to SafeDeleteQuerySet manually before sending to the serializer. I it possible? -
Problem with Error 502 in simple django method
I have a strange problem with django. I'm taking my first steps in Python, so maybe this question is stupid - if so, I apologize in advance :) I have 2 methods: def method1(self): url = settings.PAYMENT_GATEWAY_URL + "payments/" + self.bank_account_nr + "/" + settings.PAYMENT_POS_ID + "/function1/" ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE data = urllib.request.holiday(url, context=ctx) contents = data.read().decode('utf-8') # content = '{"amount_sum": "120.00"}' data = json.loads(contents) data = data.get("amount_sum") return data def method2(self): url = settings.PAYMENT_GATEWAY_URL + "payments/" + self.bank_account_nr + "/" + settings.PAYMENT_POS_ID + "/function2/" ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE data = urllib.request.holiday(url, context=ctx) contents = data.read().decode('utf-8') data = json.loads(contents) return data function2 return : {"status": "OK", "paymentsA": 1, "paymentsCt": 1, "paymentsD": 0} function1 return {"amountsum": "120.00"} When calling method 1 - everything works fine, in the case of method 2 the application takes a very long time and throws error 502, Both links load quickly in the browser. Both web addresses are on 1 server and are 1 application -
How to create Django Rest Framework translate mixin?
I'm trying to write a django translate mixin for my project. I configured the settings.py file, created a model, view, serializer and mixin. when I run the application an error occurs: "TranslationFieldMixin.get_field_names() missing 2 required positional arguments: 'declared_fields' and 'info'". This error occurred after I added this code to my serializer: def to_representation(self, instance): language = get_language() self.fields = self.get_field_names(language=language) return super().to_representation(instance) How can I solve this problem? SETTINGS.PY INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'parler', 'rest_framework', 'store', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] LANGUAGE_CODE = 'en-us' LOCALE_PATHS = [ os.path.join(BASE_DIR, 'locale'), ] LANGUAGES = [ ('en', _('English')), ('es', _('Spanish')), ('fr', _('French')), ('ru', _('Russian')), ] TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True MODELS.PY from django.utils.translation import gettext_lazy as _ class Article(models.Model): title = models.CharField(_('title'), max_length=100) content = models.TextField(_('content')) def __str__(self): return self.title VIEWS.PY class ArticleDetailAPIView(RetrieveUpdateDestroyAPIView): queryset = Article.objects.all() serializer_class = ArticleSerializer SERIALIZERS.PY class ArticleSerializer(TranslationFieldMixin, serializers.ModelSerializer): class Meta: model = Article fields = ['id', 'title', 'content'] def to_representation(self, instance): language = get_language() self.fields = self.get_field_names(language=language) return super().to_representation(instance) UTILS.PY class TranslationFieldMixin(): def get_field_names(self, declared_fields, info, language=None, *args, **kwargs): field_names = super().get_field_names(declared_fields, info, *args, **kwargs) if language: translated_field_names = [ str(_(field_name)) … -
USE_L10N deprecated, but it disables DATETIME_INPUT_FORMATS when removed
Have I found a bug in Django? The config setting USE_L10N is deprecated since 4.0 and scheduled for removal in 5.0. However, the documentation of forms.DateField for 5.0 still states If no input_formats argument is provided, the default input formats are taken from the active locale format DATE_INPUT_FORMATS key, or from DATE_INPUT_FORMATS if localization is disabled. Which begs the question, how does one disable localisation and enable the DATE_INPUT_FORMATS setting once USE_L10N = False is not longer possible? I don't want to upgrade to 5.0 yet, so I cannot easily test this. I have established that on 4.2, if I comment out the deprecated USE_L10N = False in my settings.py, then DATE_INPUT_FORMATS ceases to be honoured. I wonder whether anybody running Django 5.0 can comment? -
Django API Database Design for both Multi-Tenant and Customer (No-Tenancy) Authentication
I am developing a backend API using Python Django Rest Framework. The frontend will handle authentication at these 3 URL paths: Customer Authentication URL: www.mydomain.com Functionality: Customers can search for and purchase products. To complete a purchase, customers must create an account. This account provides access to view purchase history and the option to save payment methods. Multi-Tenancy Authentication URL with tenant subdomain: myclient.mydomain.com Functionality: Clients can login to manage their accounts and add their products to sell. Additionally, clients need the ability to give their employees their own login to assist in managing their listed products. Internal Admin Authentication URL with admin subdomain: admin.mydomain.com Functionality: Admins can access tools for customer and client support. What would be the best way to design my database schema to handle this in the most efficient way and also keeping my database organized and as clutter free as possible? I am just now starting this part of my project, so I do not have any code written for my schema as of yet. I have done a ton of Googling and YouTubing to find a solution and there isn't a whole lot of info on multi-tenancy architecture around the use case that I … -
Managing migrations while moving from default taggit tags to taggit custom tags
I was working on adding Tags to Articles, Comments using django-taggit. Butnow I need the Tags to be associated with Account - so every tag must be tied to an account_id and only Articles, Comments of that Account can access these tags. To achieve this, I had to implement a CustomTag. In between these two stages, there were few other migrations relavant to other models. Example 0021_add_tags_to_articles_and_comments.py 0022_some_other_model_migration.py 0023_some_other_model_migration.py 0024_use_custom_tag_with_custom_taggedobject.py Taggit documentation mentions the below to remove the tables taggit created and using custom tags But this is messing up with my initial migration that added taggit tables because 0021_add_tags_to_articles_and_comments.py has dependencies class Migration(migrations.Migration): dependencies = [ ( "taggit", "0006_rename_taggeditem_content_type_object_id_taggit_tagg_content_8fc721_idx", ), ("blog_app", "0020_blog"), ] I cant delete all the migrations and redo them because of these changes are being used in current app. Is there any way to achieve this? Apologies if the question doesn't seem well explained. -
How to filter by user or all users in same viewset in Django REST framework
I am a beginner in Django REST Framework and I want to ask how I can (and if at all possible) filter listings by user id or return all listings if user id is not set as a query parameter. Also, each user should be able to edit or delete only their own listings, but be able to see the listings of other users if the parameter is_listed=true. Here is the corresponding code: views.py class ListingViewSet(viewsets.ModelViewSet): """ Viewset for API endpoint that implements CRUD operations for listing(cards for sale). - To perform listing search for all users use base endpoint (api/listing/). - To perform listing search by 'is_listed' use base endpoint with ?is_listed=true/false parameter. - To perform listing search for specific user use base endpoint with ?user_id=<user_id> parameter. - To perform PUT or PATCH use base endpoint with /<listing_id> parameter. """ queryset = Listing.objects.all().order_by('id') serializer_class = ListingSerializer permission_classes = [permissions.IsAuthenticated] filter_backends = [DjangoFilterBackend] filterset_class = ListingFilter def get_queryset(self): user = self.request.query_params.get('user_id', None) if user: if [IsOwner()]: return self.queryset.filter(user=user) return self.queryset def perform_create(self, serializer): serializer.save(user=self.request.user) urls.py urlpatterns = [ path('', views.ListingViewSet.as_view({'get': 'list', 'post': 'create'}), name='listing'), path('<int:pk>/', views.ListingViewSet.as_view( {'get': 'retrieve', 'put': 'update', 'delete': 'destroy', 'patch': 'partial_update'}), name='listing_detail'), ] serializers.py class ListingSerializer(serializers.ModelSerializer): card_name … -
Django existing db records not found in testcase when using postgresql
ubuntu 22.04, mysql 8.0.35, postgresql 16.1, python 3.8.18, django 4.2 django default db = "mydb" We have a large data set saved in "mydb", generating that takes a long time. While using mysql db, I was able to fetch items from "mydb" like <ModelName>.objects.filter() in my test cases. I'm unsure if records are copied into "test_" db from "mybd" by django. Then I switched to postgres, recreated the data. When I fetch the data in APiView, it's working fine. But in testcases all model queries return blank queryset. Is there a workaround for testcases while using postgres so I would not have to recreate the data every time I run the tests ? Thanks. -
I am building Django Web Application .I am using rest-framework but i am so confused How to intregate django rest-framework with frontend
Like this method i am getting the data but how will i render the data in html file `@api_view(['POST']) @authentication_classes([JWTAuthentication]) @permission_classes([IsAuthenticated]) def homeapi(request): try: data = json.loads(request.body.decode('utf-8')) print(data) # Dummy student data (replace this with your logic to fetch real data from a database) dummy_students = [ {'id': 1, 'name': 'Alice', 'age': 20, 'grade': 'A'}, {'id': 2, 'name': 'Bob', 'age': 22, 'grade': 'B'}, {'id': 3, 'name': 'Charlie', 'age': 21, 'grade': 'C'}, # Add more students as needed ] # Return student details as JSON response return JsonResponse({'students': dummy_students}) except Exception as e: return JsonResponse({'error': str(e)}, status=400)` I am expecting that first i am requesting the data from an API after getting the data i want to show it to the user how will i do that. -
NoReverseMatch at in django
I am making an online quiz site using bootstrap and django. I want to make a system where the admin enters an OTP value that acts as password of every user(I haven't yet made the admin part hence using a constant int value for development purposes only). I have made a form but it is throwing me an error saying : NoReverseMatch at /class10.html/testlanding.html/ Reverse for 'validating_user' not found. 'validating_user' is not a valid view function or pattern name. the following is the files : url.py : from django.urls import path from . import views from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns =[ path("", views.homepage, name = "home page"), path ("class10.html/" , views.class10 , name = "Class 10th"), path ("class12.html/", views.class12, name ="class 12"), path ("class10.html/testlanding.html/", views.validating_users, name ="pre test info"), path ("class12.html/testlanding.html/", views.validating_users, name ="pre test info"), path ("class10.html/testlanding.html/testinstruction.html/", views.test_instruction, name ="pre test info"), path ("class12.html/testlanding.html/testinstruction.html/", views.test_instruction, name ="pre test info"), ] views.py from django.shortcuts import render, redirect from django.http import HttpResponse , HttpResponseRedirect from .forms import login_form # Create your views here. def homepage(response): return render (response,"main/index.html",{}) def class10 (response): return render (response, "main/class10.html", {}) def class12 (response): return render (response, "main/class12.html", {}) def validating_users (response): if response.method == "POST": … -
Import errors after upgrading django
After updating Django to version 4.2, I'm having several import issues, for example: "ImportError: cannot import name 'ugettext' from 'django.utils.translation'". All the errors point to the configuration of my virtual environment, which is build using Poetry. I have already cleared the cache and deleted the local directory (Cache). Everything (Django, Python, etc.) is in new versions and are compatible. -
I want user to be able to book for the same table but not at the same time
I have a model caled BookTable and a model Table, i want users to be able to book for the same table but not at the same time but i have no clue how am i going to make it. My BookingTable model... class BookingTable(models.Model): TIME_CHOICES =[ ('08:00', '08:00'), ('09:00', '09:00'), ('10:00', '10:00'), ('11:00', '11:00'), ('12:00', '12:00'), ('13:00', '13:00'), ('14:00', '14:00'), ('15:00', '15:00'), ('16:00', '16:00'), ('17:00', '17:00'), ('18:00', '18:00'), ('19:00', '19:00'), ('20:00', '20:00'), ('21:00', '21:00'), ] table = models.ForeignKey(Table, on_delete=models.CASCADE) user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) time = models.TimeField(default='00:00', choices=TIME_CHOICES) def get_absolute_url(self): return reverse("list_tables") def __str__(self) -> str: return self.user.username + "-" + self.table.name My Table model... class Table(models.Model): name = models.CharField(max_length=100, unique=True) size = models.PositiveIntegerField() image = models.ImageField(upload_to='static/media/images/', default='static/media/images/default.jfif') description = models.TextField(null=False, blank=False, default="This is a very beatiful table") def __str__(self) -> str: return self.name[:50] def get_absolute_url(self): return reverse("list_tables") I don't know where to start from -
Django returning status code 400 with error message from test
I'm trying to run tests from my DJango app, but I'm getting FAIL: test_login (authentication.tests.AuthTestCase) line 32, in test_login self.assertEqual(response.status_code, 200) AssertionError: 400 != 200 This is the code of my test: def test_login(self): data = {'usuario_email': 'voter1', 'password1': '123'} response = self.client.post('/authentication/login/', data, format='json') self.assertEqual(response.status_code, 200) message = response.json().get('message') self.assertEqual(message, 'Autentificación correcta') And this is the code for login: def user_login(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): cd = form.cleaned_data usuario_email = cd.get('usuario_email') password1 = cd.get('password1') user = None if usuario_email and '@' in usuario_email: # Si es un correo electrónico, busca por email user = User.objects.filter(email=usuario_email).first() else: # Si no es un correo, busca por nombre de usuario user = User.objects.filter(username=usuario_email).first() if user is not None: user = authenticate(username=user.username, password=password1) if user is not None and user.is_active: login(request, user) print("Usuario logueado correctamente") return JsonResponse({'message': 'Autentificacion correcta'}) else: return JsonResponse({'message': 'Cuenta desactivada o credenciales inválidas'}) else: return JsonResponse({'message': 'Inicio de sesión inválido'}) return JsonResponse({'error': 'Solicitud incorrecta'}, status=400) I have tried manually to login, and I get {"message": "Autentificacion correcta"} The URL I use for login is http://127.0.0.1:8000/login-form and the URL to make the POST action: http://127.0.0.1:8000/authentication/login/ I have tried to debug the test but I always … -
How connect fromm locally and run make migrations in postgresql docker service?
I am building django aplication and use docker to easy manage this. My docker file for django is : FROM python:3.11 WORKDIR /app ENV PYTHONUNBUFFERED 1 ENV DJANGO_SETTINGS_MODULE=server.settings COPY requirements/prod.txt requirements/prod.txt RUN pip install --no-cache-dir -r requirements/prod.txt COPY . . # Expose the port EXPOSE 8000 # RUN python3 manage.py makemigrations # RUN python3 manage.py migrate # Run the Django application CMD ["python3", "manage.py", "runserver", "0.0.0.0:8000"] and also docker-compose for postgres is: db: image: postgres:13 container_name: auralab-db environment: POSTGRES_DB: auralab POSTGRES_USER: admin POSTGRES_PASSWORD: admin ports: - "5432:5432" and it is my django settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'auralab', 'USER': 'admin', 'PASSWORD': 'admin', 'HOST': 'db', 'PORT': '5432', } } problem is to add make migrations in django dockerfile doesnt works, need connect and define connection for this. Actual error is then i have to access databse it has error: ProgrammingError at /api/learning/syllabus/ relation "learning_syllabus" does not exist LINE 1: ...abus"."results", "learning_syllabus"."hours" FROM "learning_... ^ -
Problem with Python suddenly goes Internal error in Azure
I'm pretty new in Python I only worked with it 3 months and I must take care with this implantation in my current job. The thing is the Django Web App inside Azure suddenly throws Internal Error Monday the Web App was working without problem, yesterday suddenly stopped working and throws Internal Error . The log is the next one. 2023-12-13T10:00:49.303444248Z: [ERROR] [2023-12-13 10:00:49 +0000] [108] [ERROR] Error handling request / 2023-12-13T10:00:49.303502748Z: [ERROR] Traceback (most recent call last): 2023-12-13T10:00:49.303508848Z: [ERROR] File "/tmp/8dbfb32227fe2fb/antenv/lib/python3.9/site-packages/gunicorn/workers/sync.py", line 135, in handle 2023-12-13T10:00:49.303512948Z: [ERROR] self.handle_request(listener, req, client, addr) 2023-12-13T10:00:49.303516548Z: [ERROR] File "/tmp/8dbfb32227fe2fb/antenv/lib/python3.9/site-packages/gunicorn/workers/sync.py", line 178, in handle_request 2023-12-13T10:00:49.303520448Z: [ERROR] respiter = self.wsgi(environ, resp.start_response) 2023-12-13T10:00:49.303523948Z: [ERROR] File "/tmp/8dbfb32227fe2fb/antenv/lib/python3.9/site-packages/django/core/handlers/wsgi.py", line 124, in __call__ 2023-12-13T10:00:49.303527548Z: [ERROR] response = self.get_response(request) 2023-12-13T10:00:49.303530848Z: [ERROR] File "/tmp/8dbfb32227fe2fb/antenv/lib/python3.9/site-packages/django/core/handlers/base.py", line 139, in get_response 2023-12-13T10:00:49.303534548Z: [ERROR] set_urlconf(settings.ROOT_URLCONF) 2023-12-13T10:00:49.303537748Z: [ERROR] File "/tmp/8dbfb32227fe2fb/antenv/lib/python3.9/site-packages/django/conf/__init__.py", line 104, in __getattr__ 2023-12-13T10:00:49.303541248Z: [ERROR] val = getattr(_wrapped, name) 2023-12-13T10:00:49.303544547Z: [ERROR] File "/tmp/8dbfb32227fe2fb/antenv/lib/python3.9/site-packages/django/conf/__init__.py", line 331, in __getattr__ 2023-12-13T10:00:49.303548047Z: [ERROR] return getattr(self.default_settings, name) 2023-12-13T10:00:49.303551347Z: [ERROR] AttributeError: module 'django.conf.global_settings' has no attribute 'ROOT_URLCONF' I know what it seems... but I double checked all configurations, maybe is something that I'm missing... This is a snippet from settings.py I can't share publicly the entire file but the folder hierarchy … -
Problem with Error 502 when run app on server
I am beginner in Python and Django. I have his code: def force_resend(self): # without this code app run ok url = settings.PAYMENT_GATEWAY_URL + "payments/" + self.secretkey+ "/" + settings.PAYMENT_POS_ID + "/resend/" req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'}) ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE data = urllib.request.urlopen(req,context=ctx) contents = data.read().decode('utf-8') contents = '{"status": "OK", "payments_accepted": 1, "payments_count": 1, "payments_declined": 0}' data = json.loads(contents) return data I try this code too: def force_resend_transaction(self): h = httplib2.Http(disable_ssl_certificate_validation=True) resp, content = h.request(settings.PAYMENT_GATEWAY_URL + "payments/" + self.secretkey+ "/" + settings.PAYMENT_POS_ID + "/resend/") # # content = '{"status": "OK", "payments_accepted": 1, "payments_count": 1, "payments_declined": 0}' c = json.loads(content) return data When I run this code on my local PC - it's work without any problems. When i try run this in my Kubernetes, i have Error 500. Other functions in my app work correctly. Problem is only with this method. How can i fix them? I use Python 3.8 Please help me :) -
Creating an object of a class whose field is a set of objects of another class
In the Django model lets create a class, eg Ingredients: class IngredientsClass(models.Model): name = models.CharField('Name', max_length=50, default='') package_price = models.FloatField() package_amount = models.FloatField() supplier = models.ForeignKey(SupplierClass) price = models.FloatField() Now lets make some product from the ingredients class DishClass(models.Model): name = models.CharField('Name', max_length=50, default='') price = models.FloatField() ingredients = models.***???*** And here is a problem... In the field ingredients of an DishClass object can be different amount of ingredients from one to thousand. How do I need to set up the field ingredients? -
Deleting items autometically after 15 days of creation from database in django
To achieve this functionality i have used Django Signals, but that is not working in my case, Please let me know if i have done this right, You can also suggest me any other way to achieve this functionality signals.py from django.db.models.signals import pre_delete from django.dispatch import receiver from django.utils import timezone from smart_search.models import UserHitCount @receiver(pre_delete, sender=UserHitCount) def delete_user_hit_count(sender, instance, **kwargs): print("signal handler triggered!") if timezone.now() - instance.created_at > timezone.timedelta(minutes=1): instance.user.delete() app.py from django.apps import AppConfig class SmartSearchConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'smart_search' def ready(self): from . import signals init.py default_app_config = 'smart_app.apps.SmartAppConfig' model.py from django.db import models from user_application.models import Registered_user class UserHitCount(models.Model): user = models.OneToOneField(Registered_user, on_delete=models.CASCADE) search_count = models.IntegerField(default=0) question_count = models.IntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True, null=True) My main objective is to delete the things once created date is less then today and this should be done automatically -
i am trying to install django but getting error in path
The script django-admin.exe is installed in 'C:\Users\HP\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\Scripts' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. after running this command :- pip install django how can i fix it -
Automatic field filling based on user information
I want the name field to be filled automatically based on the user's information and the user cannot change it while filling the form. But nothing can be written in the field, nor is it automatically filled, and the form is not sent. It should be noted that without this option, the form works perfectly. models: class Product(models.Model): choice = ( ('d', 'Dark'), ('s', 'Sweet'), ) user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=20) category = models.CharField(max_length=20) seller_price = models.DecimalField(max_digits=10, decimal_places=2) desc = models.TextField() status = models.CharField(max_length=1, choices=choice) image = models.ImageField(upload_to="img/", null=True) image_url = models.CharField(max_length=228, default = None, blank = True, null = True) active_bool=models.BooleanField(default=False) forms: class ProductForm(forms.ModelForm): user = forms.CharField(disabled=True) class Meta: model = Product fields = ['title', 'category', 'seller_price', 'desc', 'status', 'image', 'image_url'] def __init__(self, args, kwargs): super(ProductForm, self).__init__(args, **kwargs) self.fields['user'].initial = kwargs['initial']['user'] views: def create_product(request): form = ProductForm(request.POST, request.FILES) if request.method == 'POST': if form.is_valid(): form.save() return redirect('index') else: form = ProductForm() return render(request, 'auctions/create_product.html', {'form': form}) html: {% block body %} <h2>Create New Product</h2> {% if user.is_authenticated %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> {% else %} Not signed in. {% endif %} {% endblock %} -
Django REST framework and Vue.js "CSRF cookie not set" is occurred
I'm trying to implement the login feature using django and vue.js. But I got an error "CSRF cookie not set" when sending the post request. I checked that I could get the csrftoken correctly by seeing the developer tools. Below is the code of login.vue <template> <div class="hello"> <div class="title-color">This is a Login page.</div> <div class="form-container"> <form v-on:submit.prevent="getCSRF"> <h2>Add User</h2> <div class="form-group"> <label class="label">username</label> <input class="input" type="text" v-model="username" /><br> </div> <div class="form-group"> <label class="label">password</label> <input class="input" type="text" v-model="password" /><br> </div> <button class="button" type="submit">Submit</button> </form> </div> </div> </template> <script> import axios from "axios"; axios.defaults.xsrfHeaderName = 'x-csrftoken' axios.defaults.xsrfCookieName = 'csrftoken' axios.defaults.withCredentials = true; export default { name: "LoginView", props: { msg: String, }, data() { return { username: "", password: "", csrftoken: "", }; }, mounted() { }, methods: { getCSRF() { axios({ method: "get", url: "http://127.0.0.1:8000/csrf/", auth: { username: "cannot show", password: "cannot show", }, }).then((response) => { this.csrftoken = response.headers['x-csrftoken']; console.log("token is ", this.csrftoken); axios({ method: "post", url: "http://127.0.0.1:8000/login/", data: { username: this.username, password: this.password, }, headers: { 'X-Csrftoken': this.csrftoken, }, auth: { username: "Cannot show", password: "Cannnot show", }, }).then((response) => { console.log(response); }) }) }, } }; </script> Below is the views.py def loginView(request): username = request.POST['username'] password … -
is ConnectionClosedByClient exception from pika a problem
I recently upgraded to a newer version of pika and these logs started showing up where they have not been there before: User-initiated close: result=BlockingConnection__OnClosedArgs(connection=<SelectConnection CLOSED transport=None params=<URLParameters host=rabbitmq port=xxxxx virtual_host=xxxxx ssl=False>>, error=ConnectionClosedByClient: (200) 'Normal shutdown') AMQP stack terminated, failed to connect, or aborted: opened=True, error-arg=None; pending-error=ConnectionClosedByClient: (200) 'Normal shutdown' Stack terminated due to ConnectionClosedByClient: (200) 'Normal shutdown' I have looked over my changes but all I was doing before these logs showed up was to upgrade my django project libraries No changes in logic have taken place It is confusing because according to documentation this exception, ConnectionClosedByClient, is raised when "Connection was closed at request of Pika client." which is the normal behaviour? Also it says Normal Shutdown So am i safe to assume this is just a new log that is cluttering my logs and isn't an actual error because all my rabbitMQ and logs are all good and they are behaving properly as well If it is the case that it is just new logs and this exception needs to be handled for it to not appear in logs, any tips on how to do that safely as well