Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Python Error: Reverse for 'user-posts' with arguments '('',)' not found
I'm building a Django app using a popular tutorial (by @CoreyMSchafer) as a starting point. I'm getting the below error when I load http://localhost:8000/test/ in my browser. Reverse for 'user-posts' with arguments '('',)' not found. 1 pattern(s) tried: ['user/(?P<username>[^/]+)$'] models.py: from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from datetime import datetime # timezone takes timezone into consideration (even though it doesn't seem to) # we're inheriting from the models.Model # https://docs.djangoproject.com/en/3.1/topics/db/models/ class Post(models.Model): title = models.CharField(max_length=100) # character field content = models.TextField() # Unrestricted text date_posted = models.DateTimeField(default=timezone.now) last_modified = models.DateTimeField(auto_now=True) # author is a one-to-many relationship which uses a foreign key # the argument to ForeignKey is the related table # on_delete tells django to delete all posts by a user when that user is deleted author = models.ForeignKey(User, on_delete=models.CASCADE) # Convenience method to print out the title of a Post def __str__(self): return self.title def get_absolute_url(self): # todo: uncomment return reverse('post-detail', kwargs={'pk': self.pk}) class Game_c(models.Model): name = models.TextField() # Unrestricted text platform = models.CharField(max_length=100) # character field created_date = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name # return game name when game.objects.all() is called blog/views.py: from django.shortcuts … -
django admin url raises error 500 on heroku
I am having persistent '500' errors in a django app deployed on heroku. I haven't checked my django admin in a few months since november 2020 but now the error appears when trying to login to admin via the url both in my staging and production versions of the app : django.contrib.sites.models.Site.DoesNotExist: Site matching query does not exist. I am clueless on what might have caused this error since it also affects the production one and no changes have been applied to it since its last working version. -
what is the django query equivalent this next sql query
This is the sql query: SELECT TOP (1000) * FROM [dbo].[app_register] WHERE DATEDIFF(DAY, [start_date], SYSDATETIME() ) > (([duration] *30)/ 2) - 10 AND [period] = 55 My model: -
if request.META.get('HTTP_REFERER') working with Chrome but not Safari
I have the following function redirecting users if they have not come to the page from a Stripe checkout. The page will load if coming from a checkout on google chrome but if using safari on laptop on IOS it will redirect. Is there a way I can fix this to work on safari? - def register(request): if request.META.get('HTTP_REFERER') == "https://checkout.stripe.com/": return render(request, 'users/register.html') else: return redirect('error') I also have the settings for my site as SECURE_REFERRER_POLICY = "no-referrer-when-downgrade" -
Regex not matching in url
I have designed the following url pattern re_path(r'^api/refresh-token/(?P<token>[1-9]+\_[0-9a-f]{32}\Z)/$',refresh_token) 1_6506823466dc409a93b83b2c5f3b7cf2 matches the pattern [1-9]+\_[0-9a-f]+\Z. But when i hit the url it is not found. System check identified no issues (0 silenced). March 15, 2021 - 02:10:29 Django version 3.1.7, using settings 'tokenproject.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Not Found: /api/refresh-token/1_6506823466dc409a93b83b2c5f3b7cf2/ [15/Mar/2021 02:10:32] "PUT /api/refresh-token/1_6506823466dc409a93b83b2c5f3b7cf2/ HTTP/1.1" 404 3279 -
Django Integrity Error: null value in non-existent column
I am working on adding a foreign key relation between two models (Experience & Scheduler) in Django. When I originally went to add the foreign key of Experience to Scheduler, I ended up receiving an integrity error. I then removed the foreign key relation and updated my models accordingly so I could test. This still resulted in an error when I went to save my Scheduler object (I don't 100% remember but I'm pretty sure it was still an IntegrityError). I looked into some different solutions to this and I decided to run python manage.py flush to clear the database entirely because I'm on my local host and my own branch. The integrity error is still there even after wiping the database and removing the foreign key relation and I do not know why. I have been trying to figure out what the failing row represents because it doesn't look like either one of the models. The only thing I have discovered about it is that when I refresh my error page, index 0 of the column increments by one. Experience Models: from django.db import models class Experience(models.Model): type = models.CharField(max_length = 10, null=False, blank=True) description = models.TextField(max_length=100, null=False, blank=True) … -
Testing a PUT request in Django Rest Framework
When I run this test def test_update_car(self): new_car = Car.objects.create(make='Chevy', model='Equinox', year=2012, seats=4, color='green', VIN='12345671234567abc', current_mileage=19000, service_interval='3 months', next_service='april') url = reverse('car-detail', kwargs={'pk': new_car.pk}) data = { 'make': 'test', 'model': 'test', 'year': 2014, 'seats': 5, 'color': 'blue', 'VIN': '12345671234567abc', 'current_mileage': 20000, 'service_interval': '6 months', 'next_service': 'July', } response = self.client.put(url, data=data) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(new_car.make, 'test') I get an assertion error AssertionError: 'Chevy' != 'test' How should I structure this differently so that the PUT request actually changes the make and model of the new_car? -
How to log into my multi user types in django rest api
I have created my extended my model.py having four different class User(AbstractUser): is_phamacy = models.BooleanField(default=False) is_restaurant = models.BooleanField(default=False) is_grocery_shop = models.BooleanField(default=False) is_rider = models.BooleanField(default=False) class Restaurant(models.Model): restaurant_user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) restaurant_name = models.CharField(max_length=255,blank=True) full_name_of_merchant = models.CharField(max_length=255,blank=True) government_id = models.ImageField(upload_to = 'media/government_id' , null = True, blank=True) images_of_restaurants = models.ImageField(upload_to = 'media/images_of_restaurants' , null = True, blank=True) position_in_restaurant = models.CharField(max_length=255,blank=True) is_your_business_registered = models.BooleanField(default=True) tin_number = models.CharField(max_length=255,blank=True) longitude = models.FloatField(default=0000) latitude = models.FloatField(default=0000) long_you_have_been_working = models.IntegerField() want_delivery_guy = models.BooleanField(default=True) is_verified = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) and the others to follows but they have a different details taken which not done but with this the serializer.py is class RestaurantRegistrationSerializer(RegisterSerializer): restaurant_user = serializers.PrimaryKeyRelatedField(read_only=True,) #by default allow_null = False restaurant_name = serializers.CharField(required=True) full_name_of_merchant = serializers.CharField(required=True) government_id = serializers.ImageField(required=True, use_url=True) images_of_restaurants = serializers.ImageField(required=True, use_url=True) position_in_restaurant = serializers.CharField(required=True) is_your_business_registered = serializers.BooleanField(required=True) tin_number = serializers.CharField(required=True) longitude = serializers.FloatField(required=True) latitude = serializers.FloatField(required=True) long_you_have_been_working = serializers.IntegerField(required=True) want_delivery_guy = serializers.BooleanField(required=True) def get_cleaned_data(self): data = super(RestaurantRegistrationSerializer, self).get_cleaned_data() extra_data = { 'restaurant_name' : self.validated_data.get('restaurant_name', ''), 'full_name_of_merchant' : self.validated_data.get('full_name_of_merchant', ''), 'government_id': self.validated_data.get('government_id', ''), 'images_of_restaurants': self.validated_data.get('images_of_restaurants', ''), 'position_in_restaurant': self.validated_data.get('position_in_restaurant', ''), 'is_your_business_registered': self.validated_data.get('is_your_business_registered', ''), 'tin_number': self.validated_data.get('tin_number', ''), 'longitude': self.validated_data.get('longitude', ''), 'latitude': self.validated_data.get('latitude', ''), 'long_you_have_been_working': … -
(Allauth) Resending verification redirects to another page
In a custom template for a profile page, I have this form to resend a verification email: {% extends "main/base.html" %} {% load static %} {% load account %} {% block title %}Home{% endblock %} {% block body %} <p>Username: {{user.username}}</p> <p>Email: {{user.email}} {% if emailadress.verified %}(Verified){% endif %} (Unverified)</p> <form action="/accounts/email/" method="post"> {% csrf_token %} <input style="display:none" type="text" name="email" value="{{user.email}}" readonly> <button class="btn-auth" type="submit" name="action_send">Resend Verification</button> </form> {% endblock %} This form is submitted from a view located at /accounts/profile/, but when submitted, it redirects the user to /accounts/email/. I looked through the source code for allauth, but I couldn't wrap my head around how the redirect URL is determined. I tried adding a next value in the form, but that didn't do anything. Is there any way to specify the URL to redirect to after resending the verification or should I just move the /accounts/profile/ template to /accounts/email/? -
How to implement something like f-string, which calls conditional_escape()?
I like f-Strings in Python. And I like Django's SafeString. I know Django's format_html() method, but f-Strings are easier to use. Is there a way to implement something like f-Strings, but all variables get passed to conditional_escape() first? What I would like to have: local and global variables are directly available I would like to be able to do method calls inside the string. -
Django ORM get data with two aggregations where one depends on other
I'm trying to write query with next two iterations: Get avg s_sum grouped by region and city - "avg_city" Get minimum "avg_city" for each region. Model: class RegionStat(models.Model): region = models.IntegerField() city = models.IntegerField() seller = models.IntegerField() s_sum = models.IntegerField() Code to fill data: d = ((1,1,1,100), (1,1,2,200), (1,2,3,300), (1,2,4, 400), (1,2,5, 500), (1,3,6, 600), (1,3,7,700), (2,1,1, 200), (2,1,2,300)) for i in d: r = RegionStat() r.region, r.city, r.seller, r.s_sum = i r.save() Expected result: |region|min_avg_reg| |:-:|:-:| |1|150| |2|250| My progress stopped on getting: <QuerySet [{'region': 1, 'avg_city': 150.0}, {'region': 1, 'avg_city': 400.0}, {'region': 1, 'avg_city': 650.0}, {'region': 2, 'avg_city': 250.0}]> With this query: a = RegionStat.objects.annotate(avg_city=Window(expression=Avg('s_sum'),partition_by=[F('region'), F('city')])).only('region').order_by('region', 'avg_city').values('region', 'avg_city').distinct() I tried to use Subquery, but problem is i can get only one column from subquery, but i need region and avg_city to make second aggregation. -
Pushing data from an api response to an active django channel
I am new to django channels and figuring out a way to push a response from an api to an active websocket connection. Here I have a chat with two users and if I am sending a response from an api, I need to show that message from the api response to the active room. I have something like this now for testing. async def send_message_from_api(message, chat): channel_layer = get_channel_layer() chat_room = f"chat_{chat}" await channel_layer.group_send( chat_room, { 'type': 'websocket.send', 'text': message, } ) and in django rest post function, something like this, ChatConsumer.send_message_from_api(serializer.data, chat.id) This might be a dumb try, but it doesn't work. Can someone suggests a proper way to do it? or can modifying this code make it work? Thanks -
Django: Resolving "Reverse for 'password_reset_complete' not found."
I am attempting to do a password reset using Django using custom html templates. I am able to request an password reset by email (using the EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'), and I then get an "email" in the console, as I would like. The email does lead me to the "password_reset_confirm.html" page as I would like, and I can input the new passwords for the user associated with the user. However I am getting the following error when I click the "Reset password!" button: "Reverse for 'password_reset_complete' not found. 'password_reset_complete' is not a valid view function or pattern name." Despite this error, the password does actually change, however I (obviously) do not want this error. The structure of the project has a users "app" within the main structure, so it is: project main_app users ----templates --------registration ------------password_reset_form.html ------------password_reset_confirm.html ------------password_reset_done.html ------------password_reset_email.html ------------password_reset_complete.html My code for urls.py in users is as follows: from django.urls import path, include, reverse_lazy from . import views from django.contrib.auth import views as auth_views app_name = 'users' urlpatterns = [ # Default authorisation urls. path('', include('django.contrib.auth.urls')), # Registration page. path('register/', views.register, name='register'), # Password reset urls. path( 'password_reset', auth_views.PasswordResetView.as_view( template_name='registration/password_reset_form.html', email_template_name='registration/password_reset_email.html', success_url=reverse_lazy('users:password_reset_done') ), name='password_reset' ), path( 'password_reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='registration/password_reset_done.html'), name='password_reset_done' … -
Download dynamic html with images as PDF with watermark using Django Python
I am trying to create a quiz webapp where users can take the quiz online or offline. In offline mode, the user should be able to click on a button and download the pdf content with images and watermark. My dynamic html content also contains mathematical equations which is printed using Mathjx and WIRIS plugin. I have tried the following , but Its super slow in rendering I am unable to print watermark in the middle diagonally. I have also tried printing using jquery/canvas but since the html is dynamically generated, the print isn't working. Can this be achieved using jquery and some javascript packages ? Please suggest a faster method if possible. Also, when I click ,it takes around 15 seconds to download the file. I wanted to use ajax method to show in progress but unable to achieve it. Any help is appreciated. class GeneratePdf(View): def get(self, request, *args, **kwargs): #template = get_template('dashboard/exam-pdf.html') quizid = request.GET.get('quizid') quiz = Quiz.objects.get(id=quizid) questions= #Rendering Questions from model with images and MCQ Options print("link clicked") context = { 'questions': questions, 'essayquestions': essayquestions, 'quizid':quizid, 'quiz': quiz } pdf = render_to_pdf('dashboard/exam-pdf.html',context) #rendering the template return HttpResponse(pdf, content_type='application/pdf') My exam-pdf.html {% extends 'base.html' %} {% … -
Why are my media files not working in production
For server I am using Linode, as DataBase MySql, and apache2. The static files working perfectly, but images(media files) does not display :(. Already tried to restart server and change the urls.py file! settings.py STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' # STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' urls.py STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' # STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' project configuration file <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName www.example.com ServerAdmin webmaster@localhost DocumentRoot /var/www/html # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. … -
Django and Chart.js - Manipulating datetime field objects to produce a graph
I have to implement some feature in Django, letting the user upload a CSV/Excel file (containing logging data of users, such as last login date, username, etc.) from Front-End. I can't share here the code as this assignment is given at work, so I mustn't publish the source code. I've already taken care of the part of uploading the file from the front-end, processing it, and populating the database (Postgres) with the users' logging details. Now, the next thing I have to do is creating a graph: Using the last_login_field that each user has in the database, I have to create a graph (linear line) showing how many users have been active per month. That is, I have to somehow retrieve only the Month/Year parts of last_login_date of all the users, and count the number of those users who share the same Month/Year in their last_login_date field. Notice that the last_login_field field is actually a standard datetime object. The problem is I don't succeed to find a way to querying the database (Postgres) to create such a table (Month/Year against Month). I'd be glad to get help overcoming this issue. -
Not Able to Add Book using Django
I have a Django Account application running in Docker container. Account is using a CustomUser. All functionality at this point is working for Accounts. Next, I have created a "Books" app to keep things separate and for easy migration. All of my activity is ran through the docker compose command for createsuperuser, makemigrations, and migrate commands. This is structure: When I look in the postgres database, I see the below: When I call up the Books application and add a book, I get the below error: Next, I go swimming in the database and identify the fault. What I discover is the created user is in the accounts_customuser table and NOT in the auth_user table. I have no records in the auth_user table. I look how the two applications are setup in the Admin portal. This is the view: The two applications handle the admin.py differently. This is accounts admin.py: This is books admin.py: I would appreciate some guidance on how to move pass this fault and align the applications to operate together. Thanks in advance. Russ -
Access control origin error for axios get method
I am trying to communicate my front end to back end, but I am keep on getting in firefox Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:8000/getBikeParkingDetailsFromDb. (Reason: header ‘access-control-allow-origin’ is not allowed according to header ‘Access-Control-Allow-Headers’ from CORS preflight response). I added below cors headers in my request also, const options = { headers : { 'Access-Control-Allow-Origin':'*'}, url: 'http://127.0.0.1:8000/getBikeParkingDetailsFromDb', method:'get' } try { let posts = await axios(options) console.log(posts) dispatch(fetchPostsSuccess(posts) ) } catch(e){ console.log(e) } and in my back end (django) I added below lines in settings.py INSTALLED_APPS = [ 'corsheaders', #rest apps ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", ] added response headers as well def get_bike_parking_details(request): all_bike_details = BikeParkingInfo.objects.all() serialize_data = serializers.serialize('json', all_bike_details) response = HttpResponse(serialize_data, content_type="text/json") response['Access-Control-Allow-Origin'] = '*' response['Access-Control-Allow-Headers'] = '*' return response but I am still facing same issue, currently I have used extension in chrome to make it work end to end, but need to find solution for this -
Django self.kwargs returning symbols not string. any ideas?
in this listview: context: context['first_item'] = obj_prods.filter(m_category=self.kwargs['m_category_id'], category=self.kwargs['category_id'], city=self.kwargs['city']).order_by('id').first() in production: self.kwargs['city']: returning this: %d0%91%d0%b8%d1%88%d0%ba%d0%b5%d0%ba in template and in view, so filter is not working. self.kwargs['m_category_id'] - is working as it as an integar. but in localhost is working and returning string. Only in productions is not working as it as a string. Any ideas what is going on? -
Default value is not stored in model
**This is my models class and i have given a default value to the image field** class Movie(models.Model): image = models.ImageField(default='default.jpg') title = models.CharField(max_length=255) release_year = models.IntegerField() number_in_stock = models.IntegerField() daily_rate = models.FloatField() genre = models.CharField(max_length=255) date_created = models.DateTimeField(default=timezone.now) def __str__(self): return self.title Admin interface After saving the data my image field is still empty. Whats the prooblem ? -
How to insert selected items to db in django?
Here is my Template : {% for pr in productlist %} <ul> <li><input type="checkbox" name="mylistch" value="{{ pr.productid }}"></li> <li><input type="hidden" name="mylist" value="{{ pr.productname }}"></li> <li><input type="number" name="mylist" id="prqty"/></li> </ul> {% endfor %} and View : pch = request.POST.getlist('mylistch') pnch = iter(pch) pr = request.POST.getlist('mylist') pri = iter(pr) for pid, pname, ptotal in zip(pnch , pri , pri): models.Sellinvoiceitems.objects.create( productid=pid productname=pname, totalnumber=ptotal, sellinvoice = invoice, stockid = stock ) Here i checked 5 checkbox with this ids : 6 , 9 , 10 , 12 , 19, But ids : 1 , 2 , 3 ,4 ,5 inserted to db, what is problem here? -
Is there a Django/Pythonic way of keying Django querysets by a particular value of the queryset?
I have this view that I am using in Django REST API: class HSKView(APIView): permission_classes = (AllowAny,) def get(self, request): hsk_levels = HSKLevels.objects.all() serializer = HSKSerializer(hsk_levels, many=True) return Response({"hsk": serializer.data}) And here's the serializer in case it is needed: class HSKSerializer(serializers.ModelSerializer): class Meta: model = HSKLevels fields = ["level", "label", "value"] It gives me the following output: { "hsk": [ { "level": 1, "label": "HSK 1", "value": "hsk1" }, { "level": 2, "label": "HSK 2", "value": "hsk2" }, { "level": 3, "label": "HSK 3", "value": "hsk3" }, { "level": 4, "label": "HSK 4", "value": "hsk4" }, { "level": 5, "label": "HSK 5", "value": "hsk5" }, { "level": 6, "label": "HSK 6", "value": "hsk6" }, { "level": 7, "label": "HSK 6+", "value": "hsk6plus" } ] } But ideally, I'd like to have a key to each of these items, rather than just something to iterate over, so I'd most likely to prefer it to look like this: { "hsk": { 1: { "level": 1, "label": "HSK 1", "value": "hsk1" }, 2: { "level": 2, "label": "HSK 2", "value": "hsk2" }, 3: { "level": 3, "label": "HSK 3", "value": "hsk3" }, 4: { "level": 4, "label": "HSK 4", "value": "hsk4" }, 5: … -
avoiding 502 on digitalocean and django
I am working on a ViciDial project where I need to add DIDs in ViciDial through API. But before adding any DID, I need to check if it is marked as spam-likely in any operator. I am using Django for this purpose, user can upload any number of DIDs through CSV and the script will check if any of them is flagged as spam before adding in ViciDial. I am using Telnyx API to check number status, below is my concerned code def check(request): telnyx.api_key = "api_key1234" logged_user = User.objects.get(username=request.user) all_dids = table_did.objects.filter(user=logged_user) for number in all_dids: telnyx.NumberLookup.retrieve("+1"+number.did) return HttpResponse('Finish2') But the list is huge and for loop takes time before returning any response. Obviously, I get 502 error from Nginx. (Django app is hosted on DigitalOcean with Gunicorn, Nginx and Postgres). What I am looking for is something which keeps returning response from django app to my gunicorn server after every iteration. like for number in all_dids: result = telnyx.NumberLookup.retrieve("+1"+number.did) return JsonResponse({'done':result}) I know this looks silly and there will be just one iteration, but I want to keep for loop running without getting 502. Also, it doesn't matter how long it takes, as long as the user is … -
Django traverse through relations
I've got some models which relations like this: class Conversion(models.Model): class Unit(models.IntegerChoices): g = 10, 'gramy', ml = 20, 'mililitry', qty = 30, 'sztuki' name = models.CharField(max_length=128) g = models.FloatField() ml = models.FloatField(null=True, blank=True) qty = models.FloatField(null=True, blank=True) default = models.IntegerField(choices=Unit.choices, default=Unit.g) class Ingredient(models.Model): class Unit(models.IntegerChoices): g = 10, 'gramy', dkg = 11, 'dekagramy', kg = 12, 'kilogramy', ml = 20, 'mililitry', l = 21, 'litry', qty = 30, 'sztuki' Conversion = models.ForeignKey(Conversion, on_delete=models.CASCADE, related_name='ingredients') amount = models.FloatField() unit = models.IntegerField(choices=Unit.choices, default=Unit.g) class Step(models.Model): body = models.JSONField() Ingredients = models.ManyToManyField(Ingredient, related_name='steps') class Recipe(models.Model): title = models.CharField(max_length=128) teaser = models.CharField(max_length=256) Steps = models.ManyToManyField(Step, blank=True, related_name='recipes') Say there's a conversion for flour where 1ml == .53g, and the steps are separated because of how they are displayed so I thought it would be best to put it all into separate models. Now if a user tells me he has some amount(Ingredients.amount) of ingredients(Conversion) I want to find all recipes that have equal or less of these. for example user chooses 3 ingresients: |conversion.pk|amount| |-------------|------| |1 |200 | |2 |300 | |3 |1000 | If a recipe has steps.conv.pk 1 and 2 with right amount but doesn't have the 3rd one, I want … -
django-background-tasks integration
I have a simple django app that provides a login page and an authenticated dashboard. I have created a data model, and the dashboard view displays this data, taken from the django database. I have also created a class that processes the data in this model. This class is stateful and needs to be instantiated once the django app and associated db are ready. The class is not involved in the app views directly, it only modifies db content, and uses a trigger function registered with django-background-tasks to trigger class state changes. Currently I instantiate the class in a separate file, along with the background task function, but where in the django file structure should I import this and where would be best to call the background task function? Thanks.