Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Refresh a django subtemplate with javascript
I'm trying to refresh a subtemplate by calling a view with js. Nothing seems to happen, though the server gets hit and seems to return a response. The goal is to refresh the included part without refreshing the whole page. Minimal example: views.py def ajax_view(request): context = {} context['data'] = 'data' return render(request, "test.html", context)// <-- reaches here, but no rendering test.html {{data}} main.html <script type="text/javascript"> function getQuery() { var request = new XMLHttpRequest(), method = 'GET', url = '/ajax/'; request.open(method, url); request.send(); } </script> {% include "test.html" %} // <-- does not update -
filter access to detailview by a simple field and/or a manytomanyfield
i want to limit the access to detailView of a chatroom to the owner and participants of the room(joiners) model: class PublicChatRoom(models.Model): title = models.CharField(max_length=100, unique=True, blank=False) owner = models.ForeignKey(User,related_name='chatrooms_created',on_delete=models.CASCADE) joiners = models.ManyToManyField(User, blank=True,related_name='chatrooms_joined') view: class JoinerRoomDetailView(DetailView): model = PublicChatRoom template_name = 'detail.html' def get_queryset(self): return PublicChatRoom.objects.filter(Q(joiners__in=[self.request.user]) | Q(owner=self.request.user)) and some rooms give the following error : get() returned more than one PublicChatRoom -- it returned 2! if i use the view like this: class JoinerRoomDetailView(DetailView): model = PublicChatRoom template_name = 'detail.html' def get_queryset(self): return PublicChatRoom.objects.filter(Q(joiners__in=[self.request.user])) #the modified part only if the user that is in participant list have access, wich is correct and if it,s that: class JoinerRoomDetailView(DetailView): model = PublicChatRoom template_name = 'detail.html' def get_queryset(self): return PublicChatRoom.objects.filter(Q(owner=self.request.user)) #the modified part only the creator of room can see it, again correct everything works as expected. but the Goal is to acces rooms that a user own or a part of both, so how can i do that, thanks for help -
RelatedObjectDoesNotExist at /friends/ User has no profile
I am stuck now for a good 3 hours on this bug. def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You can now login!') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form':form}) def friend_list(request): p = request.user.profile friends = p.friends.all() context={ 'friends': friends } return render(request, "users/friend_list.html", context) request.user.profile is not containing an object. What could be the problem? -
How I can use swagger.json from editor.swagger.io in my Django+drf-yasg project?
I integrate drf-yasg in my project, generate json file: python manage.py generate_swagger swagger.json. After that I edit my swagger.json in editor.swagger.io and export it. And now, how i can use this manually created swagger.json file in my project instead autogenerate? Thanks. -
How to save multiple django form in one page with one submit button
i'm new when developing django. I have some question after days by days finding the answer. Here the go. What i want is making ajax form that handle 2 model form, with 1 submit button I can already saved the data in each form, but got problem in foreign key field got None instead Here we go my model: class ModelA(models.Model): name = models.CharField(max_length=100, blank=True) info = models.CharField(max_length=200, blank=True) def __str__(self): return self.name class ModelB(models.Model): xmodel = models.ForeignKey(to=ModelA, on_delete=models.CASCADE, related_name='modelX', blank=True, null=True) no_1 = models.CharField(max_length=150, blank=True) no_2 = models.CharField(max_length=150, blank=True) Form Class: class ModelAForm(forms.ModelForm): class Meta: model = ModelA fields = '__all__' class ModelBForm(forms.ModelForm): class Meta: model = ModelB exclude = ('xmodel',) View class: def AddData(request): tpl = 'add.html' if request.method == 'POST': mdla = ModelAForm(request.POST) mdlb = ModelBForm(request.POST) if mdla.is_valid(): obj = mdla.save() if mdlb.is_valid(): mdlb.save(commit=False) mdlb.xmodel=obj mdlb.save() else: mdla = ModelAForm() mdlb = ModelbForm() In TPL i'm using ajax to send, it can save model a and model b, but in modelb xmodel (foreign key) it got None when check in adminpanel. Which i do wrong, how to make it happen when handling the forms? -
Django web app with Microsoft azure custom vision
Is it possible to integrate Microsoft azure services like Custom vision in the Django app? I want to build a web app where users can upload images and train a model using those images using Custom Vision from Microsoft Azure. -
Django Google App Engine SQL db non-deterministically thinks a row does not exist
I have a Django backend server hosted on Google App Engine that uses a MySQL database. I am using Firebase (via the Pyrebase wrapper) to authenticate users. The following function is what I use to get the User object given a an auth-token that's stored in the request HTTP metadata. def user_from_request(request): refresh_token = request.META.get("HTTP_AUTHORIZATION") fb_user = auth.refresh(refresh_token) # Firebase user information. firebase_id = fb_user.get("userId") potential_user = User.objects.filter(firebase_id=firebase_id) if potential_user.count() == 0: print('auth token', refresh_token) print('firebase id', firebase_id) return None return potential_user.get() For the most part, it works fine, but there are some small cases (from what I can tell, it is non-deterministic which means it's been a pain to debug) when the auth token will exist in Firebase and we are able to get an associated Firebase id, but SQL (specifically the User.objects.filter(firebase_id=firebase_id) line will return an empty query set. The following is what is printed out when that case happens. auth token XXXXXX # changed to protect user information firebase id XXXXXX # changed to protect user information The strange part is is that there does exist a User row in the database where that Firebase id exists. Subsequent requests with the same auth token will successfully grab … -
Django Error refers to model that isn't installed after Updating
This has only come about since I've updated Django. Here is the relevant settings.py # snipped INSTALLED_APPS = [ 'ctf_club', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'ctf_club.apps', ] # snipped AUTH_USER_MODEL = "ctf_club.User" And here's the output of finding User in the ctf_club/models.py file. grep 'User' ctf_club/models.py from django.contrib.auth.models import AbstractUser # User model is just here so I can reference it, I use the default model. class User(AbstractUser): user = models.ForeignKey(User,on_delete=models.CASCADE,related_name='solves') user = models.ForeignKey('User',on_delete=models.CASCADE) #used = models.ManyToManyField(User) ctf_club/models.py from django.contrib.auth.models import AbstractUser from django.db import models from django.utils import timezone from ctf_club.util import jsonify_queryset """ CTFClub Project By Macarthur Inbody <admin-contact@transcendental.us> Licensed AGPLv3 Or later (2020) """ # User model is just here so I can reference it, I use the default model. class User(AbstractUser): points = models.IntegerField(default=0) tfa_enabled = models.BooleanField(default=False) tfa_secret = models.CharField(max_length=32,default=None) def to_dict(self): return {'id':self.id, 'username':self.username, 'email':self.email, 'is_staff':self.is_staff, 'is_superuser':self.is_superuser, 'first_name':self.first_name, 'last_name':self.last_name, 'date_joined':self.date_joined, 'is_active':self.is_active, 'last_login':self.last_login } But I'm getting the standard error of File "/usr/local/lib/python3.7/dist-packages/django/contrib/auth/__init__.py", line 165, in get_user_model "AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'ctf_club.User' that has not been installed But that makes no sense as this worked fine prior to updating it but now it … -
How to create an extended User Object in Django?
I created a model ExtendedUser to extend the User Django built-in model class using the approach described in the official documentation: https://docs.djangoproject.com/en/3.2/topics/auth/customizing/#extending-the-existing-user-model so that I can benefit from the existing authentication features provided by Django. That works all fine however I wonder now, whenever I want to create a new ExtendedUser, that means for every ExtendedUser, I also need to create an original User to fullfill the one-to-one relationship? Or what else does it mean the following: Assuming an existing Employee Fred Smith who has both a User and Employee model, you can access the related information using Django’s standard related model conventions[...] In a script to create objects, would this mean the following: u1 = User.objects.create_user(username="u_1", email="u_1@abc.com", password="pw_u_1") ext_u_1 = ExtendedUser.objects.create(id=u1.id, user=u1, prop_1="XYZ") where class ExtendedUser(models.Model): user = models.OneToOneField(User, ...) # More properties... -
django saving two model on a oneto many relationship
I have a template that I use to save two models on a one to many relationship. In this template, I have two questions the first question has radio choices and the second question has checkbox choices like what is shown on the image below. What happens is when I select, for instance, choice#1 in question 1 and check checkbox#1 in question 2 the form is saved successfully. But if I select choice#3 in question 1 and check checkbox#1 or checkbox#2 in question 2 then i get an error: CheckChoice matching query does not exist. I am not sure why i am getting this error. class Survey(models.Model): title = models.CharField(max_length=200) created_at = models.DateTimeField(default=timezone.now) archive = models.CharField(max_length=200, default='') def __str__(self): return self.title class Question(models.Model): survey = models.ForeignKey(Survey, on_delete=models.CASCADE) enter_question = models.CharField(max_length=900) def __str__(self): return self.enter_question class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice = models.CharField(max_length=100) class CheckChoice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_check = models.CharField(max_length=100) class SurveyAnswer(models.Model): orig_survey = models.ForeignKey(Survey, on_delete=models.CASCADE) class QuestionAnswer(models.Model): answer = models.ForeignKey(Choice, on_delete=models.CASCADE) check_answer = models.ForeignKey(CheckChoice, on_delete=models.CASCADE) survey_answer = models.ForeignKey(SurveyAnswer, on_delete=models.CASCADE) def survey_fill(request): ans = SurveyAnswer() orig_survey = Survey.objects.get(id=request.POST['survey_id']) ans.orig_survey = orig_survey ans.save() questions = orig_survey.question_set.all() for question in questions: qc = request.POST['question' + str(question.id)] qa = QuestionAnswer() qa.answer … -
how to add comments only to authorized users?
Added the ability to add comments, made it so that only authorized users can add comments, but for some reason this does not work, please fix it. And I also added , but for some reason it does not work either, Thanks everyone! post_detail.html {% extends 'base.html' %} {% load static %} {% block content %} <link href="{% static 'css/post_detail.css' %}" rel="stylesheet"> <div class="post-entry"> <h2>{{ post.title }}</h2> <p>{{ post.body|urlize }}</p> </div> <p><a href="{% url 'post_edit' post.pk %}">+ Edit Blog Post</a></p> <p><a href="{% url 'post_delete' post.pk %}">+ Delete Blog Post</a></p> {% if post.header_image %} <p><img src="{{post.header_image.url}}"></p> {% else %} <p></p> {% endif %} {% for comm in post.commentpost_set.all%} {{ comm.user }} <br> {{ comm.text }} <br><br> {% endfor %} <br> <hr> <h2>Comments...</h2> {% if not post.comments.all %} No Comments Yet...<a href="{% url 'post_comment' post.pk %}"> Add Comment</a> {% else %} <form method="post"> {% csrf_token %} {{ comment_form.as_p }} {% if request.user.is_authenticated %} <a href="{% url 'post_comment' post.pk %}">Add Comment</a><br><br> {% else %} <a href="{% url 'post_comment' post.pk %}">Add Comment</a><br><br disabled> {% endif %} </form> {% for comment in post.comments.all %} <strong> {{ comment.name }} - {{ comment.date_added }} </strong> <br> {{ comment.body }} <br><br> {% endfor %} {% endif %} {% … -
Django/DRF changing POST requests to GET
Whenever my frontend sends off a POST request to /api/notebooks/, Django automatically converts it to a GET request to /notebooks?name=[whatever I just typed in]. This isn't the case when I make POST requests to /api/notes/. Whenever I do, it creates a Note object and saves it to the database, the way it's supposed to. Did I mess up anything in my config? I'm 100% sure I've been shooting off my POST requests to /api/notebooks/ rather than /notebooks/... notebooks/urls.py from notebooks.views import NoteViewSet, NotebookViewSet from rest_framework import renderers notebook_list = NotebookViewSet.as_view({ 'get': 'list', 'post': 'create', }) notebook_detail = NotebookViewSet.as_view({ 'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy', 'post': 'create', }) note_detail = NoteViewSet.as_view({ 'get': 'retrieve', 'post': 'create', 'put': 'update', }) core/urls.py from django.contrib import admin from django.urls import path, include from rest_framework.routers import DefaultRouter from notebooks import views router = DefaultRouter() router.register(r'notebooks', views.NotebookViewSet, basename='notebooks') router.register(r'notes', views.NoteViewSet, basename='notes') urlpatterns = [ # auth path('auth/', include('authentication.urls')), # notebook path('admin/', admin.site.urls), path('api/', include(router.urls)), # frontend path('', include('frontend.urls')), path('notebooks/', include('frontend.urls')), path('signup/', include('frontend.urls')), path('login/', include('frontend.urls')), path('notebooks/<slug:notebook_pk>/', include('frontend.urls')), path('notebooks/<slug:notebook_pk>/notes/<slug:note_pk>/', include('frontend.urls')), path('new-note/', include('frontend.urls')), ] notebooks/serializers.py import json from django.core.files.base import ContentFile from rest_framework import serializers from .models import Note, Notebook, User class NoteSerializer(serializers.ModelSerializer): note_id = serializers.SlugField(source='id', read_only=True, required=False) … -
How would I display MediaPipe/OpenCV in Django?
Trying to run a pose estimator in my Django project. How would I get this to run in my browser? I have it set up in an algos.py file. Need it to display the video it is capturing while it is running the calcs. def pose_capture(): cap = cv2.VideoCapture(0) ## Setup mediapipe instance with mp_pose.Pose(min_detection_confidence=0.5, min_tracking_confidence=0.5) as pose: while cap.isOpened(): ret, frame = cap.read() # Recolor image to RGB image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) image.flags.writeable = False # Make detection results = pose.process(image) # Recolor back to BGR image.flags.writeable = True image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) # Extract landmarks try: landmarks = results.pose_landmarks.landmark # Get coordinates shoulder = [landmarks[mp_pose.PoseLandmark.LEFT_SHOULDER.value].x,landmarks[mp_pose.PoseLandmark.LEFT_SHOULDER.value].y] elbow = [landmarks[mp_pose.PoseLandmark.LEFT_ELBOW.value].x,landmarks[mp_pose.PoseLandmark.LEFT_ELBOW.value].y] wrist = [landmarks[mp_pose.PoseLandmark.LEFT_WRIST.value].x,landmarks[mp_pose.PoseLandmark.LEFT_WRIST.value].y] # Calculate angle angle = calculate_angle(shoulder, elbow, wrist) # Visualize angle cv2.putText(image, str(angle), tuple(np.multiply(elbow, [640, 480]).astype(int)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2, cv2.LINE_AA ) except: pass # Render detections mp_drawing.draw_landmarks(image, results.pose_landmarks, mp_pose.POSE_CONNECTIONS, mp_drawing.DrawingSpec(color=(245,117,66), thickness=2, circle_radius=2), mp_drawing.DrawingSpec(color=(245,66,230), thickness=2, circle_radius=2) ) cv2.imshow('Mediapipe Feed', image) if cv2.waitKey(10) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows() From what I was seeing so far is to run it as a view. Something along the lines of: def video(request): pose_capture() return HttpResponse() Or StreamingHTTPResonse? If this is the route to take, how does that … -
Django formsets do not save images
I have an addpage form where users have to add their card for boots model. Below i will show to you my code. SO! The problem is my images are not saving at my media directory at all. And so one of the consequences Card.model doesn't take this images, but rest of the form fields working perfictly. Sorry for my bad english and asking for support!! Models.py class Card(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='Категория') brand = models.ForeignKey(Brand, on_delete=models.PROTECT, verbose_name='Бренд') boots_model = models.CharField(max_length=100, db_index=True, verbose_name='Модель бутс') description = models.TextField(verbose_name='Описание') slug = AutoSlugField('URL', max_length=70, db_index=True, unique_with=('created', 'boots_model', 'size', 'color', 'price'), populate_from=instance_boots_model, slugify=slugify_value) price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='Цена') # image = models.ImageField(upload_to="photos/%Y/%m/%d/", blank=True, verbose_name='Загрузите фотографии') created = models.DateTimeField(auto_now_add=True, db_index=True) updated = models.DateTimeField(auto_now=True) size = models.DecimalField(max_digits=4, decimal_places=1, verbose_name='Размер') NEW = 'new' USED = 'old' STATEMENT_CHOICES = [ (NEW, 'Новые'), (USED, 'Б/У') ] statement = models.CharField(max_length=3, choices=STATEMENT_CHOICES, default=USED, verbose_name='Состояние') color = models.CharField(max_length=100, db_index=True, verbose_name='цвет') class Meta: ordering = ('-created',) verbose_name = 'Объявление' verbose_name_plural = 'Объявления' def __str__(self): return self.boots_model def save(self, *args, **kwargs): self.slug = uuslug(self.slug, instance=self) super(Card, self).save(*args, **kwargs) def get_absolute_url(self): category = self.category brand = self.brand return reverse('card', args=[str(category.slug), str(brand.slug), str(self.slug)]) class ImagePhoto(models.Model): directory = models.ForeignKey(Card, on_delete=models.CASCADE) image = models.ImageField(upload_to=upload_custom_directory, blank=True, verbose_name='Фотографии') def … -
Dramatiq execute many times a task
I'm currently running on docker-compose on an 8 core instance (docker_serivce, dramatiq_service, rabbitmq_service, postgres_service, etc): django_apscheduler==0.5.2 dramatiq [rabbitmq, watch]==1.8.1 RabbitMQ (rabbitmq: 3.8-management-alpine image) The bug is that many processes are executing the same task. The task is created only once (apscheduler BackgroundScheduler), but several processes try to execute it, and some threads are the same between different processes. Here is an example. The job is in the queue once but when it's executed, many processes take it. 139698903181056 is the thread and 21 the process "INFO | 10/06/2021 10:30:09 | 139698903181056 | app.orders.tasks | tasks | tasks.py | 22 | 39 | send_menu | Sending menu #87..." "INFO | 10/06/2021 10:30:09 | 139698894788352 | app.orders.tasks | tasks | tasks.py | 22 | 39 | send_menu | Sending menu #87..." "INFO | 10/06/2021 10:30:08 | 139698911573760 | app.orders.tasks | tasks | tasks.py | 18 | 39 | send_menu | Sending menu #87..." "INFO | 10/06/2021 10:30:07 | 139699123865344 | app.orders.tasks | tasks | tasks.py | 19 | 39 | send_menu | Sending menu #87..." "INFO | 10/06/2021 10:30:03 | 139698903181056 | app.orders.tasks | tasks | tasks.py | 21 | 39 | send_menu | Sending menu #87..." "INFO | 10/06/2021 10:30:02 | … -
queryset.update does not update the queryset data
prospects_to_els = Prospect_Properties.objects.filter(Q(file__pk=None) & Q(m2m_file_id=file.id)) if file.list: file.prospect_files.add(*list(prospects_to_els)) file.list.prospect_lists.add(*list(prospects_to_els)) if file.tag_id: tag = Tag.objects.get(id=file.tag_id) tag.prospect_tags.add(*list(prospects_to_els)) prospects_to_els.update(is_validate_complete=True) if start_indexing(prospects_to_els,'update_and_index function'): prospects_to_els.update(added_to_els=True) file.els_status = 'es done' file.save() Please see the above code, on line prospects_to_els.update(is_validate_complete=True),I am trying to update the queryset with update and it doesn't work. The code above it works fine. But if I replace the prospects_to_els.update(is_validate_complete=True) with Prospect_Properties.objects.filter(file=file).update(added_to_els=True) which gets same records again from database, it works fine. I guess the issue has something to do with update, can someone help me identify. TIA. -
Optimum Serializing in Django Rest Framework and parsing in Javascript
I am trying to adapt an event calendar vuejs module called dayspan calendar. Current entry object for an event as json is a bit strange and I want to balance the parsing of the payload before the post request and handling of data in DRF serializers. So I can get an optimum and performant client-server rest API communication. Json output is as below before any parsing: { "data": { "title": "YOK", "description": "", "location": "", "color": "#1976d2", "forecolor": "#ffffff", "calendar": "", "busy": true, "icon": "" }, "schedule": { "times": [ "17" ], "dayOfMonth": [ 11 ], "year": [ 2021 ], "month": [ 5 ] } } There are more schedule fields like "dayOFWeek", "duration" etc. that is to be expected for different entries. What would be the best approach in terms of parsing json payload before posting to DRF and in deserializing stage before saving into database? I appreciate any ideas. -
Djnago not appending slash, appeared new path which i did not add
Django not appending slash on my urls, it's appeared some new path which i did not add, and which match urls without slash. A time ago it was working, but know that thing appeared and i dont know why APPEND_SLASH it true but it's not a case MIDDLEWARE MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", "django.middleware.locale.LocaleMiddleware", 'trips.middleware.SettingsMiddleware', ] urls.py from django.urls import path, include,re_path from django.contrib import admin from django.contrib.auth import views as auth_views from django.conf import settings from django.conf.urls.static import static from django.views.generic.base import TemplateView admin.autodiscover() import trips.views urlpatterns = [ path("", trips.views.list, name="list"), path("tourist_exchange/", TemplateView.as_view(template_name = "tourist_exchange.html"), name="tourist_exchange"), path("list/", trips.views.list, name="list"), path("live_search/",trips.views.live_search, name = "live_search"), path("saveGuide/", trips.views.addToSaved, name="saveGuide"), path("unSaveGuide/", trips.views.removeFromSaved, name="saveGuide"), path("savedGuides/",trips.views.savedGuides, name = "savedGuides"), path("location/<str:location_slug>/", trips.views.list, name="list"), path("country/<str:country_slug>/", trips.views.list, name="list"), path("register/", trips.views.register, name="register"), path("login/", trips.views.social_login, name="social_login"), path("facebook_deletion/", trips.views.facebook_deletion,name = "facebook_deletion"), path("deleteProfile/", trips.views.deleteProfile,name = "deleteProfile"), path("password_recover/", trips.views.password_recover, name="password_recover"), path("agent/", trips.views.agent, name="agent"), path("profile/", trips.views.profile, name="profile"), path("profile/change_photo/",trips.views.change_photo,name="change_photo"), path("booking_list/",trips.views.bookings_list, name = "booking_list"), path("booking_list/booking_archive/",trips.views.bookings_archive, name = "booking_archive"), path("booking_list/confirm/<int:book_id>/",trips.views.confirm_booking, name = "confirm_booking"), path("booking_list/cancel/",trips.views.cancel_booking, name = "cancel_booking"), path("trip/<int:trip_id>/", trips.views.detail, name="detail"), path("review/<int:trip_id>/", trips.views.review, name="review"), path("guide_register/",trips.views.guide_register,name="guide_register"), path("email_register/",trips.views.email_register,name="email_register"), path(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', trips.views.activate, name='activate'), path(r'^recover/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', trips.views.recover, name='recover'), path("change_password/",trips.views.change_password, name = "change_password"), path("email_login/",trips.views.email_login,name="email_login"), # Footer path("feedback/",trips.views.feedback,name="feedback"), path("policy/",trips.views.policy,name="policy"), # auth path("", include("social_django.urls", namespace="social")), path("logout/", auth_views.LogoutView.as_view(), name="logout"), path("admin/", admin.site.urls), path("rosetta/", … -
How to disable a choice in django forms ChoiceField
Here is an exemple of what I have: forms.py class aForm(forms.Form): choices = [ ('value1', 'choice1'), ('value2', 'choice2'), ('value3', 'choice3') ] dropDownList = forms.ChoiceField( choices=choices) I want to add the attribute Disabledd to the first choice, like this: <select> <option selected value="value1" disabled>choice1</option> <option selected value="value2">choice2</option> <option selected value="value3">choice3</option> </select> How can I add that Disabled attribute from the forms.py file ? -
Django: Advanced StringAgg with ManyToMany
Setup I have two tables: Person name Tim Tom Tam Pet | species | color | |---------|-------| | Cat | black | | Dog | brown | And a ManyToMany that connects them: PersonToPet Person.name Pet.species Tim Cat Tim Dog Tom Cat Desired result Using Django, I would like to annotate Person such that I get this table: Person.name result Tim <a>Cat (black)</a><a>Dog (brown)</a> Tom <a>Cat (black)</a> Tam Is this possible? I've only got this: from django.contrib.postgres.aggregates import StringAgg Person.annotate( result=StringAgg('pets', delimiter=',') ) Which gives: Person.name result Tim Cat,Dog Tom Cat Tam Can anyone crack this nut? -
DjangoRestFramework : Create separate URLs for separate functions of ModelViewSet
I have a ModelViewset in Django Rest Framework : class UserViewset(viewsets.ModelViewSet): queryset = models.User serializer_class = serializers.User Its router : router = routers.DefaultRouter() router.register(r'user', views.UserViewset) I would like separate URLs for the create, update, list and retreive functions of this Viewset : /user/register/ : POST (create new user) /user/<pk>/profile : GET (retrieve profile of user) /user/<pk>/profile/update/ : PATCH (update profile of user) /user/list : GET (get list of users) How can this be achieved (using routers or URLs)? -
The name of the model does not appear in the multiple choice field
I am trying to create a form with a multiple-choice field. I have a SchoolClass model and I want to select multiple classes in the form. I can select SchoolClasses in the form but it doesn't show anything as label. I don't know how to pass a name to the choice field. Here is the form: class ExamForm(forms.Form): def __init__(self, class_choices, teacher_choices,teacher, *args, **kwargs): super(ExamForm, self).__init__(*args, **kwargs) self.fields['classes'].choices=SchoolClass.objects.filter(school_id=teacher.school_id) I am getting SchoolClass objects for choices classes = forms.MultipleChoiceField(choices=(), widget = forms.CheckboxSelectMultiple, label = "Classes for this exam.") When I run my project it shows like that : Blank choice fields -
Django: ModuleNotFoundError with Foreign Keys
I'm running into an import error with foreign keys spanning across multiple apps within my Django project. Specifically, when I run any python manage.py command, I get: from project.weather.models import Ice ModuleNotFoundError: No module named 'project.weather' Here's the structure of project: weather/ apps.py models.py ... display/ apps.py models.py ... Here's what display/models.py looks like: from django.db import models from django.contrib.auth import get_user_model from project.weather.models import Ice class DisplayManager(models.Manager): pass class Display(models.Model): objects = DisplayManager() weather = models.ForeignKey(Ice, null=False, on_delete=models.CASCADE) INSTALLED_APPS in settings.py looks like this: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'weather', 'display', ] Any reason for this? I don't believe I have a circular import issue, but if I do that would explain why the ModuleNotFoundError is popping up. However, I don't understand why it would be a circular dependency. Everything works fine when I comment out the display app by the way. -
Different HTML template for Update View Django
I use this as class as an Update view: class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Post fields = ['title', 'content_don'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): post = self.get_object() if self.request.user == post.author: return True return False Urls.py: path('post/new/', PostCreateView.as_view(), name='post-create'), path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'), path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'), Problem is, I want for User to get different template depending on choice before Update. For example, in create view a User1 can define 3 issues and then, User2 can update that model and he would be allowed to edit and see only couple of possible fields. So on my page I would have: HTML <a class="btn btn-success btn-sm mt-1 mb-1" href="{% url 'post-update1' object.id %}">Update1</a> <a class="btn btn-danger btn-sm mt-1 mb-1" href="{% url 'post-update2' object.id %}">Update2</a> <a class="btn btn-warning btn-sm mt-1 mb-1" href="{% url 'post-delete' object.id %}">Delete</a> then when selected 'Update1' or 'Update2' User2 would see different buttons, options, fields. Should this be done with different UpdateView, different HTML template or? So, redirection to different Update form depending on choice for same 'POST' -
Object owner same as Foreignkey object constraint
How can one ensure that a foreignkey (Value.user) from one object (Value) corresponds to the foreignkey (Value.userobject) of another foreignkey object (UserObject.user): Value.userobject.user == Value.user class UserObject(Model): user = ForeignKey(User, on_delete=CASCADE) dummyvalue = DecimalField(max_digits=18, decimal_places=10) class Value(Model): user = ForeignKey(User, on_delete=CASCADE) # Ensure the object is owned by user, ie. userobject.user == user.. userobject = ForeignKey(UserObject, related_name='TheUsersObject', on_delete=CASCADE) dummyvalue = DecimalField(max_digits=18, decimal_places=10) class Meta: constraints = [ CheckConstraint( name="%(app_label)s_%(class)s_same_object_owner", check=( Q( ... ) ] Currently I can think of handling this when processing the request, but would much prefer handling this as a model constraint if possible.