Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"detail": "CSRF Failed: CSRF token missing."
I was trying to test my API in DJango, but while trying to use a POST request to create a user, the following error shows up: "detail": "CSRF Failed: CSRF token missing." What should I do? Can I remove this? Or how should I pass the CSRF also in testing and in production? In theory, I put the false in CSRF_COOKIE_SECURE, so, I don't know what to do. -
Add Payment to Django project to extend the expire date of posts in a blog?
I'm working on a freelance project with Django-rest framework which contains posts and each post has an expiration date so the client want to add a payment method to it to extend the expiration date. All the tutorials or blogs i followed didn't mention how to change the database if the transaction is successful. I need help in this matter maybe library name that can help me or any suggestion to make that happen. Thanks in advance. -
Why DRF uses PUT to send files?
I'm trying to understand how file management works in Django Rest Framework, and a question lingers in my mind: Why does Django use PUT to update files? Is it possible to do the same with the PATCH method? How would I be able to push binaries through the patch? Example of model: class User(AbstractUser): id = HashidAutoField(prefix='user_', primary_key=True) picture = models.ImageField(blank=True, null=True, verbose_name=_("profile picture"), storage=PublicMediaStorage(), upload_to=upload_to) When I try to send using the patch method it only allows me to send in json format, I don't know if there is any way to user PATCH and form-data. For Patch I have something like this: { "user": { "username": "", "first_name": "", "password": "", "password_confirm": "", "email": "", "picture": null } } -
Complex Django query involving an ArrayField & coefficients
On the one hand, let us consider this Django model: from django.db import models from uuid import UUID class Entry(models.Model): id = models.UUIDField(primary_key=True, default=uuid4, editable=False) value = models.DecimalField(decimal_places=12, max_digits=22) items = ArrayField(base_field=models.UUIDField(null=False, blank=False), default=list) On the other hand, let us say we have a dictionary coefficients looking like: coefficients = {item1_uuid: item1_coef, item2_uuid: item2_coef, ... } Entry.value is intended to be distributed among the Entry.items according to coefficients (with sum(coefficients.values()) = Decimal(1)). Using Django ORM, what would be the most efficient way (in a single SQL query) to get the sum of the values of my Entries for a single Item given those coefficients? For instance, in that specific case, for item1 I want to get 168.5454...: 100 * 1 + 150 * (0.2 / (0.2 + 0.35)) + 70 * 0.2. | Entry ID | Value | Items | |-------|-------|--------------------------------------| | uuid1 | 100 | [item1_uuid] | | uuid2 | 150 | [item1_uuid, item2_uuid] | | uuid3 | 70 | [item1_uuid, item2_uuid, item3_uuid] | coefficients = { item1_uuid: Decimal("0.2"), item2_uuid: Decimal("0.35"), item3_uuid: Decimal("0.45") } So far this is what I was thinking about, unsuccessfully: def get_value_for_item(coefficients: dict[UUID, Decimal], item: Item) -> Decimal: queryset = Entry.objects.filter(items__contains=item.pk) # I'm missing a … -
How to add a new "comment" or "flag" field to every model field of existing model?
Disclaimer: I can wipe out the database anytime. So while answering this, please don't care about migrations and stuff. Imagine me having a model with multiple values: class Compound(models.Model): color = models.CharField(max_length=20, blank=True, default="") brand = models.CharField(max_length=200, blank=True, default="") temperature = models.FloatField(null=True, blank=True) melting_temp = models.FloatField(null=True, blank=True) # more (~20) especially numeric values as model fields Now I want to add a comment to be stored for every value of that model. For example I want to add a comment "measured in winter" to the temperature model field. What is the best approach to do that? My brainstorming came up with: By hand add 20 more model fields like temperature_comment = ... but that sounds not very DRY Add one big json field which stores every comment. But how do I create a Form with such a json field? Because I want to separate each input field for related value. I would probably have to use javascript which I would want to avoid. Add a model for every value and connect them to Compound via OneToOneFields. But how do I then create a Form for Compound? Because I want to create a Compound utilizing one form. I do not want … -
How to pass detailed url to ajax
I build a template in django which displays a lists with 'load more' button. It shows a list loaded from db depend on endpoint like /details/1, /details/2, /details/3 etc. How can I pass the endpoint to url in js ajax so it won't be hardcoded? something like below url: {pk}/json-details/${visible}, main.js const handleGetData = () => { $.ajax({ type: 'GET', url: `3/json-details/${visible}`, success: function (response) { console.log(response.pk) max_size = response.max const data = response.data setTimeout(()=>{ data.map(character => { console.log(character.name) charBox.innerHTML += ` <tr> <td>${ character.name }</td> <td>${ character.height }</td> <td>${ character.mass }</td> <td>${ character.hair_color }</td> <td>${ character.skin_color }</td> <td>${ character.eye_color }</td> <td>${ character.birth_year }</td> <td>${ character.gender }</td> <td>${ character.homeworld }</td> <td>${ character.date }</td> </tr>` }) }, 500) if (max_size) { loadBox.innerHTML = "<h4>No more characters to load</h4>" } }, error: function (error) { console.log(error) } }) } views.py class CollectionJSONDetails(View): def get(self, request, pk, *args, **kwargs): print(kwargs) upper = kwargs.get('num_posts') lower = upper - 10 jsonArray = [] people_data = models.Collection.objects.get(pk=pk) with open(f"./{people_data.file_name}.csv", encoding='utf-8') as file: csvReader = csv.DictReader(file) for row in csvReader: jsonArray.append(row) number_of_characters = len(jsonArray) max_size = True if upper >= number_of_characters else False jsonArray = jsonArray[lower:upper] return JsonResponse({'data': jsonArray, 'max':max_size, 'page_id':pk}, safe=False) JSON are availaible under the … -
double curly braces in quote mark - Django
Could some one tell me the full picture of the use of the quote mark and the double curly braces? <a href="{{ url_for('delete_event', id=event.id) }}" class="text-danger"> The full code is as below. Is it Django synatx {{ ... }} embeded? {% for event in events %} <tr> <td>{{ event.event }}</td> <td>{{ event.start_time }}</td> <td>{{ event.end_time }}</td> <td>{{ event.position }}</td> <td><a href="{{ url_for('delete_event', id=event.id) }}" class="text-danger">Delete</a></td> </tr> {% endfor %} -
Foreign key get parent AND children in queryset
I have the following model: class TopicModel(models.Model): topic = models.ForeignKey('self', on_delete=models.CASCADE) ... some more not relevant fields... I need to get a parent topic and its direct children in a queryset. Currently I use it with this queryset: TopicModel.objects.filter( Q(pk=10) | Q(topic__pk=10) ) I was wondering whether I can do the same in a more simple query without using Q. -
Using OpenCV HandDetector with a webcam in Django
I am working on a Django project that involves using a webcam to play a rock-paper-scissors game against a computer. I have implemented the OpenCV HandDetector algorithm to detect a hand in the webcam video feed, and a Keras classifier to classify the hand gesture. However, I am running into an issue with getting the HandDetector to work properly with the webcam video. I have tried using a single still image from the webcam, but the HandDetector does not work well with just one image. I think the solution is to use a video of the hand, but I am not sure how to implement this in my Django project. Here is the code for my jQuery script that captures the video from the webcam and sends it to a Django view: <div class="container"> <div class="row"> <div class="col-md-6"> <video id="webcam" width="640" height="480" autoplay></video> </div> <div class="col-md-6"> <button id="play-button" class="btn btn-primary" onclick="play()">Play</button> </div> </div> </div> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> $(document).ready(function() { startWebcam(); }); var video = document.getElementById('webcam'); var stream; function startWebcam() { navigator.mediaDevices.getUserMedia({ video: true, audio: false }) .then(function(localMediaStream) { stream = localMediaStream; video.srcObject = localMediaStream; video.play(); }) .catch(function(err) { console.log("An error occurred: " + err); }); } function play() { // … -
How to create auto add ShortUUIDField in Django
I need to create a django ShortUUIDField that automatically generate the value when the entry is created: Here's my code: def generate_short_uuid(): string_uuid = str(uuid.uuid4()) return string_uuid.replace('-', '')[:12] class ShortUUIDField(models.CharField): def __init__(self, *args, **kwargs): kwargs['default'] = generate_short_uuid kwargs['editable'] = False kwargs['unique'] = True kwargs['blank'] = True kwargs['null'] = True kwargs['max_length'] = 12 super().__init__(*args, **kwargs) def pre_save(self, model_instance, add): if add: while True: try: value = generate_short_uuid() setattr(model_instance, self.attname, value) return value except IntegrityError as e: if 'duplicate key' in str(e): continue raise Here's the model that use the field: class UserProfile(models.Model): uuid = ShortUUIDField() user = models.OneToOneField("users.User", on_delete=models.CASCADE, related_name="profile") Here's the error that occurs when I try to create the entry: django.db.utils.IntegrityError: null value in column "uuid" of relation "profiles_userprofile" violates not-null constraint -
Image not displaying in browser from Django project
I am trying out an ecommerce website where list of products are input in the admin section, everything works well aside the fact that the product image does not display in browser. Have check all the codes and everything seems ok. Displaying this message in my terminal "GET /media/photos/buy-1.jpg HTTP/1.1" 404 4187 Not Found: /media/photos/buy-2.jpg `HTML <h2 class="title">Latest Products</h2> <div class="row"> {% for item in object_list %} <div class="col-4"> <div> <a href="{{ item.get_absolute_url }}"> {% if item.photo %} <img src="{{ item.photo.url }}" alt="" /> {% else %} <img src="{% static 'images/product-1.jpg' %}" alt=""/> {% endif %} <h4>{{ item.title }}</h4> </a> <a href="{{ item.get_absolute_url }}" > <h6>{{ item.get_category_display }}</h6> </a> </div> <div class="rating"> <i class="fa fa-star"></i> <i class="fa fa-star"></i> <i class="fa fa-star"></i> <i class="fa fa-star"></i> <i class="fa fa-star-o"></i> </div> <p class='lead'> {% if item.d_price %} <del><span>${{ item.price }}</span></del> <span>${{ item.d_price }}</span> {% else %} <p>${{ item.price }}</p> {% endif %} </p> </div> {% endfor %} </div>` Model fie `class Item (models.Model): title = models.CharField(max_length=100) price = models.FloatField() d_price = models.FloatField(blank=True, null=True) tax = models.FloatField(blank=True, null=True) category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) label = models.CharField(choices=LABEL_CHOICES, max_length=1) slug = models.SlugField() description = models.TextField() photo = models.ImageField(upload_to='photos', null=False, blank=False) def __str__(self): return self.title def get_absolute_url(self): return … -
django.db.utils.IntegrityError: duplicate key
I have a model for Logs which is as follows: class Log(TimeStampMixin): uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) start_time = models.CharField(max_length=80, null=True, blank=True, default=None) end_time = models.CharField(max_length=80, null=True, blank=True, default=None) message = models.CharField(max_length=80, null=True, blank=True, default=None) def __str__(self): return str(self.message) I just changed message field length to max_length=1000 . After doing makemigrations when I did migrate, it giving me this error. django.db.utils.IntegrityError: duplicate key value violates unique constraint "django_migrations_pkey" DETAIL: Key (id)=(32) already exists. I tried many solution but none of them making sense for my code I also saw other similar questions but they told to write null=True, blank=True, but I already have it in my code -
Django application running inside of a container but cannoct resolve DB outside of it
I have a Django application which I've decided to setup in container as follows: #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 depends_on: - db db: image: postgres:13 volumes: - postgres_data:/var/lib/postgresql/data/ environment: - "POSTGRES_HOST_AUTH_METHOD=trust" volumes: postgres_data: with database config in settings as follows DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": "postgres", "USER": "postgres", "PASSWORD": "postgres", "HOST": "db", "PORT": 5432, } } And when I run the containers, the app works correctly with me being able to migrate and insert data into database. However when I try to run the project outside of the container by following steps: python -m venv venv source venv/bin/activate pip install -r requirements.txt python manage.py runserver I am getting an error: Traceback (most recent call last): File "/home/jdoni/code/work/tasks/venv/lib64/python3.10/site-packages/django/db/backends/base/base.py", line 244, in ensure_connection self.connect() File "/home/jdoni/code/work/tasks/venv/lib64/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/jdoni/code/work/tasks/venv/lib64/python3.10/site-packages/django/db/backends/base/base.py", line 225, in connect self.connection = self.get_new_connection(conn_params) File "/home/jdoni/code/work/tasks/venv/lib64/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/jdoni/code/work/tasks/venv/lib64/python3.10/site-packages/django/db/backends/postgresql/base.py", line 203, in get_new_connection connection = Database.connect(**conn_params) File "/home/jdoni/code/work/tasks/venv/lib64/python3.10/site-packages/psycopg2/__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not translate host name "db" to address: Name or service not known The … -
How to make Multiple dependent dropdown in CRUD Django?
Fields are such as; Phone Name(Field1) Samsung Redmi Phone Model(Field2) M30 Note10 Note : Dependency between Phone Name and Phone Model(if select samsung from the dropdown then M30 should comes and if select Redmi from the dropdown then Note10 should come. State(Field3) Karnataka Andhra City(Field4) Bangalore Tirupathi Note : Dependency between State and City(if i select "Karnataka" from the dropdown then "Bangalore" should come and if i select "Andhra" from the dropdown then "Tirupathi" should come. Data & Time(Field5) Company Name(Field6) I need form design Horizontally(col-6) in Separate page Phone Name(Field1) Phone Model(Field2) State(Field3) City(Field4) Data & Time(Field5) Company Name(Field6) I need Retrieving Data from database in Separate page Example: Phone name Phone Model State City Company Name ---------- ----------- ----- ---- ------------- -
Contact form not saving in the Database , is it the views or the HTML?
I have an issue in Django where the contact form after being filled out doesn't save in the database : My views : def CV_page(request): if request. Method == 'POST': form = ContactForm(request.POST) if form.is_valid(): # Save form data to Django models contact = ContactForm(full_name= form.cleaned_data['name'], email_sender= form.cleaned_data['email'], phone_number= form.cleaned_data['phone'], message= form.cleaned_data['message']) contact.save() # Send email to admin send_mail('CV-Website-contact', form.cleaned_data['message'], form.cleaned_data['email'], ['xxxx@xxxx.com', form.cleaned_data['email']]) return HttpResponse('success') #HttpResponseRedirect('success/') # create a success page else: form = ContactForm() else: form = ContactForm() context = {'Abouts': latest_description, 'form': form, 'categories': categories, 'portfolios': portfolios, 'pdf': final_pdf_link} return render(request, 'cv_page.html', context) models.py class Contact(models.Model): id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) name = models.CharField(max_length=100, null=True, blank=True) email = models.EmailField(max_length=254, null=False, blank=True) phone = PhoneNumberField(null=True, blank=True, unique=False) message = models.CharField(max_length=2500, null=True, blank=True) created_on = models.DateTimeField(auto_now_add=datetime.datetime.now) updated_on = models.DateTimeField(auto_now=datetime.datetime.now) forms.py class ContactForm(forms.ModelForm): class Meta: model = Contact fields = ['name', 'email', 'phone', 'message'] my HTML: <!-- Contact Section--> <section class="page-section" id="contact"> <div class="container"> <!-- Contact Section Heading--> <h2 class="page-section-heading text-center text-uppercase text-secondary mb-0">Contact Me</h2> <!-- Icon Divider--> <!-- Contact Section Form--> <div class="row justify-content-center"> <div class="col-lg-8 col-xl-7"> <form method="post"> {% csrf_token %} {{form.as_p}} <div class="form-actions"> <button type="submit">Send</button> </div> </form> </div> </div> </div> </section> I believe it is the Contactform … -
ajax request.method= 'POST' is not working in django
I have a problem,Django my ajax post is not working. when i look at the console quantity is not undefined. But my request.post is not working. <form method="POST"> {% csrf_token %} <ul> <li> <div class="form-group quantity-box"> <label class="control-label">Quantity</label> <input class="form-control" id="quantity" value="0" min="0" max="20" type="number" /> </div> </li> </ul> <div class="price-box-bar"> <div class="cart-and-bay-btn"> <a class="btn hvr-hover" data-fancybox-close="" href="#" >Buy New</a> <button type = "submit"> <a class="btn hvr-hover" data-fancybox-close="" id= "qtyButton" data-fancybox-close="" href="{% url 'addCart' %}">Add to cart</a> </button> </form> my js script $('#qtyButton').click(function(e){ e.preventDefault(); var qty = $('#quantity').val(); var id = {{product.id}}; $.ajax({ type: "POST", url: "{% url 'addCart' %}", dataType: 'json', data: { "quantity":qty, "product_id":{{product.id}}, } }); }); my wiew.py file def addCart(request): url = request.META.get('HTTP_REFERER') if request.method == 'POST': post = request.POST quantity = post.get('quantity') id = post.get('product_id') item = Product.objects.get(id=id) Cart.objects.get_or_create(user_id=request.user, product_id=item, quantity=quantity) else: return render(request, 'cart.html') return redirect(request.META.get("HTTP_REFERER", "/")) I tried so many things. But none of them is working. What should i do ? -
How to make djangoq tests use the same test database as pytest
I was beginning to write some tests that involve async tasks, and I realised these tests (using pytest-django) were failing because the async job isnt pointed at the right database. How does one point django-q /qcluster to look at the test database that pytest uses. I am mostly using the default settings from Django. DATABASE related settings.py looks like this 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', 'TEST': { 'NAME': BASE_DIR / 'testdb.sqlite3'} I am running this to check what is the db being connected to. from django.db import connection db_name = connection.settings_dict['NAME'] When the function is being run in non async mode - it rightly points to the testdb.sqlite3. When run using async mode, it points to the db.sqlite3. How do i make the async task to refer to the testdb. Any pointers would be very helpful. -
Django JsonResponse customize its header
I want to change response header of > from django.http import JsonResponse function for example change Date header how? -
Django fixing migrations order for unit testing
I'm working on a codebase which has a lot of migrations. We also have SQL views which are defined in the migrations and later updated in the migrations (whenever changes to the SQL views were required). We have a challenge where when running unit tests the migrations are not applied in the same appear as they currently appear in the django_migrations table. This causes unit tests to fail. My thought is, I could probably write a script to the dependencies of all the migrations files to follow the same order of django_migrations thus ensuring that migrations are run in the correct order. Then I can look into squashing migrations. But this is a lengthy process and I'm not sure if this will actually work. Has anyone come across this issue before? If so, how did you overcome it? -
Different websocket endpoints with Apache2 vs "manage.py runserver". Django Channels
I have different endpoints when i run Django in apache compare to when I run it in the terminal. Can it be some configuration in apache? I belive it can be this ? Apache 2 conf ProxyPass "/ws/" "ws://127.0.0.1:8000/" What does this mean; "/ws/"? Apache to work: ws_urlpatterns = [path('some_url/', Andring.as_asgi()), ] Run in terminal: ws_urlpatterns = [path('ws/some_url/', Andring.as_asgi()), ] In JS: const socket = new WebSocket("ws://" + window.location.host + "/ws/some_url/"); -
How can I use html tags on Django template?
As seen in the image, I am working on a django template, but when I try to write HTML tags, it does not offer any suggestions. When I replace Django Template with HTML, it does not detect commands written for django. In the videos I watched, they can call HTML tags without any problems, using the Django template. Do I need to add any extension or something? -
django-plotly-dash Cannot find Dashapp in the query
I've been trying to implement a dashapp into my django project, and I'm doing so by following the demonstration of the official documentation of django-plotly-dash. Weirdly enough my Dashapp does not get registered, the queryset in def get_object_or_404(klass, *args, **kwargs): which is in django shortcuts.py is returned empty, whereas in the working example it is a list of Dashapp objects registered. Any help is much appreciated. -
Create superuser for cvat
I am trying to install cvat, so I am following the Installation guide The first step run smoothly, however when I try to create a superuser with the command docker exec -it cvat_server bash -ic 'python3 ~/manage.py createsuperuser' After a few minutes, I get the following error: Traceback (most recent call last): File "/opt/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection self.connect() File "/opt/venv/lib/python3.8/site-packages/django/utils/asyncio.py", line 33, in inner return func(*args, **kwargs) File "/opt/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "/opt/venv/lib/python3.8/site-packages/django/utils/asyncio.py", line 33, in inner return func(*args, **kwargs) File "/opt/venv/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 187, in get_new_connection connection = Database.connect(**conn_params) File "/opt/venv/lib/python3.8/site-packages/psycopg2/__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not connect to server: Connection timed out Is the server running on host "cvat_db" (172.18.0.3) and accepting TCP/IP connections on port 5432? The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/django/manage.py", line 21, in <module> execute_from_command_line(sys.argv) File "/opt/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/opt/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/venv/lib/python3.8/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/opt/venv/lib/python3.8/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 79, in execute return super().execute(*args, **options) File "/opt/venv/lib/python3.8/site-packages/django/core/management/base.py", line 397, in execute self.check_migrations() File "/opt/venv/lib/python3.8/site-packages/django/core/management/base.py", line 486, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) … -
Is it possibile to have two backends in single app, and should I do it?
I am building a web app using PHP Symfony as the backend. I need to connect my backend with some controllers using TCP protocol(websockets). I need to start the socket connection and keep it alive for a period of time and wait for any messages sent from a socket. I tried so many ways, including using Ratchet library for Symfony, and can't get it to work correctly. I have done the same thing in python with ease and tried running that script from PHP, but it's also kind pain to do. So now I wonder, what if I set up another backend on that server, with python Django to handle socket connections? They would be using the same database and communicating only with the front end, not in between. -
Problem with Django StreamingHttpResponse
I'm having a problem with Django response class StreamingHttpResponse. When I return a generator as response using StreamingHttpResponse and make a request I excepted to retrieve each data block one by one, instead of that i retrieve the full data at once when the generator loop has finished. My Django View: def gen_message(msg): return '\ndata: {}\n\n'.format(msg) def iterator(): for i in range(100): yield gen_message('iteration ' + str(i)) print(i) time.sleep(0.1) class test_stream(APIView): def post(self, request): stream = iterator() response = StreamingHttpResponse(stream, status=200, content_type='text/event-stream') response['Cache-Control'] = 'no-cache' return response And I make the request like that: r = requests.post('https://******/test_stream/', stream=True) for line in r.iter_lines(): if line: decoded_line = line.decode('utf-8') print(decoded_line) When I see the output of the Django server I can see the print every 0.1 seconds. But the response in the second code only shows when the for loop is finished. Am I misunderstanding the StreamingHttpResponse class or the request class or is there another problem? Thanks:)