Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
When I run python manage.py migrate I'm getting a Error
when i try to run python manage.py migrate I always get a traceback error. Help me to solve this problem. I have deleted a model called Program. Operations to perform: Apply all migrations: admin, auth, ca, contenttypes, courses, index, languages, online_courses, sessions Running migrations: Applying courses.0007_auto_20190816_2209...Traceback (most recent call last): File "C:\Users\Prabu\Anaconda3\envs\codeforcoder\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\Prabu\Anaconda3\envs\codeforcoder\lib\site-packages\django\db\backends\sqlite3\base.py", line 383, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: NOT NULL constraint failed: new__courses_courses.program_id The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\Prabu\Anaconda3\envs\codeforcoder\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\Prabu\Anaconda3\envs\codeforcoder\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) return executor(sql, params, many, context) File "C:\Users\Prabu\Anaconda3\envs\codeforcoder\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\Prabu\Anaconda3\envs\codeforcoder\lib\site-packages\django\db\utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\Prabu\Anaconda3\envs\codeforcoder\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\Prabu\Anaconda3\envs\codeforcoder\lib\site-packages\django\db\backends\sqlite3\base.py", line 383, in execute return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: NOT NULL constraint failed: new__courses_courses.program_id -
How to interact with client side without finding any request from client
Scenario; 1. Creating QRCODE and displaying it to the client. 2. Client scanning the code from the browser by using its mobile and responding to our server by using callback uri. 3. We find the response from the qr scanner application. 4. But how we can interact with the client side on the behalf of this response, actually client is not requesting directly. I am waiting for your kind response, Thanks. -
Django App using Celery Beat + Worker as Windows Service
I created a Django app that runs tasks using Celery as specified in tasks.py. Currently, I'm running it with 2 command prompts windows, one for beat and one for worker with the following commands as per this post: celery -A main worker -l info -P gevent celery -A main beat -l info I read about supervisor but that is for Linux. I have to make this work on a Windows server. I looked at several posts and many of them are old articles with deprecated libraries. This is the most current one I found. I'm following the instructions, but I don't understand where the beat and worker commands go. How does it know to go to my tasks.py and run? I would have commented to the actual post, but I'm not allowed to post because I have less than 50 reputation. This is the script from the post with my path and directory: '''Usage : python celery_service.py install (start / stop / remove) Run celery as a Windows service''' import win32service import win32serviceutil import win32api import win32con import win32event import subprocess import sys import os import shlex import logging import time # The directory for celery.log and celery_service.log # Default: … -
Django crispy-forms how to create a 2 separated column form
I dug into the crispy forms Layout documentation as well as some stackOverflow threads, trying to create a 2 separated column form. I created this layout on a forms.Form: class BasicForm(forms.Form): label_1 = forms.CharField(label='label1') label_2 = forms.CharField(label='label2') label_3 = forms.CharField(label='label3',help_text='This is help text', widget=forms.Textarea) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Row( Field('label_1', wrapper_class='col-md-6', css_class='row-fluid'), ), Row( Field('label_2', wrapper_class='col-md-6', css_class='row-fluid'), Field('label_3', wrapper_class='col-md-6') ) ) And what i get in the browser is: You can see that the TextArea block is not aligned to top. I wanted it to be near label1. When i try this layout: self.helper.layout = Layout( Row( Field('label_1', wrapper_class='col-md-6', css_class='row-fluid'), Field('label_3', wrapper_class='col-md-6') ), Row( Field('label_2', wrapper_class='col-md-6', css_class='row-fluid') ) ) Putting the textarea on the first row, i get this: Which also does not look OK. I wanted the label2 block to be right under label1, and not under the TextArea -
How to render a bound Django model form as HTML-safe?
I am trying to return a bound form modified to insert some text and HTML into it. I have done some research and have been able to successfully insert some arbitrary text into a bound form but I haven't found any way render the injected HTML as HTML. It renders as plain text. How can I achieve my goal? Here is the code: # views.py def multi_text(request): if request.method == 'POST': data = request.POST.copy() form = MultilineForm(data=data) if form.is_valid(): cd = form.cleaned_data form.data['text'] = '<i>Hello hello</i>' return render(request, 'multi_text.html', {'form': form}) else: form = MultilineForm() return render(request, 'multi_text.html', {'form': form}) # forms.py class MultilineForm(ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['text'].widget.attrs.update({'class': 'form-control'}, verbose_name='Text', placeholder='Type your text here...') self.data['text'] = '...' class Meta: model = Multiline fields = ['text'] widgets = { 'text': Textarea(attrs={}), } # template.html <form method="post" action="" class="form"> {% csrf_token %} {{ form.text.as_widget }} <span class="input-group-btn"> <input type="submit" value="Check" class="form-control btn btn-primary"> </span> </form> -
How to add more columns to pivot table in many to many relations in Django?
I have 2 models united by a Many to Many relationship, in this case is Policies and Coverages so far it works fine, but I want to add another column to the pivot table since it wont work on any of the modeled tables (I want to add a IntegerField with the name 'amount' so I can store how much money are we covering for that specific coverage in that specific Insurance Police) class Policy(models.Model): """Insurance Policies Model""" number = models.CharField(max_length=25, unique=True) company = models.OneToOneField(Company, on_delete=models.CASCADE) client = models.OneToOneField(Client, on_delete=models.CASCADE) start_date = models.DateField() end_date = models.DateField() comission = models.PositiveIntegerField() salesperson = models.ForeignKey(Salesperson, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) rif = models.CharField(max_length=50) phone = models.CharField(max_length=100) class Meta: db_table = 'policies' class Coverage(models.Model): """Coverage of the different types of policies""" name = models.CharField(max_length=55) policies = models.ManyToManyField(Policy) class Meta: db_table = 'coverages' I made the migrations and the pivot table was made without problems, but I don't know how to add another field to the pivot table -
Django model won't update using .update()
I am trying to update a record in my database using info provided by my website's front-end using Model.objects.update(**kwargs) however on running the code I get the following error: "'Record' with this Id already exists." I would have expected that using the "update" method instead of the "create" method would mean that it shouldn't matter / should be expected that there is already a record with the same ID. def find_patient(request): my_form = ExampleForm() if request.method == "POST": my_form = ExampleForm(request.POST) if my_form.is_valid(): UserInfo.objects.update(**my_form.cleaned_data) else: print(my_form.errors) context = { 'form': my_form, 'data_input': DataInput.objects, 'sections': SECTION_CHOICES } return render(request, 'example.html', context) The resulting error looks tike this: idUser info with this Id already exists. Am I misunderstanding the use case for "update" and if so, how would I go about using kwargs to update all fields for a given record in my db? -
Displaying Django templates in a VueJS template
I have the following django index page: {% load render_bundle from webpack_loader %} <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/MaterialDesign-Webfont/3.8.95/css/materialdesignicons.css"> <meta charset="UTF-8"> <title>My test</title> </head> <body> <div id="app"> <h1>TEST</h1> </div> {% render_bundle 'main' %} </body> </html> This template is supposed to call my VueJS frontend, so that i can use Vue on my Django templates, this is the Vue template being called: <template> <v-app id="sandbox"> <v-navigation-drawer v-model="primaryDrawer.model" :clipped="primaryDrawer.clipped" :floating="primaryDrawer.floating" :mini-variant="primaryDrawer.mini" :permanent="primaryDrawer.type === 'permanent'" :temporary="primaryDrawer.type === 'temporary'" app overflow ><v-switch v-model="$vuetify.theme.dark" primary label="Dark" ></v-switch></v-navigation-drawer> <v-app-bar :clipped-left="primaryDrawer.clipped" app > <v-app-bar-nav-icon v-if="primaryDrawer.type !== 'permanent'" @click.stop="primaryDrawer.model = !primaryDrawer.model" ></v-app-bar-nav-icon> <v-toolbar-title>TRADIFY</v-toolbar-title> </v-app-bar> </v-app> </template> Which is just a simple Vuetify default template, really similar to this. Until now, it's alright, i can see the page but i don't see the Django part in my template. To debug it, i added that <h1> TEST </h1> to my index page, so when i open http://127.0.0.1:8000/ i should see the Vue template + the Django template. The problem is that i don't see the <h1>. I think that somehow the Vue/Vuetify components are hiding it, because if i remove everything from the Vue part, except <template></template> i will see the <h1>TEST</h1> appearing. I need to fix this … -
Django and VueJS. Response cookies are not being saved on browser
I have some trouble with cookies in Django. VueJS Frontend makes Django a POST request and in Django POST response I send a cookie and in the browser dev tools I see: Response headers But when I go to DevTools/Application/Cookies, the cookie does not appears. -
Django Methods in Model Not Updating Properly
I created some functions within my models.py in Django that tracks the users' money but for some reason, they only update once Profile is reloaded or when I add transactions. When I try to delete, it does not update until I refresh the page and when I try to search the tags, the method values completely disappear from the page. I have no idea why this happens nor what I can do to fix it. views.py def profile(request): if request.method == 'GET': return render(request, 'users/profile.html', { 'transactions': Transaction.objects.all(), 'balance':Profile.total_balance(request.user), 'income':Profile.total_income(request.user), 'expense':Profile.total_expenses(request.user)}) if request.method == 'POST': form = TransactionForm(request.POST) if form.is_valid(): tag = form.cleaned_data.get('tag') amount = form.cleaned_data.get('amount') category = form.cleaned_data.get('category') user=request.user Transaction.objects.create( user=user, tag=tag, amount=amount, category=category ).save() elif request.method == 'DELETE': id = json.loads(request.body)['id'] transaction = get_object_or_404(Transaction,id=id) transaction.delete() return HttpResponse('') return HttpResponseRedirect(reverse('profile')) def search(request): query = request.GET.get('q') if query and query!="": results = Transaction.objects.filter(Q(tag__icontains=query)) else: results = Transaction.objects.all() transactions = { 'transactions' : results, } return render(request, 'users/profile.html', transactions,{ 'balance':Profile.total_balance(request.user), 'income':Profile.total_income(request.user), 'expense':Profile.total_expenses(request.user)}) models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def total_balance(User): transaction_list = Transaction.objects.filter(user=User) total_balance_amount = 0 for transaction in transaction_list: if transaction.category=='Income': total_balance_amount += transaction.amount elif transaction.category=='Expense': total_balance_amount -= transaction.amount return total_balance_amount def total_income(User): transaction_list = Transaction.objects.filter(user=User) total_income_amount = 0 … -
How to handle django regex url with vue.js?
I am trying to link vue.js with my Django application but having trouble with URL, I have created my app using Django rest framework,I have a two models with one to many relationship and used regex in url to link each other . I am new to vue.js and it's getting more complicated for me to find a way to connect URL to my Django app models.py: class TreatmentGiven(models.Model): id = models.AutoField(primary_key = True) patient = models.ForeignKey(Ipd,on_delete = models.CASCADE,default = None) medicine_name = models.CharField(max_length = 100,null = True) types_of_doses = models.CharField(max_length = 100,null = True) route = models.CharField(max_length = 100,null = True) number_of_days = models.IntegerField(null = True) views.py : class DischargeViewSet(viewsets.ModelViewSet): queryset = TreatmentGiven.objects.all() serializer_class = TreatmentGivenSerializer filter_backends = (filters.SearchFilter,) search_fields = ('ipd','medicine_name','types_of_doses','route','number_of_days') @login_required def discharge_detail(request,ipd_id): object = get_object_or_404(Ipd,pk=ipd_id) if request.method == "POST": formtwo = DischargeForm(request.POST) if formtwo.is_valid() : formtwo.save() return HttpResponseRedirect(reverse('dischargelist')) else: return HttpResponse(formtwo.errors.as_data()) else: formtwo = DischargeForm() return render(request, 'dischargedetails.html', {'object':object, 'form2': formtwo}) serializers.py: class TreatmentGivenSerializer(serializers.ModelSerializer): class Meta: model = TreatmentGiven fields = '__all__' routers.py: router = routers.DefaultRouter() router.register(r'^(?P<ipd_id>\d+)/dischargedetails/$', DischargeViewSet) urls.py urlpatterns = [ path('api/', include(router.urls)), re_path(r'^(?P<ipd_id>\d+)/dischargedetails/$', my_patient.discharge_detail, name='discharge_details'), ]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) vue.js : Vue.http.headers.common['X-CSRFToken'] = "{{ csrf_token }}"; new Vue({ el: '#starting', delimiters: ['${','}'], data: { treatmentgivens: … -
Add url to API response on serializers.Serializer
I have a django-application with the followin files models.py from datetime import datetime class Comment(object): def __init__(self, email, content, created=None): self.email = email self.content = content self.created = created or datetime.now() serializers.py from rest_framework import serializers class CommentSerializer(serializers.Serializer): email = serializers.EmailField() content = serializers.CharField(max_length=200) created = serializers.DateTimeField() url = serializers.CharField(source='get_absolute_url', read_only=True) in views.py I now define a a ViewSet to return the serialized results. In this class I define a list of comments views.py from rest_framework import viewsets from .serializers import * from .models import Comment from rest_framework.response import Response class CommentViewSet(viewsets.ViewSet): lc = [Comment(email='jan@auto.com', content='hallo mike'), Comment(email='jan@auto.com', content='hallo jan'), Comment(email='jan@auto.com', content='hallo niklas')] def list(self, request): serializer = CommentSerializer(self.lc, many=True) return Response(serializer.data) def retrieve(self, request, pk=None): user = self.lc[int(pk)] serializer = CommentSerializer(user) return Response(serializer.data) When I now call the api (http://127.0.0.1:8000/comments/?format=json) I get the following result [ { "email": "jan@auto.com", "content": "hallo mike", "created": "2019-08-16T16:53:56.371890Z" }, { "email": "jan@auto.com", "content": "hallo jan", "created": "2019-08-16T16:53:56.371890Z" }, { "email": "jan@auto.com", "content": "hallo niklas", "created": "2019-08-16T16:53:56.371890Z" } ] In this response I would have hoped to see a url for each dataset. The error ist probably that url = serializers.CharField(source='get_absolute_url', read_only=True) the source is undefined in the Comment class. However I have no … -
How to submit CSRF_TOKEN with Django and Vue.js
I have a django template using Vue.js that I am using with django-rest-framework as an API. In a form I am including {% csrf_token %} but I still get the following error: {\"detail\":\"CSRF Failed: CSRF token missing or incorrect.\"}". This is the vue function that is getting called. getMarketplaces: function() { this.loading = true; this.$http.get('/app/api/marketplace/') .then((response) => { this.marketplaces = response.data; this.loading = false; }) .catch((err) => { this.loading = false; console.log(err); }) I am using django-rest-framework's router, serializer and viewset. I am using some code from the following tutorial - https://medium.com/quick-code/crud-app-using-vue-js-and-django-516edf4e4217. What have I forgotten to add/do other than including the token? -
django logging sql: can we know the line details in the views.py which executes its database query
I am trying to know the sql executed and also the line from which it got triggered in Django using logging. Django has built in loggers. So using django.db.backends in built logger we can see the raw sql in the console. The below a simple view code in views.py def test(request) import logging l = logging.getLogger('django.db.backends') l.setLevel(logging.DEBUG) l.addHandler(logging.StreamHandler()) user_set = User.objects.all() for user in user_set: print(user.last_name) # print is just for testing As we know from Django's Documentation When QuerySets are evaluated When QuerySets are evaluated¶ Internally, a QuerySet can be constructed, filtered, sliced, and generally passed around without actually hitting the database. No database activity actually occurs until you do something to evaluate the queryset. and also A QuerySet is iterable, and it executes its database query the first time you iterate over it. So in the above code the database query is executed at the line for user in user_set: I want the following information along with the sql in logging: The line number The filename with fullpath The function name Also if possible the code statement with few lines above and below. Is this possible because this can give me the full picture. I tried using formatter … -
Django calculate mean of two field from a dataset in views.py
hi i have a dataset with population of man and woman by years. i want to calculate mean of man and woman population by years. i mean (man+woman)/2 for 2018 and so on. i wrote the code below views.py def Nufus_ilce(request): dataset = models.population.objects.all() means = context = { 'dataset': dataset, 'means': means, } return render(request, 'population.html', context) population.html {{ dataset.year }} {{ dataset.man }} {{ dataset.woman }} {{ means }} so how can i calculate means? -
Change Django REST Authentication Message when `IsAuthenticated` is on the Settings
I know that you can redefine the message you get from Django REST Framework by overriding the message variable inside your custom permissions classes. However, if I put a specific permission class on my REST_FRAMEWORK settings, I seem to not be able to change the message. In my case, that might be because I have some other added settings for extra authentication procedures. For instance, my REST_FRAMEWORK settings.py looks like: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication' ], 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema' } What I want is to alter the top-level message I get from my API, e.g., when I try to login. So far, what I receive is the standard: Authentication credentials were not provided. So... what is the proper way of changing the message in this case? -
Using environment variables from .env in Django Celery
I'm using Django 2.x and Celery 4.3.x In my Django application, I'm using dotenv to serve environment variable from .env file and to load the environment variable, I have following script in the manage.py and wsgy.py files env_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), '.env') dotenv.read_dotenv(env_file) The environment variables have AWS credentials being used by anymail plugin to send mail using SES. Now, I'm using a Celery task to send the email and running the celery worker from the command line using celery -A myapp worker -l debug The worker is running but when sending an email, it gives an error in the celery task as ERROR/ForkPoolWorker-2] An error occurred (AccessDenied) when calling the SendRawEmail operation: User `arn:aws:iam::user_id:user/my-laptop` is not authorized to permorm this action... It seems trying to connect with my laptop's user instead of using the credentials defined in the .env file. How can I use the .env file to server the environment files to the Celery worker? -
ValueError : not enough values to unpack (expected 2, got 1)
I am trying to send mail through my django application the same way as I have done before, but this one returns the above error. What is wrong with my code? Please help. views def paymail(request,pk): usermail = Payment.objects.get(id=pk) centre = usermail.username.premises client = usermail.username.user.username email = UserProfile.objects.filter(role = 'Centre Manager', premises__address=centre).values_list('user__email')[0] message = 'User' + client + ' from your centre has requested to pay their dues by cash. Kindly take action soon.' msg = EmailMessage('Re : Cash Payment',message, to=[email], ) msg.send() return HttpResponseRedirect(reverse('manager:paymentclient')) The error to be specific is being displayed in msg.send(). -
Why django creates new default permissions even with default_permissions=() in the Meta?
I setup some test app to check django's behaviour. Makefile for testing: clean: rm db.sqlite3 mig_model: python manage.py migrate flights 0001 mig_all: python manage.py migrate show1 show2: python manage.py shell -c "from django.contrib.auth.models import Permission; print(list(Permission.objects.values_list('id', 'codename')))" all: clean mig_model show1 mig_all show2 removing old db migrating to the point when first own model is created after migration default permissions should be created in post_migrate signal. But I specify in Model.Meta that no default permissions should be created check all permissions - I can see that they were indeed generated migrate everything else, which is just 1 more data-migration where I delete all permissions in the system show all permissions again and I can see that old permission were deleted and new ones created after migration (they all have new ids) models.py: class Schedule(models.Model): flight_day = models.DateField() class Meta: default_permissions = () permissions = () -
How to hide a list element in html
I want to hide a list element when I click on a button. I tried it with in Javascript. This does not work. document.getElementById("1").children[0].style.display = "none" <script> function hid(){ document.getElementById("1").children[0].style.display = "none" } </script> <div class="container-fluid"> <div class="column"> <div class="col-md-2 "> <ul class="list-group" id="1"> <li id="2"><a href="{% url 'search:barbars' %}" class="list-group-item list-group-item-action">barbar <div class="image-parent"> <img src="http://cool-web.de/icons/images/024800/024768.ico" class="img-fluid" alt="nothing"> </div> <!-- The Button --> <button onclick="hid" class="btn btn-outline-success my2 my-sm-0" type="submit">Search</button> -
Define python directory in cpanel
My Cpanel host has 2 instances of Python. Python 2.6 - /usr/bin/python Python 3.6 - /usr/bin/python3.6 If I run this script: #! /usr/bin/python print "Content-type: text/html\n\n" print "<html>Hello world!</html>" It works! But If it doesn't work (Internal error 500) if I run: #! /usr/bin/python3.6 print "Content-type: text/html\n\n" print "<html>Hello world!</html>" I know python 3.6 is installed and in the specified path, as you can see below: Thanks. -
Django annotate(...) taking a dictionary
I have somewhat complex django query with a lot of .annotate: query = ModuleEngagement.objects.filter(course_id=course_id)\ .values('username')\ .annotate( videos_overall=Sum(Case(When(entity_type='video', then='count'), output_field=IntegerField()))) \ .annotate( videos_last_week=Sum(Case(When(entity_type='video', created__gt=seven_days_ago, then=1), output_field=IntegerField()))) \ .annotate( problems_overall=Sum(Case(When(entity_type='problem', then='count'), output_field=IntegerField()))) \ .annotate( problems_last_week=Sum(Case(When(entity_type='problem', created__gt=seven_days_ago, then='count'), output_field=IntegerField()))) \ .annotate( correct_problems_overall=Sum(Case(When(entity_type='problem', event='completed', then='count'), output_field=IntegerField()))) \ .annotate( correct_problems_last_week=Sum(Case(When(entity_type='problem', event='completed', created__gt=seven_days_ago, then='count'), output_field=IntegerField()))) \ .annotate( problems_attempts_overall=Sum(Case(When(entity_type='problem', event='attempted', then='count'), output_field=IntegerField()))) \ .annotate( problems_attempts_last_week=Sum(Case(When(entity_type='problem', event='attempted', created__gt=seven_days_ago, then='count'), output_field=IntegerField()))) \ .annotate( forum_posts_overall=Sum(Case(When(entity_type='discussion', then='count'), output_field=IntegerField()))) \ .annotate( forum_posts_last_week=Sum(Case(When(entity_type='discussion', created__gt=seven_days_ago, then='count'), output_field=IntegerField()))) \ .annotate( date_last_active=Max('created')) Does annotate accept a dictionary as a parameter so I can move all the annotates into it? If so, what would be the syntax? -
Celery task.status method rises a exception : AttributeError: module <module_name> has no attribute 'DoesNotExist'
Stack: django = "==2.2.2" django-celery-beat = "==1.4.0" celery = "==v4.3.0rc1" python_version = "3.7" I have a class that import some data from csv/xls file and save da data, here is my celery config: CELERY_TASK_ALWAYS_EAGER = False CELERY_BROKER_URL = config('REDIS_BROKER_URL') CELERY_RESULT_BACKEND = config('REDIS_RESULT_URL') CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' Here is where i call my task (some class based view): def form_valid(self, form): if self.request.is_ajax(): form.save() instance = form.save() kwargs = { 'corporation_id': self.corporation.id, 'file_id': instance.id, } task_id = import_file_task.apply_async( kwargs=kwargs, ) instance.tas_id = task_id instance.save() return JsonResponse( { 'form_status': 'Success', 'task_id': str(task_id), } ) return super().form_valid(form) Here is where i call my task: @celery_app.task(bind=True) def import_file_task(_, corporation_id, file_id): sale_file = SaleFile.objects.get( id=file_id, corporation_id=corporation_id, ) if sale_file.type == PRODUCT_FILE: error = ProductImporter( corporation_id=corporation_id, file_id=file_id, product_file=sale_file, ).save() elif sale_file.type == RECEIVABLE_FILE: error = ReceivableImporter( corporation_id=corporation_id, file_id=file_id, receivable_file=sale_file, ).save() else: raise ValueError('File type is not valid') task = AsyncResult(sale_file.tas_id) task.info = error task.status = 'COMPLETED' Here is where i try to poll the task status and i get the error! class TaskStatus(View): def get(self, request): task_id = request.GET.get('_task_id') task = AsyncResult(task_id) print(task) print(task.state) #HERE IS THE ERROR print(dir(task)) #THE STATUS APPEAR HERE success_response = ( { 'status': ['state: ' ], … -
Adding the class name to the selection options. Django - forms
I have a very simple forms.py PROVINCE_CHOCIES = [ (1, 'New York'), (2, 'Las Vegas'), (3, 'San Francisco'), ] class SearchForm(forms.Form): province = forms.ChoiceField(choices=PROVINCE_CHOCIES) Is it possible to add a class to the drop-down list? My form in htmlu looks like this: <option value="1">New York</option> <option value="2">Las Vegas</option> <option value="3">San Francisco</option> The expected result is: <option value="1" class="A">New York</option> <option value="2" class="A">Las Vegas</option> <option value="3" class="D">San Francisco</option If possible? how can I do this in my forms.py file, or using some external plug? The solution will be useful for me to use the simple dependent/chained drop-down list. As in this exampe. Any help will be appreciated. -
Convert context into serialize data
I have a function in django app which I want to convert into serializer data to use it in react via API. class DispatchHistory(ListView): model = DispatchPlan context_object_name = 'plan' template_name = 'classroom/teachers/dispatcher_history.html' def get_queryset (self): return DispatchPlan.objects.filter(owner_id=self.request.user.pk) def get_context_data (self, **kwargs): context = super().get_context_data(**kwargs) dispatch_plans = DispatchPlan.objects.filter(owner_id=self.request.user.pk) dis_items = [] for i in dispatch_plans: it = i.items obj_list = [] for j in it: obj = get_object_or_404(ItemBatch, id=j) obj_list.append(obj) dis_items.append(obj_list) context['t_items'] = dispatch_plans context["ttt"] = dis_items return context I created a Serializer for this: class dispatchhistorySerializer(serializers.ModelSerializer): class Meta: model = DispatchPlan fields = "__all__" and tried this: class DispatchHistoryAPI(APIView): serializer_class = dispatchhistorySerializer def get(self, request, **kwargs): try: dispatch_plans = DispatchPlan.objects.filter(owner_id=request.user.pk) context = {} dis_items = [] for i in dispatch_plans: it = i.items obj_list = [] for j in it: obj = self.serializer_class(get_object_or_404(ItemBatch, id=j)).data obj_list.append(obj) dis_items.append(obj_list) context['t_items'] = dispatch_plans context["ttt"] = dis_items #what comes here ? return JsonResponse({ "details": context }) except: raise return JsonResponse({ "details": "Failed " }, status=500) How do I use this serializer to convert the context data to serializer data to use it in an API?