Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Best Practices for migrating python2 to python3 in django
It will be more helpful if you answer the following questions as well. Dealing with models.CharField. In python2, how the CharField value is stored in the database and how it is different from the value which is going to store in python3. -
How can I return complete object which is created with generic create views?
I'm creating an object. Only two fields are required. Rest of them are not require. The problem is after creating object. i'm only getting serialize version of those two fields. But i want to get complete object that is created.. views.py class CreateProjectAPIView(generics.CreateAPIView): """This endpoint allows for creation of a Project""" permission_classes = [IsAuthenticated,] serializer_class = serializers.ProjectSerializer def create(self, request, *args, **kwargs): request.data.update({'platform_subscriber_owner': request.user.id}) print("request.data :",request.data) serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) print("serializer.data :",serializer.data) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) models.py class Project(models.Model): platform_subscriber_owner = models.ForeignKey(User, verbose_name=_("project owner"), on_delete=models.CASCADE,null=True,blank=True) platform_subscriber_id = models.CharField(_("Project Key"), max_length=64, blank=True) platform_subscriber_entity = models.CharField(_("Project Names"), max_length=64,blank=True) platform_subscriber_secret_key = models.CharField(_("Project Secret Key"), max_length=64,blank=True) update_time = models.DateTimeField(_("Updated Time"), default = timezone.now) create_time = models.DateTimeField(_("Created Time"), default = timezone.now) postman object after creating: { "platform_subscriber_entity": "naae", "platform_subscriber_owner": 2, } expecting object : { "platform_subscriber_entity": "naae", "platform_subscriber_owner": 2, "platform_subscriber_secret_key":sdakjshdjkashdj, "platform_subscriber_id":jjaskdjskakska, "create_time":now, "update_time:null, } -
How to add left sidebar in custom django admin template
I have created one custom page for Django admin, file name is server.html {% extends "admin/base_site.html" %} {% block content %} <h1>Server management</h1> {% if status == 200 and message %} <ul class="messagelist"> <li class="success">Response status: <strong>{{ status}}</strong></li> <li class="success">{{message}}</li> {% if stdout %} <li class="info">{{stdout}}</li> {% endif %} </ul> {% elif status is not 200 and message %} <ul class="messagelist"> <li class="error">Response status: <strong>{{ status}}</strong></li> <li class="error">{{message}}</li> {% if stdout %} <li class="error">{{stdout}}</li> {% endif %} </ul> {% endif %} <form method="post" id="menu_form" novalidate=""> {% csrf_token %} <div> <fieldset class="module aligned "> <div class="form-row field-parent_menu"> <div> <label for="id_parent_menu">Server action:</label> <div class="related-widget-wrapper"> <select name="server_action" id="server_action"> <option value="" selected="">---------</option> <option value="status">Status of the Server</option> <option value="start">Start the Server</option> <option value="stop">Stop the Server</option> <option value="restart">Restart the Server</option> </select> </div> </div> </div> </fieldset> <div class="submit-row"> <input type="submit" style="float: left;" value="Submit" class="default" name="_submit"> </div> </div> </form> {% endblock %} And my base_site.html looks like this {% extends 'admin/base.html' %} {% load i18n static %} {% block title %}{% trans "My admin" %}{% endblock %} {% block branding %} <div class="3a-image-header"> <img src="{% static 'images/admin-logo.svg' %}"> </div> <div class="3a-text-header"> <h1 id="site-name">{% trans 'Admin Dashboard' %}</h1> </div> {% endblock %} {% block extrastyle %}{{ block.super }} … -
Crisp throws an error 'BoundWidget' object has no attribute 'field' when i want to submit
I am trying to do an advanced rendering on my Django crispy forms the form section of my index.html looks like this <form method = "post"> {% csrf_token %} {{ form.organization |crispy}} <div class="form-row"> <div class="form-group col-md-6 mb-0"> {{ form.start_date |crispy}} </div> <div class="form-group col-md-6 mb-0"> {{ form.end_date |crispy}} </div> </div> {{ form.recommend |crispy}} </form> -
Server error in django-heroku app Server Error (500)
after i developed it in heroku and change my DEBUG = False it's throws me an error i try to fix it but i can't cause i'm juniuor web devloper. is somebody can help me fix that please thank you. this is my settings.py file: STATIC_URL = '/static/' #STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIR = (os.path.join(BASE_DIR, 'static'),) STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIR = ( os.path.join(BASE_DIR, 'static'),) STATIC_URL = '/static/' MEDIA_URL ='/images/' STATICFILES_DIR = [ BASE_DIR / 'static' ] MEDIA_ROOT = BASE_DIR / 'static/images' STATIC_ROOT = BASE_DIR / 'staticfiles' this is my profile: web: gunicorn myproject.wsgi this is my logs: 2022-01-11T06:03:20.892917+00:00 heroku[web.1]: Idling 2022-01-11T06:03:20.908352+00:00 heroku[web.1]: State changed from up to down 2022-01-11T06:03:22.072179+00:00 heroku[web.1]: Stopping all processes with SIGTERM 2022-01-11T06:03:22.169474+00:00 app[web.1]: [2022-01-11 06:03:22 +0000] [9] [INFO] Worker exiting (pid: 9) 2022-01-11T06:03:22.169649+00:00 app[web.1]: [2022-01-11 06:03:22 +0000] [10] [INFO] Worker exiting (pid: 10) 2022-01-11T06:03:22.180490+00:00 app[web.1]: [2022-01-11 06:03:22 +0000] [4] [INFO] Handling signal: term 2022-01-11T06:03:22.187455+00:00 app[web.1]: [2022-01-11 06:03:22 +0000] [4] [WARNING] Worker with pid 9 was terminated due to signal 15 2022-01-11T06:03:22.192774+00:00 app[web.1]: [2022-01-11 06:03:22 +0000] [4] [WARNING] Worker with pid 10 was terminated due to signal 15 2022-01-11T06:03:22.281450+00:00 app[web.1]: [2022-01-11 06:03:22 +0000] [4] [INFO] Shutting down: Master 2022-01-11T06:03:22.537454+00:00 heroku[web.1]: … -
Export CSV file in a bulk in Django
I'm creating a custom administration action to download a list of orders as a CSV file. I've this in my orders/admin.py: def export_to_csv(modeladmin, request, queryset): opts = modeladmin.model._meta # opts = options for order in queryset: content_disposition = f'attachment; filename=OrderID-{order.id}.csv' response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = content_disposition writer = csv.writer(response) fields = [field for field in opts.get_fields() if not field.many_to_many and not field.one_to_many] writer.writerow([field.verbose_name for field in fields]) # Write data rows for obj in queryset: data_row = [] for field in fields: value = getattr(obj, field.name) if isinstance(value, datetime.datetime): value = value.strftime('%d/%m/%Y') data_row.append(value) writer.writerow(data_row) return response However, this code doesn't download more than one csv file Even when I've selected more than one. -
Ubuntu 20.04, Django, nginx file permission error 403 -no solution in stackoverflow as of now works
I have deplloyed Django 1.8 application on ubuntu server with gunicorn Ubuntu 20.04 Django 1.8 nginx 1.18.0 Python 2.7 The media files are having following permissions # ls -l total 4 drwxrwxrwx 5 www-data www-data 4096 Apr 18 2021 media Error message I get is 2022/01/11 05:26:30 [error] 4094535#4094535: *152 open() "<full path to media>/media/cache/b3/de/b3def88cd24c122f0e1dcaf96e021ec2.jpg" failed (13: Permission denied), client: 172.68.127.176, server: server.com, request: "GET /media/cache/b3/de/b3def88cd24c122f0e1dcaf96e021ec2.jpg HTTP/1.1", host: "www.server.com", referrer: "http://www.server.com/" the permissions for files are media# ls -l cache/b3/de/b3def88cd24c122f0e1dcaf96e021ec2.jpg -rwxrwxrwx 1 www-data www-data 24008 Jul 22 23:46 cache/b3/de/b3def88cd24c122f0e1dcaf96e021ec2.jpg nginx config is server { server_name server.com www.server.com 192.175.118.100; error_log /var/log/nginx/server_error_log error; location = /favicon.ico { access_log off; log_not_found off; } client_max_body_size 250M; location /static/ { autoindex on; root /home/server/static/; } location /media { autoindex on; alias /home/server/media/media; } location / { include proxy_params; proxy_pass http://unix:/run/server_gunicorn.sock; proxy_set_header X-Forwarded-Protocol $scheme; #proxy_set_header Host $host; #proxy_set_header X-Scheme $scheme; #proxy_set_header X-SSL-Protocol $ssl_protocol; } listen 80; } We are unable to upload files due to permission error -
Django time ordering app, how to loop from database in table
I want to create app for ordering time in the schedule, the total time is divided by 15 minutes, each 15 minutes in one column. rows are defined by date, start time and period. Periods are always divisible by 15 and in minutes. data in sche_table database : id | DATE | TIME | PERIOD | ---------------------------------- 1 | 1.1.2022 | 8:00:00 | 240 | my goal is create loop in table to create row as this: DATE 8:00 8:15 8:30 8:45 ... 12:00 1.1.2022 free free free free ... [null] when Period is less then 240 generare empy <td></td> tag. Question is how generate period / 15 <td></td> tags in table and when period is less then 240 generate empty <td></td> tags becosue <th> is always from 8:00 to 12:00 code <table> <th>Date</th> <th>8:00</th> <th>8:15</th> <th>8:30</th> <th>8:45</th> <th>9:00</th> <th>9:15</th> <th>9:30</th> <th>9:45</th> <th>10:00</th> <th>10:15</th> <th>10:30</th> <th>10:45</th> <th>11:00</th> <th>11:15</th> <th>11:30</th> <th>11:45</th> <th>12:00</th> <tbody> {% for sche in sche_table %} <tr> <td>{{sche.DATE|date:'d.m.Y' }}</td> <td><a href="#">Free</a></td> </tr> {% end for %} </tbody> </table> any ideas ? -
django.db.utils.IntegrityError: UNIQUE constraint failed: account_workexperiance.id
I am getting UNIQUE UNIQUE constraint failed: account_workexperiance.id error when updating list of objects. It has been working fine so far, and I haven't done any changes to this. models.py: class TutorUser(models.Model): tutor_user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='tutor') full_name = models.CharField(max_length=255, blank=True) phone_number = models.CharField(max_length=14, blank=True) class WorkExperiance(models.Model): tutor_work = models.ForeignKey(TutorUser, related_name='tutor_work', on_delete=models.CASCADE) organization = models.CharField(max_length=255, blank=True) start_year = models.IntegerField(null=True, blank=True) serializers.py: class WorkExperianceListSerializer(serializers.ListSerializer): def update(self, instance, validated_data): tutor_work_mapping = {tutor_work.id: tutor_work for tutor_work in instance} data_mapping = {item['id']: item for item in validated_data} ret = [] for tutor_work_id, data in data_mapping.items(): tutor_work = tutor_work_mapping.get(tutor_work_id, None) if tutor_work is None: ret.append(self.child.create(data)) else: ret.append(self.child.update(tutor_work, data)) for tutor_work_id, tutor_work in tutor_work_mapping.items(): if tutor_work_id not in data_mapping: tutor_work.delete() class WorkExperianceSerializer(serializers.ModelSerializer): id = serializers.IntegerField(read_only=False) class Meta: list_serializer_class = WorkExperianceListSerializer model = WorkExperiance fields = [ 'id', 'organization', 'start_year', ] def update(self, instance, validated_data): instance.organization = validated_data.get('organization', instance.organization) instance.start_year = validated_data.get('start_year', instance.start_year) instance.save() return instance views:py class TutorWorkExperiance(APIView): def put(self, request): tutor = TutorUser.objects.get(tutor_user__id=request.user.id) tutor_work = WorkExperiance.objects.filter(tutor_work=tutor) serializer = WorkExperianceSerializer(tutor_work, data = request.data, partial=True, many=True) if serializer.is_valid(raise_exception=True): serializer.save(tutor_work=tutor) return Response(serializer.data) It is working for create() but not updating, I think it is trying to create() only instead of update() -
Could not parse the remainder: '${profiles['user']}' from '${profiles['user']}
const data = '{{ search_user }}' const rdata = JSON.parse(data.replace(/&quot;/g, '"')) const input = document.getElementById('user-input_products') let filteredArr = [] input.addEventListener('keyup', (e)=>{ box.innerHTML = "" filterMax = (fn, c) => x => c && fn(x) && c-- filter = profiles=> profiles['full_name'].includes(e.target.value) max = 30 filteredArr = rdata.filter(filterMax(filter, max)) if (filteredArr.length > 0) { filteredArr.map(profiles=>{ box.innerHTML += `<li><a href="{% url 'user_num' ${profiles['user']} %}">${profiles['full_name']}</a></li>` }) } else { box.innerHTML = "No result found" } }) And when i want to pass id to django url inside of innerHTML it's give me this error: Could not parse the remainder: '${profiles["user"]}' from '${profiles["user"]}' How can i fix that? -
Django annotate division does't calculate float numbers correctly
I'm trying to divide numbers that are stored in database in millionth, but when the result is < 1, the decimals are lost. conditions_set.annotate( _amount_from=ExpressionWrapper(F('amount_from')/1000000, output_field=FloatField()), _amount_to=ExpressionWrapper(F('amount_to')/1000000, output_field=FloatField()), _value=ExpressionWrapper(F('value')/10000, output_field=FloatField()) ).values('_amount_from', '_amount_to', '_value').order_by('amount_from') 0 = {dict: 3} {'_amount_from': 0.0, '_amount_to': 1000.0, '_value': 0.0} 1 = {dict: 3} {'_amount_from': 1000.0, '_amount_to': 3000.0, '_value': 0.0} As the 'value' is equal to 6800, I'm expecting that the result of 6800/10000 is 0,68. But I get 0.0. -
Django: foreign key (many-to-many) show value
I have the following simple django model: class Account(models.Model): """ An account is for a team of users, or a single customer """ name = models.CharField(max_length=100, unique=True) admins = models.ManyToManyField('AccountUser', related_name='+', blank=True) metadata = models.JSONField(default=dict, blank=True) def __str__(self): return self.name @property def customers(self): """Accounts linked to this account""" return self.linked_accounts.linked_accounts.all() I am trying to loop through the account table and show the account records in a view: queryset_account = Account.objects.all() for account in queryset_account: logger.warning(account.name) logger.warning(account.admins) the account name is showing but the foreign key admins is returning none. How can I display the content of admins? -
Update multiple resource together in Django DRF
Lets say I have two models in Django: class Inventory(models.Model): created_at = models.DateTimeField(auto_now_add=True) added_by = models.ForeignKey(User, on_delete=models.SET("anonymous"), blank=True, null=True) name = models.CharField(max_length=100, unique=True) nickname = models.CharField(max_length=100, blank=True, null=True) class InventoryProperties(models.Model): key = models.CharField(max_length=100) value = models.CharField(max_length=100) order = models.IntegerField() item = models.ForeignKey(Inventory, on_delete=models.CASCADE, related_name='properties') What if I would like to add an Inventory and some properties to it from the frontend on the same page (form). Then I would have to save the Inventory item first, then save the properties. As I read in REST this should not be done with one resource (because this is a different resource, so now I have /inventory/:id/properties/): How to handle updates in a REST API? What happens if something goes wrong during saving the properties? I can't rollback easily the saved Inventory item, so I end up with a half-saved object. Also this is really hard to manage on the frontend, because if some error occurs during property saving, the frontend should not save the inventory again. -
is the django application can be not working based on the country language or timezone?
I have developed a Django application and it works perfectly in my laptop but when I delivered it to my customer in germany (the application send him 504 Gateway timeout) and when he try with another laptop also it sends him another content of the application(Exist on the same server), Help please is this reliant to the country language or what exactly am stuck on. Thanks in advance -
How to get row value from table when delete button is clicked?
I am trying to delete row when delete button is clicked. <tbody> {% for dt in data %} <tr> <td> <i class="fa fa-external-link user-profile-icon"></i> <a href="{{dt.url}}" target="_blank">{{dt.url}}</a> </td> <td>{{dt.modified}}</td> <td> <button type="button" class="fa fa-trash-o btn btn-danger" data-toggle="modal" data-target="#exampleModal{{forloop.counter}}">Delete</button> </td> <div class="modal fade bd-example-modal-lg" id="exampleModal{{forloop.counter}}" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModal{{forloop.counter}}">DELETE</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <p> Are you sure you want to delete this row </p> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">No</button> <button type="submit" class="btn btn-primary">Yes</button> </div> </div> </div> </div> </tr> {% endfor %} </tbody> When I click on delete button, modal appear for confirmation and when I click Yes then I have to send the {{dt.url}} for corresponding delete button. I could use the input tag with hidden type and set the input value with {{dt.url}} . I am not able to check which delete button is clicked. Please help. -
Django, remove the querystring from a url string
Good day all. I've to modify a string in a template that use Django. the string is a URL, but this can contain a querystring, so basically the url could be: "www.test.com/something" or "www.test.com/something?page=2" I'd like to remove the "?page=2" from the url, in javascript I'd do something like urlString.split("?")[0]; is there any similar solution in django? I can only access the "frontend" of this site, so I cannot define anything, I can only modify the "templates". Thanks in advance. -
add non existing field name to django query
I'm trying to add extra field name base on its sub domains, but i cant do that, here is my views.py def daily_vistors_detail_html(request): address = request.build_absolute_uri('/') host_name = address.partition('://')[2] sub_addr = host_name.partition('.')[0] hotel_name = 'hotel 1' if sub_addr == 'hotel 2': hotel_name = 'hotel 2' lists = MyModel.objects.annotate(hotel_name=hotel_name).order_by('-pk') context = { 'lists':lists } but it returns QuerySet.annotate() received non-expression(s): hotel 1. is there away to achieve that please? thank you -
does we use generic class view more often than function based view in django rest framework
As I am fan of function based view in django_rest because it lets you more control over the class based one. but we have seen most of the functionality of django_rest can be implemented with the generic class based views e.g. pagination, search, filter etc. Could you please advice me should i use generic views more often if not then why I shouldn't? Thanks in advance -
How to Host Emails in Django?
I want to know that how can I Host Emails in Django-Python. And Created Email able to receive and send email from any platform like GMAIL Thanks -
How to use JOIN Django ORM with Postgresql
i need help to build a queryset for the following problem: I have 2 different models: class parentElement(models.Model): name = models.CharField(max_length=50) date = models.DateField() .... other fields class childElement(models.Model): name = models.CharField(max_length=50) date = models.DateField() type = models.PositiveSmallIntegerField( choices=types.CHOICES, null=True, blank=True ) parent_id = models.ForeignKey( "parentElement", related_name="rel_parent", on_delete=models.CASCADE ) .... other fields And I want to have the following query realized with the Django ORM (not in a raw SQL query): SELECT m.*, t1.date as type1_date, t2.date as type2_date FROM parentElement m LEFT INNER JOIN childElement t1 ON t1.parent_id = m.id AND t1.type = 1 LEFT OUTER JOIN childElement t2 ON t2.parent_id = m.id AND t2.type = 2 I don't want to use the .raw(), is there a solution with .annotate() and .extra()? -
Django Channels Login Page
I have a site that uses Django and Vue, hosted in Docker containers, along with other containers like Celery, Redis, Nginx, Postgress etc. I'd like to use Django Channels but cant seem to figure out how a login page is meant to work. I'm not sure if I can do a whole website with Channels exclusively or must I use something like django.contrib.auth or Django REST framework together with Channels, I tried implamenting Django REST framework but got CORS errors. According to the Channels Autentication Docs there are login and logout methods, but they sit in the receive() Channels consumer, what am I meant to do with the connect() method? Am I meant to accept the websocket connection before authenticating? Or am I meant to use another meathod of authenticating my login page? I just need a bit of guidance, your help would be much appreciated. -
How to change the Django date time format in a string
Given a long string (serialized Django object) how can we search all the timestamps and replace them with the correct format (dd/mm/YYYY HH:MM) Example string given: [{"model": "app_name.files", "pk": 294, "fields": {"filename": "user_1/A.pdf", "user": 1, "uploaded": "2022-01-11T16:49:43.897", "updated": "2022-01-11T16:49:43.897"}}, {"model": "app_name.files", "pk": 296, "fields": {"filename": "user_1/Business_Flow.pdf", "user": 1, "uploaded": "2022-01-11T16:55:05.165", "updated": "2022-01-11T16:55:05.165"}}, {"model": "app_name.files", "pk": 297, "fields": {"filename": "user_1/Business_Flow_K1Wvyz6.pdf", "user": 1, "uploaded": "2022-01-11T17:00:26.649", "updated": "2022-01-11T17:00:26.649"}}, {"model": "app_name.files", "pk": 298, "fields": {"filename": "user_1/2021M4_RF.xls", "user": 1, "uploaded": "2022-01-11T17:01:03.644", "updated": "2022-01-11T17:01:03.644"}}] Example date (from the given example): 2022-01-11T16:49:43.897 Desired date time format: 11/01/2022 16:49 What I've tried so far: @login_required def my_view(request): response = dict() if request.method == 'GET': files = Files.objects.all().filter(user=request.user) for fhr in files: fhr.updated = fhr.updated.strftime("%d/%m/%Y %H:%M:%S") data = serialize("json", files) return HttpResponse(data, content_type="application/json") return HttpResponse('') Basically I tried to edit the queryset with the correct format strftime("%d/%m/%Y %H:%M:%S") so that when I serialize the QuerySet into JSON data data = serialize("json", files) the string (data) contains the date and time in the correct format but it did not work. So now I think that the only chance is to edit directly the string and replace those timestamps with the timestamps in the correct format. -
i just want to get single record when user passing unqid and after user passing id in input it display only that record [closed]
views.py from REMC import models from .models import addnewdata as dataall def fetchingdata(request): if 'getuid' in request.GET: getuid = request.GET['getuid'] multiple_fetch= dataall.objects.filter(unqid=getuid) print(multiple_fetch) else: data = dataall.objects.all() context = { 'data': data } return render(request, 'REMC/fetchuserwise.html', context) [description: what is wrong with this code ] model.py class addnewdata(models.Model): unqid = models.AutoField(primary_key=True) voltlevel = models.IntegerField() pssname = models.CharField(max_length=100) generatorname = models.CharField(max_length=100) turbineid = models.CharField(max_length=10) agreementtype = models.CharField(max_length=50) discomtype = models.CharField(max_length=50) validfrom = models.DateTimeField() validto = models.DateTimeField() contractname = models.CharField(max_length=50) sourcetype = models.CharField(max_length=50) capacity = models.DecimalField(max_digits=5,decimal_places=3) dateofcomm = models.DateTimeField() noofmachine = models.IntegerField() developername = models.CharField(max_length=100) fetchuserwise.html <section class="container"> <div class="container"> <div class="container border border-secondary"> <form class="requies-validation" action="/fetchuser" method="POST" novalidate> {% csrf_token %} <h4 class>Search Your Record</h4><br> <div class="container"> <input type="number" id="getuid" name="getuid" class="form-control" placeholder="Enter Unique ID"> <div class="valid-feedback">Enter your Unique ID is valid!</div> <div class="invalid-feedback">Unique ID cannot be blank!</div> </div> <div class="container"> <input type="submit" class="btn btn-primary" name="searchbyid" value="submit"> </div> </form> </div> </div> <div class="container"> <div class="form-control-sm"> <div class="row align-items-start"> <div class="col"> <h5 class="text-center">Your Records</h5> <!---h4 class="text-center"><em>Total: {{messages|length}}</em></h4---> <table class="table table-bordered table-striped table-hover"> <thead class="thead-dark"> {% for data in data %} <tr> <th scope="col">Unique ID</th> <th scope="colgroup">{{ data.unqid }}</th> </tr> <tr> <th scope="col">Voltage Level</th> <th scope="colgroup">{{ data.voltlevel }}</th> </tr> <tr> <th scope="col">Name of … -
Add manytomany field query in cet_or_create method
def create(self, validated_data): employer = User.objects.get(id=self.context.get('employer')) candidate = User.objects.get(id=self.context.get('candidate_id')) report_details_id = ReportDetails.objects.filter( id__in=self.context.get('report_details_id')) (report_candidate, created) = ReportCandidate.objects.get_or_create( reported_by=employer.id, candidate_id=candidate.id,report_details_id=report_details_id) return report_candidate Here the report_details_id is a manytomanyfield query. How will apply each of the data in it in the get_or_create method? The QuerySet value for an exact lookup must be limited to one result using slicing. I'm getting this error from the above code. Thanks in Advance. -
Django: How to download file generated by python script running in celery task after completion
I am building a Django web application, and I currently have the ability to upload a dataset (.csv file). When the 'upload' button is pressed, a celery task is started that manipulates the dataset. I want to display a page with a 'download result' button when the celery task is completed. There is currently a progress bar that displays the progress of the script using the celery-progress toolkit (it takes quite a while). I already have users built-in, if that helps. Question 1: Where should I store the output file generated by the python script running in the celery task so that the user can download it? Question 2: How do I display a page with the "download result" button when the celery task is complete? Question 3: How do I actually make this button download the file pertaining to the user's file? Here is my code so far: views.py from django.conf import settings from .models import Document from .forms import DocumentForm from django.views import View from .tasks import RunBlackLight import os from django.http import Http404, HttpResponse class RunView(View): form_class = DocumentForm initial = {'key': 'value'} template_name = 'runblacklight/progress.html' error_template_name = 'runblacklight/error.html' def get(self, request, *args, **kwargs): form = self.form_class(initial=self.initial) …