Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Gitlab CI & Django: How to install custom package with pip
I have a Django project that have many dependencies and among those are several custom private Django package listed in our requirements.txt file at the project root. I want to setup simple CI that triggers our tests each time a commit is made. To do so I have written a simple .gitlab-ci.yaml file that tries to run those tests but I am having trouble installing our custom dependencies. They are listed in our requirements like follow: ... Django==3.2.12 ... -e git+ssh://git@gitlab.com/{organization}/{project}.git@{commit-sha}#egg={project} -e git+ssh://git@gitlab.com/{organization}/{project}.git@{{commit-sha}#egg={project} ... Note: All the mentionned projects lies under the same Gitlab organization Here is what my .gitlab-ci.yaml file looks like: stages: - test run-test: image: ubuntu:18.04 stage: test before_script: # installing python, pip & installing requirements - apt -y update - apt -y install apt-utils git net-tools - apt -y install python3.8 python3-pip - apt -y upgrade - python3 -m pip install --upgrade pip - cd servers/api - pip3 install -r ../requirements.txt script: - python3 manage.py test This obviously fails giving the following error: Obtaining {project} from git+ssh://****@gitlab.com/{organization}/{project}.git@{commit-sha}#egg={project} (from -r ../requirements.txt (line 32)) Cloning ssh://****@gitlab.com/{organization}/{project}.git (to revision {commit-sha}) to ./src/{project} Running command git clone --filter=blob:none -q 'ssh://****@gitlab.com/{organization}/{project}.git' /builds/{organization}/platform/servers/api/src/{project} Host key verification failed. fatal: Could not read from … -
Getting a 405 error when visiting a URL I set up
Building a drop in voice chat room using Twilio, following the tutorial outlined by Twilio I have added these as my ALLOWED_HOSTS in my settings.py: ALLOWED_HOSTS = [ ".ngrok.io", "127.0.0.1", "localhost" ] This is how my urls.py is setup: from django.urls import path from .views import RoomView, TokenView urlpatterns = [ path("rooms", RoomView.as_view(), name="room_list"), path("token/<username>", TokenView.as_view(), name="rooms"), ] My Views: @method_decorator(csrf_exempt, name="dispatch") class RoomView(View): def post(self, request, *args, **kwargs): room_name = request.POST["roomName"] participant_label = request.POST["participantLabel"] response = VoiceResponse() dial = Dial() dial.conference( name=room_name, participant_label=participant_label, start_conference_on_enter=True, ) response.append(dial) return HttpResponse(response.to_xml(), content_type="text/xml") class TokenView(View): def get(self, request, username, *args, **kwargs): voice_grant = grants.VoiceGrant( outgoing_application_sid=settings.TWIML_APPLICATION_SID, incoming_allow=True, ) access_token = AccessToken( settings.TWILIO_ACCOUNT_SID, settings.TWILIO_API_KEY, settings.TWILIO_API_SECRET, identity=username ) access_token.add_grant(voice_grant) jwt_token = access_token.to_jwt() return JsonResponse({"token": jwt_token.decode("utf-8")}) my models.py: from django.db import models class Room(models.Model): name = models.CharField(max_length=30) description = models.CharField(max_length=100) slug = models.CharField(max_length=50) def __str__(self): return self.name and apps.py: from django.apps import AppConfig class VoiceChatConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'voice_chat' This is what I have in my parent urls.py (the one I use for other routers on my app): urlpatterns = [ path('', include(router.urls)), path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), # path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/', CustomTokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('api/token/verify/', TokenVerifyView.as_view(), name='token_verify'), path('api/register', RegisterApi.as_view()), path('update_profile/<int:pk>/', views.UpdateProfileView.as_view(), … -
Calculate property with request data in Django
I have class Feedback in models in my django project. It has some charField, IntegerField.. and also custom property. Hovewer what I need is to have a property calculated from input value (from request query params). It means that it is calculated by each request. Because I want to provide this information with all attibutes and other properties of object feedback on list view. Thx for your advice. -
How to convert a models.IntegerField() instance to int?
I've read How to convert a models.IntegerField() to an integer(the poster actually need copy-constructor function).And I've searched for Google. But it doesn't help. what I want to do is: #In app/models.py class Foo: a1 = models.IntergeField() a2 = models.IntergeField() #.... #many else b1 = convertToInt(a1) * 3 + convertToInt(a2) *4 + convertToInt(a7) #calc by needing b2 = convertToInt(a2) * 2 + convertToInt(a3) + convertToInt(a5) #calc by needing #.... #many else #b(b is price actually) will be used in somewhere else.Its type need be int for programmer-friendly using any advice? P.S. English is not my first language.Please forgive my syntax mistakes. -
Python Firebase Admin SDK, Illegal Firebase credential provided
I'm trying initialising Firebase Admin SDK using .env file on a Django app and I get the following error: Illegal Firebase credential provided. App must be initialized with a valid credential instance the initialisation code: from dotenv import load_dotenv load_dotenv() # take environment variables from .env. firebase_admin.initialize_app({ "type": os.getenv("TYPE"), "project_id": os.getenv("PROJECT_ID"), "client_email": os.getenv("CLIENT_EMAIL"), "private_key": os.getenv("PRIVATE_KEY"), "client_id": os.getenv("CLIENT_ID"), "private_key_id": os.getenv("PRIVATE_KEY_ID"), "auth_uri": os.getenv("AUTH_URI"), "token_uri": os.getenv("TOKEN_URI"), "auth_provider_x509_cert_url": os.getenv("AUTH_PROVIDER_X509_CERT_URL"), "client_x509_cert_url": os.getenv("CLIENT_X509_CERT_URL"), }) -
Django SASS processor does not update CSS files in production
I am using django-sass-processor (https://github.com/jrief/django-sass-processor) in order to generate .css from .scss files. The css wiles were generated on the fly in production, based on the modified date of the scss file (as I understand it from the documentation). However, this on-the-fly-generation of files suddenly stopped working. I have moved my static folder to a different location, so I suspect that is a problem, but my regular static operations (collectstatic) works just fine - it's just the css file generation. Here are the relevant variables from my settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'sass_processor', .... ] STATIC_ROOT = '/mnt/hd5/static/' STATIC_URL = '/static/' SASS_PROCESSOR_ROOT = '/mnt/hd5/static/css/' STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'sass_processor.finders.CssFinder', ] The following file is located in /mnt/hd5/static/css: stylesheet.scss If I look at the latest filedate it is indeed the latest version, being modified more recently than the .css files. When I run collectstatic (not even sure that is needed?), it doesn't pick up any modifications. Is there a glaring problem that can be seen above? Or alternatively is there a way I can record/view any error that is generated in the process? -
Django update bootstrap modal not updating untill refresh
Hello django bootstrap modal form works when i create new data gets populated and pop up closes automatically without refresh but when updating success message appears but you have to refresh the page to see the new data. Thank You. swgindex.htm {% block extrascripts %} <script type="text/javascript"> $(function () { // Create book button opens modal with id="create-modal" $("#create-swg").modalForm({ formURL: "{% url 'create_swimmer' %}", modalID: "#create-modal" }); var asyncSuccessMessage = [ "<div ", "style='position:fixed;top:0;z-index:10000;width:100%;border-radius:0;' ", "class='alert alert-icon alert-success alert-dismissible fade show mb-0' role='alert'>", "Success: Swimmer was updated.", "<button type='button' class='close' data-dismiss='alert' aria-label='Close'>", "<span aria-hidden='true'>&times;</span>", "</button>", "</div>", "<script>", "$('.alert').fadeTo(2000, 500).slideUp(500, function () {$('.alert').slideUp(500).remove();});", "<\/script>" ].join(""); function updateModalForm() { $(".update-swg").each(function () { $(this).modalForm({ formURL: $(this).data("form-url"), asyncUpdate: true, asyncSettings: { closeOnSubmit: true, successMessage: asyncSuccessMessage, dataUrl: "/swimminglist/", dataElementId: "#swg-table", dataKey: "table", addModalFormFunction: updateModalForm } }); }); } updateModalForm(); // Read and Delete book buttons open modal with id=".bs-modal" // The formURL is retrieved from the data of the element $(".bs-modal").each(function () { $(this).modalForm({formURL: $(this).data("form-url")}); }); // Hide message $(".alert").fadeTo(2000, 500).slideUp(500, function () { $(".alert").slideUp(500); }); }); </script> {% endblock extrascripts %} Urls.py path('swimminglist/', views.SWGIndex.as_view(), name="swimminglist"), path('create/', views.SWGCreateView.as_view(), name='create_swimmer'), path('update/<int:pk>', views.SWGUpdateView.as_view(), name='update_swimmer'), path('read/<int:pk>', views.SWGReadView.as_view(), name='read_swimmer'), path('delete/<int:pk>', views.SWGDeleteView.as_view(), name='delete_swimmer'), -
MySQL 8.0.27 not accepting django check constraints
I have seen a 2 years old similar question to this but the question did not specify the MySQL version and there is no answers to the question. I'm use the django constraint API to create a model that has 2 foreign keys but both of them cannot exist together and both of them cannot be null at the same time. The constraints look something like this: CheckConstraint(check=Q(type='campaign', campaign__isnull=False), name='check_campaign_data'), CheckConstraint(check=Q(type='trigger', trigger__isnull=False), name='check_trigger_data'), The type indicates which foreign key the model will be using. However, the following warning appears on my console: (models.W027) MySQL does not support check constraints. HINT: A constraint won't be created. Silence this warning if you don't care about it. I have seen that this is now supported for MySQL 8.0.16 or higher. This is the output of mysql --version in my terminal: mysql Ver 8.0.27 for Linux on x86_64 (MySQL Community Server - GPL) Why is this not working if this version of MySQL is supposed to support this feature? -
Save multiple objects serializers
I have multiple serializers objects that comes from the request as json file. I want to store them inside databases only if they are Valid (all of them must be VALID) def post_images(trip_id,data): data['trip']=trip_id serializer = TripImageSerializer(data = data) if serializer.is_valid(): serializer.save() return Response(status = status.HTTP_201_CREATED) return Response({'images':serializer.errors},status= status.HTTP_400_BAD_REQUEST) class Trip_apiView(generics.ListCreateAPIView): queryset= Trip.objects.all() serializer_class=TripSerializer def post(self, request): data = request.data dataImg=data.pop('trip_images') if serializer.is_valid(): instance = serializer.save() respo=post_images(instance.pk,dataImg) if respo.status_code==400: return respo return Response({'trip_images' :serializer.errors}, status= status.HTTP_400_BAD_REQUEST) this is JSON : { "id": 137, "trip_images": [ {"image_title":"image1","image_order":1}, {"image_title":"image2","image_order":2} ], "title": "dqw", "description": "nice", "start_date": "2022-02-08T12:00:00Z", "end_date": "2022-02-14T12:00:00Z", } -
After adding dj-rest-auth I get a sever error 500
After adding user authentication I have not been able to get data from my MySQL database, I get an error code 500 and Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0. I think it might be something to do with my requests and after user authentication I need to add a token to make requests but I am unsure how to. I followed this tutorial: https://blog.devgenius.io/django-react-authentication-part-1-d351726b284d. Exact code can be found here as well as before and after. https://github.com/DoritoThePug/ToDoList/tree/bug%231 All of the 3rd party frameworks 'rest_framework', 'rest_framework.authtoken', 'dj_rest_auth', 'allauth', 'allauth.account', 'allauth.socialaccount', 'dj_rest_auth.registration', 'corsheaders' Custom User from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class CustomUser(AbstractUser): def __str(self): return self.email Fetch Request fetch("/api") .then(response => response.json()) .then( data => this.setState({ todoList: data }) ) As I said, this worked perfectly before I followed the tutorial and added user authentication, I can make requests to the database for user authentication register/logout/login perfectly just not get data from my api. More specific code can be found at the github link above. -
Nginx don't expose CORS headers for media files
I have a vuejs application consuming Django DRF API. All endpoints all working correctly with my current configuration. Except for media files. In Mozilla Developer tools -> Network -> Headers, I check that all API endpoints include cors headers and media files don't. I am using django-cors-headers with common configuration: CORS_ALLOW_ALL_ORIGINS = True ... MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', ... ] INSTALLED_APPS = [ ... 'corsheaders' ] I've tried with different CORS configuration, here in settings.py, as mentioned in several Stackoverflow questions, but nothing change the behavior. I suspect the problem is on NGINX. This is my configuration file: server { server_name my_domain; ... location /media { autoindex on; alias /home/myproject/media; } location / { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://localhost:8000/; } # these options are managed by Certbot, do i think it is ok. listen 443 ssl; ssl_certificate ... ssl_certificate_key ... include ... ssl_dhparam ... } server { if ($host = mydomain) { return 301 https://$host$request_uri; } server_name mydomain; listen 80; return 404; } I've also tried adding add_header Access-Control-Allow-Origin *;, but again, the cors headers are not exposed. What am I missing here? -
How to debug the Duplicate key tablename_columnname_*****
When updating python manage.py migrate I have this error (1061, "Duplicate key name 'shared_models_historicalmessagedelivery_message_title_4bf2c7cb'") I understand this means duplication error. So I truncated the shared_models_historicalmessagedelivery table but in vain. I would like to debug more, so what is the 4bf2c7cb it could be used as clue? -
Django MultiValueDictKeyError at /create/ 'howto-input'
I'm trying to make simple form that would add a comment, I'm not using the forms.forms of django, I'm doing the forms from HTML directly and i want to use ajax to submit the form my form simply has 1 file field and a publish button, everything seem finely coded but i get this MultiValueDictKeyError at /create/ 'howto-input' views.py def create(request): if request.method == "POST": content = request.POST['howto-input'] user = request.POST['howto-user'] topic = request.POST['howto-topic'] new_question = AskQuestionOnHowToTopic(user=user, content=content, topic=topic) new_question.save() messages.success(request, f'Published') success = "Posted Successfully!" return HttpResponse(success) def howtoTutorial(request, howtocat_slug, howto_slug): howtotut = HowToTutorial.objects.get(slug=howto_slug, howtocat=howtocat) context = { 'howtotut': howtotut, } return render(request, 'howto/howto-tutorial.html', context) urls.py path('create/', views.create, name="create") template.html <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <form id="howto-form"> {% csrf_token %} <input type="text" name="content" id="howto-input" /> <input type="hidden" name="user" id="howto-user" value="{{ request.user }}" /> <input type="hidden" name="topic" id="howto-topic" value="{{ howtotut }}" /> <button class="save_btn mt-2 mb-10" type="submit">Publish</button> </form> <script type="text/javascript"> $(document).on("submit", "#howto-form", function (e) { e.preventDefault(); $.ajax({ type: "POST", // url: '/how-to/<howtocat_slug>/<howto_slug>/', url: "/create/", data: { content: $("#howto-input").val(), user: $("#howto-user").val(), topic: $("#howto-topic").val(), csrfmiddlewaretoken: $("input[name=csrfmiddlewaretoken]").val(), }, success: function (data) {}, error: function (xhr, ajaxOptions, thrownError) { alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); }, }); }); </script> -
How to hide backend url in react.js
So i was making a social media app the front end in react.js and the backend is django. If a user presses on the follow button it will make this http request to https://localhost:5000/follow/username/usertobefollowed so any person can inspect the website and type this url to follow someone but i dont want it to be happen i only want the client side to access it. The url gets post method people can use softwares like workshop to send post to the url. how i can hide the url. OS - Windows Python Version - 3.10.0 NPM version - 8.1.3 -
Django: problem between id, foreignkey and views
I need help to understand a part of django. I can't understand the relationships between foreignkeys, or rather the relationships within relationships. Let me explain: I'm making a travel app. In each trip, there is the possibility to add an activity. These activities are unique per trip and are therefore linked via a Foreignkey. Each activity also has a unique address. These are also linked to the activities via a Foreignkey. I would like to do 2 things: Post each trip with these activities. For each of the activities, the addresses should be displayed. Display the lists of trips, showing the country where the activities take place "country" of "addresse" of "activities". # models.py class Adresse(models.Model): libelle = models.fields.CharField(max_length=100) numero = models.fields.IntegerField(null=True) street = models.fields.CharField(max_length=100) code = models.fields.IntegerField(null=True) city = models.fields.CharField(max_length=100, null=True) country = models.ForeignKey(Country, null=True, blank=True, on_delete=models.SET_NULL) def __str__(self): return f'{self.libelle}' class Trip(models.Model): title = models.fields.CharField(max_length=100) traveller = models.ManyToManyField(Character) date_start = models.DateField(default=date.today) date_end = models.DateField(default=date.today) def __str__(self): return f'{self.title}' class Activity(models.Model): TRANSPORT = 'TRANSPORT' HEBERGEMENT = 'Hébergement' RESTAURATION = 'RESTAURATION' LOISIR = 'LOISIR' ROLE_CHOICES = ( (TRANSPORT, 'Transport'), (HEBERGEMENT, 'Hébergement'), (RESTAURATION, 'Restauration'), (LOISIR, 'Loisir'), ) category = models.CharField(max_length=30, choices=ROLE_CHOICES) trip = models.ForeignKey(Trip, null=True, blank=True, on_delete=models.SET_NULL) adresse = models.ForeignKey(Adresse, null=True, … -
Is there any way to run docker container using django endpoint request?
I want to run docker container using Django endpoint request. I have multiple docker containers which needs to be run after the Django endpoint request calls. Or any alternative suggestions are also welcome. -
Updating a form with image field using htmx and django
I have a model Post class Post(models.Model): content = models.TextField() image = models.ImageField(upload_to='posts',blank=True) and I have form for that model class PostModelForm(forms.ModelForm): class Meta: model = Post fields = '__all__' I'm using htmx and I have some partial templates inside my main template. this is my partial template form to update my post {% load i18n crispy_forms_tags widget_tweaks %} <form action="" class="mt-2 ml-2" hx-put="{% url 'posts:edit-post-form' post.id %}" hx-target="#PostContent-{{post.id}}" enctype="multipart/form-data"> {% csrf_token %} {% render_field form.content class="form-control" name="content" %} {% render_field form.image class="form-control" name="image" %} <button type='submit' class="btn btn-outline-info">{% trans "Update" %}</button> </form> and below you can check my view from django.http.multipartparser import MultiPartParser from django.http import QueryDict def edit_post_form(request,pk): try: post = Post.objects.get(pk=pk) form = PostModelForm(request.POST or None, request.FILES or None ,instance=post) if request.user.profile == post.author: if request.method == "PUT": data = QueryDict(request.body).dict() # print(request.META['CONTENT_TYPE']) # MultiPartParser(request.META, request, request.upload_handlers).parse() if form.is_valid(): form.save() return redirect("posts:edit-post-detail" , pk=post.id) else: print(form.errors) return render(request, 'posts/partials/edit_post_form.html',context = {'post':post,'form':form}) else: return redirect("posts:main-post-view") except ObjectDoesNotExist: return HttpResponse("This post has been deleted") Since I have a "multipart/form-data" when I print data data = QueryDict(request.body).dict() print(data) I'll see the output sth like the dictionary below {'------WebKitFormBoundary4ZEQZO2qHFj9tp7w\r\nContent-Disposition: form-data; name': '"csrfmiddlewaretoken"\r\n\r\nQu0zvB12321jnzcxdfdasd7ItP9x2tLqnLjjhudnhcARv4zMkqdmzksQFuk56uq\r\n------WebKitFormBoundary4ZEQZO2qHFj9tp7w\r\nContent-Disposition: form-data; name="content"\r\n\r\nnew\r\n------WebKitFormBoundary4ZEQZO2qHFj9tp7w--\r\n'} I tried to use MultiPartParser but I … -
Python Django redirect to external url with session cookies?
Is there any way to redirect from python django page to external url and different website with it's own session cookies like JSESSIONID? My django web app doesn't use any JSESSIONID but I am planning to keep another website's JSESSIONID's and redirect it from my web app with its JSESSIONID. I think it's kinda like OAuth methodology I want to build. If I can't do this, I think I need to build a little desktop app to do this only. But changing to this method is my worst case scenario. What do you think? Thx in advance... -
How to send requests from one service to another in docker swarm?
I need a piece of advice regarding a docker swarm architecture. I have 2 nodes, a manager and a worker. In my swarm I have 3 replicas of my backend (Django), 3 replicas of my frontend (React) and 1 of my PostgreSQL database. I don't have nginx or traefik or anything else besides that. For some reason, the routing doesn't work. Sending POST requests from my frontend to my backend returns ERR_NAME_NOT_RESOLVED. I tried fetching for http://my_backend_service_name:8000/, relying on the swarm to do the load balancing. I am sure I am missing something. but from everything I read I understood this should be possible without traefik, nginx or anything else. This is my docker compose stack file: services: frontend: image: xxxxxx command: npm start ports: - "3000:3000" stdin_open: true networks: - web_network env_file: xxxxx deploy: replicas: 3 restart_policy: condition: on-failure db: image: postgres:11 ports: - "5432:5432" command: "-c logging_collector=on" volumes: - ./database/postgres_data:/var/lib/postgresql/data/ networks: - data_network environment: - POSTGRES_USER=xxxxx - POSTGRES_PASSWORD=xxxxx - POSTGRES_DB=xxxx deploy: placement: constraints: - "node.role==manager" restart_policy: condition: on-failure delay: 5s max_attempts: 3 window: 120s web: image: xxxxx depends_on: db: condition: service_started command: bash -c "python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" ports: - … -
Comment with replies in django
I am working on blog application in django and I added comment section section in blog but I am having problem show replies for parent comment. Models.py class Comment(models.Model): comment_text = models.TextField(("comment_text")) user = models.ForeignKey("account.User", related_name=("comment_user"), on_delete=models.CASCADE) post = models.ForeignKey("Post", related_name=("comment_post"), on_delete=models.CASCADE) parent = models.ForeignKey('self',related_name=("replies"), on_delete = models.CASCADE , blank= True ,null=True) timestamp = models.DateTimeField(("Comment Timestamp"), auto_now=False, auto_now_add=True) def __str__(self): return self.user.username blog.html <div Class ="container"> <h3><b>Comments...</b></h3> <div class ="row"> <div class = "col-8"> <div class ="row"> {% if not post.comment_post.all %} No comments Yet {% else %} {% for comment in post.comment_post.all %} {% if comment.parent is Null%} <br> <hr> <div class = "col-2"> <img class="rounded-circle" width="80" height="60" src="{{comment.user.profile_image.url}}"> </div> <div class ="col-10"> <strong>{{comment.user.first_name}} {{comment.user.last_name}}</strong> <span class ="float-end"><i class="far fa-clock"></i> {{comment.timestamp.date}}</span> <p>{{comment.comment_text}}</p> </div> {%endif%} {% endfor%} <hr> <br> {% endif %} <div> {{form|crispy}} <span class ="float-start">Post Comment as: <b>{{request.user.first_name}} {{request.user.last_name}} </b></span> <button type="button" class="btn btn-primary btn-sm float-end mb-2">Post comment</button> </div> </div> </div> <div class ="col-4 bg-info"> .... </div> </div> </div> views.py class PostDetailView(FormMixin,DetailView): model = Post form_class = CommentForm template_name = 'MainSite/blogpost.html' I cant think of anyway to show replies under parent comment. Thanks in advance and any advice will be helpful -
Add data-id attribute to each <option> of a <select> field or change value attribute?
This is a website for a tattoo shop. I have an Artist and Tattoo model: class Artist(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) # etc class Tattoo(models.Model): artist = models.ForeignKey(Artist, on_delete=models.CASCADE) name = models.CharField(max_length=150) image = models.ImageField(upload_to='images/') and a ModelForm designed to allow artists to filter tattoos by artist: class FilterArtForm(ModelForm): class Meta: model = Tattoo fields = ['artist'] widgets = { 'artist': forms.Select(attrs={'id': 'filter_by_artist'}), } This form will create the following: <form> <label for="filter_by_artist">Artist:</label></th> <select name="artist" id="filter_by_artist" required> <option value="" selected>---------</option> <option value="1">Artist 1</option> <option value="2">Artist 2</option> </select> </form> I am trying to store each Artist objects id in their respective <option> field. I was thinking I would have to add something like data-artist_id to each one as such: <option value="1" data-artist_id >Artist 1</option> but I suppose I could just change the value attribute? Looking at it, if the value attribute automatically increases by 1 each time it would seem that that should always align with the Artist's object id value, but it just seems like I should be more explicit to avoid future headaches(for example if an Artist object gets deleted and another added, I don't think these values will longer align)? Is there a way to build … -
Join two tables through third one with two foreign keys
I have three tables: class Bank(models.Model): ... class Deposit(models.Model): ... class DepositProposal(models.Model): percent = models.FloatField() deposit = models.ForeignKey(Deposit) bank = models.ForeignKey(Bank) Bank can participate in deposit auction applying DepositProposal instance. How can I filter Deposit rows which bank hasn't participated yet? Found that I should use two LEFT JOIN but I didn't come across it. Using PosgtreSQL. -
Django model foreignkey or charfield?
Django Model and Form that I want to make Hello. I'm fairly new to Django and I have a hard time understanding which model field to use. I didn't post any code because my code is so messy right now and most of it still following "Django for Beginner" book by William S. Vincent. I have an app consisting 2 models, product model and production model. Some fields on production model are linked to product model. Then from production model, I make a form for user input using ModelForm. There's a link to an image to help understanding model and form relation. I have several questions regarding this matter. If I set product_id on Production Model as ForeignKey to Product, what field should I use for product_name and material? When I use CharField for both product_name and material, there are entry for both product_name and material on form and I don't want that. How to change it to readonly and have value updated based on product_id? (I'm not sure if this is related to Django form or not.) Right now I'm using ModelForm to make Production Form and then using FormView to render the form. Is it the right approach? … -
Django Form: Hidden Field Error When going to next wizard: (Hidden field ) This field is required
I have tried couple of ways to avoid this error from view code and on django template as well. Also tried to popped out the fields as well but none are working and getting the same error every time(This field is required) . We are using step wizards to show and hide the fields on different form wizard steps from views.py . Whenever we visit the previous page on click on previous button then only the step 2 fields are empty and showing the error. Appreciate any quick help on this. Here is the models.py from django.db import models from django.core.validators import MinValueValidator, MaxValueValidator class CStructure(models.Model): z_caisson_lower_limit = models.FloatField(verbose_name='C level limits', default=5.0) z_caisson_upper_limit = models.FloatField(verbose_name='C limits', default=10.0) z_caisson_step_size = models.FloatField(verbose_name='C level limits', default=1) caisson_width_lower_limit = models.FloatField(verbose_name='C width limits', default=10) caisson_width_upper_limit = models.FloatField(verbose_name='C width limits', default=20) caisson_width_step_size = models.FloatField(verbose_name='C width limits', default=5) Here is the form.html {% block content %} {% if wizard.steps.current == '3' %} <div id="loading-overlay"> <i class="fas fa-spin fa-8x fa-cog" id="loading-icon"></i> <p> Calculation can be cancelled on the <a target="_blank" href="{% url 'project_detail' pk=project_id %}">project page</a>. </p> </div> {% endif %} // Below are the steps of wizards to show the fields or fields label <div class="container-fluid">`enter code … -
'CustomUser' object has no attribute get
I am having this error when I access a view. Especifically saying that my error is in `{% if form.errors %} <p>{{form.errors}}</p> {% endif %}`" But this error, is strange to me. I have a form in this view. class UserCreationLabForm(UserCreationForm): username = forms.RegexField(label=("Email"), max_length=30, regex=r'^[\w.@+-]+$', help_text = ("Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only."), error_messages = {'invalid': ("This value may contain only letters, numbers and @/./+/-/_ characters.")}) telephone = forms.IntegerField(required=False) is_secretarial = forms.BooleanField(required=False) class Meta(UserCreationForm.Meta): model = CustomUser fields = ('email', 'user_type', 'telephone', 'FKLab_User', 'is_secretarial',) exclude = ['user_type','FKLab_User', 'username',] def clean(self): cleaned_data = super(CustomUser,self).clean() email = self.cleaned_data.get('email') telephone = self.cleaned_data.get('telephone') is_secretarial = self.cleaned_data.get('is_secretarial') username = self.cleaned_data.get('username') if len(email) == 0: self._errors['email'] = self.error_class(['Insert cant be empty.']) if len(telephone) == 0: self._errors['telephone'] = self.error_class(['Insert cant be empty.']) if len(is_secretarial) == 0: self._errors['is_secretarial'] = self.error_class(['Insert cant be empty.']) if len(username) == 0: self._errors['username'] = self.error_class(['Insert cant be empty.']) return self.cleaned_data I had to override it to only accept email. But It was working fine yesterday. My view @login_required @permission_classes((IsAuthenticated,)) #Registration view. def RegistrationLab_View(request): fklab_user = HospitalViewRoleForUsers.objects.get(id = request.user.FKLab_User.id) print(fklab_user.id) if request.user.is_authenticated and request.method == "POST": form = UserCreationLabForm(request.POST) if form.is_valid(): new_user = form.save(commit=False) #new_user.username = new_user.FKLab_User = fklab_user …