Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cancel a save from save method in django models
So I have django model and I want to override save so that it only saves on certain instances. Is there a way to avoid a save from happening if a condition is met? The idea is if certain conditions defined with an if statement aren't met the instance fails to be saved. so for instance if there is not enough waiters we cancel the save, or if there is not enough tables we do the same. Here's my code: class Service(models.Model): id = models.AutoField(primary_key=True) arrival = models.DateTimeField(auto_now_add=True) exit = models.DateTimeField(null=True, blank=True) waiter = models.ForeignKey('Waiter', on_delete=models.CASCADE) table = models.ForeignKey('Table', on_delete=models.CASCADE) total_ammount= models.DecimalField(max_digits=15, decimal_places=2) def save(self, *args, **kwargs): if self.id == None: time = datetime.datetime.now() # check for waiters waiters = Waiter.objects.select_related().annotate(num_Service=Count('service', filter=Q(service__exit__gt=time))).all() available_waiters = waiters.filter(num_Service__lt=4) avalable_waiters_length = len(available_waiters) # check for tables tables = Table.objects.select_related().annotate(num_Service=Count('service', filter=Q(service__exit__gt=time))).all() available_tables = tables.filter(num_Service__lt=1) avalable_tables_length = len(available_tables) # return exception if a problem arises if avalable_tables_length == 0 and avalable_waiters_length == 0: print("not enough waiters or tables") if avalable_waiters_length == 0: print("not enough waiters") return if avalable_tables_length == 0: print("not enough tables") return # assign waiter and table waiter_obj = random.choice(available_waiters) self.waiter = waiter_obj table_obj = random.choice(available_tables) self.table = table_obj print(time.time()) # check if current … -
How do i go about making a django model field unique but only for individual users?
So I have this watchlist model class Watchlist(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='watchlist') symbol = CharField(max_length=10, unique=True) Where a user and a text symbol is saved. A user is not allowed to save two of the same symbol cuz that wouldnt be good logic. Thats why i added the unique=True. However, I later realized that i kinda misunderstood what unique does and that its unique across the whole table no matter who the user is. I only want it to be unique when the user is the same. So Test_User can save "ABC" and "DEF" but cant save "ABC" again. However User123 should be allowed to save "ABC" and so on. One bad solution to this would be taking care of it in my views when i save instances by getting a list of symbols saved already and checking if the given symbol is in that list or not and save accordingly. I consider this a bad solution because it wont work in admin and the redundancy will be insane if i need to use it in other views -
(djstripe.C001) Could not find a Stripe API key. HINT: Add STRIPE_TEST_SECRET_KEY and STRIPE_LIVE_SECRET_KEY to your settings
Stripe keys are not being detected correctly and I don't know where the error is in DJStripe. Here is how my Stripe is configured: STRIPE_SECRET_KEY = os.environ.get("STRIPE_SECRET_KEY", "sk_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx") STRIPE_PUBLIC_KEY = os.environ.get("STRIPE_PUBLIC_KEY", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx") STRIPE_TEST_SECRET_KEY = "sk_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx STRIPE_TEST_PUBLIC_KEY = "pk_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" -
How to export models from admin page with username rather than user id?
I have a participant model in models.py Django as the following: from django.db import models from django.contrib.auth.models import User class Participant(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) score = models.FloatField(default=0) completed_study = models.BooleanField(default=False) def __str__(self): return self.user.username and I want to be able to export all the data from the admin page, so under the admin.py I added the following from django.contrib import admin from .models import Participant from django.contrib.auth.admin import UserAdmin as BaseAdmin from import_export.admin import ImportExportModelAdmin from import_export import resources from django.contrib.auth.models import User class UserResource(resources.ModelResource): class Meta: model = User fields = ('id', 'username') class UserAdmin(BaseAdmin, ImportExportModelAdmin): resource_class = UserResource class ParticipantAdmin(admin.ModelAdmin): list_display = ['user', ] readonly_fields = ('created_at', 'updated_at',) class ParticipantAdmin(ImportExportModelAdmin): pass admin.site.register(Participant, ParticipantAdmin) admin.site.unregister(User) admin.site.register(User, UserAdmin) I am able to export the data from the participant model, but I want under the user field to display the actual username rather than the id. How can I do that? is that even doable? -
request.user in generic view and in pure function in django
I was using django-rest-framework-simplejwt for authentication. Here is my settings.py filesettings.py file Initially I was trying to get login user by accessing request.user in a view function as shown below and passing access token in headers berear token: function test But I wasn't able to get the logged in user. Instead when I tried RetreiveAPIView of rest framework generics, it gave me the user..Here is the code for the same..Using RetreiveAPIView UserSerializer Initially I thought that both the request objects are same but it seems that there is some difference.. Can anyone explain me what is the difference between the two? -
Django Error Following Tutorial b/c using 3.1 not 1.9 TypeError: view must be a callable or a list/tuple in the case of include()
I know what the issue is, its that in my code I cant use a string to map my views to urls but Im not sure how to rewrite it so that it works. urls. py from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), path('posts/', "posts.views.post_home"), ## *how do i rewrite this section* ] apps.py from django.apps import AppConfig class PostsConfig(AppConfig): name = 'posts' views.py from django.http import HttpResponse from django.shortcuts import render # Create your views here. def post_home(request): return HttpResponse("<h1>Hello</h1>") -
How do I load image from Django REST API?
So as stated, I'm having trouble loading images from Django backend(fetch works fine). I've looked other similar questions, but NONE OF THEM HELPED, sadly. So here's my Django code: settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') urls.py from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) model.py class Content(models.Model): objects = models.Manager() image = models.ImageField(upload_to='None', height_field=None, width_field=None, max_length=None, null=True, blank=True) key_line = models.CharField(max_length = 100, null=True) ### All 페이지에 보여지는 핵심 문장 body = models.TextField(blank=True, null=True) ### 발췌 내용 I've uploaded an image named 'eeee.PNG', and I can see the data serialized in JSON format like below: [ { "id": 5, "image": "/media/None/eeee.PNG", "key_line": "key.", "body": "blablabla", }, ] And my React code (fetch has been successfully worked) : <Container classname=""> <Row className=""> <Col className="text-text img-eachcake">{this.props.image}</Col> <Col className="text-text img-eachcake" src={this.porps.image}></Col> </Row> </Container> As you can see, I've tried two ways but none of them worked. What do you think is the problem? All the other props are loaded fine. It's just the image file that doesn't work. +in the inspection mode > Elements, I see the line as : <div src="/media/None/eeee.PNG" class="text-text img-eachcake col"></div> -
Pagination feature not working and paginator bar styling is off
I have two bugs in my code, First bug is a styling bug or frontend bug, Second bug is Pagination not working. The second bug is I'm trying to make the button active depending on what page it is, The button only lights up for page 1, When I go to page 2 the button is still active or lit up. The first bug for styling is the buttons were meant to look like this: but they look like this: Current code: <div class="row"> <div class="col-md-12"> {% if listings.has_other_pages %} <ul class="pagination"> {% if listings.has_previous %} <li class="page-item"> <a href="?page={{listings.previous_page_number}}" class="page-link">&laquo;</a> </li> {% else %} <li class="page-item disabled"> <a class="page-link">&laquo;</a> </li> {% endif %} </ul> {% endif %} {% for i in listings.paginator.page_range %} {% if listings.number == i %} <li class="page-item active"> <a class="page-link page-item">{{ i }}</a> </li> {% else %} <li class="page-item"> <a href="?page{{i}}" class="page-link">{{i}}</a> </li> {% endif %} {% endfor %} </div> </div> Intended to look code <div class="row"> <div class="col-md-12"> <ul class="pagination"> <li class="page-item disabled"> <a class="page-link" href="#">&laquo;</a> </li> <li class="page-item active"> <a class="page-link" href="#">1</a> </li> <li class="page-item"> <a class="page-link" href="#">2</a> </li> <li class="page-item"> <a class="page-link" href="#">3</a> </li> <li class="page-item"> <a class="page-link" href="#">&raquo;</a> </li> </ul> </div> … -
How to temporary store a generated image for download
I have written some code for taking an image, and adding some text to it. Currently it just saves the file locally, but I would like it to store the new generated image temporary, so when the session is closed the file is deleted. Also, so in the future multiple users would be able to use the function at the same time, without one user owerwriting another ones image. My current code is: def Output(request): inputValue = request.GET.get('t', '') my_image = Image.open(os.path.join(BASE_DIR, 'media', 'blank.jpg')) title_font = ImageFont.truetype(os.path.join(BASE_DIR, 'homepage', 'static', 'homepage', 'Mistral.ttf'), 60) title_text = inputValue image_editable = ImageDraw.Draw(my_image) image_editable.text((45,333), title_text, (0, 0, 0), font=title_font) my_image.save(os.path.join(BASE_DIR, 'media', 'result.jpg')) return TemplateResponse(request, 'homepage/output.html', {'title': 'Output'}) so instead os saving the image locally as result.jpg, how do I save it temporary for a specific session? -
django channels redis took too long to shut down and was killed
so i was trying to do some basic stuff with channels. i wrote a script in my html to return a message script <script> const chatsocket = new WebSocket( 'ws://'+window.location.host+'/ws/test/' ) chatsocket.onmessage = function (e) { const data = JSON.parse(e.data) console.log(data) chatsocket.close() } </script> my consumers.py from channels.exceptions import StopConsumer from channels.generic.websocket import AsyncWebsocketConsumer import json class NotificationConsumer(AsyncWebsocketConsumer): async def connect(self): self.group_name = 'notificationgroup' await self.channel_layer.group_add( self.group_name, self.channel_name ) await self.accept() await self.channel_layer.group_send( self.group_name, { 'type': 'tester_message', 'tester': 'hello world' } ) async def tester_message(self, event): tester = event['tester'] await self.send(text_data=json.dumps({ 'tester': tester })) async def disconnect(self, close_code): await self.channel_layer.group_discard( self.group_name, self.channel_name ) raise StopConsumer() so basically i get my desired output in the console... when i have CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels.layers.InMemoryChannelLayer' } } but when i use an aws redis cluster (after installing channels-redis obviously) CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('aws redis endpoint', 6379)], }, }, } i get this error WebSocket HANDSHAKING /ws/test/ [127.0.0.1:51551] WebSocket DISCONNECT /ws/test/ [127.0.0.1:51551] Application instance <Task pending name='Task-4' coro=<StaticFilesWrapper.__call__() running at E:\intes\sync\shero\venv\lib\site-packages\channels\staticfiles.py:44> wait_for=<Future pending cb=[BaseSelectorEventLoop._sock_write_done(1216)(), <TaskWakeupMethWrapper object at 0x000001F7D5226C70>()]>> for connection <WebSocketProtocol client=['127.0.0.1', 51551] path=b'/ws/test/'> took too long to shut down and was killed. what … -
Error message on entering duplicate in django form
I am trying to avoid duplicate email in my website form . Till now I was able to do this: 1.Whenever I enter duplicate email, it navigate back to homepage and user is not saved{ In my case team is not joined}. 2.In admin page when I try to enter duplicate email , I get my error message of duplicate email address I want this message in my form too, but it navigates to homepage. This is my model in models.py: class Team(models.Model): username = models.CharField(max_length=100) email = models.EmailField(max_length=100,unique=True,error_messages={'unique':"Email already exists"}) contact=models.IntegerField(null=False,blank=False,default=1234567890) def __str__(self): return self.username This is my form in forms.py: class TeamMembers(forms.ModelForm): username = forms.CharField(required=True,max_length=100) email = forms.EmailField(required=True,max_length=100,error_messages={'unique':"Email already exists"}) contact=forms.IntegerField(required=True) class Meta: model=Team fields = ['username','email','contact'] This is my function in views.py class TeamMembers(forms.ModelForm): username = forms.CharField(required=True,max_length=100) email = forms.EmailField(required=True,max_length=100,error_messages={'unique':"Email already exists"}) contact=forms.IntegerField(required=True) class Meta: model=Team fields = ['username','email','contact'] This is my join_team.html {% extends 'base.html' %} {%load crispy_forms_tags%} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Join our team</legend> {{form|crispy}} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Join</button> </div> </form> </div> {% endblock content %} I want to display error message on form page instead of going to homepage. I … -
I need to show date in formatted (like a short date ) in django page
I need to show date in formatted (like a short date ) in django page . I changed in settings.py USE_L10N = False and DATE_FORMAT = '%y-%m-%d' DATE_FORMAT = 'Y-m-d' And in templates : <h2> Created at : {{ data.date|date:'Y-m-d'}}</h2> But , I get blank output (no date displayed) , I get it when I print onlt data.date but in the following format : 2021-02-10T16:48:04.401985Z I need a cleaner format . my models.py : date = models.DateTimeField(default=now, editable=False) -
Why in an AllowAny view of Django I get 401 Unauthorized using Firefox but not using Edge or Postman?
I'm using knox LoginView to make the login of my backend. This is the code of the view: class Login(LoginView): permission_classes = (AllowAny,) def post(self, request, format=None): serializer = AuthTokenSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] login(request, user) return super(Login, self).post(request, format=None) When I execute my frontend (developed with angular) and try to login using Microsoft Edge everything works fine. I get the token and save it in local. Same result if I execute a POST using Postman. But, If I try to do the same using Firefox I receive 401 Unauthorized with this JSON: {"detail":"Invalid token."} Why does it ask for a token if its an AllowAny view? Why does it work in Edge and Postman but not in Firefox? More data: This is the authentication class in settings.py: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'knox.auth.TokenAuthentication', ), } EDIT: Actually, it works usign Firefox Developer Edition. -
Triggers are not being created in django-transitions
I am trying to build a basic implementation of django-transitions following the example here. It seems to me that I did everything in line with the example. When I create an instance of my model, however (and even of just the defined mixin itself), there are no triggers. I'm at a loss at what I may have done wrong and why that leads to triggers not being created. Can anyone confirm/help? Here is my workflow definition (lifecycles.py): from django_transitions.workflow import StatusBase, StateMachineMixinBase from transitions import Machine class ContactLifecycleStatus(StatusBase): # Define states ACTIVE = "ACTIVE" INACTIVE = "INACTIVE" BLOCKED = "BLOCKED" # Define human-readable labels for states # TODO: translate labels STATE_CHOICES = ( (ACTIVE, "active"), (INACTIVE, "inactive"), (BLOCKED, "blocked"), ) # Define transitions as constants ACTIVATE = "activate" DEACTIVATE = "deactivate" BLOCK = "block" UNBLOCK = "unblock" # Define human-readable label and css class for use in Django admin # TODO: translate labels TRANSITION_LABELS = { ACTIVATE: {'label': 'Activate', 'cssclass': 'default'}, DEACTIVATE: {'label': 'Deactivate'}, BLOCK: {'label': 'Block', 'cssclass': 'deletelink'}, UNBLOCK: {'label': 'Unblock', 'cssclass': 'default'}, } # define collection of states for machine SM_STATES = [ACTIVE, INACTIVE, BLOCKED,] # define initial state for machine SM_INITIAL_STATE = ACTIVE # define transitions as … -
Django - how do create a model right after User creating form?
So I'm working on this school managing system and I would like to make a signup form, that not only create User, but also create an object with one-to-one link to user. I've tried dozens of options, and still nothing is working. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) teacher = models.BooleanField() forms.py class UserCreateForm(UserCreationForm): teacher = forms.BooleanField() class Meta: model = User fields = ('username', 'password1', 'password2, 'teacher') views.py class SignUp(CreateView): form_class = forms.UserCreateForm success_url = reverse_lazy('accounts:login') template_name = 'signup.html' Do you have any ideas how can I do that? -
Django ModuleNotFoundError: No module named 'asgiref'
I have a Django service we are trying to schedule in conjunction with the main application that runs periodically to send automated emails via a batch script. The Django application itself starts up fine, but when I try running the batch script, I get the following traceback: Traceback (most recent call last): File "C:\Program Files\compuweather\compuweather\webapp\management\commands\send_all_clients.py", line 2, in <module> from django.core.management.base import BaseCommand File "C:\ProgramData\Anaconda3\lib\site-packages\django-3.2- py3.8.egg\django\core\management\__init__.py", line 13, in <module> from django.apps import apps File "C:\ProgramData\Anaconda3\lib\site-packages\django-3.2-py3.8.egg\django\apps\__init__.py", line 1, in <module> from .config import AppConfig File "C:\ProgramData\Anaconda3\lib\site-packages\django-3.2-py3.8.egg\django\apps\config.py", line 7, in <module> from django.utils.deprecation import RemovedInDjango41Warning File "C:\ProgramData\Anaconda3\lib\site-packages\django-3.2-py3.8.egg\django\utils\deprecation.py", line 5, in <module> from asgiref.sync import sync_to_async ModuleNotFoundError: No module named asgiref I find that odd considering I have the batch file set to run from an anaconda environment that has Asgiref installed. I can verify this with pip freeze. Here are the versions of the packages I'm using: asgiref==3.3.1 Django==3.1.6 I saw a similar issue here, that was due to the Django and asgiref packages being outdated. I've tried updating both asgiref and Django to the latest versions (those listed), but that also didn't help. My best guess after looking through the traceback is either something is trying to use a deprecated … -
STRIPE KEYS not being detected. Can someone tell me why? Thank you! Django [closed]
The stripe keys are not being detected correctly but I don't know where is wrong. It is programmed in Django. STRIPE_SECRET_KEY = os.environ.get("STRIPE_SECRET_KEY, "sk_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx") STRIPE_PUBLIC_KEY = os.environ.get("STRIPE_PUBLIC_KEY", "pk_live_xxxxxxxxxxx") STRIPE_TEST_SECRET_KEY = STRIPE_SECRET_KEY STRIPE_TEST_PUBLIC_KEY = STRIPE_PUBLIC_KEY STRIPE_LIVE_MODE = False DJSTRIPE_WEBHOOK_SECRET = os.environ.get("STRIPE_WEBHOOK_SECRET") -
Django for loop only catching the last iteration on button click
I am building a Django movie app which makes use of the TMDB API. The way I have it set up currently is that I have a function in my main.js which is run when the page is loaded which makes the call to the API based on which media_id is clicked from the search results, which saves to local storage. This works fine in this regard. I implemented a review functionality where logged in users are able to leave reviews on whichever title they wish and it saves to the DB, and then on the user account page I have a list displayed of all the reviews a logged in user has left. Up till here everything works as intended but this is where my error lies. Next to each review in the users account page I have a button I want to take the user to the page in which they left the review, however I can only seem to get it to link me to the final title in the list of reviews. The code I have in my account.html file is as follows: <tbody> {% for review in reviews %} <script type="text/javascript"> function resetValues() { localStorage.setItem('movieId', … -
OSError: [WinError 127] The specified procedure could not be found
Context: I've been trying to create a spatial database for a geolocation-based app using GEOS/GIS/GDAL. First I had an issue saying windows could not find GDAL, so I followed these steps https://stackoverflow.com/a/49159195/9660287 which kind of worked but it now raises a WinError127. I checked for multiple versions of python on my system but I only have 1, version 3.9.1. Traceback (most recent call last): File "D:\health\manage.py", line 22, in <module> main() File "D:\health\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Python\lib\site-packages\django-3.1.5-py3.9.egg\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Python\lib\site-packages\django-3.1.5-py3.9.egg\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Python\lib\site-packages\django-3.1.5-py3.9.egg\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python\lib\site-packages\django-3.1.5-py3.9.egg\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Python\lib\site-packages\django-3.1.5-py3.9.egg\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Python\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "D:\health\facility\models.py", line 1, in <module> from django.contrib.gis.db import models File "C:\Python\lib\site-packages\django-3.1.5-py3.9.egg\django\contrib\gis\db\models\__init__.py", line 3, in <module> import django.contrib.gis.db.models.functions # NOQA File "C:\Python\lib\site-packages\django-3.1.5-py3.9.egg\django\contrib\gis\db\models\functions.py", line 3, in <module> from django.contrib.gis.db.models.fields import BaseSpatialField, GeometryField File "C:\Python\lib\site-packages\django-3.1.5-py3.9.egg\django\contrib\gis\db\models\fields.py", … -
i send my django project to my client and on his laptop it gives him error
Although I use python version 3and he use python version 3.8. and also he download database sqlite3 browser. the error is -
Celery shared_task hangs on task call
I have a simple celery task with print statement. The problem is in shared_task decorator, because if I change the decorator to app.task it works fine. @shared_task def generate_pdf(): print('Just to test if its working') But calling this task from a view or django shell just stucks until i hit Ctrl+C. Here is the traceback after keyboard interupt when celery hangs. ^CTraceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/kombu/utils/objects.py", line 41, in __get__ return obj.__dict__[self.__name__] KeyError: 'tasks' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/kombu/utils/objects.py", line 41, in __get__ return obj.__dict__[self.__name__] KeyError: 'data' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/kombu/utils/objects.py", line 41, in __get__ return obj.__dict__[self.__name__] KeyError: 'tasks' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/local/lib/python3.8/site-packages/celery/local.py", line 143, in __getattr__ return getattr(self._get_current_object(), name) File "/usr/local/lib/python3.8/site-packages/celery/local.py", line 105, in _get_current_object return loc(*self.__args, **self.__kwargs) File "/usr/local/lib/python3.8/site-packages/celery/app/__init__.py", line 69, in task_by_cons return app.tasks[ File "/usr/local/lib/python3.8/site-packages/kombu/utils/objects.py", line 43, in __get__ value = obj.__dict__[self.__name__] = self.__get(obj) File "/usr/local/lib/python3.8/site-packages/celery/app/base.py", line 1259, in tasks self.finalize(auto=True) File "/usr/local/lib/python3.8/site-packages/celery/app/base.py", line 511, in finalize _announce_app_finalized(self) File "/usr/local/lib/python3.8/site-packages/celery/_state.py", line 52, in … -
in django model foreign key not retrieving actual value
in django i defined two tables 1. country 2.state while i am trying to print country_id from State table its retriving like "State object (1)" i am expectin number alone like 1 ,2 3 # location lookup class Country(models.Model): country_id=models.AutoField(auto_created=True,primary_key=True) country_name=models.CharField(max_length=50) country_code=models.CharField(max_length=50,null=True,blank=True) # state lookup class State(models.Model): state_id=models.AutoField(auto_created=True,primary_key=True) state_name=models.CharField(max_length=50) country_id=models.ForeignKey(Country, on_delete=models.CASCADE,db_column='country_id') -
Django-Run a function in the background forever
In my case,I need to process something in the background indefinitely and as often as possible. Tools like Celery,RQ,etc have minimum limit as 1 second to run something periodically. But what I need is a way to run a function in the background without blocking the Django server from running. I tried while loop.But it blocks the server. I need something like below def call_me_once_and_run_forever_as_often_as_possible(): print("I am running here indefinitely without affecting serving of Web requests") call_me_once_and_run_forever_as_often_as_possible() I read about async.But can't quite understand how to run it forever. Any small snippet would be of great help. Thanks for helping -
NoReverseMatch at /listings/ Reverse for 'listing' not found. 'listing' is not a valid view function or pattern name
So I'm getting this error when I visit the page, I'm trying to use paginator and I don't know where i'm wrong, index function handles the page I'm talking about views.py def index(request): listings = Listing.objects.all() paginator = Paginator(listings, 3) page = request.GET.get('page') paged_listings = paginator.get_page(page) params = {'listings':paged_listings} return render(request, 'listings/listings.html', params) def listing(request, listing_id): return render(request, 'listings/listing.html') def search(request): return render(request, 'listings/search.html') listings.html {% extends 'base.html' %} {% block content %} {% load humanize %} <!-- Breadcrumb --> <section id="bc" class="mt-3"> <div class="container"> <nav aria-label="breadcrumb"> <ol class="breadcrumb"> <li class="breadcrumb-item"> <a href="{% url 'index' %}"> <i class="fas fa-home"></i> Home</a> </li> <li class="breadcrumb-item active"> Browse Listings</li> </ol> </nav> </div> </section> <!-- Listings --> <section id="listings" class="py-4"> <div class="container"> <div class="row"> {% if listings %} {% for listing in listings %} <div class="col-md-6 col-lg-4 mb-4"> <div class="card listing-preview"> <img class="card-img-top" src="{{ listing.photo_main.url }}" alt=""> <div class="card-img-overlay"> <h2> <span class="badge badge-secondary text-white">${{ listing.price | intcomma}}</span> </h2> </div> <div class="card-body"> <div class="listing-heading text-center"> <h4 class="text-primary">{{ listing.title }}</h4> <p> <i class="fas fa-map-marker text-secondary"></i>{{ listing.city }} {{ listing.state }}, {{ listing.zipcode }}</p> </div> <hr> <div class="row py-2 text-secondary"> <div class="col-6"> <i class="fas fa-th-large"></i>Sqfit: {{ listing.sqft }}</div> <div class="col-6"> <i class="fas fa-car"></i>Garage: {{ listing.garage }}</div> </div> … -
django url parameter creating in the process
I have no idea how to solve this problem: I have a django webshop project. At the end of the order I would like to redirect the user to a new page about the confirmation. urls.py: `path('confirmation/<str:order_id>/', views.confirmation,` name="confirmation"), views.py: def confirmation(request, order_id): items = OrderItem.objects.filter(order__id = order_id) context = {'items':items} return render(request, 'store/pages/confirmation.html', context) I have a javascript part another view where I do a POST method. If it is successfully done I would like to navigate to the confirmation page. In the data I get back the order_id. var url = '/process_order/' fetch(url,{ method: 'POST', headers: { 'Content-Type':'application/json', 'X-CSRFToken':csrftoken, }, body: JSON.stringify({'myForm':myFormData}) }) .then((response) => response.json()) .then((data) => { window.location.href = "{% url 'confirmation' data %}" }) I guess the problem is that in the very beginning of the execution there is no value of the data, because it is creating in the process. So the view can not render because of the parameter. (But my problem is that the order_id is creating after the POST method). (The Exception Value: Reverse for 'confirmation' with arguments '('',)' not found. 1 pattern(s) tried: ['confirmation/(?P<order_id>[^/]+)/$'] ) What would be the good solution of this situation?