Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
react doesnt see django localhost when loading images
Name: {item.name} <img src={item.photo} alt="description "></img> json: { "id": 9, "name": "name", "photo": "http://127.0.0.1:8000/media/image.jpg", } item.photo is loaded from django rest framework api and it returns: GET http://127.0.0.1:8000/media/image.jpg 404 (Not Found) ,item.name works normally. When i cut off "http://127.0.0.1:8000" from json image is displaying. How to reapair that? -
Django Get image from s3 bucket if image source is stored in a database
I have a model where users upload pictures to an s3 bucket. class Curso(models.Model): titulo = models.TextField() foto = models.ImageField(upload_to='media/cursos') #this goes to mybucket/media/cursos alt = models.TextField() ... It uploads fine to the s3 bucket but the source to the images gets stored in the database like "media/cursos/theimage.jpg" And I would like to display the images from the objects in a template like this <img class='curso__tarjeta--imagen' loading="lazy" src="{{curso.foto}}" alt={{curso.alt}}"> But it doesn't work because the path is not the whole path my s3 bucket My static tag is pointing to my s3 bucket. My question is: is there a way to do something like this -> {% load static %} <img class='curso__tarjeta--imagen' loading="lazy" src="{%static%}{{curso.foto}}" alt={{curso.alt}}"> I'm trying like that but it doesn't work! What should I do? Help! And thank you in advance -
DRF Pagination page_size not working with ModelViewSet
I am trying to use ModelViewSet and PageNumberPagination together but can't seem to get page_size working. I have set my size to 200 but it lists 200+ items always. Here is my code snippet: class ExamplePagination(pagination.PageNumberPagination): page_size = 200 max_page_size = 200 class VideosViewSet(viewsets.ModelViewSet): parser_classes = (FormParser, JSONParser) serializer_class = VideoSerializer pagination_class = ExamplePagination queryset = Video.objects.all() @swagger_auto_schema(responses={200: VideoSerializer}) def list(self, request): """ Request to list all videos """ queryset = Video.objects.all().order_by("-published_at") if queryset.exists(): page = self.paginate_queryset(queryset) if page is not None: serialized = VideoSerializer(queryset, many=True) return self.get_paginated_response(serialized.data) return Response(status=http_status.HTTP_404_NOT_FOUND) I tried everything from custom mixins to setting the page size in settings.py Here is my settings.py as well REST_FRAMEWORK = { "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination", 'PAGE_SIZE': 200, } -
Django serialize object return array
Django serialize object return an array, and i cant get it in template with js my view.py: def MyExempleView(request): data = serializers.serialize("json", myModel.objects.all()) context = { "data" : json.loads(data) } return render(request, 'consulta/myTemplateExemple.html', context=context) my template: {{ data|json_script:"data" }} if ($("#data").length) { var data= JSON.parse(document.getElementById('data').textContent); } my result exemple: "[{"key": "value"}, {"key2": "value2"}]" -
Django API for upload taking to long to upload files
I am working on a django rest api to upload 3 files and save it to disk. The files are [file.svo, file.db3 and file.yaml]. The code below works fine and fast when I test it locally. However, when I put it on a server the files it takes a really long time to upload the files. When I comment out the upload and saving the file.svo part from the code the upload run very fast. # in built libraries import os from time import sleep from pathlib import Path # external libraries import requests from django.http import JsonResponse from rest_framework.views import APIView from django.core.files.storage import FileSystemStorage # environment variables from keys import USER_DIR #this is a directory class SaveRosBag(APIView): def post(self, request, *args, **kwargs): # integer_key & timestamp integer_key = self.kwargs['integer_key'] timestamp = self.kwargs['timestamp'] # required files if "db3_file" in request.FILES: db3_file = self.request.FILES["db3_file"] else: return JsonResponse({"error":"KeyError [db3_file]"}) if "yaml_file" in request.FILES: yaml_file = self.request.FILES["yaml_file"] else: return JsonResponse({"error":"KeyError [yaml_file]"}) if "svo_file" in request.FILES: svo_file = self.request.FILES["svo_file"] else: return JsonResponse({"error":"KeyError [svo_file]"}) # make directory if it doesn't exit Path(os.path.join(USER_DIR, str(integer_key), str(timestamp), 'chdir') ).mkdir(parents=True,exist_ok=True) # define paths svo_folder = os.path.join(USER_DIR,str(integer_key),str(timestamp)) yaml_db3_folder = os.path.join(ride_folder,'chdir') # saving rosbag save_db3 = FileSystemStorage(location=yaml_db3_folder) save_db3.save(db3_file.name, db3_file) # … -
Execute a test with a django application on gilab
can someone please help me. I have problems to do test on gitlab with a django application. It's about connexion to the server, I've try with postgress or mysql but nothing!! -
How to get rid of python manage.py permission denied problem in Vs code?
I tried to run command "python manage.py runserver" in VS code but i always get this message: "bash: /c/Users/ACER/AppData/Local/Microsoft/WindowsApps/python: Permission denied" Python permission denied picture And also, i tried to run command "py manage.py runserver" still it does not run, instead it says: "Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases." py manage.py runserver pic -
Django EmailMessage.content_type = 'html' keep newlines?
How can I keep new lines in a Django's EmailMessage that has a content_type = 'html'? I need the html content type because of signatures. Email: Welcome User, this is a welcome email. Is rendered properly when sent as a text but when sent as an html, it (obviously) doesn't render newlines. Email: Welcome User,this is a welcome email. I'd like to have just a plain text in my templates but I'd like them to be converted into html with proper newlines. Is there a way to do that or do I need to write html tags myself? -
Show only the last form field in Django
I have form model with three fields but the template shows me only one : forms.py class ChooseAvailabilities(forms.Form): timeslots_day1 = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple, choices=TIMESLOT_LIST ), timeslots_day2 = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple, choices=TIMESLOT_LIST ) timeslots_day3 = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple, choices=TIMESLOT_LIST ) views.py def chooseAvailabilities(request): if request.method == "POST": form = ChooseAvailabilities(request.POST) if form.is_valid(): temp = form.cleaned_data.get("timeslots") print(temp) else: form = ChooseAvailabilities() return render(request, 'panel/choose_availabilities.html', {"form" : form}) choose_availabilities.html {% extends 'panel/base.html' %} {% block content %} <form method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit"> </form> {% endblock content %} It shows me only the checkbox field of timeslots_day3, I want also to see timeslots_day2 and timeslots_day1 I tried to show them one by one with this code : {% extends 'panel/base.html' %} {% block content %} {{ form.non_field_errors }} <div class="fieldWrapper"> {{ form.timeslots_day1.errors }} <label for="{{ form.timeslots_day1.id_for_label }}">timeslots_day1:</label> {{ form.timeslots_day1 }} {{ form.timeslots_day2.errors }} <label for="{{ form.timeslots_day2.id_for_label }}">timeslots_day2:</label> {{ form.timeslots_day2 }} {{ form.timeslots_day3.errors }} <label for="{{ form.timeslots_day3.id_for_label }}">timeslots_day3:</label> {{ form.timeslots_day3 }} </div> {% endblock content %} But It shows me this... : -
Is there anything I should be doing to protect my security when opening a port?
I'm new to this, so I apologize if my question is a little too simplistic or I don't have the correct understanding. I can't find anything in the django guide and I'm not sure if the general port information is the same considering what i'm doing with Django. I'm running a django runserver on '0.0.0.0:8000', which allows me to access the server remotely on another device in the same household. Is there anything I should be doing to help protect from outside attacks as the port is open? I believe I read that although this won't grant access to the device running the server, it can leave it vulnerable to issues. But there shouldn't be any sensitive data being transmitted as it's been used to enter data into a database. -
Django image background loading time
There is a latency when my website page loads between the display of all the differents elements composing the page and the display of the background image. I tried to drastically reduce the background image quality but no improvement in the loading time. Here is my CSS code for the background image: body { background: url("images/background.jpg") no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; background-attachment: fixed; } -
Cant navigate between different html pages in django
When i try to navigate from the home page to any other page is works just fine but trying to navigate from that other page back to the home page will just add home to the domain name which will give an error this is the html code <nav> <ul> <li><a href="">Home</a></li> <li><a href="./about">About</a></li> <li><a href="./pizza">pizzas</a></li> </ul> this the urls.py file from django.contrib import admin from django.urls import path from pizza_man import views urlpatterns = [ path('admin/', admin.site.urls), path('' , views.home_view , name='home' ,), path('about/' , views.about , name ='about'), path('pizza/' , views.show_pizza , name = 'pizza') ] what do i need to change to make this workout see the link -
How can i select some columns with or operator in views?
How can i select some columns with or operator in views.py? I want to run the below query in views.py in Django: SELECT name,family FROM student WHERE male = True OR degree=False I used this ORM: student = stu.objects.filter(male = True).values('name','family') | stu.objects.filter(degree = False).values('name','family') Is this correct? Is there a way that i can remove duplicate values('name','family') in query? -
Sending data from Django view to Django form
I have a Django view and I want to send the request data to a form. class PostDetailView(DetailView): model = Post form = CommentForm def get_form_kwargs(self): kwargs = super(PostDetailView, self).get_form_kwargs() kwargs['user'] = self.request.user.username return kwargs def post(self, request, *args, **kwargs): form = CommentForm(request.POST) if form.is_valid(): post = self.get_object() form.instance.user = request.user form.instance.post = post form.save() return redirect(reverse("post-detail", args=[post.pk])) from django import forms from .models import Comment from djrichtextfield.widgets import RichTextWidget class CommentForm(forms.ModelForm): user = forms.ChoiceField(required=True) def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) super(CommentForm, self).__init__(*args, **kwargs) self.fields['user'].choices = self.user content = forms.CharField(widget=RichTextWidget(attrs={ 'class': 'md-textarea form-control', 'placeholder': 'Comment here ...', 'rows': '4', })) class Meta: model = Comment fields = ('author', 'content',) According to the docs, get_form_kwargs allows key-value pairs to be set in kwargs. The kwargs is then passed into the form. The form's init function should then be able to pick up the user value from kwargs. However, self.user returns None, and debugging showed that get_form_kwargs did not run at all. I have two questions: how do functions in view classes get executed? And what is the correct method to pass data from a view to a form? -
Django create dynamic url with unique id
I am working on a ecommerce project and trying to integrate a third party payment API. In the product checkout view I have something like the code below, where a payment id is generated. In future when customer has paid, I will receive a get call on my backend with this payment id and I need a way to recognize that and redirect that get call to payment confirmation page. class checkout(View): def get(self, request, *args, **kwargs): ... paymentId = call_thirdParty_for_payment_id(paymentDetails) ... #The returned paymentId id is alphanumeric. Is there a way to tell Django that in future if we receive a request containing this payment id in the url it should direct the request to payment confirmation page? return render(request, 'paymentUI.html') After the customer has paid I will receive a get call with a url like: https://www.example.com/payment?paymentId=xxxxxxxx Right now my backend respond with an error as it does not know how to handle that get call. -
Django model property is not working - Django
I'm facing a issue with while trying to define a property in Django model and access them. I have 2 models first one is product and second one is product attributes. Product attributes has several field like Color and Brand. I want to create properties to get the product's brand and color for usage in template and filtering( django-filter) but property in model not giving result as expected. Please find the below codes and remarks for your reference and help. Product Model : class Product(models.Model): measurement_choices = (('Liter', 'Liter'), ('Kilogram', 'Kilogram'), ('Cloth', 'Cloth'), ('Shoe', 'Shoe')) name = models.CharField(max_length=200) sku = models.CharField(max_length=30, null=True) stock = models.CharField(max_length=10, null=True) measurement = models.CharField(choices=measurement_choices, max_length=20, null=True) description = models.CharField(max_length=10000) price = models.DecimalField(max_digits=7, decimal_places=2) discounted_price = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True) image = models.ImageField(upload_to='product/images', default='product.png', null=True, blank=True) image_one = models.ImageField(upload_to='product/images', null=True, blank=True) image_two = models.ImageField(upload_to='product/images', null=True, blank=True) image_three = models.ImageField(upload_to='product/images', null=True, blank=True) image_four = models.ImageField(upload_to='product/images', null=True, blank=True) image_five = models.ImageField(upload_to='product/images', null=True, blank=True) tags = models.ManyToManyField(Tags) sub_category = models.ForeignKey(SubCategory, on_delete=models.SET_NULL, null=True,related_name='+') status = models.CharField(max_length=20, choices=(('Active', 'Active'), ('Inactive', 'Inactive'))) history = HistoricalRecords() Property i have created to get the brand name: def p_brand(self): brand = '' all_attributes = self.productattribute_set.all() for att in all_attributes: brand = att.brand.title print(brand) return brand … -
django e postgres"DETAIL: Key (field)=() is duplicated"
i been makein migrations in my database, and i received this error: (env)$ python manage.py migrate System check identified some issues: Operations to perform: Apply all migrations: account, admin, auth, contenttypes, models, sessions, sites, socialaccount Running migrations: Applying models.0018_auto_20210809_1124...Traceback (most recent call last): File "/home/lucas/MaxiLimpService/env/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UniqueViolation: could not create unique index "models_funcionario_cpf_funcionario_d9311e70_uniq" DETAIL: Key (cpf_funcionario)=() is duplicated. The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/lucas/MaxiLimpService/env/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/lucas/MaxiLimpService/env/lib/python3.8/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/lucas/MaxiLimpService/env/lib/python3.8/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/home/lucas/MaxiLimpService/env/lib/python3.8/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/home/lucas/MaxiLimpService/env/lib/python3.8/site-packages/django/core/management/base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/home/lucas/MaxiLimpService/env/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 244, in handle post_migrate_state = executor.migrate( File "/home/lucas/MaxiLimpService/env/lib/python3.8/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/lucas/MaxiLimpService/env/lib/python3.8/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/lucas/MaxiLimpService/env/lib/python3.8/site-packages/django/db/migrations/executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "/home/lucas/MaxiLimpService/env/lib/python3.8/site-packages/django/db/migrations/migration.py", line 126, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/home/lucas/MaxiLimpService/env/lib/python3.8/site-packages/django/db/migrations/operations/fields.py", line 244, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File … -
Command 'docker exec -it gridd-alpha grid product create --owner myorg --file product.yaml' returned non-zero exit status 1
Here I am trying to communicate between 2 docker containers, namely djangoapp and gridd-alpha. Here the command 'docker cp product.yaml gridd-alpha:/' is executing fine from inside django app in djangoapp container, but the next command 'docker exec -it gridd-alpha grid product create --owner myorg --file product.yaml' is throwing a error - Command 'docker exec -it gridd-alpha grid product create --owner myorg --file product.yaml' returned non-zero exit status 1. ## views.py ## import subprocess cmdCpToContainer = 'docker cp product.yaml gridd-alpha:/' cmdCreateProduct = 'docker exec -it gridd-alpha grid product create --owner myorg --file product.yaml' resultCoppied = subprocess.run(cmdCpToContainer, shell=True, capture_output=True, universal_newlines=True, check=True) print('resultCoppied: ' + str(resultCoppied.stdout)) resultCreatedProduct = subprocess.run(cmdCreateProduct, shell=True,capture_output=True , universal_newlines=True, check=True) print('resultCreatedProduct: ' + str(resultCreatedProduct.stdout)) Here I am communicating through /var/run/docker.sock version: "3.9" services: app: container_name: djangoapp build: . command: python manage.py runserver 0.0.0.0:8000 ports: - 8000:8000 volumes: - /var/run/docker.sock:/var/run/docker.sock networks: default: name: mongodb_network I have also tried using --user, but it throws the same error. docker exec -it gridd-alpha grid product create --owner myorg --file product.yaml Output ## OUTPUT ## Exception Type: CalledProcessError Exception Value: Command 'docker exec -it gridd-alpha grid product create --owner myorg --file product.yaml' returned non-zero exit status 1. Can anyone help me resolve this, and thanks … -
How to save the implementation in javascript in Django
I am a student who is learning Janggo. I am implementing a page that represents the information of the selected option when I select the option. The source code can be written as follows to adjust the quantity, and the price has been implemented to change depending on the quantity. I want to save the quantity and price parts in db, but I have no idea what to do. How can we solve this? html <form method="POST" action="{% url 'zeronine:join_create' id=product.product_code %}"> <div class="form-group row" style="margin-top: -5px"> <label for="optionSelect" class="col-sm-6 col-form-label"><b>옵션</b></label> <div class="col-sm-6" style="margin-left: -90px;"> <select type="text" class="form-control" name="value_code" id="optionSelect" value="{{ form.value_code }}"> <option value="none">옵션을 선택하세요.</option> {% for option in option_object %} {% if option.option_code.option_code.option_code == value.option_code %} {%if option.product_code == product %} <optgroup label="{{option.name}}"> {% for value in value_object %} {% if value.option_code.option_code == option.option_code %} {%if value.product_code == product %} <option data-price="{{value.extra_cost}}"value="{{value.value_code}}">{{value.name}} (+{{value.extra_cost}}원)</option> {% endif %} {% endif %} {% endfor %} {% endif %} {% endif %} {% endfor %} </optgroup> </select> </div> <div id="selectOptionList" style="margin-top:10px; margin-left: 20px; margin-bottom: -10px;"></div> </div> script <script> $().ready(function() { $("#optionSelect").change(function() { var checkValue = $("#optionSelect").val(); var checkText = $("#optionSelect option:selected").text(); var product = $("#productname").text(); var price = parseInt($("#price").text()); var test = … -
How to subtract date (in numbers) in python? [duplicate]
I have a weird need. Lets say, I have start_date = 2021-08-31 00:30:00 date = "120 days" How to subsctract start_date with the days with 120 days ? Is it even possible ? And by the way am asking this to use in "django" -
add another objects on click django
I have an object with name, surname and email and I have a button that when clicked should create another empty object for me to fill in and then with another button create the two objects in the database. How can I create the event that generates a new object for me? -
Displaying data in a leaderboard - Django
I have the following model: class UserDetail(models.Model): donations = models.IntegerField(blank=True, null = True,) points = models.IntegerField(blank=True, null = True,) requests = models.IntegerField(blank=True, null=True) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True, ) I want to get the top 5 users with the most points and display them in an HTML leaderboard template. Please help -
How to check the type of uploaded file?
I only want .xlsm files to be uploadable to the form. This my field in models.py ... pdf = models.FileField( upload_to=customer_directory_path, null=True, blank=True) ... How can I do that? -
Can't access django server remotely
I cannot access localhost / 0.0.0.0:8000 from any other device. The current django project is built off of an older project I was playing around with last year where this worked. Unfortunately i've lost the previous project so I cannot compare their settings.py files, although there should be hardly any difference between them. . The setup Dropbox - holds project and sqlite database file Laptop - running server, had no changes over last year Desktop - / iPhone - / . Where the problem is The fault must be on my laptop where the server is running because I cannot access the server on either my desktop nor my iPhone, the latter worked last year with the previous project, I did not have my desktop at the time. . The project's allowed hosts list I've added several as i've been trying out different solutions recommended by others. ALLOWED_HOSTS = [ '*', '0.0.0.0.', '0.0.0.0:8000', 'localhost' 'localhost:8000' '{laptop's IP address}', '{desktop's IPv4 address}', '{desktop's Default gateway}', ] . When I try to access the localhost on desktop or iPhone Nothing appears in the laptop's terminal, the quit server help line remains the last line. I remember last year, it would update with … -
Could not import view_production.views. Error was: No module named reportlab.graphics.shapes
First of all, I am not a django expert or even a web dev, I dont have any documentation for this app, and the guy that have made it, last time I saw it, was 4 years ago. I am migrating one web app that contains django 0.97 with python 2.7 and wgsi 4.5.15, from a shared host to a new shared host. On my new shared host, Apache is working, and while testing that webservice, I notice that for a login form, I was obtaining this error: ViewDoesNotExist at /login/ajax/ Could not import view_production.views. Error was: No module named reportlab.graphics.shapes Traceback (most recent call last): File "/home/user1/apps/django/RMA/django/core/handlers/base.py" in get_response 68. callback, callback_args, callback_kwargs = resolver.resolve(request.path) File "/home/user1/apps/django/RMA/django/core/urlresolvers.py" in resolve 163. sub_match = pattern.resolve(new_path) File "/home/user1/apps/django/RMA/django/core/urlresolvers.py" in resolve 163. sub_match = pattern.resolve(new_path) File "/home/user1/apps/django/RMA/django/core/urlresolvers.py" in resolve 119. return self.callback, args, kwargs File "/home/user1/apps/django/RMA/django/core/urlresolvers.py" in _get_callback 128. raise ViewDoesNotExist, "Could not import %s. Error was: %s" % (mod_name, str(e)) ViewDoesNotExist at /login/ajax/ Could not import view_production.views. Error was: No module named reportlab.graphics.shapes I've already installed all python 2.7 dependencies that it were in previous host, but no changes. On /home/user1/apps/django/RMA/view_production/urls.py I have this: from django.conf.urls.defaults import * from django.views.generic import list_detail, …