Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Ngnix & Django(Guicorn) & Docker - ssl not works
I'm have tryed some ways... but it not works I'm using Docker ssl certs exist on /etc/ssl ngnix.conf upstream hello_django { server web:8000; } server { listen 443 ssl; server_name phoenix-constructor.pw; ssl_certificate /etc/ssl/phoenix-constructor.crt; ssl_certificate_key /etc/ssl/phoenix-constructor.key; location / { proxy_pass http://hello_django; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /staticfiles/ { alias /home/app/web/staticfiles/; } } Dockerfile FROM nginx:1.19.0-alpine RUN rm /etc/nginx/conf.d/default.conf COPY nginx.conf /etc/nginx/conf.d COPY phoenix-constructor.crt /etc/ssl/ COPY phoenix-constructor.key /etc/ssl/ docker-compose.prod.yml https://pastebin.com/BM8BnNXL (can't past here) https://phoenix-constructor.pw/ -- not working http://phoenix-constructor.pw/ -- working (before new nginx.conf) -
Customers can't view Merchant product in Django
i have successfully build a multivendor website for merchant and customers. The only problem now i am getting is when a merchant add products,then the customer can't see it. views.py def index(request): listing=Category.objects.all() context={ 'listing':listing } return render(request,'catalog/index.html',context) models.py class Merchant(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE, primary_key=True) class Product(models.Model): name = models.CharField(max_length=255, unique=True) brand = models.CharField(max_length=50) categories = models.ManyToManyField(Category) merchant=models.ForeignKey(Merchant, on_delete=models.CASCADE) class Customer(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE, primary_key=True) thanks beforehand. -
How to write Flask Query in Django
I have a flask query below, I want to write it in django. I don't know flask much and I'm starting out in Django location = db.session.query(EmploymentLocation.location_id).join(Employment).join(Employment.status).filter(db.and_( EmploymentStatus.status.in_([EMPLOYMENT.STATUS_ACTIVE, EMPLOYMENT.STATUS_LEAVE]), db.or_(EmploymentLocation.thru_date == None, EmploymentLocation.thru_date >= datetime.utcnow().date())) ).distinct().all() So far I have tried to use select_related in django to write queryset but it doesn't work. I guess this is the wrong method to do it. location = EmploymentLocation.objects.select_related('employmentlocation','employment','employmentstatus').filter(employmentstatus__status__in=[STATUS_ACTIVE,STATUS_LEAVE]) models class EmploymentStatus(models.Model): flask_id = models.IntegerField() employment = models.ForeignKey(Employment, on_delete=models.PROTECT) organization = models.ForeignKey(Organization, on_delete=models.PROTECT, null=True, blank=True) status = models.CharField( max_length=100, choices=EmploymentStatusChoices.choices() ) # state = FSMField(default='new') from_date = models.DateField() status_from_date = models.DateTimeField(auto_now_add=True) status_thru_date = models.DateTimeField(null=True) actual_thru_date = models.DateField(blank=True, null=True) termination_type = models.TextField() absconding_application = models.TextField() leave_type = models.TextField() contact_detail = models.TextField() reason = models.TextField() class EmploymentLocation(models.Model): flask_id = models.IntegerField() employment = models.ForeignKey(Employment, on_delete=models.PROTECT) location = models.ForeignKey(Location, related_name='location_employments', on_delete=models.PROTECT) from_date = models.DateField() # auto_now_add=True thru_date = models.DateField(blank=True, null=True) class Employment(models.Model): flask_id = models.IntegerField() user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='user_employments', on_delete=models.PROTECT) organization = models.ForeignKey(Organization, related_name='organization_employments', on_delete=models.PROTECT) contractor = models.ForeignKey(Organization, related_name='contractor_employments', on_delete=models.PROTECT, null=True) employment_type = models.CharField(max_length=50, choices=EMPLOYMENT_TYPES.items()) offer_acceptance_date = models.DateField() join_date = models.DateField(null=True) termination_date = models.DateField(null=True) -
Derive a Django 3.0 Choices class from existing Enum?
Django 3 brought a new way to define field choides: Field.choices. This brings some adavantages, e.g. enforces uniqueness and allows supplying human readable tags. Unfortunately, I can't find a clean way to define the choices in a non-django module, so that these choices can be imported from non-django applications. Concretely: in my django app, I might have a shape that has colors. these color choices are to be used in my django model, but also in other non-django packages that need to know all valid choices (e.g. analysis) Therefore I want to define these colors as stand-alone class in exactly one place, e.g.: class ShapeColor(Enum): BLUE = 1 GREEN = 2 RED = 3 In the past I imported this Enum 'ShapeColor' anywhere I needed it. But I have not found a clean way to translate this Enum into the new models.IntegerChoices class. I tried to inherit from my Enum: class ColorChoices(models.IntegerChoices, ShapeColors): pass But of course this gives a TypeError("Cannot extend enumerations"). It would be great if anyone had a suggestion on how to cleanly derive a django choice enum from an existing Enum or similar construct. -
Django and Flask are downloading static files (css / js) instead of displaying it
Django and Flask are downloading static files (css / js) instead of displaying it so it won't load in my html pages any solution ? -
Django, edit device info making duplicate entry while keeping the old entry as well
I have created a below function to update the device info in my django app, it does update the device information but also keeping the old data in the table, it should overwrite rather than duplicating the previous entry with the updated change. can someone please take a look and suggest ? def updateDevice(request, id): hostlist_upt = HostList.objects.get(id__exact=id) form = HostListForm(instance=hostlist_upt) if request.method == 'POST': form = HostListForm(request.POST, instance=hostlist_upt) if form.is_valid(): form.save() return redirect('/devices') context = {'form': form} return render(request, "add_device.html", context) -
TypeError: unsupported operand type(s) for +: 'method' and 'int'
I want to update a field in database but when i run the code i have that error for : old.count = count + 1 the code is: if otp: otp = str(otp) count = 0 old = PhoneOTP.objects.filter(phone__iexact=phone) if not old: count = count + 1 PhoneOTP.objects.create( phone=phone, otp=otp, count=count, ) else: count = old.count old.count = count + 1 old.otp = otp old.save() error is in line 2 of else statement. how to fix it ??? -
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