Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Thumbnail of Videos not loading on Server | Django
I am fairly new to Django and currently I'm making a Youtube Clone to understand Django in depth. So the problem I'm facing right now is that I can't seem to get the thumbnail to appear in homepage when I run the server. I've spent a lot of time trying but can't seem to find an answer! I'll provide what I think relates to my problem; 1) Templates homeview.html: `{% block body %} {% for video in most_recent_video %} <div class="video-card"> <img src="/get_thumbnail/{{ video.thumbnail.path }}" alt="{{ video.title }} thumbnail"> <h5>{{ video.title }}</h5> <p>Uploaded By {{ video.user }} on {{ video.datetime }}</p> <p>{{ video.description }}</p> <p><a href="/video/{{ video.id }}">Watch Video</a></p> </div> {% endfor %} {% endblock %}` thumbnail.html: `{% block body %} <div class="header-bar"> <h2>Thumbnail View</h2> <hr> </div> <div class="main-body"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <table> {{ form.as_p }} </table> <button type="submit">Upload Thumbnail</button> </form> {% if errors %} <div class="errors"> <h3>Errors:</h3> <ul> {% for field_errors in errors.values %} {% for error in field_errors %} <li>{{ error }}</li> {% endfor %} {% endfor %} </ul> </div> {% endif %} </div> {% endblock %}` 2) views.py `class ThumbnailView(View): template_name = 'base/thumbnail.html' def get(self, request): if not request.user.is_authenticated: return HttpResponseRedirect('/login/') form = ThumbNailForm() … -
Exception Type : ValueError with The 'image' attribute has no file associated with it in Django
Geting error ValueError at / The 'image' attribute has no file associated with it. when I try to post a image from a user not having admin access then i am getting this error and the picture doesnot display. index.html <div class="container m-auto"> <!--<h1 class="lg:text-2xl text-lg font-extrabold leading-none text-gray-900 tracking-tight mb-5"> Feed </h1>---> <div class="lg:flex justify-center lg:space-x-10 lg:space-y-0 space-y-5"> <!-- left sidebar--> <div class="space-y-5 flex-shrink-0 lg:w-7/12"> <!-- post 1--> {% for post in posts reversed %} <div class="bg-white shadow rounded-md -mx-2 lg:mx-0"> <!-- post header--> <div class="flex justify-between items-center px-4 py-3"> <div class="flex flex-1 items-center space-x-4"> <!-- <a href="#"> <div class="bg-gradient-to-tr from-yellow-600 to-pink-600 p-0.5 rounded-full"> <img src="{% static 'assets/images/avatars/avatar-2.jpg' %}" class="bg-gray-200 border border-white rounded-full w-8 h-8"> </div> </a> --> <span class="block capitalize font-semibold "> {{post.user}} </span> </div> <div> <a href="#"> <i class="icon-feather-more-horizontal text-2xl hover:bg-gray-200 rounded-full p-2 transition -mr-1 "></i> </a> <div class="bg-white w-56 shadow-md mx-auto p-2 mt-12 rounded-md text-gray-500 hidden text-base border border-gray-100 " uk-drop="mode: hover;pos: top-right"> <ul class="space-y-1"> <!-- <li> <a href="#" class="flex items-center px-3 py-2 hover:bg-gray-200 hover:text-gray-800 rounded-md "> <i class="uil-share-alt mr-1"></i> Share </a> </li> <li> <a href="#" class="flex items-center px-3 py-2 hover:bg-gray-200 hover:text-gray-800 rounded-md "> <i class="uil-edit-alt mr-1"></i> Edit Post </a> </li> <li> <a href="#" class="flex items-center … -
How to prevent datatable search and pagination rows from repeating when pressing previous or forward buttons?
I am experiencing an issue with JQuery Datatables. Indeed, I am working on a django and Htmx project that has a base template. Inside of it, I initialize datatables like this: $(document).ready(function() { $('#datatable').DataTable({ }); }) Now, given that I am using HTMX, I have a #main-content id on an html element where I replace the content that is returned when Htmx issues an Hx-get request. Each time a request is made, I have to reinitialize the table in the returned template inside a <script><script/> tag using the same code as above and everything works perfectly fine. However, when I press the previous or next browser buttons, the datatable search and pagination rows get repetead multiple times, when there is data in my table, but it doesn't when there is no data. Thank you for helping me. I've tried to destroy the table using the destroy() method inn Javascript, but I still had the same issue. -
Django - Insert data into child table once the parent record is created
I am using Django REST Framework and facing a problem during inserting data into the child table. There are 2 models named Card and ContactName that have the following fields. The Card has a relation with ContactName via a foreign key field name card. models.py: class Card(models.Model): image = models.ImageField(upload_to='images', max_length=255, null=True, blank=True) filename = models.CharField(max_length=255, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.filename class ContactName(models.Model): first_name = models.CharField(max_length=255, null=True, blank=True) last_name = models.CharField(max_length=255, null=True, blank=True) confidence = models.FloatField(default=0) card = models.ForeignKey(Card, on_delete=models.CASCADE, related_name='contact_name') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.first_name My serializers.py file: class ContactNameSerializer(serializers.ModelSerializer): class Meta: model = ContactName fields = ['id', 'first_name', 'last_name', 'confidence', 'card', 'created_at', 'updated_at'] class CardSerializer(serializers.ModelSerializer): contact_name = ContactNameSerializer(many=True, read_only=True) class Meta: model = Card fields = ['id', 'image', 'filename', 'contact_name', 'created_at', 'updated_at'] In my ViewSet once the card record is created, I also want to add the following ContactName JSON data into the child table, set the reference (card_id) as an id of that card, and return the newly added record in the response. e.g. [ { "first_name": "John", "last_name": "Doe", "confidence": 0.9 }, { "first_name": "John", "last_name": "Doe", "confidence": 0.9 } ] views.py: class CardViewSet(viewsets.ModelViewSet): … -
Is there an option for alter table in django?
I have a very complicated cyclic dependency issue and I can't use late initialization (encapsulating the table name in quotations) because of some other dependencies on the table so the only logical solution to solve cyclic dependency at this point is to delay the creation of the foreign key through an alter table migration but i can't seem to find a way. just for clarification I want a way in django to execute the SQL command ALTER TABLE, please don't try to solve my cyclic dependency issue some other way i have exhausted every other option. I know there is a way for it in laravel and most major backend frameworks i just can't find anyway to achieve it in django. -
Django : How to filter in between 2 same objects in 2 different models?
I have integrated Microsoft Graph API with my django project and after login in successfully, I am storing both access and refresh token in 2 different models. the models are ModelA and ModelB. Assume that microsoft organisation account holders get their access and refresh token saved in ModelA. The ModelA includes the following attributes: class ModelA(models.Model): active = models.BooleanField(null = True , blank = True) for_user = models.ForeignKey(ModelX, null=True, blank=True, on_delete=models.CASCADE) for_firm = models.ForeignKey(ModelMain, related_name="microsoft_for_firm", null=True, blank=True, on_delete=models.CASCADE) access_token = models.TextField(null=True, blank=True) refresh_token = models.TextField(null=True, blank=True) and microsoft personal accounts holders get their access and refresh tokens saved in ModelB. The ModelB includes the following attributes: class ModelB(models.Model): active = models.BooleanField(null = True , blank = True) for_user = models.ForeignKey(ModelX, null=True, blank=True, on_delete=models.CASCADE) for_firm = models.ForeignKey(ModelMain, related_name="microsoft_for_personal", null=True, blank=True, on_delete=models.CASCADE) access_token = models.TextField(null=True, blank=True) refresh_token = models.TextField(null=True, blank=True) What I want to Achieve? I want to open a docx file using either microsoft organisation or personal account. before opening the file, I want to let the user open the file according to their account type. If a account type is personal, then it should use ModelB's access_token or refresh_token. If an account type is organisation then it should use the … -
How to filter a QuerySet based on whether the objects in it are present in another model?
I have a QuerySet called time_slots which contains objects of model class TimeSlot. time_slots = <QuerySet [ <TimeSlot: Room: Number: 1, category: Regular, capacity: 4, advance: 12, manager: anshul, from: 01:00:00, till: 02:00:00>, <TimeSlot: Room: Number: 1, category: Regular, capacity: 4, advance: 12, manager: anshul, from: 04:07:00, till: 06:33:00>, <TimeSlot: Room: Number: 1, category: Regular, capacity: 4, advance: 12, manager: anshul, from: 09:22:00, till: 10:55:00> ]> models,py class Room(models.Model): class Meta: ordering = ['number'] number = models.PositiveSmallIntegerField( validators=[MaxValueValidator(1000), MinValueValidator(1)], primary_key=True ) CATEGORIES = ( ('Regular', 'Regular'), ('Executive', 'Executive'), ('Deluxe', 'Deluxe'), ) category = models.CharField(max_length=9, choices=CATEGORIES, default='Regular') CAPACITY = ( (1, '1'), (2, '2'), (3, '3'), (4, '4'), ) capacity = models.PositiveSmallIntegerField( choices=CAPACITY, default=2 ) advance = models.PositiveSmallIntegerField(default=10) manager = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models. CASCADE ) class TimeSlot(models.Model): class Meta: ordering = ['available_from'] room = models.ForeignKey(Room, on_delete=models.CASCADE) available_from = models.TimeField() available_till = models.TimeField() """class used when a user books a room slot.""" class Booking(models.Model): customer = models.ForeignKey(User, on_delete=models.CASCADE) check_in_date = models.DateField() timeslot = models.ForeignKey(TimeSlot, on_delete=models. CASCADE) Each time slot can be either booked or vacant. In order to find if it is booked or vacant, I do the following- if request.session['occupancy'] == '': for time_slot in time_slots: try: Booking.objects.get(check_in_date=request.session['date'], timeslot=time_slot) time_slot.occupancy = … -
Django ManyToMany field is not saved
I need to update ManyToMany field on object save. I've tried to override save method, but it doesn't update m2m. There is my authors field authors = models.ManyToManyField( to='author.Author', blank=True ) And save method is def save(self, *args, **kwargs): super(Album, self).save(*args, **kwargs) sounds = self.sounds.all() authors = [author for sound in sounds for author in sound.authors.all()] self.authors.set(authors) print(self.authors.all()) In output <QuerySet [<Author: Slick Killa>, <Author: 6feetdeep>]>, but database have not changed I will be glad of any help :) -
AttributeError: 'WSGIRequest' object has no attribute 'get' Internal Server Error: /
This is the code in modules.py class Payment(models.Model): cardnumber = CardNumberField(('card number') , default='Card Number') cardexpiry = CardExpiryField(('expiration date')) CVV = SecurityCodeField(('security code'), default='cvv') card_type = models.CharField(max_length=30 , default='Card Type') def __str__(self): return self.cardnumber + self.cardexpiry + self.CVV + self.card_type This is the code in forms.py from django.forms import ModelForm from .models import Payment class paymentForm(ModelForm): class Meta: model = Payment fields = \['cardnumber', 'cardexpiry', 'CVV' ,'card_type'\] This is the code in views.py from django.shortcuts import render from .forms import paymentForm def payment(request): if request.method == 'POST': form = paymentForm(request.POST) if form.is_valid(): \# Save the form data to the database form = paymentForm(request) else: form = paymentForm() return render(request, 'payment.html', { 'form': form }) i just want to display the forms in html page + save the update to database -
How can i install dlib in my azure web application
It requires cmake but how can i install it using azure because when i just use "pip install cmake" it doesnt work even in my local host but when i install the exe file it starts to work in my local host so how am i supposed to install it on a azure web application this is the error [06:40:02+0000] Building wheel for dlib (setup.py): started [06:40:02+0000] Building wheel for dlib (setup.py): finished with status 'error' error: subprocess-exited-with-error × python setup.py bdist_wheel did not run successfully. │ exit code: 1 ╰─> [8 lines of output] running bdist_wheel running build running build_py package init file 'tools/python/dlib/init.py' not found (or not a regular file) running build_ext ERROR: CMake must be installed to build dlib [end of output] I tried installing it using azure power shell but it still didn't work as i said earlier -
Django - Generic detail view DailyForecastDetailView must be called with either an object pk or a slug in the URLconf
Can someone assist me with this? I am new to Django and am apparently missing a connection between my code somewhere. I already tried some of the sollutions mentioned on SOF for this problem, but I can't get it working. I get the error: Generic detail view DailyForecastDetailView must be called with either an object pk or a slug in the URLconf On my local url with date (http://127.0.0.1:8000/forecast/narnia/2023-03-26/) and without the date parameter (http://127.0.0.1:8000/forecast/narnia/) ** models.py**: from django.conf import settings from django.db import models from django.utils.text import slugify User = settings.AUTH_USER_MODEL # Create your models here. class DefaultProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile") bio = models.TextField() def __str__(self): return f"{self.__class__.__name__} object for {self.user}" class Location(models.Model): name = models.CharField(max_length=255, unique=True) slug = models.SlugField(unique=True) country = models.CharField(max_length=255) region = models.CharField(max_length=255, blank=True, null=True) lat = models.DecimalField(max_digits=9, decimal_places=6) lon = models.DecimalField(max_digits=9, decimal_places=6) timezone_id = models.CharField(max_length=255) def save(self, *args, **kwargs): self.slug = slugify(self.name) super().save(*args, **kwargs) def __str__(self): return self.name class Meta: verbose_name_plural = "locations" # class CurrentWeather(models.Model): class Forecast(models.Model): location = models.ForeignKey(Location, on_delete=models.CASCADE, related_name="forecasts") created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) class DailyForecast(Forecast): date = models.DateField() date_epoch = models.IntegerField() maxtemp_c = models.DecimalField(max_digits=5, decimal_places=2) maxtemp_f = models.DecimalField(max_digits=5, decimal_places=2) mintemp_c = models.DecimalField(max_digits=5, decimal_places=2) mintemp_f = models.DecimalField(max_digits=5, decimal_places=2) … -
How to avoid IntegrityError issue with update_or_create?
I would appreciate it if someone could explain why I'm having IntegrityError exception being thrown here, and how to avoid it. When an object already exists, isn't the update_or_create method supposed to update it ? models.py class OHLCV(TimestampedModel): market = models.ForeignKey(Market, on_delete=models.CASCADE, related_name='candles', null=True) index = models.ForeignKey(Index, on_delete=models.CASCADE, related_name='candles', null=True) timeframe = models.CharField(max_length=10) open, high, low, close, volume = [models.FloatField(null=True) for i in range(5)] datetime = models.DateTimeField(null=True) class Meta: verbose_name_plural = "OHLCV" unique_together = [['market', 'timeframe', 'datetime'], ['index', 'timeframe', 'datetime']] tasks.py @app.task def bulk_update_ohlcv(timeframe): for obj in Market.objects.filter(active=True): if obj.exchange.is_status_ok(): update_ohlcv.delay('market', obj.pk, timeframe) @app.task def update_ohlcv(self, type, pk, timeframe): [code here] if obj.__class__ == Market: ohlcv, created = OHLCV.objects.update_or_create(market=obj, timeframe=timeframe, datetime=dt, open=candle[1], defaults=defaults ) elif obj.__class__ == Index: ohlcv, created = OHLCV.objects.update_or_create(index=obj, timeframe=timeframe, datetime=dt, open=candle[1], defaults=defaults ) Error: -celery_worker-1 | 2023-04-01T06:55:47.710298043Z IntegrityError: duplicate key value violates unique constraint -celery_worker-1 | 2023-04-01T06:55:47.710302260Z "market_ohlcv_market_id_timeframe_datetime_8ffd84de_uniq" -celery_worker-1 | 2023-04-01T06:55:47.710306227Z DETAIL: Key (market_id, timeframe, datetime)=(84, 5m, 2023-03-31 21:20:00+00) -celery_worker-1 | 2023-04-01T06:55:47.710310646Z already exists. -
I can connect django with two databases?
I want to use two databases in my Django project to store the data in the first and the metadata in the second. is it possible and how do I do it? -
How to use React and Django for user token authentication and storage
I am aware this has been asked so many times but the more I search the more conflicted I seem with the answers I find. What I want to accomplish is a secure and user experience friendly approach to authenticating and storing user's token. As seen here the recommended answer suggests to use a set of two cookies which would have to have the secure and httpOnly attributes (Since I have Django and React on different domains I would not be able to use any sort of sameSite cookie) In the same question the next best answer proposes using Redux (Is Redux even more secure?) to store the token in a variable and refresh it with a refresh token stored in LocalStorage that would be used to get a auth token. Now the problem I see with this is that he mentions that he used LocalStorage in his solution as a cookie would not be good for his stateless approach. If I am not mistaken a cookie is neither stateful nor stateless as is just a transport medium and what is inside is what is stateless or not such as a sessionId which Django does with its templates and Session … -
Django doesn't load static files from React
Django gives 404 error for static files. I created a Django and React projects in separate folders following this tutorial but created the React project with Vite https://www.youtube.com/watch?v=tYKRAXIio28 . Then brought React project as "frontend" into the Django. Ran npm run build which created below inside frontend folder. │ index.html │ vite.svg │ └───assets index-757929e7.js index-a9bba2ed.css Added BASE_DIR / 'frontend/dist' in Django settings.py file TEMPLATES = [ { "DIRS": [ BASE_DIR / 'frontend/dist' ], }, ] Added this below that for static files npm created. STATICFILES_DIRS = [ BASE_DIR / 'frontend/dist/assets' ] Added path('', TemplateView.as_view(template_name='index.html')) to urls.py When I go to 127.0.0.1:8000 it successfully loads the html file but not the css or js. I'm getting this error in the browser. Refused to apply style from 'http://localhost:8000/assets/index-a9bba2ed.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. The html file in frontend/dist folder. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <link rel="icon" type="image/svg+xml" href="/vite.svg" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Vite + React</title> <script type="module" crossorigin src="/assets/index-757929e7.js"></script> <link rel="stylesheet" href="/assets/index-a9bba2ed.css"> </head> <body> <div id="root"></div> </body> </html> -
How to pass a model name to django realated like _set?
IS there any way to pass dinamically model name to realted field if my qyery is like instance.instance_set.all()? Here's my code? Models class Category(models.Model): name = models.CharField(max_length=100, db_index=True, verbose_name='Имя категории') slug = models.SlugField(max_length=255, unique=True, db_index=True, verbose_name='URL') objects = CategoryManager() class Product(models.Model): class Meta: abstract = True MIN_RESOLUTION = (400, 400) MAX_RESOLUTION = (1800, 1800) # MAX_IMAGE_SIZE = 3145728 MAX_IMAGE_SIZE = 314 title = models.CharField(max_length=255, verbose_name='Наименование товара') slug = models.SlugField(max_length=255, unique=True, db_index=True, verbose_name='URL') description = models.TextField(blank=True, verbose_name='Описание') price = models.DecimalField(max_digits=9, decimal_places=2, verbose_name='Цена') photo = models.ImageField(upload_to='photos/%y/%m/%d', verbose_name='Фото', blank=True, null=True) time_create = models.DateTimeField(auto_now_add=True, verbose_name='Дата создания') time_update = models.DateTimeField(auto_now=True, verbose_name='Дата обновления') category = models.ForeignKey('Category', on_delete=models.CASCADE, verbose_name='Категория') class NoteBook(Product): diagonal = models.CharField(max_length=255, verbose_name='Диагональ') display = models.CharField(max_length=255, verbose_name='Тип дисплея') processor = models.CharField(max_length=255, verbose_name='Частота процессора') ram = models.CharField(max_length=255, verbose_name='Оперативная память') video = models.CharField(max_length=255, verbose_name='Видеокарта') chargeless_time = models.CharField(max_length=255, verbose_name='Время автономной работы') Abastract class for child models I want to get all Notebook objects through model Category, so i created a serializer for products. It would be easier to get Notebook objects not using Category model, but problem is Notebook model's parent is abstract class Product and i don't know how to pass a model name to serialier dynamically Serializer class CategorySerializer(serializers.ModelSerializer): products = serializers.SerializerMethodField(method_name='get_product') class Meta: model = … -
how I can connect project django with HDFS?
I want to connect my project django with HDFS to storage data I want to connect my project django with HDFS to storage data, how can I do that -
Django Debug toolbar is not showing though `view page source` is showing debug tool's html
I am a beginner at Django. Django-debug-tool is not showing. I have gone through the official documentation step by step. But It did work for me. I have seen lots of existing answers as well seems it doesn't work. Interestingly from the browser when I go to view page source it shows the debug tool's HTML after my page's code. But it doesn't show. Django version: 4.1.7 django-debug-toolbar: latest settings.py from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = "django-insecure-ug*k0401%7v_i887cu4m$szp%(i=h=*9yyi&4b#71%ozksz1%6" # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "playground", "debug_toolbar" ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", "debug_toolbar.middleware.DebugToolbarMiddleware", ] INTERNAL_IPS = [ "127.0.0.1", ] ROOT_URLCONF = "storefront.urls" TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "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", ], }, }, ] WSGI_APPLICATION = "storefront.wsgi.application" DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": BASE_DIR / "db.sqlite3", } } AUTH_PASSWORD_VALIDATORS = [ { "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator", }, { "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator", }, … -
Axios request not sending expected cookie header to Django server
I'm trying to upload a file to a Django server using an Axios post request in a React app. The server expects a CSRF cookie to be included in the request headers. The request already includes all the methods I could find for setting the cookie. Through document.cookie, setting withCredential: true, and specifying the Cookie header. Here is my Axios request: const onSubmit = async (data) => { const formData = new FormData() formData.append('file', data.file[0]) const csrftoken = getCookie('csrftoken'); document.cookie = `csrftoken=${csrftoken}` const res = await axiosInstance.post('/upload/', formData, { timeout: 0, headers: { 'Cookie': `csrftoken=${csrftoken}`, 'Content-Type': 'multipart/form-data', 'x-csrftoken': csrftoken, }, withCredentials: true, }) console.log(res) } And here is my Django view: def upload_file(request): form = UploadFileForm() if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): file_id = save_file_to_database(request.FILES['file']) response = JsonResponse({'id': file_id}, status=201) return response else: response = HttpResponse({'message': 'Upload failed'}, status=400) return response return render(request, 'upload.html', {'form': form}) Also, I believe I have properly set the relevant Django settings in settings.py: CORS_ORIGIN_WHITELIST = ( "http://localhost:8000", "http://127.0.0.1:5173", ) CSRF_TRUSTED_ORIGINS = [ "http://127.0.0.1:5173" ] SESSION_COOKIE_SAMESITE = 'None' What can I do to ensure that the CSRF cookie is included in the request headers or that the CSRF requirements are met … -
is it sensible to make a utility function in django that redirects a user to the same page that they came from?
i frequently involve using taskflows that accept a form input through a [synchronous] post request. is it sensible to make a function for redirecting the user to the same page that the request came from? my understanding is that redirecting the user is desirable as opposed to just rendering the same page from the post request. this allows the user to refresh the page without getting the popup for resubmitting the form. i'm thinking of this design pattern here https://en.wikipedia.org/wiki/Post/Redirect/Get does django have any inbuilt utilities to perform this? i'm imagining a code like this def redirect_to_self(request: HttpRequest, path_suffix: str = '') -> HttpResponseRedirect: return redirect(request.path+path_suffix) this also allows me to return messages to the user through ?alert=hello or something like that. using only asynchronous submits [via fetch api or such] is another option. but i dont want to touch the frontend for the time being. of course, this is assuming that the post request for submitting the form is handled by the same view that renders the form via get, which is true for my use case. -
Why does GET Details returns all Null and Delete Details returns "detail": "Method \"GET\" not allowed." when getting some and deleting some objects?
I built a rest framework in Django. When I do getAll, I get all the data from my database (no problem). The problem is when I do GET details and DELETE details. For the get and delete, I need to return and delete multiple objects (not just one and not all). models.py: class ProA(models.Model): var1 = models.CharField(max_length=200, null=True, blank=True) var2 = models.CharField(max_length=200, null=True, blank=True) var3 = models.CharField(max_length=200, null=True, blank=True) serializers.py: class ProASerializer(serializers.ModelSerializer): class Meta: model = ProA fields = '__all__' urls.py: urlpatterns = [ path('proa-getAll/', views.getAll, name='proa_getAll'), path('proa-getOne/<str:var1>', views.getOneSet, name='proa_getOne'), path('proa-delete/<str:var1>', views.deleteOneSet, name='proa_delete'), ] views.py: @api_view(['GET']) def getAll(request): proas = ProA.objects.all() serializer = ProASerializer(ProA.objects.all(), many=True) return Response(serializer.data) @api_view(['GET']) def getOneSet(request, var1): proa = ProA.objects.filter(var1=var1) serializer = ProASerializer(proa, many=False) return Response(serializer.data) @api_view(['DELETE']) def deleteOneSet(request, var1): try: data = ProA.objects.filter(var1=var1) except data.DoesNotExist: return Response({'message': 'The var1 value does not exist'}, status=status.HTTP_404_NOT_FOUND) data.delete() return Response({'message': 'Data was deleted successfully!'}, status=status.HTTP_204_NO_CONTENT) When I go to the getOneSet URL to get all the objects where var1=MS107, I get the following: When I go to the deleteOneSet URL to delete all the objects where var1=MS107, I get the following: I have tried many things, but no idea how to solve them. I am new to Django, … -
Django: I'm adding the correct namespace to my apps but it doesn't work
I have 2 apps main and accounts this is the urls: Main: enter image description here Accounts: enter image description here enter image description here I did try to make changes in the settings but nothing worked -
Django DRF serializer multiple database
When I check if data is valid or not serializer.is_valid() Serializer checks relationships in defualt connection but i am using different database connection. How makes Serializer using/change database connection or stop check, I mean ignore this message Invalid pk \"27\" - object does not exist.? serializers.py class CompetitionSerializer(serializers.ModelSerializer): sections = SectionSerializer(many=True) class Meta: model = Competition # depth = 1 #fields = '__all__' exclude = ('updated_date_at', ) -
Python (Django rest framework): Trying to remove a temporary file in unit test tearDown() claims file is in use
I'm creating a simple API using DRF, where one of my models ("Card") has an ImageField. I'm now writing unit tests for the serializer and I'm having trouble on one specific test that updates the image field. The file keeps being in use so the temp directory created to store it can't be deleted. My model stores this image files in <project_root>/media/img. My test class has a setup method that creates a temp folder and then creates some test data, including an image: class CardSerializerTestCase(APITestCase): def setUp(self): # Temporary directory for images: super().setUp() temp_dir = os.path.join(settings.BASE_DIR, "media") self.temp_media = tempfile.TemporaryDirectory(dir=temp_dir, prefix=f"{self.__class__.__name__}_") settings.MEDIA_ROOT = self.temp_media.name print("Created temp directory for images:", self.temp_media.name) # test data 1: self.valid_card = { "image": self.create_temp_image('image1.png') # some other fields, not important now } # test data 2: self.updated_card = { "image": self.create_temp_image('image2.png') # some more fields } def create_temp_image(self, filename): img_data = BytesIO() img = Image.new("RGB", (100, 100)) img.save(img_data, format="PNG") img_data.seek(0) return SimpleUploadedFile(filename, img_data.getvalue()) Now this is my unit test (the relevant part, since there are other fields being tested): def test_card_serializer_update(self): # Create a new card serializer = CardSerializer(data=self.valid_card) self.assertTrue(serializer.is_valid()) card = serializer.save() # Update card with new values serializer = CardSerializer(instance=card, data=self.updated_card) self.assertTrue(serializer.is_valid()) saved_card … -
How to remove an object from a QuerySet in Django
A room consists of predefined timeslots and a customer can book any time slot. models,py class Room(models.Model): class Meta: ordering = ['number'] number = models.PositiveSmallIntegerField( validators=[MaxValueValidator(1000), MinValueValidator(1)], primary_key=True ) CATEGORIES = ( ('Regular', 'Regular'), ('Executive', 'Executive'), ('Deluxe', 'Deluxe'), ) category = models.CharField(max_length=9, choices=CATEGORIES, default='Regular') CAPACITY = ( (1, '1'), (2, '2'), (3, '3'), (4, '4'), ) capacity = models.PositiveSmallIntegerField( choices=CAPACITY, default=2 ) advance = models.PositiveSmallIntegerField(default=10) manager = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models. CASCADE ) class TimeSlot(models.Model): class Meta: ordering = ['available_from'] room = models.ForeignKey(Room, on_delete=models.CASCADE) available_from = models.TimeField() available_till = models.TimeField() """class used when a user books a room slot.""" class Booking(models.Model): customer = models.ForeignKey(User, on_delete=models.CASCADE) check_in_date = models.DateField() timeslot = models.ForeignKey(TimeSlot, on_delete=models. CASCADE) A room manager can see the list of all the time slots and also filter them. forms.py class SearchTimeSlotsForm(forms.Form): date = forms.DateField(widget=FutureDateInput(attrs={'class': 'unbold-form'}), required=False, initial=date.today()) available_from = forms.TimeField(widget=TimeInput(attrs={'class': 'unbold-form'}), required=False) available_till = forms.TimeField(widget=TimeInput(attrs={'class': 'unbold-form'}), required=False) STATUS = ( (None, 'Any'), ('Vacant', 'Vacant'), ('Booked', 'Booked'), ) occupancy = forms.ChoiceField( required=False, widget=forms.RadioSelect(attrs={'class': 'unbold-form'}), choices=STATUS, ) SORT = ( ('available_from', 'Ascending'), ('-available_from', 'Descending'), ) sort_by = forms.ChoiceField( widget=forms.Select(attrs={'class': 'unbold-form'}), choices=SORT, ) """Function to ensure that booking is done for future and check out is after check in""" def clean(self): cleaned_data = …