Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django smart-selects how to add cutom attributes to select options?
I am newbie to Django and I am working on a project where I have two dropdown lists one includes a list of countries and another for the cities. when the user selects a country from the country dropdown list, the city dropdownlist is updated to show the cities of the selected countries using django smart-selects I need to customize theattributes of the chained select html of cities so that each option in the cities dropdown list will include the information of the relative lat & long of the selected city, So I can have something like this: <select name="city" class="form-control" required="" id="id_city"> <option value="248" data-lat="29.664037" data-long="32.352000"> City 1</option> </select> Any help how to implement this? Thanks in advance -
Django forms integration with legacy UI component library
I'm working on a Django project and would like to incorporate a proprietary UI component library that my company created into my application. The library has CSS utility classes for positioning, font, margin, padding, etc. (similar to Tailwind or Bootstrap). These are simple enough to put into a Django template without overhead. However, I'm struggling with using the library's form/input components (which rely on JSON data as well as HTML). # html <custom-select id="multiple-select-example" label="State" placeholder="Choose your state." multiple ></custom-select> # js var multipleSelect = document.getElementById("multiple-select-example"); multipleSelect.options = [{ text: "Pennsylvania", value: "PA" }, { text: "California", value: "CA" }, { text: "Texas", value: "TX" }]; In a vacuum, it's easy enough to use Django's "json_script" tag to load JSON directly into the '.options' and process the user's data input in JS. But I feel like this misses out on some of the benefits of using Django's built-in Forms (validation, serialization, etc.). How do I get the best of both worlds? Do I have to create custom form fields in Django? Or custom widgets with media assets? I don't know what to do, everything I do is messy. Please help. -
Webshell upload in django webapp
What file can be uploaded on a webapp built on django framework if it's allowing unrestricted file upload? When I uploaded a shell.py it simply rendered as text in the browser but html and javascript are executing fine. -
Validation with checking all model objects. Django
class Questions(models.Model): question = models.CharField(max_length=350) class AnswerOptions(models.Model): answer = models.CharField(max_length=150) yesorno = models.BooleanField(default=False) question = models.ForeignKey('Questions', on_delete=models.CASCADE) I am new to django and would appreciate any suggestions. I really hope for help. How in my case to implement validation in the admin panel? it is necessary to prohibit marking all answers as incorrect and all answers as correct. here the BooleanField field is responsible for this. in the admin.py model, the connection is implemented through “inline”. -
Django dynamically modifying querysets
I've got a Django 2.2.28 application running on Python 3.7.7 and I'm trying to add what I think is an unusual query filter. One of the displays is generated by a queryset that is filtered in the normal way against a PostgreSQL database. This data is presented in using a paginator. I'm being asked to add a filter the data on the display by an additional filter using data that comes from a REST API call (not the database). A simplified presentation to explain what's desired, let's say I have a display with 2 columns, Id and Name that comes from the database: Id Name 1 George 2 Anne 3 Susan 4 Mark The add ask is to add a 3rd column for Status, which comes from a REST API by passing a list of Id values. Adding the Status to the above display would theoretically present this if the list of Ids were passed to the REST API: Id Name Status 1 George True 2 Anne False 3 Susan True 4 Mark False The users would like to filter the display based on the Status (True/False) and still have a full page of results (4). The problem is if … -
'NoneType' object is not subscriptable Rasise Validation Error if same name filled twice Django
I am trying to create a validation that will raise validation error if same name filled twice , but i am getting 'NoneType' object is not subscriptable error. Model.py fruit_name = models.ManyToManyField( "Fruits", blank=True, null=True, verbose_name=_("Fruit Nmaes"), ) form.py class ScenarioForm(forms.ModelForm): def clean(self): fruit_name_set=[] count = int(self.data.getlist('fruit_set-TOTAL_FORMS')[0]) if count > 1: for i in range(count): fruit_name_code = self.data.get(f'fruit_set-{i}-fruit_name')[3] if fruit_name_code not in fruit_name_set: fruit_name_set.append(fruit_name_code) else: fruit_name_set = models.Fruit.objects.filter(pk=fruit_name_code).last() raise ValidationError( "Duplicate Fruit Name not allowed! " ) But I am getting this error, how to solve the error NoneType' object is not subscriptable -
How can I write text under the label of my Django model form?
I am working on a register form on Django. Under my TextFields label I want to write "For multiple purchased units any of the item barcode works." Like below: image How can I add this to my form? -
Allowing users to pay and ship items for each others in Django website
I want to allow users to have the option of shipping an item between two users, one of the related users can ship an item to the other, can anyone please explains to me how it can be done and what packages or tools can help me to achieve it and thank you so much -
i want to integrate an Machine Learning system in my web app using Django Back-end from Nyckel Machine Learning Service?
i send the request to Nyckel Service and get the response back as text but the response i get is invalid format i am working on implement image classification : the result i need to get is this depends on the image i send it through the POST request for Nyckel Service : { "labelName": "harissa", "labelId": "label_684pbumtvbzp3k9q", "confidence": 0.76 } @api_view(['POST','GET']) def addProductByNyckel(request): data = request.data image = data['image'] url = 'https://www.nyckel.com/v1/functions/7aaigszss2ejx7t8/invoke/?format=json' header = { 'Content-type': 'application/json', 'Accept': 'text/plain' } urlimg = 'http://127.0.0.1:8000/media/images/chamia_2lJVXBC.jpg' img = requests.get(urlimg,params=request.GET) m = img.content result = requests.post(url,m, headers=header) dict = result.json() labelName= dict.get("labelName"), labelId = dict.get("labelId"), confidence = dict.get("confidence") return Response(dict ) ` the error message is : **{ "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1", "title": "One or more validation errors occurred.", "status": 400, "traceId": "00-983824a0cb2b204855f4387cf92f2dca-780a95630f9dc3d6-00", "errors": { "$": [ "'0x89' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0." ], "input": [ "The input field is required." ] } }** -
How to pass a number from an html form to Django views
<form action="{% url 'item' %}" method="GET"> {% csrf_token %} Choose an item's id: <input type="number" name="number" value="{{ request.GET.id }}"> <input type="submit"> </form> class SearchResultView(ListView): model = Item template_name = 'item_buy.html' def get_queryset(self): return Item.objects.get(id='') I need to pass an id from the form to the ListView's queryset, however, I don't understand how to call it in the view. Please, tell me how do I need to change the form and the view. -
Django Rest Framework: How to get data from a post request at class based API views?
This is the simple api view: class ReceiveNewData(APIView): def post(self, request): return Response('response') When we are posting some data to somewhere, we can send some data with it. For example: request.post(url, data={//the data will be sent}) Or from the body section in Postman program. The question is: how can I receive any data at my api view like that? -
Django Tutorial. Page not found
I already search for any answer which could help me before write this question, but I haven't found anything that helps. The thing is that I follow the tutorial and I can't see the view that I created. Now I'm going to share my code: project urls.py: from django.contrib import admin from django.urls import include, path urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] polls urls.py: from django.urls import path from . import views urlpatterns = [ path(" ", views.index, name='index'), #127.0.0.1/polls/ ] polls views.py from django.http import HttpResponse from django.shortcuts import render # Create your views here. def index(request): HttpResponse("Welcome to de Polls Universe Index") -
Why is my Boostrap-Card header not filling entire width of the card?
I am new to Bootstrap and Django. I am trying to style a card, but card header (background) does not fill entire width of the card. Here is an example: Here is the code: <div class="container"> <div class="grid"> <div class="row"> {% for list, content in content.items %} <div class="card col-md-6 shadow-lg"> <a href="{{user_name}}/{{list}}"> <div class="card-header bg-secondary text-white">{{list}}</div> <div class="card-body"> <ul> {% for row in content %} <li>{{row}}</li> {% endfor %} </ul> </div> </a> </div> {% endfor %} </div> </div> </div> -
Getting the error : ImportError: cannot import name 'to_const'
getting the following import error in my Django application, is there a workaround ? from graphene.utils.str_converters import to_camel_case, to_const ImportError: cannot import name 'to_const' -
how to put radio button from admin.py?
one question is that I am using admin.py to make my profile edition page; I had to do it like this to add more fields and customize it. Everything works fine, except for one thing: I don't know how to format a form field (it's called country) to be a radio button and have the options "canada", "USA" and "other" does anyone have an idea? how to do it? I am using UserCreationForm and UserChangeForm but I don't know how to edit forms that are already preset admin.py class CustomUserAdmin(UserAdmin): add_form = UserCreationForm form=UserChangeForm model=CustomUser list_display = ['pk','email','username','first_name','last_name'] add_fieldsets = UserAdmin.add_fieldsets+( (None,{'fields':('email','first_name','last_name','image','location','phone1','phone2','fax','website', 'socialMedia1','socialMedia2','socialMedia3','alternativeContact','country','address', 'city','state','zip')}), ) fieldsets = UserAdmin.fieldsets+( (None,{'fields':('email','first_name','last_name','image','location','phone1','phone2','fax','website', 'socialMedia1','socialMedia2','socialMedia3','alternativeContact','country','address', 'city','state','zip')}), ) admin.site.register(CustomUser) -
MyPy, Django, VSCode. ModuleNotFound Error
I really need your help here! I am using VSCode and MyPy extension to type check the Django code that I am writing. I have installed all the necessary requirements for Django like: pip install mypy pip install django-stubs-ext pip install django-stubs I have installed the extension for the VSCode to check my code as well. However, whenever I try to use this extension it outputs the following error: ModuleNotFoundError: No module named 'md_project.settings' I have attached the screenshots of the .ini and .json files of my project. Moreover, I have attached the screenshot of the project tree. I just dont know whats going on with the MyPy. By the way, I am using Windows 10. mypy.ini settings.json project tree -
How to send 'image' via POSTMAN? (Django Image Field)
I'd like to send image via postman like this and save to 'media' directory but don't know how to do this. enter image description here And these are my codes that I use. models.py class Article(models.Model): emotion = models.TextField() location = models.TextField() menu = models.TextField() weather = models.TextField() song = models.TextField() point = models.IntegerField() content = models.TextField() image = models.ImageField(default = 'media/coffee_default.jpg', upload_to = "%Y/%m/%d") user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) created = models.DateTimeField(default = now) liked = models.BooleanField(default = False) num_liked = models.IntegerField(default = 0) views.py @api_view(['POST']) @permission_classes([]) def post_articles(request): user = request.user body = json.loads(request.body) article = Article( emotion = body['emotion'], location = body['location'], menu = body['menu'], weather = body['weather'], image = body['image'], song = body['song'], point = body['point'], content = body['content'], user = user) article.save() serializers = ArticleSerializer(article) return JsonResponse({ "success": True, "data": serializers.data }) serializers.py class ArticleSerializer(serializers.ModelSerializer): class Meta: model = Article fields = ['emotion', 'location', 'menu', 'weather', 'song', 'point', 'content', 'image', 'user', 'created', 'liked', 'num_liked'] -
Pycharm - FastAPI issue with static files
I am struggling to reference my static css files in my template index.html file In my head tag in index.html I have: <link href="{{ url_for('static', path='./styles.css') }}" rel="stylesheet"> It is giving me this error "Cannot resolve directory" In main.py I have the files mounted like so: app.mount("/static", StaticFiles(directory="static"), name="static") Folder Structure: ├── Project_name ├── main.py ├── static │ ├── styles.css ├── Templates │ ├── index.html What could be the cause of this, how can I specify the correct path? -
password_reset_confirm and password_reset_complete in Django
I have used Django's built-in password reset functionality. everything is working fine but when I open the password reset link from Gmail browser redirects me to Django's built-in "password_reset_confime " template instead of my custom template I don't know where I have done mistake in rendering custom template please help me to do that its really appreciated usrl.py Code app_name="accounts" urlpatterns=[ path('password_reset/',auth_views.PasswordResetView.as_view( template_name='password_reset.html', success_url=reverse_lazy('accounts:password_reset_done')),name='password_reset'), path('password_reset_done/', auth_views.PasswordResetDoneView.as_view(template_name='password_reset_done.html'), name='password_reset_done'), path('password_reset_confirm/<uidb64>/<token>/',auth_views.PasswordResetConfirmView.as_view(template_name='password_reset_confirm.html',success_url=reverse_lazy('accounts:password_reset_complete')),name='password_reset_confirm.html'), path('password_reset_complete/', auth_views.PasswordResetCompleteView.as_view(template_name='password_reset_complete.html'), name='password_reset_complete'), ] And I also want to implement a feature while entering an email id into the input field, I want to check if the user's entered email exists or not, if do not exist I want to show an error message "this email id is not existed" please help me to implement this feature and provide a solution for rendering my custom password_reset_confirm.html and password_reset_complete.html pages -
How to send several fields in the response with a PUT request?
I would like when my PUT request is successful it returns me a response with all the fields in my PlantSerializer because currently the response returns me this: { "id":48, "name":"Jar", "width":"50", "height":"50", "exposure":"None", "qr_code":"", "garden":65, "plant":[ 7 ] } But, I would like the response to return this instead: { "id":48, "name":"Jar", "width":"50", "height":"50", "exposure":"None", "qr_code":"", "garden":65, "plant":[ "id":7, "name":"Artichoke", "image":null ] } How can I achieve this result? Here is my serializers and my model class : class Plot(models.Model): name = models.CharField(max_length=50) garden = models.ForeignKey('perma_gardens.Garden', on_delete=models.CASCADE) width = models.CharField(max_length=50, blank=True, null=True) height = models.CharField(max_length=50, blank=True, null=True) plant = models.ManyToManyField('perma_plants.Plant', related_name='%(class)s_plant', blank=True) # Here is my serializers : class GardenSerializer(serializers.ModelSerializer): class Meta: model = Garden fields = ('id', 'name',) class PlantSerializer(serializers.ModelSerializer): class Meta: model = Plant fields = ('id', 'name', 'image') class ReadPlotSerializer(serializers.ModelSerializer): garden = GardenSerializer(required=True) plant = PlantSerializer(many=True) id = serializers.IntegerField(read_only=True) class Meta: model = Plot fields = '__all__' read_only_fields = [fields] class WritePlotSerializer(serializers.ModelSerializer): class Meta: model = Plot fields = '__all__' And here is my views : class PlotViewSet(viewsets.ModelViewSet): queryset = Plot.objects.all() def create(self, request, *args, **kwargs): serializer = WritePlotSerializer(data=request.data, many=isinstance(request.data, list)) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, pk): snippet … -
The easiest way to add attachment in an email - Django
What is the easiest way to add an attachment in a sent e-mail from a model object. If it impossible how look example with EmailMessage. Models.py class File(models.Model): file = models.FileField() Views.py topic = 'Title message' massage = 'Content message' to = ['recipient@example.com', ] attachment = File.objects.last() send_mail(topic, massage, 'bsender@example.com', to, attachment) -
In Django forms I can't use regex validators
Good day. I want to use regex validator for my full_name field in Django 1.11.10. But when I run the below code it doesn't work. How can I fix it? forms.py class CustomerForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(CustomerForm, self).__init__(*args, **kwargs) self.fields['orderorbarcode'].widget.attrs['readonly'] = True self.fields['orderorbarcode'].label = "Order ID or Item Barcode" self.fields['full_name'].label = "Full Name" self.fields['phone_number'].label = "Phone Number" self.fields['full_name'].widget = forms.TextInput(attrs={'placeholder': '*required'}) self.fields['email'].widget = forms.TextInput(attrs={'placeholder': '*required'}) self.fields['phone_number'].widget = forms.TextInput(attrs={'placeholder': '*required'}) class Meta: model = Customer fields = ( 'orderorbarcode','full_name','company','email', 'phone_number','note') AlphanumericValidator = RegexValidator(r'^[0-9a-zA-Z]*$', 'Only alphanumeric characters are allowed.') full_name = forms.CharField(max_length=50, validators=[AlphanumericValidator]) -
Django MIgrations Issues
I'm facing Django migrations problems for a very long time and used to solve that problem using the --fake keyword but then I realized that it's not a good approach and even creates more problems, so after that whenever I faced that issue so I remove the DB and recreate it and then applied migrations and it was working fine but now our data is important and can't remove the DB. The problem is I've created a new Django app in my project and generated the migrations and applied them and working fine at the local but it throws the error I attached below related to migrations. I tried to apply them using the --fake keyword because the feature needs to be at that time but again it was not working I checked the migrations using python manage.py showmigrations and the migrations is there but when I checked django_migrations table in my DB and not a single migration file of that app is not found there, what's the best solution to overcome this issue? error: ProgrammingError at .... column .... does not exist -
django-filter more results when explicitly setting a filter value
I am trying to understand what happens what a field specified in the filterset_fields of the viewset is not specified. My viewset is the following: class DetectionTrainingViewSet( mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet ): queryset = Detection.objects.all() serializer_class = DetectionSerializer filterset_fields = ( 'annotation_set__annotator__id', 'annotation_set__bbox__annotator__id', ) I am making the following GET calls my endpoint http://127.0.0.1:8000/api/v1/detections/: ?annotation_set__annotator__id=2 -> I get 4 results ?annotation_set__annotator__id=2&annotation_set__bbox__annotator__id=2 -> I get 16 results I expected the second call to return a subset of the following one. What's happening here? How can I specify that when a parameter is not explicitly specified any value (if it does not exist) should match the query? -
Static Files not being served with nginx + gunicorn + doker + django
I am making a docker image of a django application with nginx and gunicorn. The configuration files are given below. This server serves static files with ease in development but fails to do so in docker container. What changes do I need to make to serve files in docker? docker-compose.yml version: '3.7' services: segmentation_gunicorn: volumes: - static:/static env_file: - .env build: context: . ports: - "8000:8000" nginx: build: ./nginx volumes: - static:/static ports: - "80:80" depends_on: - segmentation_gunicorn volumes: static: requirements.txt FROM python:3 RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt COPY ./segmentation_site /app WORKDIR /app COPY ./entrypoint.sh / ENTRYPOINT ["sh", "/entrypoint.sh"] requirements.txt DJANGO==4.0.4 gunicorn==20.0.4 tensorflow django-resized pillow==9.1.0 django-crispy-forms==1.14.0 entrypoint.sh python manage.py migrate --no-input python manage.py collectstatic --no-input gunicorn --bind 0.0.0.0:8000 segmentation_site.wsgi:application Dockerfile for nginx FROM nginx:1.19.0-alpine COPY ./default.conf /etc/nginx/conf.d/default.conf default.conf upstream django { server segmentation_gunicorn:8000; } server { listen 80; client_max_body_size 100M; location / { proxy_pass http://django; } location /static/ { alias /static/; } } settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static")