Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NoReverseMatch error when using reverse function
I am trying to redirect from one view to another and I get the following error: NoReverseMatch at /challenges/1/answer/ Reverse for 'results' with arguments '(1,'test')' not found. 1 pattern(s) tried: ['challenges\/(?P<challenge_id>[0-9]+)\/results\/$'] I have the following code in views.py: def answer(request, challenge_id): challenge = ... result = "test" return HttpResponseRedirect(reverse('challenges:results', args=(challenge.id, result))) def results(request, challenge_id, result): Here's urls.py path('<int:challenge_id>/', views.detail, name='detail'), path('<int:challenge_id>/results/',views.results, name='results'), path('<int:challenge_id>/answer/',views.answer, name='answer'), My understanding is that 'reverse' in an HttpResponseRedirect would redirect to results if I pass the 'result' in args? Thanks in advance! -
From javascript to server
I have this code which allows you to upload an image onto the canvas and mark out segments on the canvas. When the canvas is double clicked, the coordinates of the segments would be added to an array. Is it possible to write this array segmentList into a JSON file or send it to a django server? Also is there anywhere that i could read up on this? Thanks in advance. $("#imageCanvas").click(function(e) { var x = e.offsetX var y = e.offsetY // Adding 'X' and 'Y' values to the respective list xList.push(x); yList.push(y); var coods = document.getElementById("coods"); coods.innerHTML = 'X: ' + x + ' Y: ' + y; }) $('#imageCanvas').on('dblclick', function() { first = new Segmentation(); xList.pop() yList.pop() first.X = xList; first.Y = yList; segmentList.push(first); if(first.X == "" && first.Y == "") { alert("No points seleected!") } else if(first.X.length < 3 && first.Y.length < 3) { alert("Please select at least more than 3 points!") } else { for( i=0; i< first.X.length; i++) { if(i<first.X.length-1) { console.log(first.X) context.beginPath(); xpos = first.X[i]; console.log(first.X[i]) ypos = first.Y[i] var xpos1 =first.X[i+1] var ypos1 =first.Y[i+1] } if(i==first.X.length-1) { xpos = first.X[i] ypos = first.Y[i] var xpos1 =first.X[0] var ypos1 =first.Y[0] } context.moveTo(xpos, ypos) context.lineTo(xpos, … -
Making my Django Views into a DjangoRestFramework API Endpoint
I have a payment verification View which utilizes some parameters like the secret key, and some other authentication parameters. I would like to make the view into an API endpoint whereby i can just enter the parameter and the it returns the response. P.S: I am also utilizing an external API which has the response, all i have to do is send the required parameters and then if they are correct, it returns the response. Views.py def verify_paystack_payment(request): url = "https://api.paystack.co/transaction/verify/262762380" payload = { "email": "email@yahoo.com", "amount": "10000", "currency": "NGN", "reference": "262762380", "metadata": { "custom_fields": [ { "display_name": "Mobile Number", "variable_name": "mobile_number", "value": "+2348012345678" } ] } } files = {} headers = { 'Authorization': 'Bearer **MY SECRET KEY**', 'Content-Type': 'application/json' } response = requests.request("GET", url, headers=headers, data= payload, files=files) return render(request, "transaction/pay.html") -
Django - How to identify if an url path is from admin site
In my Django project, I am modifying the request body for PUT and POST requests. I do not want to do those processes for the URL path from the Django admin site. Is there any better way to identify if an URL path is from the Django admin site? I am doing the following thing right now. from django.utils.deprecation import MiddlewareMixin from django.contrib import admin from django.urls import resolve class ProcessRequestMiddleware(MiddlewareMixin): """ This middleware appends new payload in request body """ def process_view(self, request, view_func, *view_args, **view_kwargs): path = request.path resolved_path = resolve(path) print(resolved_path.app_name) if resolved_path.app_name == 'admin': # Do something -
Invalid byte sequence for encoding "UTF8": 0xff
I want to copy all my data from txt to PostgreSql via command: COPY employees FROM 'C:/Users/Public/staff.txt' WITH (FORMAT csv); But getting error as in title. Here is my example from staff.txt: 1,0XSUJ0F,Jax,Teller,John,15.01.1944,02.12.1968,02.12.1988,Vice-president,3500 And my employee table has number, fin, name, surname, patronimic, birthdate, contractstart, contractend, position and salary columns. -
Django + Tempus Dominus - Submit django form without submit button
I have a functioning datepicker on my django app called tempus dominus. I am having some trouble trying to set this datepicker to submit without having to click on a submit button. Their documentation is horrible but I finally figured at least part of it, it seems that I have to trigger one of their custom events (change.datetimepicker). Below you will find my implementation... My js skills are quite rusty so probably the problem lies somewhere there... my forms.py class MyForm(forms.Form): date_from = forms.DateField( required=True, widget=DatePicker( options={ 'minDate': '2018-01-20', 'maxDate': '2020-10-20', }, ), initial='2020-08-01', ) date_to = forms.DateField( required=True, widget=DatePicker( options={ 'minDate': '2018-01-20', 'maxDate': '2020-10-20', }, ), initial='2020-10-19', ) my template <div class="col" id="form_div"> <form method="post" action="." id="datetimepicker" class="form-inline justify-content-center"> {% csrf_token %} {{ form.as_p}} <input type="submit" id="submit" value="enviar" style="width:70px" /> </form> </div> my js file $("#datetimepicker").on("change.datetimepicker", function () { $( "#datetimepicker" ).submit(); }); Any help is appreciated! -
How display Inline checkboxes using django cripsy form?
I have Article with many categories. MODEL.py: class Article(Created, HitCountMixin): title = models.CharField(max_length=120) category = models.ManyToManyField(ArticleCategory, related_name='articles') I made Form to Edit Article: FORMS.py class EditArticleForm(forms.ModelForm): title = forms.CharField( label="Tytuł", max_length=120, help_text="Tytuł newsa", widget=forms.TextInput(attrs={"class": "form-control form-control-lg pr-5 shadow p-1 mb-1 bg-white rounded"}), required=True) class Meta: model = Article fields = ('title', 'image', 'category', 'snippet', 'body') widgets = { 'category': forms.CheckboxSelectMultiple() } labels = { 'category': 'Kategorie', } Also I made template to display this form. I used django cripsy-forms: HTML template <form method="post" enctype='multipart/form-data'> {% csrf_token %} {{ form.media }} {# {% crispy form %}#} {# {{ form|crispy }}#} {{ form.title|as_crispy_field }} {{ form.image|as_crispy_field }} {{ form.category|as_crispy_field }} <-- HOW DISPLAY THIS INLINE? {{ form.snippet|as_crispy_field }} {{ form.body|as_crispy_field }} <button type="submit" class="btn btn-outline-primary">EDIT</button> How can I display category checkboxes inline? -
Django Models - Relationship between siblings through a child
How can I list MyModelB objects for each MyModelA, when thier relations are not direct, but through MyModelC like below. name = models.CharField(max_length=50) class MyModelB(models.Model): name = models.CharField(max_length=50) class MyModelC(models.): name = models.CharField(max_length=50) my_model_a = models.ForeignKey(MyModelA, on_delete=models.CASCADE) my_model_b = models.ForeignKey(MyModelB, on_delete=models.CASCADE)``` -
How to allow the user to crop their profile image in django
I am trying to use django-image-cropping to allow users to crop their profile images before uploading them. Following the docs, I have installed it with pip along with easy_thumbnails and have added both to my installed apps and adjusted the thumbnail processors. settings.py: INSTALLED_APPS = [ 'easy_thumbnails', 'image_cropping', ] from easy_thumbnails.conf import Settings as thumbnail_settings THUMBNAIL_PROCESSORS = ( 'image_cropping.thumbnail_processors.crop_corners', ) + thumbnail_settings.THUMBNAIL_PROCESSORS I have also added an ImageRatioField to my Profile model which also contains the image I want to be cropped. models.py: from django.db import models from image_cropping import ImageRatioField class Profile(models.Model): image= models.ImageField(blank=True, null=True, default='profile_pics/default.png', upload_to='profile_pics') cropping = ImageRatioField('image', '300x300') I then integrated ImageCroppingMixin to my ModelAdmin. admin.py: from django.contrib import admin from image_cropping import ImageCroppingMixin class ProfileAdmin(ImageCroppingMixin, admin.ModelAdmin): pass admin.site.register(Profile, ProfileAdmin) My users can update their profiles via a modal which is rendered from ProfileModelForm... forms.py: class ProfileModelForm(forms.ModelForm): class Meta: model = Profile fields = ('first_name', 'last_name', 'image') ...and my_profile_view. views.py: def my_profile_view(request): profile = Profile.objects.get(user=request.user) form = ProfileModelForm(request.POST or None, request.FILES or None, instance=profile) if request.method == 'POST': if form.is_valid(): form.save() context = { 'profile': profile, 'form': form, } return render(request, 'users/my_profile.html', context) Here is the modal in my template: <button data-toggle="modal" data-target="#update" type="submit">Edit Profile</button> <div … -
How to do a translator in an invented language?
I am currently coding my first website, which is a translator in an invented language. You input a random phrase and it should get translated in the invented language. Here's the code for the translation: class TranslatorView(View): template_name= 'main/translated.html' def get (self, request, phrase, *args, **kwargs): translation = "" for letter in phrase: if letter.lower() in "a": if letter.isupper(): translation = translation + "U" else: translation = translation + "u" elif letter.lower() in "t": if letter.isupper(): translation = translation + "A" else: translation = translation + "a" elif letter.lower() in "c": if letter.isupper(): translation = translation + "G" else: translation = translation + "g" elif letter.lower() in "g": if letter.isupper(): translation = translation + "C" else: translation = translation + "c" return render(request, 'main/translator.html', {'translation': translation}) def post (self, request, *args, **kwargs): phrase = request.POST.get('text', 'translation') translation = phrase context = { 'translation': translation } return render(request,self.template_name, context) Template where you input the phrase: {% extends "base.html"%} {% block content%} <form action="{% url 'translated' %}" method="post">{% csrf_token %} <div class="form-group"> <center><h2 class = "display-3">TRANSLATE YOUR DNA CHAIN</h2></center> <br> <br> <textarea class="form-control" name='text' id="exampleFormControlTextarea1" rows="6"></textarea> <br> <button type='Submit' class= "btn btn-primary btn-lg btn-block">Translate</button> </div> </form> {% endblock content %} Template where … -
redirect, can't leave login page
in my views.py I have this function for login, def login_view(request, *args, **kwargs): form = AuthenticationForm(request, data=request.POST or None) if form.is_valid(): user_ = form.get_user() login(request, user_) **return redirect("/")** context = { "form": form, "btn_label": "Login", "title": "Login" } return render(request, "accounts/auth.html", context) however when i try to change the redirect , i only get errors, what should I put in the redirect? i've tried everything like return redirect("/tweets/list.html") and return redirect("public/index.html") both are locations of file names in the templates folder. I am getting the error, "Page not found (404)". The only address that did redirect was when I put https://www.google.com/ thnx -
Insert foreign key using django marshmallow
serializer.py class ClientSerializer(Schema): id = fields.Integer() name = fields.String(required=True, validate=lambda x: len(x) > 0) created_at = fields.DateTime() updated_at = fields.DateTime() class ProjectSerializer(Schema): id = fields.Integer() name = fields.String(required=True, validate=lambda x: len(x) > 0) project_type = EnumField(ProjectType, by_value=True) status = EnumField(ProjectStatus, by_value=True) client = fields.Nested(ClientSerializer(), dump_only=True) views.py project_serializer = ProjectSerializer(data=request.data) project_serializer.is_valid(raise_exception=True) Request { "name": "Test 1", "client": "Test Client" } models.py class Project(TenantBaseModel): name = models.TextField() project_type = EnumChoiceField(ProjectType, choice_builder=attribute_value) status = EnumChoiceField(ProjectStatus, choice_builder=attribute_value, default=ProjectStatus.CREATED) client = models.ForeignKey(Client, on_delete=models.PROTECT) I have already created a Client with the name "Test Client" using Django admin. I've tried passing the ID but nothing seems to work instead of the client name. I get the following error, {'client': [ErrorDetail(string='Unknown field.', code='invalid')]} -
Bootstrap base navs in django for loop
I am trying to use base navs of bootstrap in django using for loop to display the summary and profile of book based on the book id. I am getting "Could not parse the remainder: '()' from 'book.objects.all()'" error. Please let me know if there is any other way to fix this. Can anyone please hint me how to go ahead? book_review.html:- {% extends 'books/base.html' %} {% block content %} <div class = "container"> <ul class = "nav nav-tabs" id = "myTab" role = "tablist"> <li class = "nav-item"> <a class = "nav-link active" id = "summary-tab" data-toggle = "tab" href = "#summary" role = "tab" aria-controls = "summary" aria-selected = "true">Summary</a> </li> <li class = "nav-item"> <a class = "nav-link" id = "profile-tab" data-toggle = "tab" href = "#profile" role = "tab" aria-controls = "profile" aria-selected = "false">Profile</a> </li> <li class = "nav-item"> <a class = "nav-link" id = "relatedbooks-tab" data-toggle = "tab" href = "#relatedbooks" role = "tab" aria-controls = "relatedbooks" aria-selected = "false">Related Books</a> </li> </ul> <div class = "tab-content" id = "myTabContent"> <div class = "tab-pane fade show active" id = "summary" role = "tabpanel" aria-labelledby = "summary-tab"><br><br> {% for booksummary in book.objects.all() %} {{booksummary.summary}} {% … -
How to send extra data to serializers in django?
I have these models class Patient(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Doctor(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Visit(models.Model): patient = models.ForeignKey( 'Patient', on_delete=models.CASCADE, ) doctor = models.ForeignKey( 'doctor.Doctor', on_delete=models.CASCADE, ) date = models.DateField(auto_now=False, auto_now_add=False) time = models.TimeField(auto_now=False, auto_now_add=False) title = models.CharField(max_length=100) detail = models.TextField() And this serializer: class VisitSerializer(serializers.ModelSerializer): class Meta: model = Visit fields = '__all__' And I queried patient and doctor from db in views and want to send them to serializer: @api_view(['POST', ]) @permission_classes((IsAuthenticated, )) def add_visit_view(request, doctor_pk): try: patient = Token.objects.get(key=request.auth.key).user doctor = Doctor.objects.get(pk=doctor_pk) except Patient.DoesNotExist: return Response(data={'error': 'patient does not exist.'}, status=status.HTTP_404_NOT_FOUND) except Doctor.DoesNotExist: return Response(data={'error': 'doctor does not exist.'}, status=status.HTTP_404_NOT_FOUND) user = request.user if patient != user: return Response({'error': 'user and patient do not match'}, status=status.HTTP_400_BAD_REQUEST) context = { 'doctor': doctor, 'patient': patient } serializer = VisitSerializer(data=request.data, context=context) data = {} if serializer.is_valid(): patient = serializer.save() data['message'] = 'visit added successfully' else: data = serializer.errors return Response(data) I know I have to send extra data using context field but how to set them in serializer I overwrited create method like this: def create(self, validated_data): visit = Visit( patient=self.context['patient'], doctor=self.context['doctor'], date=self.validated_data['date'], time=self.validated_data['time'], title=self.validated_data['title'], detail=self.validated_data['detail'] ) visit.save() return visit But when I send request it says … -
Chart of price changes in Django
I want to save the new price and update date every time I change the price of the product, I created a new model for this and every time this change is saved in my model through the signal. I have a problem, if I change the name or number or ... of the product, these changes will be recorded in my model, I want the changes to be saved only when I change the price because the duplicate prices in the price change chart Occurs. my product model: class Product(models.Model): name = models.CharField(max_length=300) update = models.DateTimeField(auto_now=True) unit_price = models.PositiveIntegerField(default=0) create = models.DateTimeField(auto_now_add=True) .... my chart model : class Chart(models.Model): name = models.CharField(max_length=100, blank=True, null=True) create = jmodels.jDateTimeField(blank=True, null=True) update = jmodels.jDateTimeField(blank=True, null=True) unit_price = models.PositiveIntegerField(default=0, blank=True, null=True) product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='pr_update') my signal : def product_post_saved_receiver(sender, instance, created, *args, **kwargs): product = instance variations = product.pr_update.all() if variations.count() < 100: Chart.objects.create(product=product, name=product.name, create=product.create, unit_price=product.unit_price, update=product.update) post_save.connect(product_post_saved_receiver, sender=Product) -
How to add django-wiki to Wagtail
I want to add django-wiki to my wagtail app, so I can modify with the editor like any webpage that I already have in wagtail. I do not know if that if possible. -
How to set SameSite None value in django settings
I tried to add samesite=none in the Django settings file. In the cookie is set samesite=none value but the Django app is not redirecting page. how to fix this issue. Settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django_cookies_samesite.middleware.CookiesSameSite', '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', 'cp.middleware.ViewName', 'cp.middleware.GetCompany', 'cp.middleware.TimezoneMiddleware' ] SESSION_COOKIE_SAMESITE = 'None' How to solve this issue. If my question is could not understand. can you please check this link(https://community.shopify.com/c/Shopify-APIs-SDKs/SameSite-Cookie-with-Python-Django-and-the-Embedded-App-SDK/m-p/660233#M44775) Someone asked a question this question I will be asking and he has given some solution that also I tried but it's not working for me.can you please give some other solution. My Djanog Version: 2.0.2 My Python Version: Python 3.6.4 -
Django - Random - order_by('?')
When you make queryset in Django, argument "?" for order_by returns queryset in random order Model.objects.order_by('?') Documentation warns, that it may be slow. Also many articles tell not use this method for big database. I know question will sound dumb, but what is database limit size in order to user order_by efficiently? How many objects may I have in my database before order_by will get slower? Or this is all up to machine specs? -
Handle multiple parameters from URL in Django
In my app I am trying to make query on multiple parameters from the URL which is something like the following: /allot-graph/?sc=Infac%20India%20Pvt.ltd&type=FLC there are 2 parameters sc and type at times they can be empty as well I was handling the single parameter like the following: class AllotmentbyMonth(APIView): def get(self, request): q = 0 try: q = request.GET['sc'] except: pass if q == 0: print("q", q) dataset = Allotment.objects.all().annotate( month=TruncMonth('dispatch_date')).values( 'month').annotate(c=Sum('flows__alloted_quantity')).values('month', 'c') else: print("q") client = Client.objects.filter(client_name = q)[0].pk print("client", client) dataset = Allotment.objects.filter(sales_order__owner=client).annotate( month=TruncMonth('dispatch_date')).values( 'month').annotate(c=Sum('flows__alloted_quantity')).values('month', 'c') date = list(dataset) months = list() for i in date: months.append(i['month'].strftime("%B")) chart = {'chart': {'type': 'column', 'height': 400}, 'title': {'text': 'Allotments by Months'}, 'xAxis': {'categories': months}, 'yAxis': {"title": {"text": 'Count'}}, 'series': [{'name': 'Months', 'data': [{'name': row['month'], 'y': row["c"]} for row in dataset]}]} print("chart", chart) return Response(chart) I know it's not the ideal way but this was my workaround. How can I handle the filter type in this as writing too many if-else just doesn't seem right. The filter for type is this : .filter(flows__kit__kit_type = type) -
How to do Django pagination without page reload?
I am displaying questions with options in template page. on click next and previous i am getting questions with options. because of page reload user selected option is loosing. How to solve this problem. I am new to Ajax. I posted my script below. views.py: def render_questions(request): questions = Questions.objects.all() p = Paginator(questions, 1) page = request.GET.get('page', 1) try: page = p.page(page) except EmptyPage: page = p.page(1) return render(request, 'report.html', {'ques': page}) template.html: <div class="row display-content"> <div class="col-lg-8"> <form id="myform" name="myform" action="answer" method="POST"> {% csrf_token %} {% for question in ques %} <h6>Q &nbsp;&nbsp;{{ question.qs_no }}.&nbsp;&nbsp;<input type="hidden" name="question" value="{{ question.question }}">{{ question.question }}</h6> <div class="radio pad"> <label><input type="radio" name="answer" value="{{question.option_a}}">&nbsp;&nbsp;&nbsp;A)&nbsp;&nbsp;{{ question.option_a }}</label> </div> <div class="radio pad"> <label><input type="radio" name="answer" value="{{question.option_b}}">&nbsp;&nbsp;&nbsp;B)&nbsp;&nbsp;{{ question.option_b }}</label> </div> <div class="radio pad"> <label><input type="radio" name="answer" value="{{question.option_c}}">&nbsp;&nbsp;&nbsp;C)&nbsp;&nbsp;{{ question.option_c }}</label> </div> <div class="radio pad"> <label><input type="radio" name="answer" value="{{question.option_d}}">&nbsp;&nbsp;&nbsp;D)&nbsp;&nbsp;{{ question.option_d }}</label> </div> {% endfor %} <ul class="pagination"> {% if ques.has_previous %} <li><a href="?page={{ques.previous_page_number}}" class="button">Previous</a></li> {% else %} <li class="disabled button">Previous</li> {% endif %} {% if ques.has_next %} <li><a href="?page={{ques.next_page_number}}" class="button">Next</a></li> {% else %} <li class="disabled button">Next</li> {% endif %} <input type="submit" value="Submit" onclick="submitTest()" class="button"> </ul> </form> </div> </div> script: $(document).ready(function(){ $("ul.pagination a").click(function() { $.ajax({ type: "GET", url: $(this).attr('href'), success: … -
TypeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper in Django BaseCommand
I work on learning to create a custom command to rename the project of Django boilerplate. Below snippets lives in appname/management/commands/rename.py extending from BaseCommand. from django.core.management.base import BaseCommand import os class Command(BaseCommand): help = 'Rename project' def add_arguments(self, parser): parser.add_argument('new_project_name', type=str, help='The new project name') def handle(self, *args, **kwargs): new_project_name = kwargs['new_project_name'] files_to_rename = ['demo/settings/base.py', 'demo/wsgi.py', 'manage.py'] folder_to_rename = 'demo' for file in files_to_rename: with open(file, 'r') as file: filedata = file.read() file.close() filedata = filedata.replace('demo', new_project_name) with open(file, 'w') as file: file.write(filedata) os.rename(folder_to_rename, new_project_name) self.stdout.write(self.style.SUCCESS( 'Project has been renamed to %s' % new_project_name)) while running python manage.py rename newprojectname I get the below error: File "D:\GitHub\django-boilerplate\src\core\management\commands\rename.py", line 30, in handle with open(file, 'w') as file: TypeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper For me it sounds like open function looks for a string, albeit I already passed that list of string to it. The file is also closed in read only part through with. How I am getting this error? any help please? Thank you -
django objects filtering according to date
lately I have faced this situation in Django and can not understand clearly why there is difference between these 2 kind of queries is anybody could help me to understand it, thank you >>> date datetime.datetime(2020, 11, 1, 0, 0) >>> Contract.objects.filter(deadline_on__gt=date).count() 220 >>> Contract.objects.filter(deadline_on__month__gt=10, deadline_on__year__gt=2019).count() 30 >>> -
I am trying to do Django authentication with Facebook. I have an extended User model in my application which has a required fullname field
I am using the social_django application. How do I combine first_name and last_name received from Facebook and put them in the fullname attribute. Error : TypeError at /social-auth/complete/facebook/ create_user() missing 1 required positional argument: 'fullname' The error message The attribute in etended model : fullname = models.CharField(max_length=255, verbose_name='Fullname') Requested fields : SOCIAL_AUTH_FACEBOOK_SCOPE = ['email'] -
Django Rest Frawork: Where to put logic that modifies database?
I have a Django project using the Rest Framework. In some view I'm trying tu execute some logic every time I call these views, but it works when I have an existing Database. If I have to do a migrate to create a new Database it gives me the error django.db.utils.OperationalError: no such table: bar_reference because I don't have any Database. So I understand it's not the right way to do it, but so how/where should I execute this logic? Here is my view: from rest_framework import viewsets from rest_framework import permissions from rest_framework.permissions import AllowAny from ..models.reference import Reference from ..models.stock import Stock from ..models.bar import Bar from ..serializers.reference import * class MenuViewSet(viewsets.ModelViewSet): permission_classes = [AllowAny] references = Reference.objects.all() bars = Bar.objects.all() for reference in references: ref_id = reference.id quantity = 0 for bar in bars: bar_id = bar.id stocks = Stock.objects.filter(ref_id=ref_id, bar=bar_id) for stock in stocks: quantity += stock.stock if quantity == 0: reference.availability = "outofsotck" reference.save() else: reference.availability = "available" reference.save() queryset = Reference.objects.order_by('id') serializer_class = MenuSerializer -
in django each database should have superuser?
i am using MongoDB for database. i am working on Django to create app similar to-do app and try to create two databases. by default Django create some collections and to create super user for each databases