Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Add headers to a Django redirect
I am returning a file to the client via redirect(s3_url). According to the docs I should be able to add a custom header: response = redirect(s3_url) response['File-Name'] = file_name return response In chrome dev tools, I don't see any File-Name header in the response headers. -
DRF - upload CSV file and print each row
Using regular Django views I can iterate over each row in a CSV file like this: class FileUploadForm(forms.Form): file = forms.FileField() class ProductUpload(FormView): template_name = 'file_upload.html' form_class = FileUploadForm def form_valid(self, form): file = form.cleaned_data['file'] decoded_file = file.read().decode() io_string = io.StringIO(file) reader = csv.reader(io_string) for row in reader: print(row) messages.success(self.request, 'File uploaded successfully.') return redirect(self.request.path) But I can't figure it out using Django Rest Framework. I'm using parsers.FileUploadParser but not sure if this is correct - the form will be submitted through browser on the front end. class ProductUploadAPIView(views.APIView): parser_classes = (parsers.FileUploadParser,) def post(self, request, *args, **kwargs): file = request.data['file'] decoded_file = file.read().decode() # upload_products_csv.delay(decoded_file, request.user.pk) io_string = io.StringIO(decoded_file) reader = csv.reader(io_string) for row in reader: print(row) return Response(status=status.HTTP_204_NO_CONTENT) Here's my cURL request and the console output curl -v -X POST -u user:pass http://localhost:8000/api/file_upload/ -F "file=./file.csv" -H "Content-Type: text/csv" -H "Content-Disposition: attachment; filename=file.csv" ['--------------------------8e8e5ed08fe4ca99'] ['Content-Disposition: attachment; name="file"'] [] ['./file.csv'] ['--------------------------8e8e5ed08fe4ca99--'] -
Ordering choice fields
I'm creating an RESTFull Django API. I've created model, serializers and viewsets, just fine. Models.py: class Payer(AddressAbstract, ContactAbstract, DateTimeDBOps, SoftDeleted): CPF = '1' CNPJ = '2' DU_TYPE_CHOICE = ((CPF, _("CPF")), (CNPJ, _("CNPJ"))) DIGITACAO = 1 BANCO = 2 IMPORTACAO_ARQUIVO = 3 IMPORTACAO_CSV = 4 TYPE_ORIGIN = ( (DIGITACAO, 'Digitação'), (BANCO, 'Banco'), (IMPORTACAO_ARQUIVO, 'Importação arquivo'), (IMPORTACAO_CSV, 'Importação CSV') ) id = models.AutoField( verbose_name=_('Id'), primary_key=True, db_column='cd_pagador' ) covenant = models.ForeignKey( Covenant, verbose_name=_('Covenant'), on_delete=models.CASCADE, db_column='cd_convenio', blank=True, null=True ) name = models.CharField( verbose_name=_('Name'), max_length=40, db_column='nm_pagador' ) ... Viewset.py: class PayerCreateListView(ListCreateAPIView): serializer_class = PayerListSerializer ordering_fields = ('name', 'created_at', 'type_origin', 'type_origin_display', 'id', 'covenant', 'du', 'du_type', 'dt_last_access', 'email', 'phone', 'address', 'neighborhood', 'city', 'uf', 'cep') filter_fields = ['covenant'] filter_class = PayerFilter search_fields = ('name', 'du', 'covenant__code', 'covenant__bank__name', 'covenant__bank__id', 'covenant__company__name', 'covenant__company__du') def get_queryset(self): return Payer.objects.active() def get_serializer_class(self): if self.request.method == 'POST': return PayerCreateSerializer return PayerListSerializer Serializers.py: class PayerListSerializer(serializers.ModelSerializer): covenant = CovenantSerializer() du = serializers.SerializerMethodField('payer_du') type_origin_display = serializers.SerializerMethodField() class Meta: model = Payer fields = ('id', 'covenant', 'name', 'created_at', 'updated_at', 'du', 'du_type', 'email', 'phone', 'address', 'neighborhood', 'city', 'uf', 'cep', 'type_origin', 'type_origin_display') def payer_du(self, obj): return format_du(obj.du_type, obj.du) def get_type_origin_display(self, obj): return '{}'.format(obj.get_type_origin_display()) Now i want to order those fields on the viewset (ordering_fields). But when i try to order the … -
Django rest api to list values ManytoMany field
Im have two models, Manager and Template, one Template has n Managers, I want with the template id to get all the managers of the same I tried to make an api that takes the url template id, and filters the relationship table but it returns me empty This my models class Template(TimestampedModel, permissions.TemplatesPermission): title = models.CharField( max_length=1000, db_column='titulo', verbose_name='título', db_index=True, ) description = models.TextField( db_column='descricao', verbose_name='descrição', ) active = models.BooleanField( default=True, ) managers = models.ManyToManyField( Manager, through='TemplateManager', ) validity_date = models.DateTimeField( db_column='data_vigencia', verbose_name='data de vigência', ) class Meta: db_table = 'declaracoes_template' verbose_name = 'Template' verbose_name_plural = 'Templates' def __str__(self): return self.title class Manager(TimestampedModel): user = models.ForeignKey( settings.AUTH_USER_MODEL, models.CASCADE, verbose_name='usuário', ) file = models.CharField( max_length=1000, db_column='assinatura', verbose_name='assinatura do gestor', ) position = models.ForeignKey( Position, models.PROTECT, db_column='cargo', verbose_name='cargo', ) class Meta: db_table = 'declaracoes_gestor' verbose_name = 'Gestores' verbose_name_plural = 'Gestores' def __str__(self): return self.user class TemplateManager(TimestampedModel): manager = models.ForeignKey( Manager, on_delete=models.PROTECT, db_column='gestor_id', ) template = models.ForeignKey( Template, on_delete=models.CASCADE, db_column='template_id', ) This my view class TemplateManagerView(APIView): pagination_class = BasePagination def get(self, request, id): template = get_object_or_404(models.Template.objects.all(), id=id) managers = (models.TemplateManager.objects .filter(template=template) .all()) serializer = serializers.ManagerSerializer(managers, many=True) return Response(serializer.data) and my serializers class ManagerSerializer(serializers.ModelSerializer): position = PositionSerializer() user = serializers.CharField(source='user.first_name') class Meta: model … -
Which has optimal performance for generating a randomized list: `random.shuffle(ids)` or `.order_by("?")`?
I need to generate a randomized list of 50 items to send to the front-end for a landing page display. The landing page already loads much too slowly, so any optimization would be wonderful! Given the pre-existing performance issues and the large size of this table, I'm wondering which implementation is better practice, or if the difference is negligible: Option A: unit_ids = list(units.values_list('id', flat=True).distinct()) random.shuffle(unit_ids) unit_ids = unit_ids[:50] Option B: list(units.values_list('id', flat=True).order_by("?")[:50]) My concern is that according to the django docs, order_by('?') "may be expensive and slow" https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.order_by We are using a MySQL db. I've tried searching for more info about implementation, but I'm not seeing anything more specific than what's in the docs. Help! -
Update Django Template if boolean is True
I am making a form using a model in Django. In that form, I have a boolean. When I click that boolean box, I want it to display some options and when I uncheck it, hide it. I have tried using the if blocks but it doesn't work. My boolean: employee_overtime_applicable = models.BooleanField() My if block that I did: {{ form.employee_overtime_applicable }} {% if form.employee_overtime_applicable %} <div class="row"> <label class="form-control-label">Overtime</label> <input type="text" placeholder="Overtime Rate"> </div> {% endif %} Don't worry, I know the overtime input box does nothing in Django. I just want to know how I can update it. -
Heroku CLI does not work after switching the shell
Heroku CLI was working well with my MacOS. Currently the login doesnot work via command line. mysystem% heroku-login zsh: command not found: heroku-login Only thing I remember is changing the shell from Bash to Zsh. Will it have any effect? Heroku exists and mysystem% heroku-login works -
How to design a structure that can lead user request to related app's view?
I am developing a web application which gets feedbacks from shifts in a factory by asking questions to employees and getting answers from them. Currently I am responsible for one area and it is called plastic injection. Afterwards plastic assembly, plastic connector and metal production areas will be in my list as well. We can consider areas as departments. In frontend I am using Vue.js and there is no problem so far. Backend side I created an API using Django with Django REST Framework. The API has two apps. First one is called 'core' app. It handles authentication and only has User model. This app will have another models and logics for feature plans. Second and last one is called 'plastic_injection' app. It has necessary models to get feedbacks from shifts. Problem I face shows up when I add another app for example 'plastic_assembly' or 'plastic_connector'. In frontend, users login then they answer some questions to send feedbacks of the shift they are inside of. At this point I need a logic to know which app user is belong to call endpoint of the app. The reason I created different app for different plastic areas(departments) is eventhough its models and … -
Using aggregate inside a subquery inside an annotate in Django
I have a queryset of objects (products). Each object has children (snapshot of the product at the moment of an order, for historical reasons); every child might or might not meet my requirements. Also, every child has a "quantity" field (the quantity of the product that was ordered). I want to sum the quantities of all the children that meet my requirements. So far I have the following query: qs = Product.objects.to_public_objects(to_country="USA", children__item_list__retailorder__isnull=False).annotate( quantity=Subquery( Product.objects.get( id=OuterRef("id") ).children.filter( item_list__retailorder__isnull=False ).aggregate( qq=Sum("quantity") )["qq"] ) ) This doesn't seem to be working as Django is complaining about not being able to use OuterRef because it's not in a Subquery (which I believe it's not). I'm not really sure why Django is complaining about that. The subquery, executed on it's own, works as expected, meaning, it returns the right quantity that has been sold to retail, for the product. How can I fix my query in order to use OuterRef? -
why it cost much time when call sorted function in django sometimes?
I added my logic code to django servers,and find somethin strange.When i using cat file,to send request to server,server will handle some requests slowly,and i print cost time,found that it will cost much time when call sorted function.But if i send this request alone,it is ok.Is it relevant with django server? using Django server 2.2.4 def generate(input_dict): id = input_dict["id"] title = input_dict["title"] starttime = datetime.datetime.now() word_list,nn_word_list = seg_title(title) seg_time = datetime.datetime.now() #print (nn_word_list) recall_tags = recall(word_list) recall_time = datetime.datetime.now() nn_tags = nn_ranking(id,nn_word_list,recall_tags) nn_time = datetime.datetime.now() print (seg_time-starttime,recall_time-seg_time,nn_time-recall_time) return nn_tags def recall(word): dict_result = {} starttime1 = datetime.datetime.now() word_fields = word.split(":") for i in range(0,len(word_fields)): if word_fields[i] == "": continue key = word_fields[i] if key in seg_dict: row_index = seg_dict[key] for i in range(csr_matrix.indptr[row_index],csr_matrix.indptr[row_index+1]): col_index = csr_matrix.indices[i] value = csr_matrix.data[i] if col_index not in dict_result: dict_result[col_index] = 0.0 dict_result[col_index] += value recall_tag = "" starttime2 = datetime.datetime.now() #pre_result = sorted(dict_result.items(),key=lambda x: x[1], reverse=True) pre_result = sorted(dict_result.items(), key=operator.itemgetter(1),reverse=True) starttime3 = datetime.datetime.now() for i in range(0,len(pre_result)): tag_id = index_dict[pre_result[i][0]] recall = recall+tag_id+":" if i >=19: break starttime4 = datetime.datetime.now() print (starttime2-starttime1,starttime3-starttime2,starttime4-starttime3) return recall_tag[:-1] client code is: for line in sys.stdin: line = line.rstrip('\n') fields = line.split("\t") id = fields[0] title = fields[1] … -
Is it possible that the check box that was previously selected was selected during the next edition
I want to create the opportunity to create a series of posts in my blog application. So far I've created the form and models, but I have a problem when editing already existing cycles, because in the check boxes I do not have selected previously selected posts belonging to the cycle. Do you have an idea how to fix it? models.py class Cycle(models.Model): title = models.CharField(max_length=200, unique=True) description = models.TextField(max_length=500, default="Brak opisu") date_created = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ManyToManyField(Post) def __str__(self): return self.title forms.py class CycleForm(BSModalForm): post = forms.MultipleChoiceField(required=False, widget=forms.CheckboxSelectMultiple, choices=((x.id, x.title) for x in Post.objects.all())) title = forms.CharField() description = forms.CharField() class Meta: model = Cycle fields = ['title', 'description', 'post'] views.py class CycleUpdateView(BSModalUpdateView): model = Cycle template_name = 'blog/cycle_update.html' form_class = CycleForm success_message = 'Success: Cycle was updated.' def get_success_url(self): reverse_user = self.request.user return reverse('profile', kwargs={'username': reverse_user}) html file <form method="post" action=""> {% csrf_token %} <div class="modal-header"> <h5 class="modal-title">Update Cycle</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> {% for field in form %} <div class="form-group{% if field.errors %} invalid{% endif %}"> <label for="{{ field.id_for_label }}">{{ field.label }}</label> {{ field }} {% for error in field.errors %} <p class="help-block">{{ error }}</p> {% … -
Remove space of a string in template file
I'm new to python and django. I'm playing with a travel site with a different destination. I want to create a link for the destination from the name of it, some make it lower and delete the whitespace. The .lower work but .replace(" ", "") give me an error Could not parse the remainder: '(" ", "")' from 'dest.name.lower.replace(" ", "")' {% for dest in dests %} <div class="destination_title"><a href="{{ dest.name.lower.replace(" ","")}}.html">{{ dest.name }}</a></div> {% endfor %} If the city is San Francisco, the result should be sanfrancisco Thanks in advice and sorry for my English -
calling Django API using apache (mod_wsgi)
I have a frontend web tool which interacts with REST API written in danjgo. Each API calls take long time to process the call and is also CPU/GPU intensive. So I am planning to run only 1 call at a time and putting rest of the calls in queue. Now I am not sure if Celery with redis can be helpful here or should I stick with job queue approach at the java side. So, the tool would be used by multiple users and and so each user would have their jobs. So, I need to put the jobs in queue so that they can be processed one by one asynchronously. Would Celery be helpful here? -
How to get all value displayed from loop in javascripts using d3.js? always got last value displayed in charts
I'm using django for my personal projects, and using javascript to display value from database to charts model. But the problem is the value that displayed is always the last value of iteration When not using charts, I already checked that the value is displayed in every iteration. image When using charts, why charts can't be displayed in every iteration. image The code: <script src="//d3js.org/d3.v3.min.js"></script> {% block script %} {% for status in projects_status %} <h2>{{ status.task }} </h2> <div class="chart"></div> <script> let data=[{{status.user_requirements}},{{status.uat}},{{status.sit}},{{status.uat}},{{status.implementation}}]; let chart = d3.select(".chart"); let bar = chart.selectAll("div"); let barUpdate = bar.data(data); let barEnter = barUpdate.enter().append("div"); barEnter.style("width", function(d) { return d * 10 + "px"; }); barEnter.text(function(d) { return d; }); </script> {% endfor %} {% endblock %} I want each iteration to display charts Thanks for any help -
Django - authentication only with the email
Im trying to make a custom authentication where I login only with the e-mail address without password. I searched over internet but I dont find a good answer. Im new in Django maybe this is the reason for why I cant find a solution. Can anyone help me with some source code? Thanks -
Django background tasks not taking new code into account
I am using django background tasks to run some code in background. My project has been deployed and I run the background tasks using cron. The problem is when I made changes to my code, the ones related to the background tasks are not taken into account. It seems the cron still using the old code. This is my crontab */5 * * * * /home/.../venv/bin/python /home/.../manage.py process_tasks [duration 299] I think i need to kill the cron command and allow the code to update before running it again. -
raise FieldError("Cannot compute %s('%s'): '%s' is an aggregate" % (c.name, name, name))
I need create a group by queryset with Sum and Func utils from Django But when put all functions inside a annotate I have this error raise FieldError("Cannot compute %s('%s'): '%s' is an aggregate" % (c.name, name, name)) django.core.exceptions.FieldError: Cannot compute Sum(''): '' is an aggregate I need to get something like this for the DRF serializer [ { 'quantity': '1520', 'employee__profile__empcod': 762, 'operation__baseqty': Decimal('480.0000000000'), 'duration': 14678.0, 'standar': '30,57' }, { 'quantity': '150', 'employee__profile__empcod': 589, 'operation__baseqty': Decimal('600.0000000000'), 'duration': 94070.0, 'standar': '95,68' }, { 'quantity': '150', 'employee__profile__empcod': 758, 'operation__baseqty': Decimal('720.0000000000'), 'duration': 5060.0, 'standar': '150,68' } ], This is the queryset to get all tasks tasks = TaskOperation.objects.filter(startdt__gte=start, startdt__lte=end, enddt__isnull=False, operation__baseqty__gt=0).order_by('employee_id') tasks = tasks.values('employee__profile__empcod', 'employee__profile__firstname') tasks = tasks.annotate( duration=Sum(Cast(Func('startdt', 'enddt', function='datediff', template='%(function)s(ss,%(expressions)s)'), FloatField())), standar= Sum(Case( When(duration__lte=0, then=0), default=Sum((F('quantity') * 100) / (F('duration') / F('operation__baseqty'))), output_field=FloatField() )) ) -
How to fix error trying to migrate manage.py
I am a beginner when it comes to python so i watch tutorials regulary. The Django framework tutorial i'm watching right now eventually had a step where i had to run the command python manage.py migrate i got the error django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3. i know that there are other answers to this error but none work for me. does anybody have a fix? -
How to handle google authentication in django when app is in docker container?
I'm creating Django app and I'm using docker containers to put everything together and use the social-auth-app-django library to login through Google. Due to the principles of deployment in the organization I work for, it's necessary to have one nginx container that listen on 0.0.0.0:2000 and redirects traffic to container with django app on port 8080. I've done this (code to nginx conf file below) and everything works fine to this time, and addtionally set up proxy pass on my local computer to redirect traffic like this: erp.localhost.pl -> localhost:2000 What I've done: Set everything up in my Django files (code below); Created project in google developers console; Got oauth client ID and secret key; Added both http://erp.localhost.pl/complete/google-oauth2/ and http://dev.erp.app/complete/google-oauth2/ to authorized redirect URIs in Google dev console; Added Google+ API to my project in Google dev console. When I go to erp.localhost.pl/login and click on Login with Google I see this error: error while logging from erp.localhost.pl/login But when I'm doing same steps but with localhost:2000/login I see this error: error while logging from localhost:2000/login I have 4 containers in my docker-compose file: version: '3' services: dev_erp_postgres: container_name: dev.erp.postgres image: postgres:latest restart: "no" expose: - "5432" dev_erp_app: container_name: dev.erp.app … -
Field initial data does not display in a ModelSelect2Widget
I am building a django-filter FilterView, using ModelSelect2Widget for some of the filter form fields. It correctly work to select items, and build the right query params in URL, but when I reload the page, passing the filter instance in the context, the ModelSelect2Widget does not display the previously selected item. In template I checked that {{ filter.form.data }} effectively contains the selected data : it is OK. In the principle, the codebase is like this : class BookFilterSet(FilterSet): author = MethodFilter(widget=ModelSelect2Widget( queryset=User.objects.all(), search_fields=['username__icontains',] ), action = 'no_action' def no_action(self, queryset, name, value): """a neutral action""" return queryset class FilterView(FilterView): filterset_class = BookFilterSet template_name = "books.html" Do I need to override some method to display filter.form.initial in the ModelSelect2Widget ? -
i can not load my font on my page, Not allowed to load local resource ERROR
i'm using django for webdeveloping i get a template from https://materializecss.com and it worked well now i wanna change the font of page i write this code to my style.css @font-face { font-family: vazir-medium; src: url(C:\Users\HP\Desktop\uni_project\tutorial\static\font\Farsi-Digits\Vazir-Medium-FD.woff); } body, div, p, a, ul, li, span, i,b, strong, h1, h2, h3, h4, h5, h6, nav, footer { font-family: vazir-medium; } but it doesn't work and i get this error when i see inspect element in chrome Not allowed to load local resource: file:///C:/UsersHP%C3%9Esktopuni_projecttutorialstatic%0Font%C3%BArsi-DigitsVazir-Medium-FD.woff -
DRF: How do I correctly add the HyperlinkedRelatedField field to the serializer?
I want to make it possible for a json that gives all the model instances to go to a particular instance using the additional url field in the serializer. There is a view to display the list class DocumentsListView(viewsets.ViewSetMixin, generics.ListCreateAPIView): user = serializers.PrimaryKeyRelatedField(read_only=True,) queryset = Documents.objects.all() serializer_class = DocumentsSerializer permission_classes = [] def perform_create(self, serializer): serializer.save(author=self.request.user) urls.py router = DefaultRouter() router.register('', DocumentsListView) urlpatterns = [ url('', include(router.urls), name='files') ] serializers.py class DocumentsSerializer(serializers.ModelSerializer): url = serializers.HyperlinkedRelatedField(view_name='???????') class Meta: model = Documents fields = ('id', 'filename', 'datafile', 'type', 'created', 'url') What value should I use for the required view_name field ? -
How to load fixtures for a LiveServerTestCase
I am attempting to write test cases in Django using Selenium. I want to use existent fixtures so my test database has test data for every test. I have some model test cases (just using the TestCase class) as follows; from django.test import TestCase from missions.models import Mission, MissionDataRecord from django.contrib.staticfiles.testing import LiveServerTestCase class MissionModelTests(TestCase): fixtures = ['myproject_common/fixtures/auth_initial_load.json', 'worklog/fixtures/worklogs_initial_load', 'missions_initial_load.json'] def test_object_name_is_mission_title(self): mission = Mission.objects.get(id=1) self.assertEqual(mission.title, str(mission)) def test_object_name_is_mission_title_again(self): mission = Mission.objects.get(id=1) self.assertEqual(mission.title, str(mission)) This works as expected when run like this (I get two test passes). However, for Selenium testing I need to use LiveServerTestCase instead of TestCase. The simple example above is a model test, but for illustrative purposes of the issue I'm facing with Selenium, if I simply replace "TestCase" with "LiveServerTestCase" the first test passes, but the second test fails, with the error django.db.utils.IntegrityError: Problem installing fixture '[...]/fixtures/auth_initial_load.json': Could not load auth.User(pk=1): UNIQUE constraint failed: auth_user.username This error occurs in the _fixture_setup of /django/test/testcases.py. This seems to suggests that my fixtures (specifically the auth_initial_load fixture) is attempting to load again ON TOP of existing data. However, from django docs reading this should not be taking place, because each test should run in its own transaction (which … -
IntegrityError In Django(NOT NULL constraint failed)
So, I was following this a Django tutorial series on youtube(thenewboston), While I was following this tutorial, the guy decided to do some weird stuff off-screen and decides to delete every single thing related to a function. I tried to delete everything of that certain function. And now I'm getting an integrity error of a statement that doesn't exist in my code. I've checked every single file and found no line related to the error. I know this is weird but it would be a huge help for me. The error is this: http://dpaste.com/29EKRY9 The Code Is At My Github: https://github.com/diayush/Django Thanks In Advance. -
django how to override an error page to a specific endpoint?
I'm trying to override the 500 error view https://docs.djangoproject.com/en/2.2/ref/views/ I have implemented 500.html but i want to ensure that any instance of a 500 gets redirected to my own custom specific endpoint (say my-error/) How do I accomplish this?