Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I change the database time-out period in django?
I have django script which fetch the data from model. try: myuser = MyUser.objects.get(id=user_id) except Exception as e: print(e) # do next process Then, what I want to do is ,,, When database is stopped or not reached, I want to catch and do next process. However my program return the 502 immediately, because it reachs to the aws lambda's timeout. 2022-06-23 19:09:51 127.0.0.1 - - [23/Jun/2022 19:09:51] "POST /webhook HTTP/1.1" 502 - Function 'MyDjangoFunction' timed out after 300 seconds No response from invoke container for MyDjangoFunction Invalid lambda response received: Lambda response must be valid json So, my idea is set django - sql timeout shorter. Is there any good method?? -
Problem in panel of Django3.0 after migrations
why is the error appearing in django/admin? Migrations ok, I need to have 3 items in the table where I will have results. Thx for your help. class Robot(models.Model): """Robot model, speed and position simulation""" product = models.IntegerField(choices=CHOOSE) velocity = models.FloatField() positionX = models.FloatField() positionY = models.FloatField() angleTHETA = models.FloatField() class Meta:`enter code here` verbose_name = "Robot" verbose_name_plural = "Robots" def __str__(self): resum = self.get_product_display() return resum ProgrammingError at /admin/robot/robot/ column robot_robot.velocity does not exist LINE 1: ...LECT "robot_robot"."id", "robot_robot"."product", "robot_rob... -
id_username showing up in django form without reason
Im looking for some help with my custom user model. For whatever reason I cannot understand the field id_username pops up after clicking on the submit button. This field is missing from the form which I have cut down to {{ form.as_ p }} in the html urls.py path('login/', LoginView.as_view(template_name="registration/login.html"), name='login'), forms.py class LoginForm(forms.Form): email = forms.EmailField(label='Email', widget=forms.TextInput(attrs={'placeholder': 'Email'})) password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password'})) views.py class LoginView(FormView): form_class = LoginForm success_url = '/about/' template_name = 'registration/login.html' def form_valid(self, form): request = self.request next_ = request.GET.get('next') next_post = request.POST.get('next') redirect_path = next_ or next_post or None email = form.cleaned_data.get("email") password = form.cleaned_data.get("password") user = authenticate(request, username=email, password=password) if user is not None: login(request, user) try: del request.session['guest_email_id'] except: pass if is_safe_url(redirect_path, request.get_host()): return redirect(redirect_path) else: return redirect("/about/") return super(LoginView, self).form_invalid(form) models.py class User(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, help_text='Email Address' ) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) # a admin user; non super-user admin = models.BooleanField(default=False) # a superuser timestamp = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = [] # Email & Password are required by default. objects = UserManager() def get_full_name(self): # The user is identified by their email address return self.email ... etc ... @property def is_active(self): "Is the … -
Django - How to include form field logic in modelForm and not in a Createview, so that form can be unittested without also testing the view?
I have a Campaign Model, and a CampaignCreateForm which is a ModelForm. The Campaign model has a contact_list field of type JSONField. When a user is creating a campaign using the CampaignCreateFormthey upload a CSV file which is processed to create the JSON data for thecontact_list` field. What is the best way to approach this so that I can test the form separately from the view? I've built this using a CampaignCreateView which inherits from CreateView, and included the logic to parse the CSV file and create the JSON data in the views form_valid method, but this makes unit-testing the form (and any form field validation) impossible. I want to test the functions included in the forms clean method. With my current approach the view and form must be tested together, and that feels wrong. How can I create the form such that all the logic for the form (processing the CSV file to create the JSON data and discarding the uploaded file) is handled in the form only? My current CreateView and ModelForm are below: View: class CampaignCreateView(LoginRequiredMixin, CreateView): model = Campaign form_class = CampaignCreateForm # required if you want to use a custom model form, requires `model` also … -
Apps aren't loaded yet - Django, Gunicorn, Docker
I am trying to run my django project using gunicorn in docker. It worked perfectly while I used regular python manage.py runserver 0.0.0.0:8000 command. They I switched to using gunicorn command: command: > sh -c "export DJANGO_SETTINGS_MODULE='clubhouse.settings' && gunicorn clubhouse.wsgi" And now I have this error: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. docker-compose.yml version: '3.8' services: postgres: image: postgres ports: - '5432:5432' volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=clubhouse - POSTGRES_DB=clubhouse - POSTGRES_PASSWORD=secret redis: image: redis restart: always ports: - '6379:6379' command: redis-server --save 20 1 --loglevel warning --requirepass eYVX7EwVmmxKPCDmwMtyKVge8oLd2t81 volumes: - redis:/data api: build: context: . dockerfile: Dockerfile command: > sh -c "export DJANGO_SETTINGS_MODULE='clubhouse.settings' && gunicorn clubhouse.wsgi" volumes: - .:/code ports: - '8000:8000' env_file: - ./.env depends_on: - postgres - redis volumes: postgres_data: redis: full log: Starting clubhousebackend_redis_1 ... done Starting clubhousebackend_postgres_1 ... done Starting clubhousebackend_api_1 ... done Attaching to clubhousebackend_postgres_1, clubhousebackend_redis_1, clubhousebackend_api_1 postgres_1 | postgres_1 | PostgreSQL Database directory appears to contain a database; Skipping initialization postgres_1 | postgres_1 | 2022-06-23 09:41:37.225 UTC [1] LOG: starting PostgreSQL 14.3 (Debian 14.3-1.pgdg110+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 10.2.1-6) 10.2.1 20210110, 64-bit postgres_1 | 2022-06-23 09:41:37.225 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 postgres_1 | 2022-06-23 09:41:37.225 UTC [1] … -
Error response from daemon: failed to create shim: OCI runtime create failed: container_linux.go:380
I'm trying to run this command docker-compose run --rm app sh -c "flake8", but it fails with the following error: Error response from daemon: failed to create shim: OCI runtime create failed: container_linux.go:380: starting container process caused: exec: "/bin/bash": stat /bin/bash: no such file or directory: unknown Dockerfile content: FROM python:3.9-alpine3.13 LABEL maintainer="dsha256" ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /tmp/requirements.txt COPY ./requirements.dev.txt /tmp/requirements.dev.txt COPY ./app /app WORKDIR /app EXPOSE 8000 ARG DEV=false RUN python -m venv /py && \ /py/bin/pip install --upgrade pip && \ /py/bin/pip install -r /tmp/requirements.txt && \ if [ &DEV = "true" ]; \ then /py/bin/pip install -r /tmp/requirements.dev.txt ; \ fi && \ rm -rf /tmp && \ adduser \ --disabled-password \ --no-create-home \ django-user ENV PATH="py/bin:&PATH" USER django-user docker-compose.yml content: version: "3.9" services: app: build: context: . args: - DEV=true ports: - "8000:8000" volumes: - ./app:/app command: > - sh -c "python manage.py runserver 0.0.0.0:8000" Any ideas to fix it? Thanks! -
How to find year-on-year growth from a query?
I have a dict type object in my Django app. I want to calculate Year-on-year growth(%) for every month. And the calculation for that is Percentage Growth in Cases Number compared to the previous year. And this is my data: <QuerySet [{'date_created__year': 2018, 'count_case': 1335}, {'date_created__year': 2019, 'count_case': 3469}, {'date_created__year': 2020, 'count_case': 3585}, {'date_created__year': 2021, 'count_case': 2589}, {'date_created__year': 2022, 'count_case': 144}]> I'm trying to create a template tag for that. @register.filter(name='get_yoy_query') def get_yoy_query(val,query): yoy = ? return yoy And in the template: {% for case in query_trend %} <td>{{case.count_case|get_yoy_query:query_trend}} %</td> {% endfor %} -
Django mptt Multiple references to class objects
I need to make a model for spices. Some spices may consist of others, or be basic. I need something like TreeForeignKey with multi-select option. I tried to use TreeManyToManyField, but I can't set null for base spices there. Here is my code: class Goods(MPTTModel): category = models.ForeignKey(Category, related_name='goods', on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=150, db_index=True) parent = TreeManyToManyField( 'self', blank=True,) -
Mongo Aggregate - Match condition only on second collection but provide all documents from the first
Basically, I have 2 collections in my Mongo DB -> Books , Scores. Books { "BOOK_ID" : "100", "BOOK_NAME" : "Book 1", "BOOK_DESC" : "abcd", }, { "BOOK_ID" : "101", "BOOK_NAME" : "Book 2", "BOOK_DESC" : "efgh", }, { "BOOK_ID" : "102", "BOOK_NAME" : "Book 3", "BOOK_DESC" : "ijkl", } Scores { "BOOK_ID" : "100", "BOOK_CATEGORY" : "kids", "BOOK_SCORE" : "6", }, { "BOOK_ID" : "100", "BOOK_CATEGORY" : "Educational", "BOOK_SCORE" : "8", }, { "BOOK_ID" : "101", "BOOK_CATEGORY" : "Kids", "BOOK_SCORE" : "6", } { "BOOK_ID" : "101", "BOOK_CATEGORY" : "Fantasy", "BOOK_SCORE" : "7", } Expected output : Searching for all books with BOOKS_CATEGORY="Kids" and BOOKS_SCORE=6 { "BOOK_ID" : "100", "BOOK_NAME" : "Book 1", "BOOK_DESC" : "abcd", "BOOK_CATEGORY" : "Kids", "BOOK_SCORE" : 6 }, { "BOOK_ID" : "101", "BOOK_NAME" : "Book 2", "BOOK_DESC" : "efgh", "BOOK_CATEGORY" : "Kids", "BOOK_SCORE" : 6 }, { "BOOK_ID" : "102", "BOOK_NAME" : "Book 3", "BOOK_DESC" : "ijkl", } Notice that, for all the books to which scores are available, they are appended. If a Book does not have any score associated, it still comes in the result. What I have tried? I have tried using $lookup pipeline = [ { "$lookup": { "from": "Scores", … -
Huge discrepancy between access.log, Google Analytics and Mapbox Statistics
I have a website made in django and served using gunicorn in which a single Mapbox map is loaded on the home page using mapbox-gl.js. Users can then navigate the map and change styles at will. The map is initialized and loaded only once and only in the home page. The service is billed on a "map load" basis. The Mapbox pricing page says A map load occurs whenever a Map object is initialized, offering users unlimited interactivity with your web map. I would have expected to see a count, if not exactly identical, at least comparable between the data recorded by Mapbox billing, the accesses to the home page recorded by Google Analytics and the hits on the home page recorded on the server access.log. Instead, the Mapbox count is in average about 25 times higher than Analytics and the access.log, which have similar numbers. As an example, here are the numbers for yesterday: Analytics: home page was loaded 890 times access.log: 1261 requests for the home page Mapbox: 23331 map loads I am using URL restriction from the Mapbox control panel, but I guess the enforcement is not that strict, since they strongly suggest to also rotate the … -
Pass array data through AJAX and get in python file(views.py)
I want to pass array data in views.py file for that I use AJAX and passing data through AJAX. But there I am not able to get all data in views.py file, some of the data are missing. display.html var SelectedID = []; function getvalues() { $(':checkbox:checked').each(function (i) { SelectedID[i] = $(this).val(); $.ajax({ url: "{% url 'display' %}", type: "POST", dataType: "json", data:{ SelectedID : SelectedID[i], csrfmiddlewaretoken: '{{ csrf_token }}' }, success: function (data) { alert("Successfully sent the Data to Django"); }, error: function (xhr, errmsg, err) { alert("Could not send URL to Django. Error: " + xhr.status + ": " + xhr.responseText); } }); }); } views.py def display(request): is_ajax = request.headers.get('x-requested-with') == 'XMLHttpRequest' if is_ajax and request.method == "POST": SelectedID = request.POST.get('SelectedID') print(SelectedID) return render(request, 'display.html',{}) SelectedID[i] = $(this).val(); in this selectedID There are 10 records but in print of views.py there is only 6 records, other data are missing. -
How to filter queryset based on serializer field?
How to filter queryset based on query parameters and dynamically calculated serializer field? What i need: filter GET request output by payment_min and payment_max query parameters. In simple cases we can perform all filtering via annotation, but I have not found a way run custom function on each queryset element. My model class MortgageOffer(models.Model): bank_name = models.CharField( 'Наименование банка', max_length=200, unique=True, ) term_min = models.PositiveIntegerField( 'Срок ипотеки, ОТ', ) term_max = models.PositiveIntegerField( 'Срок ипотеки, ДО', ) rate_min = models.DecimalField( 'Ставка, ОТ', max_digits=4, decimal_places=2, ) rate_max = models.DecimalField( 'Ставка, ДО', max_digits=4, decimal_places=2, ) payment_min = models.PositiveIntegerField( 'Сумма кредита, ОТ', ) payment_max = models.PositiveIntegerField( 'Сумма кредита, ДО', ) class Meta: verbose_name = 'Ипотечное предложение' verbose_name_plural = 'Ипотечные предложения' My serializer class MortgageOfferFilteredSerializer(serializers.ModelSerializer): payment = serializers.SerializerMethodField() class Meta: model = MortgageOffer fields = '__all__' def get_payment(self, obj): return calculate_payment( int(self.context['request'].query_params['price']), int(self.context['request'].query_params['deposit']), int(self.context['request'].query_params['term']), float(obj.rate_max), ) My viewset class MortgageOfferViewSet(viewsets.ModelViewSet): http_method_names = ['post', 'patch', 'get', 'delete'] filter_backends = (DjangoFilterBackend,) filterset_class = MortgageOfferFilter def get_queryset(self): return MortgageOffer.objects.all() def get_serializer_class(self): if self.action in ('create', 'update', 'partial_update'): return MortgageOfferWriteSerializer elif self.action in ('retrieve', 'list'): if self.is_filter_request(): return MortgageOfferFilteredSerializer return MortgageOfferReadSerializer return super().get_serializer_class() def is_filter_request(self): return (self.request.query_params.get('price') and self.request.query_params.get('deposit') and self.request.query_params.get('term')) -
Building urls with django template system
So I need to build an url querying multiple objects. I tried to use the template system from django to build it with no success. I was wondering if there is any way of doing this in the template or if I should just write a view function. {% url 'service-ticket/new' as request %} {% with request|add:"?" as request %} {% endwith %} {% for entry in object.items.all %} {% with request|add:"spareparts="|add_string:entry.item.id|add:"&" as request %} {% endwith %} {% endfor %} <a class="btn-add float-right" href={{ request }} role="button"> THIS SHOW HAVE ALL </a> -
After refreshing angular application in browser: django response
I´m currently working on an application: Django backend and angular frontend. Everything works fine, but after refreshing one page in the browser I don´t get the angular response anymore. But what I get is a successful answer from my Django server (HTTPResponse: 200). My Django urls.py is as followed: from django.urls import path from quickstart import views # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ path('images/', views.ImageList.as_view()), path('images/<str:id>/', views.Image.as_view()), path('images/<str:id>/explanations', views.Explanation.as_view()) ] My app-routing.modules.ts: const routes: Routes = [ {path: 'home', component: MainComponent}, {path: 'images', component: ImageComponent, children: [ { path:':id', component: ImageDetailComponent } ]}, {path: '', redirectTo: '/home', pathMatch: 'full'}, ]; @NgModule({ imports: [RouterModule.forRoot( routes )], exports: [RouterModule] }) export class AppRoutingModule { } Thanks for helping! -
Django Model isn't migrating even after i saved and added app to installedApps
from django.db import models from django.contrib.auth import get_user_model user = get_user_model # Create your models here. class Post(models.Model): title = models.CharField(max_length=200) text = models.TextField(max_length=100) author = models.ForeignKey( user, on_delete=models.CASCADE) created_date = models.DateTimeField() published_date = models.DateTimeField() PS C:\Users\hp\Desktop\djangomodels> cd I4G006918VEO PS C:\Users\hp\Desktop\djangomodels\I4G006918VEO> python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: No migrations to apply. -
Django Rest Framework: After defining permissions I'm not able to access user details of logged in user
I want the admin user to access every user detail (GET, POST) and the non-admin user to get access to its own detail only but I'm getting error while implementing this. As I've shared my views.py, permissions.py, and models.py for the same. I'm using Postman for API testing and this is working fine for admin user but for an individual user, it's not working. views.py class UserListCreateAPIView(generics.ListCreateAPIView): permission_classes = [IsStaffOrTargetUser] queryset = User.objects.all() serializer_class = UserSerializer class UserRetrtieveUpdateDestroyAPIView(generics.RetrieveUpdateDestroyAPIView): permission_classes = [IsStaffOrTargetUser] queryset = User.objects.all() serializer_class = UserSerializer permissions.py class IsStaffOrTargetUser(BasePermission): def has_permission(self, request, view): # allow user to list all users if logged in user is staff return request.user or request.user.is_staff def has_object_permission(self, request, view, obj): # allow logged in user to view own details, allows staff to view all records return request.user.is_staff or obj == request.user models.py class User(AbstractBaseUser): email = models.EmailField(verbose_name='Email',max_length=255,unique=True) name = models.CharField(max_length=200) contact_number= models.IntegerField() gender = models.IntegerField(choices=GENDER_CHOICES) address= models.CharField(max_length=100) state=models.CharField(max_length=100) city=models.CharField(max_length=100) country=models.CharField(max_length=100) pincode= models.IntegerField() dob = models.DateField(null= True) # is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name','contact_number','gender','address','state','city','country','pincode','dob'] def __str__(self): return self.email def has_perm(self, perm, obj=None): "Does the user have a … -
How do i increase the number of likes
How do i increase the number of likes in a answer models. I want when a user posted the answer, some user's in the application would be able to like it, like social media likes system, is anyone who can shows me how to increase the number of likes in my views and template ? I really don't know how to use count() function in the views and template, so this is my first time trying to add likes system in django application. class Answer(models.Model): user = models.ForeignKey(User, blank=False, null=False, on_delete=models.CASCADE) answer = RichTextField(blank=False, null=False) post = models.ForeignKey(Question, blank=False, null=False, on_delete=models.CASCADE) def __str__(self): return str(self.user) my like model: class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Answer, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.user) my views: def viewQuestion(request, slug): question = get_object_or_404(Question, slug=slug) answers = Answer.objects.filter(post_id=question) context = {'question':question, 'answers':answers} return render(request, 'viewQuestion.html', context) my viewQuestion template: <div class="container"> {% for answer in answers %} <div class="row justify-content-center"> <div class="card my-2"> <div class="card-header"> Answer </div> <div class="card-body"> <h5 class="card-title">From: {{answer.user.username.upper}}</h5> <p class="card-text">{{answer.answer|safe}}</p> </div> </div> </div> {% endfor %} -
Django admin Resource Policy COEP ERR_BLOCKED_BY_RESPONSE
The static files of my Django admin site are on a S3 bucket (DigitalOcean Spaces actually) and in the Console I get a ERR_BLOCKED_BY_RESPONSE.NotSameOriginAfterDefaultedToSameOriginByCoep 200 In the network panel all the static files are considered 3rd party and blocked for this reason (not same origin) The response to any one of these files contains a not set cross-origin-resource-policy error which says: To use this resource from a different origin, the server needs to specify a cross-origin resource policy in the response headers. What I tried : Following the error message, I tried to set a response header on the ressources, something like Cross-Origin-Resource-Policy: cross-origin. But in a DigitalOcean Spaces I cannot set headers other than Content-Type, Cache-Control, Content-Encoding, Content-Disposition and custom x-amz-meta- headers. I tried to extend the Django admin/base.html template, duplicate a few link tags and manually set a crossorigin attribute to them. This way the resources are queried twice, one query is blocked as before and the other one is working. The only difference in the headers is that the Origin is set. Is there a way to tell Django to add a crossorigin attribute to all link and script and img tags of the Django admin templates … -
How to append value to the ArrayField in Django with PostgreSQL?
I have created a model with the ArrayField in Django Model. I am using PostgreSQL for the database. I want to create new rows in the database or update the existing rows. But I can not insert or append data to the ArrayField. Model class AttendanceModel(BaseModel): """ Model to store employee's attendance data. """ user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='attendance_user') date = models.DateField() time = ArrayField(models.TimeField(), blank=True, null=True) class Meta: unique_together = [['user', 'date']] def __str__(self): return f'{self.user.username} - {self.date}' View attend, created = models.AttendanceModel.objects.get_or_create(user=fingerprint.user, date=attendance_date) attend.time = attend.time.append(attendance.timestamp.time()) attend.save() The time field does not being created or updated with the new value. How can I do this? -
TypeError: add() missing 1 required positional argument: 'resubscribe' in Django 3
Here i am using Django 3.0 and Python 3.7 I am getting 2 errors here: TypeError: add() missing 1 required positional argument: 'consent_to_track' TypeError: add() missing 1 required positional argument: 'resubscribe' Here is my code from models.py where the issue is def subscribe_to_signup_email_list(self): # campaign monitor subscriber = createsend.Subscriber({'api_key': settings.CAMPAIGN_MONITOR_API_KEY}, settings.CAMPAIGN_MONITOR_LIST_MCAM_ADMINS, self.email) try: email_returned = subscriber.add(settings.CAMPAIGN_MONITOR_LIST_MCAM_ADMINS, self.email, self.name, [], True) except Exception as e: ''' print type(e) print e.args print e ''' # it is not obvious what the error is subject, from_email, to = 'Welcome Email Error', 'noreply@mycontactandme.com', "notifications+errors@mycontactandme.com" client = self.client text_content = "Name: " + self.name + "\n" text_content += "Email: " + self.email + "\n" text_content += "Phone: " + client.phone + "\n" text_content += "Company: " + client.name + "\n" text_content += "Website: " + client.website + "\n" text_content += "Country: " + client.country + "\n" text_content += "\n\n" + traceback.format_exc() + "\n" msg = EmailMultiAlternatives(subject, text_content, from_email, [to], []) msg.send() return False return True Here is my error traceback for error 1 (i.e TypeError: add() missing 1 required positional argument: 'consent_to_track') Traceback (most recent call last): File "/home/harika/krishna test/dev-1.8/mcam/server/mcam/core/models.py", line 1005, in subscribe_to_signup_email_list email_returned = subscriber.add(settings.CAMPAIGN_MONITOR_LIST_MCAM_ADMINS, self.email, self.name, [], True) TypeError: add() missing 1 … -
Save custom Date and Time in created_at field Django
I want to save a custom date and time in created_at field. Currently my model has created_at = models.DateTimeField(auto_now_add=True) I want to give my own date and time which i will receive from user current time . How can i do this -
can't install django using pipenv/unable to create process using python "blah blah"
Newbie python learner here. Was following Mosh's guide (yt: /watch?v=rHux0gMZ3Eg&t=804s) but I got stuck in the pipenv part.. I tried a lot of workarounds/solutions but none of them worked (..ones I found so far), I just want to proceed on coding my first web app using Django. The dilemma taught me a lot about virtual environments and dependencies tho, but I've been stuck on this for 2 days now and I wanna move on. Actually, at first, I got to install Django but I was tracing back and redoing the processes to learn and fix the errors on VSCode but it got me a few steps back and I got stuck eventually. Out of frustration, I deleted a couple of files because I had to do reinstallation of Python for both "All users" and "Specific users" - and the paths messed up and so there were Python folder at C:\Programs Files and there were in C:...\Users, so I had to delete the other one. I also deleted a pipfile and pipfile.lock - idk if this was where the problem is but I couldn't generate any pipfile.lock anymore - but maybe it's just because I couldn't install Django. My setup: Windows … -
How to display M2M field in in editing Django?
I have M2M fiedl that i need to displa in edit form. It looks like this When i create new entry i just use {{ form.analog }} with this form "analog": SelectMultiple(attrs={ 'multiple': 'multiple', 'name': 'favorite_fruits', 'id': 'fruit_select', But i dont khow how to display this in edit form with already selected values -
Update Django model without using a Serializer
How do I better update a model without using the built in serializer from Django Rest Framework? I have a view here that updates the RecipeIngredient model. My serializer is defined inside my view and I do not want to make it responsible for hitting the database, only for serializing/deserializing the data. I have a services.py which handles all the database calls. So I send it the data it updates the model and saves it. This does not seem like a very good approach to me. Is there a better way to accomplish this? View class RecipeIngredientUpdateApi(APIView): class InputSerializer(serializers.Serializer): magnitude = serializers.FloatField(required=False) unit = serializers.CharField(max_length=255, required=False) def post(self, request, id): serializer = self.InputSerializer(data=request.data) serializer.is_valid(raise_exception=True) recipe_ingredient_update(id=id, **serializer.validated_data) return Response(serializer.data, status=status.HTTP_200_OK) Service.py This service is what I am trying to clean up. def recipe_ingredient_update(*, id, magnitude, unit): """Updates an existing RecipeIngredient""" recipe_ingredient = RecipeIngredient.objects.get(id=id) recipe_ingredient.magnitude = magnitude recipe_ingredient.unit = unit recipe_ingredient.full_clean() recipe_ingredient.save() return recipe_ingredient -
Django: Filter AbstractUser records using SQL, only show logged in user records
I have an AbstractUser. I want to restrict the records they're shown to their own (only show the records of the logged in user). I'd really like to do it with an SQL query as there are neighbouring tables to deal with. Any ideas? models.py class Teacher(AbstractUser): profile = models.ManyToManyField(Profile, through='TeacherProfile') unit = models.ManyToManyField(Unit, through='TeacherUnit') mobile = models.CharField(max_length=16) email = models.EmailField(max_length=100, unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'first_name', 'last_name'] def __str__(self): return self.email