Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to kill a Celery task if it's not finished after a set period of time?
I have a Celery task that runs the main function of external Python scripts. However, some of the scripts may take a very very long time to execute and I'd like to set a time limit after which the tasks are aborted if they're not finished. I've tried all the ways I've found on other similar questions but I couldn't find a way to implement it. My task is the following : @app.task(name="execute_script", bind=True, base=CallbackTask) def execute_script(self, script_id, variables, name, start_time): self.update_state(state='EXECUTING') script = Script.objects.get(pk=script_id) mod = Script.get_script(script) # Getting the script's module try: mod.main(variables, name) except Exception as e: raise e return name Is there a way to set a time limit on a Celery task after which it's aborted if not finished ? -
Django css loads into admin site, but will not change the appearance
I am using nginx to load my static files. All of my static files appear where the should be in the STATIC_URL. When I inspect the admin page, I see the files loading properly. The styling still does not work. See, everything loads as expected, yet the css is not doing anythings. Does anybody know how to fix this? -
Multiple send request at one time
In a Django Project, Multiple send request at one time how can be handle. for example, If multiple person hit send button at same time in the website. How can be queue the request in Django-Website? -
I want to host django website which is more than 50mb as on github it only takes 25 mb .How can I do that?
Any hosting site like Heroku uses GitHub but the file is more than 50 Mb so I can't upload it -
Run bash file from Django views in Windows
I would like to run a bash file from a class written in views file of Django. I have tried many ways but didn't seem to work. So can you suggest some effective method for this ? -
Error during WebSocket handshake: Unexpected response code: 502 - Django
I am running my server on a ec2 instance with gunicorn and nginx. My site and project works but it gives error connecting with websockets. I am using Websocket in js to connect with Django channels. On my local server everything was working correctly but after deploying my site. Websockets are not working and giving me this error Error during WebSocket handshake: Unexpected response code: 502. What I have tried uptil now... I have installed redis and daphne. Configured daphne setting in nginx configuration. My Server is running on 80 port and I have set daphne on 8001 port. When I start daphne service it runs for some time and then disconnect/fail automatically but when it is running my websockets still cant connect. Any kind of help will be great for me. -
ModuleNotFoundError: No module named 'indiacowin'
enter image description hereplz, help me I don't think about the error.where indiacowin is my app name. -
How to use path parameter in GenericViewSet, Mixin CBS?
I'm new in DRF, Django. I want to make get API with path parameter which name is period. (ex. localhost:8000/api/ranks/{period}) # views.py class RankingView(mixins.ListModelMixin, GenericViewSet): queryset = Record.objects.all() serializer_class = RecordSerializer @action(methods=['GET'], detail=False, url_path='<str:period>', url_name='<str: period>') def get_rank(self, request, period): #logic return # urls.py router.register(r'api/ranks', RankingView) urlpatterns = [ path('', include(router.urls)), ] but it is not working. it might be easy to solve but I couldn't find answer, thank you for your help. -
Queryset random order specific to each user in Django
I want to order queryset randomly which is fixed for each user. When I use order_by("?") order change each time but I want different order for each user than don't change next time. For example for user one order is [obj1, obj5, obj3, obj4, obj2] and for user two is [obj5, obj2, obj1, obj3, obj4] and order for user one don't change but is different from other users. How can I do this? -
How to update redis - Django
I need help updating my cache. I use redis in my django project. Is there a way to trigger an auto refresh on redis itself so it performs a look up on the db to make an update on the cache. I am trying to implement this while avoiding signals and tasks. Is there anyway to trigger an auto refresh for a particular key in redis cache? -
Not able to view the data that I am inserting in Products model
I am doing shopping CRUD with Products model with categories,sub_categories,color,size as foreign key. the problem is that I am unable to view the data that I am trying to insert,below are the codes that I have tried. below is the model class Products(models.Model): categories = models.ForeignKey(Categories,on_delete=models.CASCADE) sub_categories = models.ForeignKey(SUBCategories,on_delete=models.CASCADE) color = models.ForeignKey(Colors,on_delete=models.CASCADE) size = models.ForeignKey(Size,on_delete=models.CASCADE) image = models.ImageField(upload_to = 'media/',width_field=None,height_field=None,null=True) title = models.CharField(max_length=50) price = models.CharField(max_length=10) sku_number = models.CharField(max_length=10) product_details = models.CharField(max_length=300) quantity = models.IntegerField(default=0) isactive = models.BooleanField(default=True) below is the show and insert function def show(request): showall = Products.objects.filter(isactive=True) print(showall) serializer = POLLSerializer(showall,many=True) print(serializer.data) return render(request,'polls/product_list.html',{"data":serializer.data}) def insert(request): if request.POST == "POST": print('POST',id) insert_clothes = {} insert_clothes['categories']=request.POST.get('categories') insert_clothes['sub_categories']=request.POST.get('sub_categories') insert_clothes['color']=request.POST.get('color') insert_clothes['size']=request.POST.get('size') # insert_clothes['image']=request.POST.get('image') insert_clothes['title']=request.POST.get('title') insert_clothes['price']=request.POST.get('price') insert_clothes['sku_number']=request.POST.get('sku_number') insert_clothes['product_details']=request.POST.get('product_details') insert_clothes['quantity']=request.POST.get('quantity') form = POLLSerializer(data = insert_clothes) if form.is_valid(): form.save() # print('data',form.data) print(form.errors) messages.success(request,'Record Updated successfully :)!!!!') return redirect('polls:show') else: print(form.errors) else: print('GET',id) form = POLLSerializer(data=request.POST) if form.is_valid(): form.save() messages.success(request, "Record Updated Successfully...!:)") return redirect("polls:show") return render(request,'polls/product_insert.html') show.html <td><b>{{result.categories}}</b></td> <td><b>{{result.sub_categories}}</b></td> <td><b>{{result.color}}</b></td> <td><b>{{result.size}}</b></td> <td><b>{{result.title}}</b></td> <td><b>{{result.price}}</b></td> <td><b>{{result.sku_number}}</b></td> <td><b>{{result.product_details}}</b></td> <td><b>{{result.quantity}}</b></td> insert.html <form method="POST"> {% csrf_token %} <table> <thead> <tr> <td>Categories</td> <td> <select class="form-select" aria-label="Default select example" name="categories"> <option selected>Open this select menu</option> <option value="9-6 WEAR">9-6 WEAR</option> <option value="DESI SWAG">DESI SWAG</option> <option value="FUSION WEAR">FUSION WEAR</option> <option value="BRIDAL WEAR">BRIDAL … -
ImportError: attempted relative import beyond top-level package whilst referring within same app
I am here because google search didn't solve the issue yet. Project structure created in Visual Studio Community 2022 is like as follows, Project0 | --Project0 | ---settings.py --- <> | --App1 | ---models.py ---views.py ---forms.py | --App2 | ---models.py ---views.py ---forms.py ---tables.py Project0, App1, App2 are all in same hierarchy. When trying to run the solution, I am getting the following errors with App2 files, File "D:\Projects\Django\Project0\App2\urls.py", line 2, in <module> from . import views File "D:\Projects\Django\Project0\App2\views.py", line 5, in <module> from .tables import ProductTable, ProductHTMXtable File "D:\Projects\Django\Project0\App2\tables.py", line 2, in <module> from ..App1.models import List ImportError: attempted relative import beyond top-level package 1st issue: Here in App2 there are no models created. Instead, importing models from App1's model. So I guess the line --> from ..App1.models import List <-- might be wrong. If I remove those 2 dots '..' then I get Import could not be resolved error and the models are not being referred though its not stopping the solution from running. 2nd issue: Why do --> from . import views <-- & --> from .tables import <-- too are throwing errors. Unable to fix theses issues. Please help. -
how do i include get_absolute_url in my success_url of a class view
how do i include the get_absolute_url defined in the model in the class based view? model class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="comments") name = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField(default="This is the Body of a Comment.") date_added = models.DateField(auto_now_add=True) time_added = models.DateTimeField(auto_now_add=True) date_updated = models.DateField(auto_now=True) time_updated = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = "Post Comments" ordering = ["-time_updated"] def __str__(self): return self.post.title + " | " + self.name.username def get_absolute_url(self): return f"/blogs/post/{self.post.slug}" view class DeleteCommentView(DeleteView): model = Comment template_name = "delete_comment.html" success_url = (refer the get_absolute_url) -
Hostname taking in python
In python i want to take current device hostname or mac address. Because i need to know which device user is using. List item I used socket.gethostname() but it shows me server host not current using device. -
Did you have anyone use eZee Reservation api
Need to find out create booking and need all the information about parameters in the create a booking api [ { "Error Details": { "Error_Code": "ParametersMissing", "Error_Message": "Missing parameters." } } ] -
Django Import-Export is not processing List fields properly
I am using Django-import-export In one model I have ListTextField In exported csv file it is displayed correctly ['parameter1', 'parameter2'], however when I import it back it goes like this ''' ["['parameter1'", " 'parameter2']"] ''' I need help here ) -
How to convert raw sql to Django ORM?
I have been given sql query and I have to convert it to Django ORM and output should be the same. sql_query = "SELECT a.ID, a.post_title, a.post_name, a.post_date, d.meta_value, e.meta_value FROM wp_8_posts a, wp_8_term_relationships b, wp_8_term_relationships c, wp_8_postmeta d, wp_8_postmeta e WHERE a.post_type = :post_type AND a.post_status = 'publish' AND a.ID = b.object_id AND b.term_taxonomy_id = 1 AND a.ID = c.object_id AND c.term_taxonomy_id = :post_tag AND a.ID = d.post_id AND d.meta_key = 'upurl' AND a.ID = e.post_id AND e.meta_key = 'target' ORDER BY a.post_date DESC;" models.py class Wp_8Post(models.Model): ID = models.IntegerField(primary_key=True,null=False,default=None) post_author = models.IntegerField(null=False,default=0) post_date = models.DateTimeField(null=False) post_title = models.TextField(null=False,default=None) post_status = models.CharField(max_length=20,null=False,default='publish') post_name = models.CharField(max_length=200,null=False,blank=True) post_modified = models.DateTimeField(null=False) guid = models.CharField(max_length=255,null=False,blank=True) post_type = models.CharField(max_length=20,null=False,default='post') class Meta: app_label = 'cms' db_table = 'wp_8_posts' class Wp_8Postmeta(models.Model): meta_id = models.IntegerField(primary_key=True,null=False,default=None) post_id = models.ForeignKey(Wp_8Post,on_delete=models.CASCADE) meta_key = models.CharField(max_length=255,null=True,default=None) meta_value = models.TextField(null=True,default=None) class Meta: app_label = 'cms' db_table = 'wp_8_postmeta' class Wp_8Termrelationships(models.Model): object_id = models.ForeignKey(Wp_8Post,on_delete=models.CASCADE) term_taxonomy_id = models.IntegerField() term_order = models.IntegerField(null=False,default=0) class Meta: app_label = 'cms' db_table = 'wp_8_term_relationships' UniqueConstraint( name = 'term_relationship', fields = ['object_id','term_taxonomy_id'] ) First I thought to minimize the sql query by using INNER JOIN so I tried this but I got confused why same table is being used two times … -
Django forms how to initialze only not required field instead of passing all required fields
class Student(models.Model): name = models.CharField(null=True, blank=True) fieldA = models.TextField(null=True, blank=True) fieldB = models.TextField(null=True, blank=True) fieldC = models.TextField(null=True, blank=True) fieldD = models.TextField(null=True, blank=True) class Meta: model = Student fields = '__all__' Based on the above example all fields are taken in UpdateView or CreateView. If i need to take only required field i can change Meta to class Meta: model = Student fields = ['name','fieldA',fieldB','fieldC'] So my question is how can add only fields that should not pass in the Meta.From above example 'fieldD' is not passed. Is there is any way to say 'fieldD' is not required instead on passing all required fields in Meta.So that the code can be reduced. Above one is a small example. Consider I have 200 fields and only 1 field that I didnot want to pass so instead of passing 199 required fields in Meta is there is anyway to tell only the 1 field should not pass -
Not able view the data that I am trying to insert in CRUD
I am doing a CRUD of Products.I am struggling to view the data that I am trying to insert. below is the models,serializer(since I am suppsoed to use serializers instead of forms),functions and htmls class Products(models.Model): categories = models.CharField(max_length=15) sub_categories = models.CharField(max_length=15) color = models.CharField(max_length=15) size = models.CharField(max_length=15) # image = models.ImageField(upload_to = 'media/',width_field=None,height_field=None,null=True) title = models.CharField(max_length=50) price = models.CharField(max_length=10) sku_number = models.CharField(max_length=10) product_details = models.CharField(max_length=300) quantity = models.IntegerField(default=0) isactive = models.BooleanField(default=True) class POLLSerializer(serializers.ModelSerializer): class Meta: model = Products fields = "__all__" def show(request): showall = Products.objects.all() print(showall) serializer = POLLSerializer(showall,many=True) print(serializer.data) return render(request,'polls/product_list.html',{"data":serializer.data}) def insert(request): if request.POST == "POST": print('POST',id) insert_clothes = {} insert_clothes['categories']=request.POST.get('categories') insert_clothes['sub_categories']=request.POST.get('sub_categories') insert_clothes['color']=request.POST.get('color') insert_clothes['size']=request.POST.get('size') # insert_clothes['image']=request.POST.get('image') insert_clothes['title']=request.POST.get('title') insert_clothes['price']=request.POST.get('price') insert_clothes['sku_number']=request.POST.get('sku_number') insert_clothes['product_details']=request.POST.get('product_details') insert_clothes['quantity']=request.POST.get('quantity') form = POLLSerializer(data = insert_clothes) if form.is_valid(): form.save() # print('data',form.data) print(form.errors) messages.success(request,'Record Updated successfully :)!!!!') return redirect('polls:show') else: print(form.errors) else: print('GET',id) insert_clothes = Products.objects.all() form = POLLSerializer(data = insert_clothes) if form.is_valid(): print(form.errrors) return render(request,'polls/product_insert.html') below is insert html code <form method="POST"> {% csrf_token %} <table> <thead> <tr> <td>Categories</td> <td> <select class="form-select" aria-label="Default select example" name="categories"> <option selected>Open this select menu</option> <option value="1">9-6 WEAR</option> <option value="2">DESI SWAG</option> <option value="3">FUSION WEAR</option> <option value="">BRIDAL WEAR</option> </select> </td> </tr> <tr> <td>Sub-Categories</td> <td> <input type="text" name="sub_categories" placeholder="SUB_CATEGORIES"> </td> </tr> <tr> … -
aws Beanstalk eb deploy relative path makemigrations ERROR Failed to deploy application
I keep getting an 2022-07-08 03:11:06 ERROR Instance deployment failed. For details, see 'eb-engine.log'. and ERROR: ServiceError - Failed to deploy application. when trying to run eb deploy when deploying a Django application to Elastic Beanstalk on aws. It is failing on Command 01_makemigrations it seams.. But here is the thing that is making me go crazy; the models.py works fine in http://127.0.0.1:8000/ (locally) with this one line: image = models.ImageField(upload_to=os.path.join(BASE_DIR, 'static'), null=True, blank=True). I noticed that is the line of code in the model, is causing an issue when deploying to production. I commented it out and it deployed fine but I need that method obviously.. Is this something with a Linux vs. Windows path issue?.. I am developing locally in Windows 10. 👽 django.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: the_slim_fatty.wsgi:application container_commands: 01_makemigrations: command: "source /var/app/venv/*/bin/activate && python3 manage.py makemigrations --noinput" leader_only: true 02_migrate: command: "source /var/app/venv/*/bin/activate && python3 manage.py migrate --noinput" leader_only: true 03_superuser: command: "source /var/app/venv/*/bin/activate && python3 manage.py createsu" leader_only: true eb-engine.log 2022/07/08 03:11:06.780830 [INFO] Error occurred during build: Command 01_makemigrations failed 2022/07/08 03:11:06.780855 [ERROR] An error occurred during execution of command [app-deploy] - [PostBuildEbExtension]. Stop running the command. Error: container commands build failed. Please refer to /var/log/cfn-init.log … -
How to use Django without database
I'm creating an app with a React frontend. The purpose of the backend is to call a public API, process the data retrieved from the public API, and then with a REST API transfer the post-processed data to the view (React frontend). I would like to use python in the backend, so I started with using Django. However, it seems Django is very much focused on Models and Databases. I do not need a database for this app. Is Django the right tool to use for this? -
I am using celery and setup celery command in supervisor and facing this issues in my django project
supervisor: couldn't exec /home/tspl/python_project/venv/bin/celery: ENOENT supervisor: child process was not spawned -
Django user with main password and multiple passwords
I have one different type login idea, One single User have multiple Accounts (ManyToMany or Foreign Key). Now my logic is, if User login with main user password. access the all Accounts related details. But if User login with Accounts based password, access that one Account related details only. -
Django: Nested Sum() annotations across three Model Relations
I am using Django to sort out a storefront environment to handle orders and am struggling on one of the annotations I am attempting to write. The salient data models are as such class Order(ClusterableModel): "various model fields about the status, owner, etc of the order" class OrderLine(Model): order = ParentalKey("Order") product = ForeignKey("Product") quantity = PositiveIntegerField(default=1) base_price = DecimalField(max_digits=10, decimal_places=2) class OrderLineOptionValue(Model): order_line = ForeignKey("OrderLine", related_name="option_values") option = ForeignKey("ProductOption") value = TextField(blank=True, null=True) price_adjustment = DecimalField(max_digits=10, decimal_places=2, default=0) The OrderLine represents one or more of a specific product being bought at a specific base price and quantity. This base price has been copied from the product model in order to preserve the price of the product at the time the order was created. The Order therefore is just a collection of multiple OrderLines The complexity comes in the OrderLineOptionValue model which represents a modification to the base price based on the choices made by the user, and each order line may have multiple adjustments if the product has multiple options. Color, size, weight, etc may each have variable price impacts. When querying the OrderLine model I have been able to successfully annotate each result with that line's appropriate line … -
MAC M1 Chip Python Architecture Error (have 'x86_64', need 'arm64e')
I am having trouble running django on my M1 Mac. When ever i try to run server or make migrations i get an (mach-o file, but is an incompatible architecture (have 'x86_64', need 'arm64e') error. My terminal is being open with Rosetta and I am using VSCode ide.