Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is post request data not available in Django app?
I have send a post request from a flutter app using dio in the code below Map<String, String> getData() { return { "firstname": firstname.value, "lastname": lastname.value, "phonenumber": phoneNumber.value, "password": password.value, "accounttype": accounttype.value }; } void signup(context) async { Dio dio = Dio(); final response = await dio.post( 'http://192.168.0.101:8000/signup/', data: getData(), ); debugPrint(response.toString()); } and tried to print it in django from the code below from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt @csrf_exempt def signup(request): if request.method == 'POST': print(request.POST) return HttpResponse('Hello, world!') I get an empty dictionary when it is printed. -
Django - Replace manually-entered primary key with AutoField
The issue I have a model with fields like this: class MyObject(models.Model): id = models.CharField(max_length=200) title = models.CharField(max_length=200, blank=True) [more fields not relevant to issue] I think I made the wrong decision using a manually-entered CharField as my primary key, so I would like to switch to an AutoField as my primary key. Ideally the resulting schema would look like this: class MyObject(models.Model): id = AutoField(primary_key=True) url = models.CharField(max_length=200) # containing the same data id used to contain title = models.CharField(max_length=200, blank=True) [more fields not relevant to issue] However, I am struggling to perform this migration, so I am looking for solutions on how to migrate to the new schema. What I've tried When I make a migration that just renames id to url, any page I try to load gives an error. For example, the admin page gives an error like MyObject has no attribute 'id'. I tried to add an AutoField named autogen_id to the model, and make that the primary key. However, when using the makemigrations command, I got the message It is impossible to add a non-nullable field 'autogen_id' to myobject without specifying a default. This is because the database needs something to populate existing rows. … -
Expenses Tracker Django Web App: Issue with Extract all expenses, sort and aggregate total expenses by month to display as js with chart.js
I am building a expenses tracker web app with django and have issues with the logic to sort and aggregate total expenses by month. The values are derived from a web form where the user enters an expense details which includes its date. From the date field, i want to sort and sum up each months total expenses to output the results as js into bar charts with chart.js. Should i be using .annotate(month=ExtractMonth('date'))? Under models.py: class Expenses(models.Model): amount = models.FloatField() date = models.DateField(default=now) description = models.TextField() owner = models.ForeignKey(to=User, on_delete=models.CASCADE) category = models.CharField(max_length=266) def __str__(self): return self.category class Meta: ordering: ['-date'] Under views.py: def db_expense_summary(request): #extract all expenses for past 6 months date_today = datetime.date.today() date_previous_six_months = date_today - datetime.timedelta(days=30*6) expenses = Expenses.objects.filter(owner=request.user,date__gte=date_previous_six_months,date__lte=date_today) exp_total = {} #dictionary to store each month's expenses def get_month(expense): #extract month values from expenses return expense.date.month month_list = list(set(map(get_month, expenses))) def get_expense_month_total(month): # aggregate expenses amount by month expense_amount=0 filtered_by_month = expenses.annotate(month=ExtractMonth('date')) for item in filtered_by_month: expense_amount += item.amount return expense_amount for expense in expenses: for month in month_list: exp_total[month] = get_expense_month_total(month) return JsonResponse({'expense_month_data': exp_total}, safe=False) The results i got is: {"expense_month_data": {"3": 12450.0, "4": 12450.0, "5": 12450.0}} The individual months show up in … -
Create a copy of the request data for every user UUID in a list
Hello I'm just now learning Django and I'm creating a mini todo/task project, currently I'm trying to create a task app that allow you to assign a bunch of user when you create the task and then it will make a copy of the data for every user in the list of UUID This is more or less my request : { "task" : "Daily meeting", "description" : "Daily meeting with company x", "date": "2023-05-08", "priority":"high", "label" :"group", "asignees" : ["cf0ea929-4775-4e0f-976b-15e7fc7686d7","edf7b114-9b84-433f-b6b3-21b5941bc880"] } this is my User Model: class User(AbstractBaseUser, PermissionsMixin): pkid = models.BigAutoField(primary_key=True, editable=False) id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) email = models.EmailField(verbose_name="Email", db_index=True, unique=True) username = models.CharField( verbose_name="Username", default="Employee", max_length=225 ) is_staff = models.BooleanField(default=False) is_team_lead = models.BooleanField(default=False) is_active = models.BooleanField(default=True) updated_at = models.DateTimeField(auto_now=True) date_joined = models.DateTimeField(default=timezone.now) USERNAME_FIELD = "email" REQUIRED_FIELDS = ["username", "password"] objects = CustomUserManager() class Meta: verbose_name = _("user") verbose_name_plural = _("users") db_table = "account_user" this is my Activity Model : class Activity(TimeStampedUUIDModel): class Priority(models.TextChoices): LOW = "low", _("low") MEDIUM = "medium", _("medium") HIGH = "high", _("high") date = models.DateField(verbose_name=_("tanggal"), default=date.today()) time = models.TimeField( verbose_name=_("waktu"), default=datetime.now().strftime("%H:%M:%S") ) task = models.CharField(verbose_name=_("judul"), max_length=225) description = models.TextField(verbose_name=_("deskripsi")) priority = models.CharField( verbose_name=_("priority"), choices=Priority.choices, default=Priority.MEDIUM, max_length=15, ) class labels(models.TextChoices): PERSONAL = "personal", _("personal") … -
Django `ImageField.file.read()` raises `bytes` object has no attribute `read`
This is the model I'm using: from django import models class Image(models.Model): file = models.ImageField(upload_to='uploads/images/') Now, if I do image.file.read() I get AttributeError: 'bytes' object has no attribute 'read' >>> from images.models import Image >>> img = Image.objects.first() >>> img.file.read() Traceback (most recent call last): File "<console>", line 1, in <module> File "...\.venv\lib\site-packages\django\core\files\utils.py", line 42, in <lambda> read = property(lambda self: self.file.read) File "...\.venv\lib\site-packages\django\core\files\utils.py", line 42, in <lambda> read = property(lambda self: self.file.read) AttributeError: 'bytes' object has no attribute 'read' image.file.file returns a bytes object and not a File object. I'm using Django 4.2.1 with python 3.10.7. The following piece of code solves it, but is not a viable workaround. import io from images.models import Image img = Image.objects.first() img.file.file.file = io.BytesIO(img.file.file.file) img.file.read() # Runs without errors I believe that image.file.file.file should be a File object but it is returning a bytes object instead. Is there something I'm missing? -
Why pop password2 in cleaned_data when form.is_valid() called?
I use custom usercreationform in my django forms. from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1','password2'] def clean(self): cd = super().clean() if cd['password2'] != cd['password1']: raise forms.ValidationError("Not match!") return cd first form = UserRegisterForm(request.POST or None) when form.is_valid() called and error occur just return (username,email,password1) -
Is it safe to keep using django web app on local server and how safe is my data if I do it that
This might seem like a stupid question, but is it okay to keep using a django based web app on localhost. The abstract is that I made a accounting web app that I would like to use for my daily business transactions, I don't want to deploy the web app on internet. Is it okay to keep using it on local server with sqlite3 or is there another method of achieving the same? -
Unique together and sending null with nested serializer cause constranit error
I'm having an issue with making both of those two work... Did I miss something? I'm sending Json to my post(creating comment): { "content":"message", "myuser":{ "username":"ztestz", "source":"test", "email":null} } Which answers to unique_together fields for this model: class MyUser(models.Model): username = CharField(max_length=50, null=True, blank=True) source = CharField(max_length=50, default='discord') email = EmailField(null=True, blank=True) class Meta: unique_together = (('username', 'source',),('email', 'source',)) My nested serializer contains given create: class CommentSerializer(serializers.HyperlinkedModelSerializer): myuser = MyUserSerializer() def create(self, validated_data): myuser_data = validated_data.pop('myuser') print(validated_data) # myuser = MyUser.objects.filter( # Q(name=validated_data['username'], source=validated_data['source']) | Q(name=validated_data['email'], source=validated_data['source'])) # print(myuser) myuser = MyUser.objects.get_or_create(**myuser_data) print(myuser) # myuser = MyUser.objects.get_or_create(myuser, defaults={'source': validated_data['source'], 'username': validated_data['username'], 'email': validated_data['email']}) comment = Comment.objects.create(user_related=myuser[0], **validated_data) return comment For unknown to me reason, get_or_create returns constraint invalidation, even through the item definitely exists: { "myuser": { "non_field_errors": [ "The fields username, source must make a unique set." ] } } Could anyone explain to me, what is happening in here? Is there some kind of requirement for nested serializers to work with unique_together, or get_or_create to contain certain data? The data in **validated_data contains all the fields that would be included in default... -
django weird migration issue - ProgrammingError: column does not exist - seemingly only within Celery?
I have a django app a docker-compose setup, also using celery. I am receiving an error relating to a model field that I recently deleted. I only noticed there was an issue when calling a certain function within a celery task. Some notes: I've confirmed the column no longer exists in the db I have ran makemigrations and migrate, django says everything is all good The only place the field is referenced in my project is in migration files The error I am receiving: celery | The above exception was the direct cause of the following exception: celery | celery | Traceback (most recent call last): celery | File "/usr/local/lib/python3.9/site-packages/celery/app/trace.py", line 451, in trace_task celery | R = retval = fun(*args, **kwargs) celery | File "/usr/local/lib/python3.9/site-packages/celery/app/trace.py", line 734, in __protected_call__ celery | return self.run(*args, **kwargs) celery | File "/code/src/leads/tasks.py", line 71, in try_to_sell_lead celery | results = lead.get_contracts_qualified_for_in_sell_order(to_contract_ids, ignore_contract_filters, celery | File "/code/src/leads/models.py", line 339, in get_contracts_qualified_for_in_sell_order celery | elif not contract.has_enough_credit(): celery | File "/code/src/contracts/models.py", line 261, in has_enough_credit celery | for batch in batches: celery | File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 398, in __iter__ celery | self._fetch_all() celery | File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 1881, in _fetch_all celery | self._result_cache = list(self._iterable_class(self)) … -
Can't Get Braintree Dropin UI To Show
I am trying to display braintree's dropin ui in my code but so far only have a purchase button that does nothing. <div id="dropin-container"></div> <button id="submit-button" class="btn btn-primary btn-block">Purchase</button> <script> var button = document.querySelector('#submit-button') var braintree_client_token = "{{braintree_client_token|safe}}" braintree.dropin.create({ authorization: braintree_client_token, container: '#dropin-container' }, function (createErr, instance) { button.addEventListener('click', function () { instance.requestPaymentMethod(function (err, payload) { // Submit payload.nonce to your server }); }); }); </script> I have gone through the braintree docs and tried countless examples but still haven't been able to get this to work. I am developing this on django. Any help will be greatly appreciated. -
Whats the best way of accessing django database with python script?
I have a django project which is made for running a website. I want to have a python script that is going to read django database and insert new data. Whats the best way of doing that? I assume that if I would just regulary connect to the database (using sqlite library for example) it might cause some conflicts because django app and my script are accessing same database at the same time. -
how to combine 2 models to realize permissions system
I am designing pet project for communities news system. I have this models: User, Group, Post, Like. I want to allow each User to Like posts. In addition to this some Users can be managers of Groups (like manyToMany relation), so they will be able to edit Group information and create Posts from Group name. But one of this "group managers" will have role "shef", and will be able to add/remove managers from his group. "shef" can be added just in Django Admin. What is the best way to design User <-> Group relation? I thought about Group having manyToMany to User (managers) and foreignKey to "shef", will it be optimal solution? How should I design the project to follow best practices, or should I use 3rd party libraries like django-guardians in this situation? -
getaddrinfo failed in django using librouteros to connect to RB Mikrotik
Im try create dashboard using django to connect my RB Microtik, but i'm not getting. this is the erro info: [Errno 11001] getaddrinfo failed Request Method: GET Request URL: http://127.0.0.1:8000/mkqueue/list/ Django Version: 4.2.1 Exception Type: gaierror Exception Value: [Errno 11001] getaddrinfo failed Exception Location: C:\Python311\Lib\socket.py, line 962, in getaddrinfo Raised during: mkqueue.views.queue_list and this is my code: from django.shortcuts import render # Create your views here. import librouteros def queue_list(request): conn = librouteros.connect( host='8.8.8.8:8888', username='admin', password='pass', timeout=30, ) queues = conn(cmd='/queue/simple/print') return render(request, 'queue_list.html', {'queues': queues}) I already tried to put the port separate from the host. Any idea to fix this ? thanks. -
Need Assistance to Correct Inaccurate Activity Diagram for my project "Blood Bank Management System'
I want to make Activity Diagram for my project file but I am not sure are they correct or not. Every time some mistake comes out and honestly, only today I got to know what actually is a activity diagram , UML Plant code and stuff that's why I'm not sure that the diagram is Actually correct or not. I'm providing both my Plant UML code and project link. Please take a look to both of them and correct me where I'm doing wrong so that I can make a correct activity diagram. Link of Project and the code of my Activity Diagram start :Login; if (Login successful?) then (yes) if (User is Admin?) then (yes) :Show Admin Dashboard; :See blood stock, donor and request numbers on Dashboard; :View, update, or delete donor; :View donation requests; if (Request approved?) then (yes) :Add unit of blood to stock; else (no) :Do not add any unit of blood to stock; endif :View blood requests; if (Request approved?) then (yes) :Reduce unit of blood from stock; else (no) :Do not reduce any unit of blood from stock; endif :See blood request history; :Update unit of particular blood group; else (User is Donor) :Show … -
Django module not found error: email verification
I'm new to python and Django so sorry in advance if I'm missing something obvious. I'm trying to install the module 'django-email-verification' following this tutorial to add email verification to my users. I've already done the pip install while on my virtual enviroment, and tried adding it to INSTALLED_APPS in settings, but still getting error. Here is an image of the error I'm getting I have tried pip install django-email-verification==0.0.4, pip install django-email-verification pip3 install django-email-verification And in settings with 'django-email-verification', 'django_email_verification', It says it's already installed, but still no module named like it. Am I missing something? -
Django allauth Google login problems
Im trying to use google login for a project i need to make, tried to find something similar but could not find it. The problem is when i try to log in with google it redirects me to http://127.0.0.1:8000/accounts/google/login/ and does not show me the box to choose with which account i want to sign in. Im using a custom user, and forms. settings.py INSTALLED_APPS = [ 'WebFinalExam.base', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.request', ], }, }, ] AUTH_USER_MODEL = 'base.AppUser' LOGIN_URL = reverse_lazy('sign-in') LOGIN_REDIRECT_URL = reverse_lazy('index') LOGOUT_REDIRECT_URL = reverse_lazy('index') AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ] SITE_ID = 1 SOCIALACCOUNT_PROVIDERS = { 'google': { 'SCOPE': [ 'profile', 'email', ], 'AUTH_PARAMS': { 'access_type': 'online', }, 'OAUTH_PKCE_ENABLED': True, } } ACCOUNT_FORMS = { 'login': 'WebFinalExam.base.forms.SignInForm', 'signup': 'WebFinalExam.base.forms.RegisterForm' } ACCOUNT_USER_MODEL_USERNAME_FIELD = 'email' ACCOUNT_LOGOUT_REDIRECT_URL = 'account_login' project urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('WebFinalExam.base.urls')), path('forum/', include('WebFinalExam.forum.urls')), path('accounts/', include('allauth.urls')), ] app urls.py urlpatterns = [ path('', views.HomePage.as_view(), name='index'), path('sign-up/', views.SignUp.as_view(), name='sign-up'), path('sign-in/', views.SignIn.as_view(), name='sign-in'), path('sign-out/', views.SignOut.as_view(), name='sign-out'), ] models.py class AppUser(auth_models.AbstractBaseUser, auth_models.PermissionsMixin): email = models.EmailField( unique=True, null=False, blank=False ) is_staff = models.BooleanField( … -
TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block
This is my models.py file class Tag(models.Model): name = models.CharField(max_length=31, unique=True) slug = models.SlugField(max_length=31, unique=True, help_text = 'A label for URL config') class Meta: ordering = ['name'] def __str__(self): return self.name.title() def get_absolute_url(self): return reverse('organizer_tag_detail', kwargs={'slug': self.slug}) def get_update_url(self): return reverse('organizer_tag_update', kwargs={'slug' : self.slug}) def get_delete_url(self): return reverse('organizer_tag_delete', kwargs={'slug':self.slug}) class StartUp(models.Model): name = models.CharField(max_length=31, db_index=True) slug = models.SlugField(max_length=31,unique=True, help_text='A label for URL config') description = models.TextField() founded_date = models.DateField() contact = models.EmailField('date founded') website = models.URLField() tags = models.ManyToManyField(Tag, blank=True) class Meta: ordering = ['name'] get_latest_by = 'founded_date' def __str__(self): return self.name def get_absolute_url(self): return reverse('organizer_startup_detail', kwargs={'slug':self.slug }) def get_update_url(self): return reverse('organizer_startup_update', kwargs={'slug': self.slug}) def get_delete_url(self): return reverse('organizer_startup_delete', kwargs={'slug': self.slug}) class NewsLink(models.Model): title = models.CharField(max_length=63) slug = models.SlugField(max_length=63) pub_date = models.DateField('date published') link = models.URLField(max_length=255) startup = models.ForeignKey(StartUp, on_delete=models.CASCADE) class Meta: verbose_name ='news article' ordering = ['-pub_date'] get_latest_by = 'pub_date' unique_together = ('slug', 'startup') def __str__(self): return "{} : {}" .format( self.startup, self.title ) def get_absolute_url(self): return self.startup.get_absolute_url() def get_update_url(self): return reverse('organizer_newslink_update', kwargs={'pk':self.pk}) def get_delete_url(self): return reverse('organizer_newslink_delete', kwargs={'pk':self.pk}) Here is my 0005_newslink_data migration file from django.db import migrations, models from datetime import date NEWSLINKS = [ { "title" :"Redundant Homepage Link", "link": "http://jambonsw.com", "pub_date" : date(2013,1, 18), "startup" : "jambon-software", … -
Django Docker allauth Cannot assign requested address
First things first, I have gone through the similar questions but none of them worked out for me (I might have missed something though). I building an app using: Django = 4.0.4 allauth Postgres Docker docker-compose.yml Docker FROM python:3.10.4-slim-bullseye # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /code # Install dependencies COPY ./requirements.txt . RUN pip install -r requirements.txt # Copy project COPY . . docker-compose.yml version: '3.9' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 - 587:587 depends_on: - db environment: - DJANGO_SECRET_KEY=blablabla - DJANGO_DEBUG=True - POSTGRES_NAME=blablabla - POSTGRES_USER=blablabla - POSTGRES_PASSWORD=blablabla db: image: postgres:13 volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_HOST_AUTH_METHOD=trust - POSTGRES_DB=blablabla - POSTGRES_USER=blablabla - POSTGRES_PASSWORD=blablabla volumes: postgres_data: Django settings.py related to email backend (a bit more) DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" AUTH_USER_MODEL = "accounts.CustomUser" # django-crispy-forms CRISPY_ALLOWED_TEMPLATE_PACKS = "bootstrap5" CRISPY_TEMPLATE_PACK = "bootstrap5" # django-allauth config LOGIN_REDIRECT_URL = "home" ACCOUNT_LOGOUT_REDIRECT = "home" SITE_ID = 1 AUTHENTICATION_BACKENDS = ( "django.contrib.auth.backends.ModelBackend", "allauth.account.auth_backends.AuthenticationBackend", ) EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" ACCOUNT_SESSION_REMEMBER = True ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = False ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = "email" ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True DEFAULT_FROM_EMAIL = "admin@admin.com" EMAIL_HOST = 'localhost' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'mail' … -
How solve this RuntimeError in django
[enter image description here](https://i.stack.imgur.com/CIiro.jpg) enter image description here I'm learning Django with Web Development with Django. In chapter 4 of the book... The author wants to Customize admin I do according to the book... But Django give that RuntimeError . What's the solution? -
Django not displaying images which are in media folder?
In my django project I just want to plot some image which are there in my media folder. Eventhough the path I am seding to my frontend exists and I have verified multiple times if the path is correct. The images wont display and the error is Not Found: /home/harish/Desktop/project/visual/media/section_1_2.png [07/May/2023 16:15:52] "GET /home/harish/Desktop/project/visual/media/section_1_2.png HTTP/1.1" 404 2490 I have checked this same path with os.path.exists() and I get True as output but for some reason the images wont get displayed in the front end SETTINGS.PY MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' STATUSFILES_DIRS = ( os.path.join(BASE_DIR, 'static') ) URLS.PY urlpatterns = [ path('admin/', admin.site.urls), path('', views.get_logfile_path, name = "input_log_file"), path('output/', views.graphs, name= 'graphs') ] output/ is where I am displaying the images VIEWS.py for image in sec_1_image_names: sec_1_image_paths.append(os.path.join(output_plots,image)) # Sample outputpf sec_1_image_paths # ['/home/harish/Desktop/project/visual/media/section_1_4.png'] return render(request, 'output.html', {'image_urls':sec_1_image_paths}) OUTPUT.HTML <!DOCTYPE html> <html> <head> <title>Image View</title> </head> <body> <h1>Images:</h1> {% for url in image_urls %} <img src="{{ url }}" /> {% endfor %} </body> </html> ERROR "GET /home/harish/Desktop/project/visual/media/section_1_1.pn HTTP/1.1" 404 2490 -
Add a field for manual input when a radio button is checked and update database with django
I want to update the database from frontend using a form in django. The model I created is (I include only the relevant part to be more clear): class Stoixeia_pelati(models.Model): tainies_name = models.CharField(max_length=20, blank=True, null=True) Because I want to make a radio button selection on the frontend, I made a forms.py file. But I want when someone clicks other to open a new field where someone can write a value: class Stoixeia_pelatiForm(ModelForm): CHOICES = [ ('Choice1', 'Choice1'), ('Choice2', 'Choice2'), ('other', 'other'), ] tainies_name = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect) class Meta: model = Stoixeia_pelati fields = ['name', 'tainies_name', 'skarfistires_name', 'belones_name'] In html I render the form: <form class="form" method="POST"> {% csrf_token %} <div class="form__field"> <label for="formInput#text">{{field.label}}</label> {{form.tainies_name}} </div> <input type="submit"> <form> In my views I added: form = Stoixeia_pelatiForm(instance=pelatis) if request.method == 'POST': form = Stoixeia_pelatiForm(request.POST, instance=pelatis) if form.is_valid(): form.save() return redirect(reverse('pelatis_krini', args=[pelatis_slug])) context = { 'pelatis':pelatis, 'syntages':syntages, 'form':form, } The selection is being submited and it works fine. My problem is that I don't know how to make a new field appear when someone clicks "othr" and then submit the value to the database and update "tainies_name" to the manually inputted value. -
How do I include a csrf token on a post request from a flutter app using dio to a django backend?
I am trying to send a post request to a django backend from a flutter app using dio, how do I get and include the csrf token in the request. Chatgpt suggested me to use a get request to get the csrf from the backend and include it in the post request. Is it the correct practice? -
how to create REST API system in Django which use a load balancer and messaging bus queue
Design a distributed banking REST API system that consists of a load balancer and two banking servers. The load balancer should direct read-only API requests to one of the banking servers, while transactional API requests should be sent to a message bus queuing system, which will distribute them to both banking servers. For example, bank account balance queries should be sent to one of the banking servers by the load balancer, while account creation, credit, and debit transactions should be sent to both banking servers by the load balancer via the message bus system. Can you write a prototype of this program using REST API and a message bus system? If you were to use either Django or Flask, how would you approach this problem? Does creating 2 different Django projects mean having 2 servers? -
мне нужно чтобы через urls удалялся api данные
enter image description here in the photo, you need to delete data from the api I tried everything but I got errors -
I want to search between multiple fields but i got this error
I want to search a query between 3 models that have some fields in common but i got this error Cannot resolve keyword '' into field. Choices are: actors, baner, comments, content_rating, country_of_origin, creators, description, ending_date, genre, id, name, pictures, ratings, release_date, seasons, slug, storyline, videos, watchlist This is my code: def search_content(query: str) -> QuerySet|None : if query: search_query = SearchQuery(query, search_type="websearch") search_vector = SearchVector('name', weight='A') + SearchVector('description', weight='B') qs = (Show.objects.annotate(search=search_vector, rank=SearchRank(search_vector, search_query)) .union(Movie.objects.annotate(search=search_vector, rank=SearchRank(search_vector, search_query))) .union(Episode.objects.annotate(search=search_vector, rank=SearchRank(search_vector, search_query))) .order_by('-rank') .values('id', 'name', 'baner', 'release_date')) return qs else: return None class SearchView(APIView): def get(self, request): query = request.GET.get("q", "") if query: object_list = search_content(query) data = { "query": query, "result": SearchContentserializer(object_list, many=True).data } return Response(data) return Response()