Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Thinkific and multiple login prevention
I recently started using Thinkific and happy about well documented API & Webhook. However, one of the major concern is unable to prevent or monitor 'multiple login access and usage'. Made a request to Thinkific support team for help, no feature so no solution. Can anyone put some light on how to deal with such issue on SaaS platform like Thinkific, is there any middle ware like Django can be used to solve, if so, how to integrate with SaaS like Thinkific? Or is there any other tools can be used - if so please suggest. Any help would be grateful. -
Setting Global Axios Headers in Vue 3
I am trying to use Axios to hit my backend (Django), but I am having some trouble setting my global headers to include the CSRF token in the header. This is reaching my server: import axios from "axios"; async function loadCards() { var instance = axios.create({ xsrfCookieName: window.rootData.csrfToken, xsrfHeaderName: "X-CSRFTOKEN", }); return await instance.post(window.rootData.urlpaths.loadCards, { 'state': props.state.label, 'filter': props.filter.label, 'project': window.rootData.project }) } However, I want these headers to apply to all of my internal api requests. So I thought I would establish them in a separate file: axios-site.js import axios from "axios"; var siteApi = axios.create({ xsrfCookieName: window.rootData.csrfToken, xsrfHeaderName: "X-CSRFTOKEN", }); export default { siteApi } Vue Component import siteApi from "@/axios-site"; setup () { async function loadCards() { return await siteApi.post(window.rootData.urlpaths.loadCards, { 'state': props.state.label, 'filter': props.filter.label, 'project': window.rootData.project }) } } Here is the error in console: Uncaught (in promise) TypeError: _axios_site__WEBPACK_IMPORTED_MODULE_4__.default.post is not a function at _callee$ (ActionColumn.vue?ba4f:97) at tryCatch (runtime.js?96cf:63) at Generator.invoke [as _invoke] (runtime.js?96cf:293) at Generator.eval [as next] (runtime.js?96cf:118) at asyncGeneratorStep (asyncToGenerator.js?1da1:3) at _next (asyncToGenerator.js?1da1:25) at eval (asyncToGenerator.js?1da1:32) at new Promise (<anonymous>) at eval (asyncToGenerator.js?1da1:21) at _loadCards (ActionColumn.vue?ba4f:80) It seems something is being lost when I run it through the external file. I'm sure I … -
django rest api serializer cant update a nested serializer
I created two model named office and phone that phone save the office phones (each office can have several phone number) for working with this two model I created a nested serializer and two generic view shown in below in pictures one for post and get request and the other one for put delete and retrieve I don't have problem in post ,get ,delete ,retrieve but in case of update cant update phone numbers how can I update the phone number??? image of office and phone model image of office and phone serializer image of office views -
how to map user model to customer model (Django)
I'm using Django as backend, PostgresSQL as DB and HTML, CSS, Javascript for Frontend. I stuck on mapping the User with Customer model. Error: I get "null value in column "user_id" of relation "product_cart" violates not-null constraint" when I try to map user with Customer Model in Django. What I'm trying do: When customer visit my website and choose the product then customer click the ADD button to put that product into cart. But while clicking user get error as above. So I deleted that code, And I try to do something else like this Question link here. But didn't help me. I'm failing to link the customer model with the user. Please do help me to get out with this problem. The Code goes here. account/views.py (User Registration) def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') email = form.cleaned_data.get('email') htmly = get_template('account/email.html') d = { 'username': username } subject, from_email, to = 'welcome', 'your_email@gmail.com', email html_content = htmly.render(d) msg = EmailMultiAlternatives(subject, html_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send() messages.success(request, f'Your account has been created ! You are now able to log in') return redirect('account:login') else: form = UserRegisterForm() return render(request, 'account/register.html', {'form': form, … -
Display crypto price in a table using django and cryptocompare
I'm trying to make a simple webpage in django where I can display the price of some cryptocurrencies. The user stores in the database the name of the crypto and its initial price. Then I want to fill a table with the ticker and the initial price taken from the database and the current price of each crypto taken with cryptocompare. This is where the problem begin: the value of 'current price' is taken using cryptocompare, but how can I dinamycally display the value of the current price of each crypto in the table? Maybe the problem is easy to solve but I'm really new and I'm stuck, thanks in advance! If you need more information ask me! This is how the table in the index look like. I need to fill the last column with the daily price of the crypto models.py from django.db import models # Create your models here. class crypto(models.Model): ticker = models.CharField(max_length=200) initial_price = models.FloatField() def __str__(self): return self.ticker views.py from .models import crypto def index_view(request): chart = FuncAnimation(plt.gcf(), animate, interval=1000) ticker_list = crypto.objects.all() return render(request, 'cryptochart/index.html', {'chart': chart, 'ticker_list': ticker_list}) and last, in a file called utils.py I wrote the functions to get the … -
Django get sub domain from which the request was sent from
i have a standalone front ends serving on different sub domains, and a single backend responding to all requests through API(s) Say i have following subdomains first.example.com second.example.com third.example.com and my backend is at backend.example.com in my backend views i want to know which subdomain sent me request i tried self.request.get_host().split('.')[0] but this gave me "backend" as result from every sub-domain what i want to have : if request was sent from first.example.com > in my backend.example.com view i want to have "first" if request was sent from second.example.com > in my backend.example.com view i want to have "second" and so on Technologies information: Subdomains using React Backend using Django Server Nginx other server Gunicorn -
Django/Python - Save file from command output to ImageField
at my models.py I have a ImageField cover = models.ImageField(verbose_name=_("Cover"), blank=True, null=True, upload_to=get_file_path_images) I need to save an Image to this field the following command outputs (preferably only saved in RAM): ffmpeg -i "path_to_my_mp4_file" -map 0:v -map -0:V -c copy cover.jpg Can smb. Help? Thanks in advance -
How to save user that created and modified a record in django admin site?
I have a ReportModel in my django app with 2 field create_user (represents the user that created the report) and write_user (represents the user that last modified the report). I want to automatically save that two fields according to the user that is logged in on django admin site . How do I do that? Here is the definition of the model class ReportModel(models.Model): name = models.CharField(verbose_name=_("Nombre"), max_length=50, blank=False, null=False) location = models.PointField(verbose_name=_("Localización"), srid=4326, blank=False, null=False) report_type_id = models.ForeignKey("ReportTypeModel", verbose_name=_("Tipo"), blank=True, null=True, on_delete=models.SET_NULL, related_name="reports") start_date = models.DateField(verbose_name=_("Fecha inicio")) end_date = models.DateField(verbose_name=_("Fecha fin")) create_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='+', verbose_name=_('Creado por'), editable=False, null=True, blank=True) write_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='+', verbose_name=_('Modificado por'), editable=False, null=True, blank=True) def __str__(self): return self.name -
How to dynamically create and close infinitely running Celery tasks using Django Channels
I am creating a Cryptocurrency application where users get real-time data of currency pairs (e.g. 'BTC/USD'). I am trying to set up a system where users subscribing to the same pair can share API calls. So far I can dynamically create websocket connections and users are added to the groups. # routing.py URLRouter([ path('ws/data/<pair>/', PriceFeedsConsumer.as_asgi()), ]) # consumers.py class PriceFeedsConsumer(AsyncWebsocketConsumer): async def connect(self): self.pair = self.scope['url_route']['kwargs']['pair'] self.pair_group_name = 'pair_group_%s' % self.pair await self.channel_layer.group_add( self.pair_group_name, self.channel_name ) await self.accept() ... I have set up redis as the broker service and celery as a task manager system. I know how to send data from celery tasks to the consumer groups, but I want to begin the tasks when a group is created, and ultimately close the task when the group is discarded. This seems to be the most efficient way to manage API calls. Is it possible to initialize celery tasks from the creation of a django group? And in doing so, pass a parameter (pair, in this case) to the celery tasks? Alternatively, is this the correct architecture for this type of problem?