Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filter distinct queryset by fields of a ForeignKey
(I think, the title of the question is far from being perfect, which might be the reason why I cannot find any useful help for this. Edits are welcome!) Assume the following models: class Pizza(models.Model): name = models.CharField(max_length = 128) class Person(models.Model): name = models.CharField(max_length = 128) The next model connects connects person and pizza and has a an additional boolean field. for the example, let's say the model stores the top pizzas for each person and the boolean field indicates whether the corresponding pizza is among the absolute favorites for the respective person. class TopPizzasForPerson(models.Model): person = models.ForeignKey( Person, related_name = 'top_pizzas', on_delete = models.CASCADE ) pizza = models.ForeignKey( Pizza, on_delete = models.CASCADE ) is_nearly_perfect = models.BooleanField(default = False) The last model stores when a certain person has eaten a certain pizza. class PizzaPersonDateRelation(models.Model): person = models.ForeignKey( Person, related_name = 'eaten_pizzas', on_delete = models.CASCADE ) pizza = models.ForeignKey(Pizza) date = models.DateField() I would like to have a list which contains the last date when someone has eaten a specific pizza. So, all combinations of person and pizza from PizzaPersonDateRelation should appear, but in case of multiple occurences of this combination, only the last one should be included. Currently, I … -
I want to render to a template a form inline. I am using django_filter
<div class="row"> <div class="col s2 offset-s3"> <form method="get"> {{ myFilter.form }} <button class="btn btn-primary" type="submit">Search</button> </form> </div> </div> How can I display the form inline? I am familiar with Bootstrap and Materialize. My problem: 1 2 3 I want: 1 2 3 -
Please Guide me top python library that will be using in 2021?
I have searched on many websites but not satisfy on any websites about famous python library using in 2020-2021. I believe on stackoverflow. Here developers Guide me me right way. I already done Python and Django. I'm interested to learning more in python Please give me your suggestions thank you -
DRF: Using Serializer field 'fields'
I want to use a serializer having the field fields: class MySerializer(Serializer): fields = CharField(required=True) But Serializer class already has a method named fields. So there is ambiguity in using this attribute of the instance and class, which can lead to errors and mess up with static analyzers: >>> a = MySerializer() >>> a.fields {'fields': CharField(required=True)} >>> A.fields <django.utils.functional.cached_property object at 0x543543215670> So, I wonder, is there the way to declare a serializer class with an alias like: class MySerializer(Serializer): fields_ = CharField(required=True, alias='fields') The important part is to make it able to parse input data with the alias fields: >>> a = MySerializer(data={'fields': 'some text'}) >>> a.is_valid() True >>> a.validated_data OrderedDict([('fields', 'some text')]) -
Pytest Django Importing apps issues
I have a question regarding pytest and django 3.1. I have an app structure like that: main_app ├── config │ └── settings │ └── base.py / local.py / prod.py ├── main_app │ ├── sub_apps │ │ └── models.py tests.py apps.py views.py etc... │ ├── templates │ │ ├── account │ │ ├── sub_apps │ │ ├── pages │ │ ├── userpreferences │ │ └── users │ ├── userpreferences │ │ └── models.py tests.py apps.py views.py etc... │ ├── users │ │ └── tests --> test_models.py test_views.py test_forms.py etc... │ └── utils └── requirements Following the structure of pydanny/cookiecutter. With this cookiecutter, the preferred test method is via pytest. But pytest is giving me a bunch of headaches: In my settings, INSTALLED_APPS I register sub_apps within the LOCAL_APPS =["sub_app_1", "sub_app_2", ...] When I start django, everything is fine. But if I want to run tests, pytest is complaining heavily, it can't import the sub_app modules. I suspect mixed up relative and absolute import paths but am not seeing how to solve this atm. As a background: I use a separate userpreferences model which is imported in the settings via LOCAL_APPS = ["main_app.userpreferences.apps.UserpreferencesConfig"] In the apps.py I have to define the app … -
React not integrating with Django
I have created Django+ React app import React, { Component } from "react"; import Modal from "./components/Modal"; import axios from "axios"; class App extends Component { constructor(props) { super(props); this.state = { viewCompleted: false, activeItem: { title: "", description: "", completed: false }, todoList: [] }; } componentDidMount() { this.refreshList(); } refreshList = () => { axios .get("http://localhost:8000/api/todos/") .then(res => this.setState({ todoList: res.data })) .catch(err => console.log(err)); }; displayCompleted = status => { if (status) { return this.setState({ viewCompleted: true }); } return this.setState({ viewCompleted: false }); }; renderTabList = () => { return ( <div className="my-5 tab-list"> <span onClick={() => this.displayCompleted(true)} className={this.state.viewCompleted ? "active" : ""} > complete </span> <span onClick={() => this.displayCompleted(false)} className={this.state.viewCompleted ? "" : "active"} > Incomplete </span> </div> ); }; renderItems = () => { const { viewCompleted } = this.state; const newItems = this.state.todoList.filter( item => item.completed === viewCompleted ); return newItems.map(item => ( <li key={item.id} className="list-group-item d-flex justify-content-between align-items-center" > <span className={`todo-title mr-2 ${ this.state.viewCompleted ? "completed-todo" : "" }`} title={item.description} > {item.title} </span> <span> <button onClick={() => this.editItem(item)} className="btn btn-secondary mr-2" > {" "} Edit{" "} </button> <button onClick={() => this.handleDelete(item)} className="btn btn-danger" > Delete{" "} </button> </span> </li> )); }; toggle … -
Simple JWT TokenRefreshView modification
I am using the default implemenation of simple jwt. In the refresh, you give the refresh tpken and a new access token is being generated. How can you modify this to deactivate the old access token since a new one is being created? -
Django rest_framework custom errror handler
I want to write django custom error handler as in flask custom error handler . Suppose i have 100 api's which gets the same error everytime let's say json.decoder.JSONDecodeError Sample code def post(self, request): if not request: return Response({"message": "Please enter credentials"}) input_param = json.load(request) print(input_param) In flask custom error can be written as @app.errorhandler(json.decoder.JSONDecodeError) def handle_marshmallow_validaton_errors(err): return jsonify({"error": "Bad request"}), 400 In django is there any way we can write custom error handlers Thanks in advance -
Way to count the number of filled fields in django model
I want to get the count of filled input fields in Django model. Ex. suppose I have student profile model and I have more than 70 fields student name, phone, email, add. etc. I want to get count how much fields student've filled. Like if he filled 35 fields out of 70 I want to get 35 in views.py. I dont want to use if, else condition for every field. What is the way to do it? -
Hello, I'm attempting to have different prices for an A2, A3, and A4 sized product in an art gallery Ecommerce store using Django
I'm looking for the simplest way to set and display different prices on a product depending on the size. eg. A2 - £10, A3 - £15, and so on... The approach i've tried is only displaying all product prices and the same time. I've posted the code below to further explain. models.py: class Product(models.Model): title = models.CharField(max_length=150) slug = models.SlugField(unique=True) image = models.ImageField(upload_to='product_images') description = models.TextField() a2_price = models.IntegerField(default=0) a3_price = models.IntegerField(default=0) a4_price = models.IntegerField(default=0) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) available_sizes = models.ManyToManyField(SizeVariation) def __str__(self): return self.title def get_absolute_url(self): return reverse("cart:product-detail", kwargs={'slug': self.slug}) def get_a2_price(self): return "{:.2f}".format(self.a2_price / 100) def get_a3_price(self): return "{:.2f}".format(self.a3_price / 100) def get_a4_price(self): return "{:.2f}".format(self.a4_price / 100) I tried defining the 2 different price options and then displaying them in the template using an else if loop. Template: <td> {% if get_a2_price %} {{ item.product.get_a2_price }} {% elif get_a3_price %} {{ item.product.get_a3_price }} {% elif get_a4_price %} {{ item.product.get_a4_price }} {% endif %} </td> If anyone knows a simpler way (or working way) that can help me, that would be great! Thanks in advance and if any additional info is needed please let me know, i'll be happy to provide. -
Using two API requests in two different views, how do I loop through each JSON response(for each) and store in DB?
Endpoint for first user def liked(request): # creates a Spotify object for calling methods sp= Spotify(auth=request.session.get("token")) # Gets JSON from Spotify data = sp.current_user_saved_tracks(limit=1)['items'] ### So I want to save certain keys and values from this JSON and save in DB Endpoint for second user def liked2(request): # Gets JSON from Spotify sp= Spotify(auth=request.session.get("token")) data = sp.current_user_saved_tracks(limit=1)["items"] ## I also want to save "data" in the DB The issue here is both endpoints return different data based on the user. How do I save to DB on user basis to show evident distinction between data? Looking at sample JSON, multiple objects of the same kind will be generated in the list for one view call. How would I loop through multiple objects in the list to save track name and artiste name? And do same for the other and store it also. For this sample, track name = Brown Sugar artiste = D'Angelo Sample JSON data = [ { "added_at": "2020-12-07T17:05:39Z", "track": { "album": { "album_type": "album", "artists": [ { "external_urls": { "name": "D'Angelo", "type": "artist", "uri": "spotify:artist:336vr2M3Va0FjyvB55lJEd" } ], "available_markets": [], "id": "4HTVABUq8amDUxBv3zJbX4", "name": "Brown Sugar", "release_date": "1995-07-03", "release_date_precision": "day", "total_tracks": 10, "type": "album", "uri": "spotify:album:4HTVABUq8amDUxBv3zJbX4" }, "artists": [ … -
Heroku: Failed to load the native TensorFlow runtime
2020-12-08T10:59:55.062424+00:00 app[worker.1]: Failed to load the native TensorFlow runtime. 2020-12-08T10:59:55.062424+00:00 app[worker.1]: 2020-12-08T10:59:55.062424+00:00 app[worker.1]: See https://www.tensorflow.org/install/install_sources#common_installation_problems 2020-12-08T10:59:55.062424+00:00 app[worker.1]: 2020-12-08T10:59:55.062425+00:00 app[worker.1]: for some common reasons and solutions. Include the entire stack trace 2020-12-08T10:59:55.062425+00:00 app[worker.1]: above this error message when asking for help. 2020-12-08T10:59:55.173431+00:00 heroku[worker.1]: Process exited with status 1 2020-12-08T10:59:55.213760+00:00 heroku[worker.1]: State changed from up to crashed 2020-12-08T11:00:59.000000+00:00 app[api]: Build succeeded 2020-12-08T11:15:35.000000+00:00 app[api]: Build started by user ronald.onwubuya@gmail.com 2020-12-08T11:19:49.200060+00:00 app[api]: Release v30 created by user ronald.onwubuya@gmail.com 2020-12-08T11:19:49.200060+00:00 app[api]: Deploy 573ba502 by user ronald.onwubuya@gmail.com 2020-12-08T11:19:49.739131+00:00 heroku[worker.1]: State changed from crashed to starting 2020-12-08T11:20:22.200631+00:00 heroku[worker.1]: Starting process with command python project.py 2020-12-08T11:20:22.831537+00:00 heroku[worker.1]: State changed from starting to up 2020-12-08T11:20:26.683779+00:00 heroku[worker.1]: Process exited with status 1 2020-12-08T11:20:26.724216+00:00 heroku[worker.1]: State changed from up to crashed 2020-12-08T11:20:26.727684+00:00 heroku[worker.1]: State changed from crashed to starting 2020-12-08T11:20:26.490677+00:00 app[worker.1]: Traceback (most recent call last): 2020-12-08T11:20:26.490740+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow.py", line 58, in 2020-12-08T11:20:26.490750+00:00 app[worker.1]: from tensorflow.python.pywrap_tensorflow_internal import * 2020-12-08T11:20:26.490750+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in 2020-12-08T11:20:26.490823+00:00 app[worker.1]: _pywrap_tensorflow_internal = swig_import_helper() 2020-12-08T11:20:26.490829+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper 2020-12-08T11:20:26.490998+00:00 app[worker.1]: _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description) 2020-12-08T11:20:26.491010+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.6/imp.py", line 242, in load_module 2020-12-08T11:20:26.491187+00:00 app[worker.1]: return load_dynamic(name, filename, file) 2020-12-08T11:20:26.491192+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.6/imp.py", line 342, in load_dynamic 2020-12-08T11:20:26.491470+00:00 app[worker.1]: … -
DJANGO - Default filter in model
I have 3 models : class Product(models.Model): name = models.TextField() class Company(models.Model): name = models.TextField() users = models.ManyToManyField('auth.User') class Sales(models.Model): product= models.ForeignKey(Product) company= models.ForeignKey(Company) seller = models.ForeignKey('auth.User') My goal is to display the list of all products sold by the company of request.user so in my views I do : Enterprise= Company.objects.filter(users=request.user)[0] Products_sold = Sales.objects.filter(company=Enterprise) But since I have a lot of views I'm wondering if there is a way to it directly in the model? -
Flow execution logging in django-vieflow
How can I track process/task execution in viewflow with logger? In the docs is mentioned: In case if you need to track some execution info or add logging, you can do it by extending viewflow.models.Task I could not find any example or more detailed documentation for logging in django-viewflow though. -
HTML audio tags are not working on my django website
[This image shows how the play button is greyed out and plays nothing][1] This works on raw HTML file. The second image shows that the button works on raw HTML file <audio controls> <source src="F:/udemy.django/website/my_web/personal_web/mysite/my_app/static/css/bigger text.wav" target='_blank' type="audio/wav"> Your browser does not support the audio element.</audio> -
how to do 'for loop' for a model inside another linked model in django
i have this model 'person' class Person(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() and this model is for the 'son' class Son(models.Model): father = models.ForeignKey(Person,on_delete=models.CASCADE) name = models.CharField(max_length=200) agent = models.IntegerField() so each person can have multiple sons, the problem is that i'm trying to loop over all the persons and at the same time i want to show their sons under ech person, using this view def persons(request): persons = Person.objects.all() sons = Son.objects.all() return render(request, 'persons.html',locals()) i have been trying different methods and nothing seems to work, what i'm trying to achieve is something like this {% for person in persons %} {{ person.name }} {% for person.sons %} {{son.name}} {% endfor %} {% endfor %} any ideas -
How to apply a function on the values selected in Django queryset?
Say I'm having the below model in Django class Book(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=200, blank=False, null=False) I want to get the length of title of all the Books as values - [ { "id": 1, "title": "foo.bar", "length_of_title": 7 }, { "id": 2, "title": "foo", "length_of_title": 3 } ] I tried the following, but it's not the proper way to do it - Books.objects.all().values('id', 'title', length_of_title=len('title')) -
How can I make django query based on function input?
I want to make django query based on function input.I don't want to check input with if and else in 2 separate line and then make query like this: def customer_number(mall,store=None): if store : customer = models.Customer.objects.filter(mall=mall,store=store) else : customer = models.Customer.objects.filter(mall=mall) return customer.count -
Filtering Django JSONB items in list
I have a Django data JSONField with the following data in { "title": "Some Title", "projects": [ {"name": "Project 1", "score": "5"}, {"name": "Project 2", "score": "10"}, {"name": "Project 3", "score": "2"}, ] } And I need to filter rows by project scores (numeric type), i.e. where project -> score <= 5 Django ORM provides the basics of filtering and working with a Postgres JSONB field. That is, I can do Model.objects.filter(data__title="Some Title") But it is not so straight forward when having a list of items in the JSON culumn, i.e. I can't do Model.objects.filter(data__projects__score__lte=5) Only way I can reach the `score` in Django ORM is to use the array index, i.e. Model.objects.filter(data__projects__0__score__lte=5) But that doesn't really work now, I'm interested in all items in that list, which can be however many Where I am currently: I've joined that list to the queryset as a jsonb_array_elements queryset.query.join(join=join_cfg) Which appended the following sql to the QUERY LEFT JOIN LATERAL jsonb_array_elements("my_table"."data" -> 'projects') projects ON TRUE Now, in Raw SQL, I can do something like this to filter that list WHERE (projects->>'score')::numeric < 5 Problem is I can't get this to play nicely with the Django ORM Currently, I'm adding this WHERE … -
Django Tenant Querying another tenant data inside public tenant
I want to fetch all users from specific tenant. Querying another tenant data is not working from public. class ClientDetailView(DetailView): model = Client def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['users'] = None with schema_context(self.object.schema_name): context['users'] = User.objects.all() return context -
Passing multiple parameters to hotel offers search in Amadeus python SDK
I am trying to pass multiple parameters to hotel offers using the Amadeus Python SDK but I am getting a 400 error code. How can I include checkInDate and checkOutDate in the request? here's the code : amadeus = Client( client_id = clientID, client_secret = ClientSecret ) try: hotels_by_city = amadeus.shopping.hotel_offers.get(cityCode=citycode,checkInDate=checkindate,checkOutDate=checkoutdate,adults=adults,roomQuantity=rooms) k = hotels_by_city.data print(k) -
I have an issue with the new_defect method with the 1 to many relationship between Inspection and Defect
I am doing another fun project in Django that involves two classes, Inspections and Defects, which can be created once an Inspection is created. The goal of the new_defect method in views.py is to create a new defect within an Inspection report When I submitted the form with valid information, I got an IntegrityError at inspections/1/new with NOT NULL constraint failed. The result I wanted was a new Defect in an Inspection class. Here is my views.py that I used from django.shortcuts import render,get_object_or_404 from .forms import NewDefectForm from .models import Inspection # Create your views here. def home(request): inspections = Inspection.objects.all() return render(request, 'home.html', {'inspections': inspections}) def inspection_topics(request, pk): inspection = get_object_or_404(Inspection, pk=pk) return render(request, 'topics.html', {'inspection': inspection}) def new_defect(request, pk): -> integrityError occurs at inspections/1/new inspection = get_object_or_404(Inspection, pk=pk) if (request.method == 'POST'): form = NewDefectForm(request.POST) if form.is_valid(): defect = form.save(commit=False) defect.name = inspection defect.location = inspection form.save() return redirect('inspection_topics', pk=Inspection.pk) else: form = NewDefectForm() return render(request, 'new_defect.html', {'inspection': inspection, 'form': form}) Here is my new_defect.html that I used {% extends 'base.html' %} {% block title %}Start a New Defect{% endblock %} {% block breadcrumb %} <li class="breadcrumb-item"><a href="{% url 'home' %}">Inspections</a></li> <li class="breadcrumb-item"><a href="{% url 'inspection_topics' inspection.pk … -
Origin null on POST request form
I'm currently trying to integrate a payment gateway into my website, the payment gateway have already whitelisted my domain but it's currently rejecting my post request due to Origin "null" in my request header. The request header is as such: Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9 Accept-Encoding: gzip, deflate, br Accept-Language: en-GB,en-US;q=0.9,en;q=0.8 Cache-Control: max-age=0 Connection: keep-alive Content-Length: 363 Content-Type: application/x-www-form-urlencoded Host: payment.ipay88.com.my Origin: null Sec-Fetch-Dest: document Sec-Fetch-Mode: navigate Sec-Fetch-Site: cross-site Sec-Fetch-User: ?1 Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36 The cross domain posting did not result in any Access control allow origin error and the form is just submitting a navigation to another page with some posted fields as such: <form action="https://payment.ipay88.com.my/epayment/entry.asp" method="POST"> <input type="hidden" name="MerchantCode" value="xx"> <input type="hidden" name="PaymentId" value="xx"> <input type="hidden" name="RefNo" value="xx""> <input type="hidden" name="Amount" value="xx"> <input type="hidden" name="Currency" value="xx"> <input type="hidden" name="ProdDesc" value="xx"> <input type="hidden" name="UserName" value="xx"> <input type="hidden" name="UserEmail" value="xx"> <input type="hidden" name="UserContact" value="xx"> <input type="hidden" name="Remark" value=""> <input type="hidden" name="Lang" value="xx"> <input type="hidden" name="SignatureType" value="xx"> <input type="hidden" name="Signature" value="xx"> <input type="hidden" name="ResponseURL" value="xx"> <input type="hidden" name="BackEndURL" value="xx"> <input id="submit" type="submit" class="btn-lg btn-danger" value="Submit" /> </form> How do i get the origin to display the domain of the request for cross … -
How to allow blank password via django-rest-api user create
In my case, I need to have one user group which email and password will not be set on user creation. They will not require to auth themselves either. I managed to do custom user with a nullable email, but I cannot find a way to allow blank password in API call or Django admin forms. I do not really care much about forms, but I need to have it working via API. How could I allow to create a new custom user with a blank password and maybe set it to something meaningful if it comes blank (like set_unusable_password())? Thanks! -
Django using select options in registration forms.py
Django using select options in registration forms.py I put some teams in my models.py in this way: class Account(AbstractBaseUser): TEAM = (('python', 'python'), ('php', 'php')) ... username = models.CharField(max_length=16, unique=True) first_name = models.CharField(max_length=16, unique=True) last_name = models.CharField(max_length=16, unique=True) member_of = models.CharField(max_length=20, choices=TEAM, default=TEAM[0][0]) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['first_name', 'last_name'] objects = AccountManager() def __str__(self): return self.username def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True and my forms.py is like: class RegistrationForm(UserCreationForm): #email = forms.EmailField(max_length=50) class Meta: model = Account #fields = '__all__' fields = ['username', 'first_name', 'last_name', 'password1', 'password2', 'member_of'] So when I want to use it in my registration.html I am not able to create account: <div class="group text-left"> <label for="exampleFormControlInput1">team</label> <select name="status" class="form-control" id="exampleFormControlSelect2"> {% for team in registration_form.member_of %} {{team}} {% endfor %} </select> </div> and also it is not important to use registration_form.member_of. If I only put member_of in my forms.py I can't register new users.