Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest API with okta OAUTH token authentication
I have a problem with Okta token authentication, I know how to authenticate with drf token and jwt token auth. In my project, I have to use okta token which is a type of jwt as well, however, this token is generated by front-end and send back to me in the request so here you can see how I authenticate the okta token with okta_jwt package: def post(self, request, *args, **kwargs): access_token = request.META.get('HTTP_AUTHORIZATION') try: validate_token(access_token, config.issuer, config.aud, config.client_id) except Exception as e: return JsonResponse({"result": e.args[0]}, status=400) .......... Basically I have to take the token out from the header and check with okta_jwt to see if it's legal Obviously, I don't think it's a good solution and it's hard to do unit test Can anyone provide a better solution for this? Thanks -
Go to newly created post
Once the user has made a valid post and pressed Post, I want them to be taken to the valid post. I ran a test with return redirect('post-detail', 18). At the moment once a valid post had been made then the post with ID 18 is loaded. I am trying to get the ID of the newly created post. What I am trying to write is return redirect('post-detail', id of newly created post) As this line works form.instance.author = self.request.user, I tried form.instance.id but it didn't have the desired results. Does anyone have any suggestions? class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['title', 'content'] def form_valid(self, form): form.instance.author = self.request.user return redirect('post-detail', 18) #print (form.instance.id) return redirect('post-detail', form.instance.id) -
I am trying to send the email to the user when user click on register button
def register_view(request): # Creates a New Account & login New users if request.user.is_authenticated: return redirect("/") else: title = "Register" form = UserRegistrationForm(request.POST or None) print(form.is_valid()) if form.is_valid(): user = form.save(commit=False) password = form.cleaned_data.get("password1") user.set_password(password) user.save() # new_user = authenticate(email=user.email, password=password) login(request, user) return redirect("/books") subject = "Greetings" msg = "Congratulations Yor Account is created Successfully. Do not share your login credentials with anyone else" to = "Ak4695755@gmail.com" res = send_mail(subject, msg, settings.EMAIL_HOST_USER, [to]) context = {"title": title, "form": form} return render(request, "accounts/signup.html", context) -
django.db.utils.ProgrammingError: can't adapt type 'CharField?
I am getting this error "django.db.utils.ProgrammingError: can't adapt type 'CharField' ", why is this error raising when i am trying to migrate to database -
Sort items by price on clicking dropdown
I have a dropdown and list of property. The dropdown contains two option, Low to High and High to Low. If any user clicks on any one of the dropdown item, the properties listed should sort by its price. How can I achieve that using javascript? property.html <div class="col-sm-6"> <div class="pxp-sort-form form-inline float-right"> <div class="form-group"> <select class="type-regular custom-select" id="pxp-sort-results" name="price-sorting"> <option value="" selected="selected disabled">Default Sort</option> <option class="price-sorting" value="l2h" id="l2h">Price (Lo-Hi)</option> <option class="price-sorting" value="h2l">Price (Hi-Lo)</option> </select> </div> </div> </div> <div class="row products-grid"> {% for item in properties.all %} <div class="col-sm-12 col-md-6 col-xxxl-4 product"> <a href="{% pageurl item %}" class="pxp-results-card-1 rounded-lg" data-price="{{ item.price }}" data-prop="1"> <div id="property-{{item.id}}" class="carousel slide" data-ride="carousel" data-interval="false"> <div class="carousel-inner"> {% for j in item.prop_images.all %} {% image j.prop_img original as property_img %} <div class="carousel-item {% if forloop.first %} active {% endif %}" style="background-image: url('{{property_img.url}}')"></div> {% endfor %} </div> <span class="carousel-control-prev" data-href="#{{item.prop_name}}" data-slide="prev"> <span class="fa fa-angle-left" aria-hidden="true"></span> </span> <span class="carousel-control-next" data-href="#property-{{item.id}}" data-slide="next"> <span class="fa fa-angle-right" aria-hidden="true"></span> </span> </div> <div class="pxp-results-card-1-gradient"></div> <div class="pxp-results-card-1-details" id="prop-dtls"> <div class="pxp-results-card-1-details-title">{{item.prop_name}}</div> <div class="pxp-results-card-1-details-price price">{{item.price}}</div> </div> <div class="pxp-results-card-1-features"> <span>{{item.bedroom}} BD <span>|</span> {{item.bathroom}} BA <span>|</span> {{item.sqft}} SF</span> </div> <div class="pxp-results-card-1-save"><span class="fa fa-star-o"></span></div> </a> </div> {% endfor %} </div> The values are coming dynamically from backend. -
my django view is always throwing "unexpected keyword argument error
i am familiar with python and started to learn django and it is fun in the begining how ever a table insertion becomes nightmare to me from 2 days and always throwing the following error sample() got an unexpected keyword argument 'firstname' i have tried all the possible ways on documentation and stackoverflow but nothing works. but another view with same syntax got worked for me that's so weird. here are my files. this is my stack trace. Traceback (most recent call last): File "C:\Users\manee\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\manee\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\manee\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\manee\myapp\PE\views.py", line 77, in sample a=sample(firstname=name) Exception Type: TypeError at /sample Exception Value: sample() got an unexpected keyword argument 'firstname' this is the combination of the worked view and troubling view(problems is working fine,sample is not working). def problems(request): name=request.POST['name'] title=request.POST['title'] difficulty=request.POST['example'] description=request.POST['description'] solution=request.POST['solution'] code=request.POST['code'] question=problem(name=name,title=title,difficulty=difficulty,description=description,solution=solution,code=code) question.save() return render(request,'thanks.html') def sample(request): name=request.POST['name'] email=request.POST['email'] rno=request.POST['rno'] a=sample(firstname=name,email=email,rno=rno) a.save() return render(request,'example.html',{'name':name}) and here is my models.py from django.db import models #Create your models here. class problem(models.Model): id=models.AutoField(primary_key=True) name=models.CharField(max_length=20) title=models.CharField(max_length=30) difficulty=models.CharField(max_length=10) description=models.TextField() solution=models.TextField() code=models.TextField() def __str__(self): return self.name class sample(models.Model): … -
How to Implement OR function on my queryset
I have currently created a model as shown below class Customer(models.Model): first_name = models.CharField(max_length=200, null=True) middle_name = models.CharField(max_length=200, blank=True,default='') last_name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) In my views.py I have, customer_list = Customer.objects.all() myFilter1 = CustomerlistFilter(request.GET,queryset=customer_list) customer_list = myFilter1.qs And within my filters.py I have written what is shown below class CustomerlistFilter(django_filters.FilterSet): id = CharFilter(lookup_expr='icontains') first_name = CharFilter(lookup_expr='iexact') middle_name = CharFilter(lookup_expr='iexact') last_name = CharFilter(lookup_expr='iexact') class Meta: model = Customer fields = ['id', 'first_name', 'middle_name', 'last_name'] Is there way of implementing the OR function, so that I can have one search box instead of multiple boxes for each field? -
Fetch data to input field django API
I am currently trying to get a city based on postal code. The situation: I got two input fields, zip code and city where when 4 digits are typed in zip code, the city field should be auto filled. What I've tried so far I got following code by far: template.html {% render_field form.zip_code id="zip_code" type="text" class="form-control w-100 mt-2" placeholder="Zip Code" %} {% if city %} {% render_field form.city id="city" type="text" value="{{ city.name }}" class="form-control w-100 mt-2" placeholder="City" %} {% else %} {% render_field form.city id="city" type="text" value="" class="form-control w-100 mt-2" placeholder="City" %} {% endif %} <script type="text/javascript"> $(document).ready(function() { $('#zip_code').on('change', function(){ var zipcode = $(this).val(); if(zipcode.length % 4 === 0){ $.ajax({ type:"GET", url:"https://dawa.aws.dk/postnumre?nr="+zipcode, success: function(data) { $('#city').val(data['navn']); }, error : function(){ alert('City not found!'); }, dataType: 'jsonp', }); }; }); }); </script> I am not sure why nothing happens. I can make a div, call it text and get the data via executing $('.text').text(JSON.stringify(data['navn'])); with a hit on enter. No auto check at 4 digits. But it won't somehow appear in my input fields value attribute. How can I make it from here? Thank you! -
Django Template IF inside Listing FOR
I am tryin use an object from a listing in an IF structure inside the FOR LOOP, but when I am trying to compare the object whit a String (That is 'TRUE'), I can not go inside the True case lines of the IF structure. Example: When equipo.Department = "Equipo", i don know why the IF ({% if equipo.Department == 'Equipo' %}) is not working. Code: {% autoescape off %} {% if equipos %} {% for equipo in equipos %} <tr></tr> <td>{% if equipo.Department == 'Equipo' %} E {% else %}{{ equipo.Department }}{% endif %}-{{ equipo.Equipment_id }}</td> <td>{{ equipo.Name }}</td> <td>{{ equipo.Description }}</td> <td>{{ equipo.SerialNo }}</td> <td>{{ equipo.Vendor }}</td> <td>{{ equipo.Tag }}</td> <td>{{ equipo.OutOfService }}</td> <td>{{ equipo.Location }}</td> <td>{{ equipo.Plan }}</td> <td>{{ equipo.ManualPath }}</td> <td>{{ equipo.ImagePath }}</td> </tr> {% endfor %} {% else %} <h1>No existen registros</h1> {% endif %} {% endautoescape %} -
showing only two out of three cards in my dashboard
I am creating the dashboard view for my CRM. However while displaying the card view, only two of the three card views are visible. Can anyone help me regarding this? Is this a code formatting issue? I am adding an image of the dashboard for my CRM below as well as the code for the cards given below. example.html: {% extends 'base.html' %} {% block content %} <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" /> <!-- Begin Page Content --> <div class="container-fluid"> <!-- Page Heading --> <div class="d-sm-flex align-items-center justify-content-between mb-4 mt-4"> <h1 class="h3 mb-0 text-gray-800">Welcome to NexCRM</h1> <a href="#" class="d-none d-sm-inline-block btn btn-sm btn-primary shadow-sm"><i class="fas fa-download fa-sm text-white-50"></i> Generate Report</a> </div> <!-- Main Content Here --> <div class="row"> <!-- Company Card Example --> <div class="col-xl-3 col-md-6 mb-4"> <div class="card border-left-primary shadow h-100 py-2"> <div class="card-body"> <div class="row no-gutters align-items-center"> <div class="col mr-2"> <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">Companies</div> <div class="h5 mb-0 font-weight-bold text-gray-800">4,083</div> </div> <div class="col-auto"> <i class="fas fa-building fa-2x text-gray-300"></i> </div> </div> </div> </div> </div> <!-- Company Card Example --> <div class="col-xl-3 col-md-6 mb-4"> <div class="card border-left-primary shadow h-100 py-2"> <div class="card-body"> <div class="row no-gutters align-items-center"> <div class="col mr-2"> <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">Companies</div> <div class="h5 mb-0 font-weight-bold text-gray-800">4,083</div> </div> … -
How do I mix vocals and music with python? [closed]
I want to make a website that offers free hip hop beats to rappers and hip hop artists. On this website, they should be able to record their vocals by listening to the music, and then both the music files and vocals should be synced together which makes a song. How can I do this? -
MultiValueDictKeyError at /account/register
Error: MultiValueDictKeyError at /account/register 'first_name' Request Method: POST Request URL: http://127.0.0.1:8000/account/register Django Version: 2.2.7 Exception Type: MultiValueDictKeyError Exception Value: 'first_name' Exception Location: C:\Users\Maansi\AppData\Roaming\Python\Python37\site-packages\django\utils\datastructures.py in getitem, line 80 views.py: def login(request): if request.method=='POST': username=request.POST['username'] password=request.POST['password'] user=auth.authenticate(username=username,password=password) if user is not None: auth.login(request,user) return redirect("/") else: messages.info(request,'invalid credentials') return redirect('login') else: return render(request,"login.html") def register(request): if request.method=='POST': first_name=request.POST['first_name'] last_name=request.POST['last_name'] username=request.POST['username'] password1=request.POST['password1'] password2=request.POST['password2'] email=request.POST['email'] if password1==password2: if User.objects.filter(email=email).exists(): messages.info(request,'Email Taken') return redirect('register') elif User.objects.filter(username=username).exists(): messages.info(request,'Username Taken') return redirect('register') else: user=User.objects.create_user(username=username,password=password1,email=email,first_name=first_name,last_name=last_name) user.save() print('user created') return redirect('login') else: messages.info(request,"Password don't match!") return redirect('register') else: return render(request,"register.html") login.html <div class="col-sm-6"> <div class="form-group"> {% csrf_token %} <input class="form-control valid" name="username" id="name" type="text" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Enter your username'" placeholder="Enter your username"> </div> </div> <div class="col-sm-6"> <div class="form-group"> {% csrf_token %} <input class="form-control valid" name="password" id="password" type="password" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Enter Password'" placeholder="Enter Password"> </div> </div> register.html: <div class="col-lg-8"> {% csrf_token %} <form class="form-contact contact_form" action="register" method="post"> <div class="row"> <div class="col-sm-6"> <div class="form-group"> {% csrf_token %} <input class="form-control valid" name="first_name" id="name" type="text" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Enter your name'" placeholder="Enter your name"> </div> </div> <div class="col-sm-6"> <div class="form-group"> {% csrf_token %} <input class="form-control valid" name="last_name" id="name" type="text" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Enter … -
Django: Is it Possible to create a model like Profile Model, to create an instance at the time of registration automatically
I have a custom user model and has created a profile model from it as well. so when user sign up a profile instance is created in the profile model as well. Now I have another similar model which is the address model. I tried configuring it in the same way but the address instance isn't getting created. Is it possible to do that? This is just for an understanding, whether similar model like profile can be created. this is my model. class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) summary = models.TextField(max_length=250, blank=True, null=True) birth_date = models.DateField(null=True,blank=True, auto_now_add=False, auto_now=False) country = CountryField(blank_label='(select country)') profile_pic = models.ImageField(upload_to='pimage/', default='pimage/default.png') def __str__(self): return f'{self.user.username} Profile' class Address(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE, blank=True, null=True) address = models.CharField(max_length=200, null=True) city = models.CharField(max_length=200, null=True) state = models.CharField(max_length=200, null=True) zipcode = models.CharField(max_length=200, null=True) mobile = models.CharField(max_length=12, null=True) def __str__(self): return f'{self.user.username} Address' views @login_required def address_add(request): if request.POST: a_form = AddressForm(request.POST, instance=request.user.address) if a_form.is_valid(): a_form.save() messages.success(request, f'Address Saved') return redirect('user_address') else: a_form = AddressForm(instance=request.user.address) context = {'a_form':a_form,} return render(request, 'áccounts/user_address.html', context) -
How can I make sure the subscription is paid for now and every another invoice?
I am working on an intelligent cloud platform able to analyse data of the users. I am going to use Stripe payments and subscription plan. Everything seems to be working properly however I have some uncertainty. To wit, I wonder how can I check whether the subscription has been paid for the next month? I have to be 100% sure because if the user will be able to use the service without paying in advance he can spend almost unlimited funds for which I will have to pay out of pocket. So this is super important for me to be sure that I had already received his money in Stripe and only then I give him access to my services and he uses what he paid for. I need to verify his payment when I create a subscription for him when he is creating an account. At this moment I create subscription in my Django backend in this way: customer = stripe.Customer.create( email=user.email, source=request.data['token'] ) subscription = stripe.Subscription.create( customer=customer.id, items=[ { 'plan': ‘myexampleplan’, 'quantity': request.data['amount'], }, ], expand=['latest_invoice.payment_intent'], ) # So here I want to have information if I already have his money for the next month. I guess that … -
SignUp without validation afrer press button
I try to add recaptcha in django 2.2 on the sign up form. The problem is with validation, when I press the SignUp button, the form validation does not appear, only the recaptcha form remains on the page, and the form to create the account disappears. The form is built using: django-widget-tweaks code in view.py class SignupView(CreateView): template_name = 'registration/signup.html' form_class = forms.SignUpForm success_url = '/' def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): recaptcha_response = request.POST.get('g-recaptcha-response') data = { 'secret': 'my_key_to_recaptacha', 'response': recaptcha_response } r = requests.post('https://www.google.com/recaptcha/api/siteverify', data=data) result = r.json() if result['success']: return redirect('/') else: print('someting is going on with recaptcha') else: form = self.form_class() return render(request, self.template_name, {'form': form}) -
With pytest and factory-boy, how do I create a factory for a non-traditional type of object?
I'm using Django 2, Python 3.7 and factory-boy. Trying to create a factory for the django-address' AddressField -- https://pypi.org/project/django-address/ , which I guess is a non-traditional model, in that it doesn't inherit from "models.Model". I created this factory, using "objects = models.Manager()" ... class AddressFactory(factory.DjangoModelFactory): """ Define Address Factory """ objects = models.Manager() class Meta: model = AddressField street_number = "123" route = "Rd" raw = "123 Fake Rd" formatted = "123 Fake Rd." latitude = 87.1234 longitude = -100.12342 locality = factory.SubFactory(LocalityFactory) Then I have this test ... @pytest.mark.django_db def test_address_create(self): """ Test address model """ # create customer model instance address = AddressFactory() assert address is not None but running the test results in the below error ... davea$ python manage.py test --settings=maps.test_settings Creating test database for alias 'default'... System check identified no issues (0 silenced). setUpTestData: Run once to set up non-modified data for all class methods. setUp: Run once for every test method to setup clean data. EsetUp: Run once for every test method to setup clean data. . ====================================================================== ERROR: test_address_create (tests.test_models.ModelTests) Test address model ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/factory/django.py", line 126, in _get_manager manager = model_class.objects AttributeError: type object 'AddressField' has … -
Django relation to two colums from another table
I would like to have a relation with the ToDoLists using the foreign key and have the date from the ToDoLists in my ToDoItems. Explaining it more specifically: I want a realtion of One to Many from my ToDoLists table to te ToDoItems table so I need the foreign key to be the id of the ToDoLists but I need the date from the ToDoLists on the ToDoItems table I have: class ToDoLists(models.Model): todo_id = models.AutoField(primary_key=True) date = models.DateField(null=False) class ToDoItems(models.Model): item_id = models.AutoField(primary_key=True) to_do_list = models.ForeignKey(ToDoLists,related_name='to_do_items', on_delete=models.CASCADE) date = models.ForeignKey(ToDoLists, to_field='date', on_delete=models.CASCADE) I would like to have a relation with the ToDoLists using the foreign key and have the date from the ToDoLists in my ToDoItems, but I get this error: ERRORS: api.ToDoItems.date: (fields.E311) 'ToDoLists.date' must set unique=True because it is referenced by a foreign key. As a date I don't want it to be unique as I can have multiple To do lists with the same date -
How to use Httprequest object in FormView?
i was converting the below function view in class based view : but the problem was the below login code uses request object . so how to use this request in a form view . Functional view i wanted to change to class based view : def login(request): if request.method == 'GET': form = UserLoginForm() elif request.method == 'POST': form = UserLoginForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('name') password = form.cleaned_data.get('password') user = User.objects.filter(name=username, password=password).first() if user is not None: request.session['user'] = username return redirect('index') else: messages.error(request, 'Username or password no matched') return render(request, 'products_app/login.html', {'form': form}) FormView/class based view of the above code i changed to that gives error : class Login(FormView): template_name = 'products_app/login.html' form_class = UserLoginForm success_url = reverse_lazy('index') def form_valid(self, form): username = form.cleaned_data.get('name') password = form.cleaned_data.get('password') user = User.objects.filter(name=username, password=password).first() if user is not None: request.session['user'] = username else: messages.error(request, 'Username or password no matched') super().form_valid(form) here the problem is ,request is not being received unlike in the functional view of above def login(request). so gives error: module 'django.http.request' has no attribute 'session' -
Django. Why would my foreign key does not match the same data from parent primary key
I have 2 models: class Director(models.Model): director_name = models.TextField(primary_key=True) director_firstname = models.CharField(max_length=32) def __str__(self): return f'{self.director_name}' def get_absolute_url(self): return reverse('director-detail', args=[str(self.director_name)]) class Meta: managed = False db_table = 'director' ordering = ['director_name'] class Connection(models.Model): director_connect = models.ForeignKey('Director', models.DO_NOTHING, db_column='director_connect') worker_connect = models.ForeignKey('Worker', models.DO_NOTHING, db_column='worker_connect') class Meta: managed = False db_table = 'connection' unique_together = (('director_connect', 'worker_connect'),) ordering = ['director_connect'] def __str__(self): return f'{self.director_connect}' def get_absolute_url(self): return reverse('director-detail', args=[str(self.director_connect)]) This is my view.py file: class DirectorDetailView(generic.DetailView): model=Director template_name = 'company/director_detail.html' def get_context_data(self, **qwargs): a = super(DirectorDetailView, self).get_context_data(**qwargs) a['cons'] = Connection.objects.all() return a When I am trying to match 2 columns in html with for loop and if statement, they do not match, although they are similar one to one copies of each other: {% extends "index.html" %} {% block content %} <h1>{{ director.director_name }}</h1> <p>{{ director.firstname }}</p> {% for con in cons %} {% if object.director_name == con.director_connect %} <li>{{con.id}}, {{con.director_connect}}, {{con.worker_connect}}</li> {% endif %} {% endfor %} {% endblock %} How could I fix it? I would like to bring the list of workers under director's name. -
Django - deployment with DigitalOcean issue - python collectstatic
I'm trying to deploy my django project, I've done all the process with gunicorn and nginx, I've arrived to the last line and I had to finally collect with "python manage.py collectstatic" when I get this error: File "manage.py", line 16 ) from exc here my manage.py file #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'piattaforma.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() Do you have any idea on how to solve it? thank you -
Django: loop all the records in a table and then get field from another table
I got two class models called Buy and Sell: class Buy(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) image = models.FileField() date = models.DateField() buy_price = models.DecimalField(max_digits=6, decimal_places=2) sell_price = models.DecimalField(max_digits=6, decimal_places=2) def __str__(self): return str(self.id) class Sell(models.Model): item = models.OneToOneField(Buy, on_delete=models.CASCADE) date = models.DateField() discount = models.DecimalField(max_digits=6, decimal_places=2) total_paid = models.DecimalField(max_digits=6, decimal_places=2) buyer = models.ForeignKey(Buyer, on_delete=models.CASCADE) def __str__(self): return str(self.item) In a template, I'd like to display all the records from the Sell table and also the image class-attribute from Buy table. Below, my view.py: def sell(request): buys = [] sells = Sell.objects.order_by('-id') for sell in sells: buys.append(Buy.objects.filter(id=str(sell.item))) context = {'sells': sells, 'buys': buys} return render(request, 'sell.html', context) Template: {% for sell in sells %} <tr> <td>{{ sell.item }}</td> <td>{{ sell.date|date:'d-m-Y' }}</td> <td>{{ buys[0].image}}</td> <td>R$ {{ sell.discount }}</td> <td>R$ {{ sell.total_paid }}</td> <td>{{ sell.buyer }}</td> </tr> {% endfor %} I'm wondering if there is a simple way to do that. I need some help in my view.py! -
Django: How to display database results based on form input selection?
I am trying to query the database to display results from the form. Once I select the form drop-down fields for my wanted query e.g. Ford C-Max 2019 1.2 Petrol 1500 , from which I coded for now to display results (regardless of Make & Model as I only have one atm) , then instead of showing me the table with matched results I get the full table with all results instead of the query I want. Portion of what I get after submitting the form (includes results I want filtered out): year liter fuel mileage average entered 2019 1.2 Petrol 1500 12075 April 8, 2020, 11:11 p.m. 0 None 13780 April 14, 2020, 5:25 p.m. 2018 1.6 Diesel 5000 15000 April 15, 2020, 2:23 p.m. What I want to get based on selecting 2019 1.2 Petrol etc. in the form: 2019 1.2 Petrol 1500 12075 April 8, 2020, 11:11 p.m. My code: views.py from django.shortcuts import render from django.http import HttpResponse from django.views.generic import FormView from django.db.models import Q from .models import Average, Query from .forms import QueryForm class QueryMakeModel(FormView): template_name = 'QueryMakeModel.html' success_url = '/data/' form_class = QueryForm def form_valid(self, form): return HttpResponse("Sweet.") def index(request): if request.method == … -
how to change data in model1 while saving data to model2 on django
models.py class EquipmentWorker(models.Model): date = models.DateField() count = models.IntegerField() class Admission(models.Model): name = models.CharField(max_length=100,db_index=True) date = models.DateField() in_stock = models.IntegerField(null=True, blank=True) out_of_stock = models.IntegerField(null=True, blank=True) forms.py class AdmissionForm(forms.ModelForm): class Meta: model = Admission fields = ['date', 'name', 'admission', 'id_type', 'in_stock', 'out_of_stock'] class EquipmentWorkersForm(forms.ModelForm): class Meta: model = EquipmentWorkers fields = ['date', 'equipment', 'type', 'id_workers', 'id_room'] views.py class AssignToWorker(View): def get(self, request, admission_id): admission = Admission.objects.get(id=admission_id) form = EquipmentWorkersForm(instance=admission) return render(request, 'inventory/assignToWorker.html', context={'form': form, 'admission': admission}) def post(self, request, admission_id): admission = Admission.objects.get(id=admission_id) admission_form = AdmissionForm() form = EquipmentWorkersForm(request.POST) if form.is_valid(): form.save() return redirect(equipments_list) class AdmissionCreate(View): def get (self, request): form = AdmissionForm() return render(request, 'inventory/addAdmissions.html', context={'form': form}) def post(self, request): form = AdmissionForm(request.POST) if form.is_valid(): form.save() return redirect(admission_list) it is necessary that the value of the out_of_stock field of the Admission model is updated when the value is saved in the count field of the EquipmentWorker model, for example, out_of_stock = 0 after the value is saved in the count = 2 field, the out_of_stock field is updated (out_of_stock = 2) view AssignToWorker accepts admission_id to identify the value in Admission.objects.get() that needs to be updated -
NGINX ISSUE - reload?
I am still stuck at this point. I'd like to show this error as to where I have been stuck after reloading the nginx. Does this (pls see photo)look familiar to you all? It shows reloading is failed when I tried to reload it. I used the systemctl status nginx command line to check the status and this message says the same reload errors. Thank you in advance for your help! -
Django, dynamically change model output on index page based on dropdown list selection
I am new to Django framework and currently trying to create a web page that has an input form for Product bids and outputs the entire model on the same page, calculating mean values in a separate div. The list of Products is predefined and can be selected by the user in a dropdown menu. I am looking for a way to filter the model output based on the Product selected before the user makes his input into the remaining form fields. models.py class ProductModel(models.Model): product = models.CharField(max_length=20,blank='False') minval = models.DecimalField(max_digits=5,decimal_places=2,name='minval') maxval = models.DecimalField(max_digits=5,decimal_places=2,name='maxval') date = models.DateField(auto_now_add=True) def __str__(self): return str(self.product) forms.py prod_choices = [('Prod1','Prod1'), ('Prod2','Prod2'), ('Prod3','Prod3')] class InputPred(forms.ModelForm): #custom validation go here do for min-max-close product = forms.ChoiceField(choices=prod_choices,label='Product') minval = forms.DecimalField(min_value=0,label='Minimum Price') maxval = forms.DecimalField(min_value=0,label='Maximum Price') def clean(self): clean_data = super().clean() min_val = clean_data['minval'] max_val = clean_data['maxval'] if (min_val > max_val): raise forms.ValidationError('Minimum Price higher than Maximum Price') class Meta: model = ProductModel fields = ['product','minval','maxval'] views.py def index(request): data_list = models.ProductModel.objects.order_by('product').filter(product='Prod1') #MAKE THIS DYNAMIC min_avg = round(models.ProductModel.objects.all().filter(product='Prod1').aggregate(Avg('minval')).get('minval__avg'),2) #MAKE THIS DYNAMIC max_avg = round(models.ProductModel.objects.all().filter(product='Prod1').aggregate(Avg('maxval')).get('maxval__avg'),2) #MAKE THIS DYNAMIC form = InputPred() if request.method == "POST": form = InputPred(request.POST) if form.is_valid(): form.save(commit=True) return HttpResponseRedirect('/') else: form = InputPred() return_data = {'data_list':data_list,'min_avg':min_avg,'max_avg':max_avg,'form':form} …