Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ValidationError is raise if one custom validator is used two more than one model when are running tests
I have two models which have one common field but in a different context. models.py: import uuid from django.core.validators import (EmailValidator, MaxLengthValidator, MaxValueValidator, MinLengthValidator, MinValueValidator,) from django.db import models from django.utils import timezone from .validators import (validar_cep, validar_ddd, validar_numero_telefone, validar_uf,) class Endereco(ModeloComum): bairro = models.CharField(max_length=255) cep = models.CharField( error_messages={ 'max_length': 'CEP inválido. O CEP deve conter uma entrada com 8 ' 'digitos numéricos.', }, max_length=8, validators=[validar_cep], ) cidade = models.CharField(max_length=255) complemento = models.CharField(blank=True, max_length=32, null=True,) logradouro = models.CharField(max_length=255) numero = models.PositiveIntegerField( error_messages={ 'invalid': 'Insira um número válido. A entrada "%(value)s" não é ' 'um valor inteiro positivo.', } ) pessoa = models.ForeignKey( 'Pessoa', models.PROTECT, related_name='enderecos', related_query_name='endereco', ) uf = models.CharField( error_messages={ 'max_length': 'UF inválido. UF deve conter somente 2 caracteres ' 'em letras maiúsculas', }, max_length=2, validators=[validar_uf], ) class Meta: ordering = ('uf', 'cidade', 'bairro', 'cep', 'numero', ) verbose_name = 'Endereco' verbose_name_plural = 'Enderecos' def __str__(self): return '[%s - %s, %s/%s]' % ( self.cep, self.bairro, self.cidade, self.uf ) class SeguroAuto(ModeloComum): cep_pernoite = models.CharField( error_messages={ 'max_length': 'CEP inválido. O CEP deve conter uma entrada com 8 ' 'digitos numéricos.', }, max_length=8, validators=[validar_cep], ) cep_maior_frequencia = models.CharField( error_messages={ 'max_length': 'CEP inválido. O CEP deve conter uma entrada com 8 ' 'digitos numéricos.', … -
Passing django template variables to js datatables
Hi I would like to create table using JS datatables library. I got problem when passing value in template to js script. I created JSON object from my table which I want to display. It's passed correctly to template, when I display it everything is fine, but when trying to pass it to script nothing happend and I got empty table. Thats the way I do it: class VotesList(generic.ListView): model = Vote template_name = 'votes-list.html' def get_context_data(self, **kwargs): votes = Vote.objects.all().values('user', 'group', 'council') votes_json = json.dumps(list(votes)) context = super(VotesList, self).get_context_data(**kwargs) context['orderby'] = self.request.GET.get('orderby', 'created_date') context['json_data'] = votes_json return context template: {% block javascript %} {% load static %} <script type="text/javascript"> $(document).ready(function() { var json=JSON.parse('{{ json_data | safe }}'); $('#votes_list').DataTable({ data: json, columns:[ { title: "user" }, { title: "group" }, { title: "council" }] } ); }; </script> {% endblock %} {% block content %} <p>{{ json_data | safe }}</p> <<< here data is printed fine {% if vote_list %} <table id="votes_list" class="display", style="width:100%"> <thead> <tr> <th>Właściciel</th> <th>Grupa</th> <th>Rada</th> </tr> </thead> </table> {% else %} <p>Brak głosowań!</p> {% endif %} {% endblock %} and output data looks like that: [{"user": 2, "group": 1, "council": 1}, {"user": 2, "group": 2, "council": … -
Per user database authentication in Django
Good afternoon, I am writing a front-end for a research database that holds sensitive health information. My institution has a policy that user actions be logged by the SQL server so that they can perform audits on the server log files in the event of a breach. Because of this policy, I cannot create connect Django to the db as a system user (otherwise, all users of the front-end actions would be logged by the server as the Django system user instead as the actual user individually). Is there a way to connect to the DB using per user credentials so that actions performed on the front end will be logged as that user on the db server? I have been able to find a lot of information about using multiple databases, but nothing about per user authentication of those databases. Thank you in advanced! -
Modify queryset in django after retreiving using rest framework
I used this example: https://www.django-rest-framework.org/tutorial/quickstart/ In my case I have has_read field which guarantees one time reading. models.py: from django.db import models class Message(models.Model): date_time = models.DateTimeField(auto_now=True) content = models.TextField(blank=True) attachment = models.FileField() has_read = models.BooleanField(default=False) views.py: class MessageViewSet(viewsets.ModelViewSet): queryset = Message.objects.filter(has_read=False)\ .order_by('-date_time') for i in queryset: i.has_read = True i.save() serializer_class = MessageSerializer serializers.py class MessageSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Message fields = ('date_time', 'content', 'attachment') Queryset updates only after rebooting server. I want user could retreive a message only one time, but at now he can retrieve as many times as he wishes. Is it possible to update queryset after every get-query, modifying serializer or viewset? -
Serving static files in django for image processing
Can anyone please explain how to serve static files in django, keeping in mind, i also have to fetch images from the location of hosting and then resize them, after that send to my template.. Can't find any YouTube video or documents that explains it clearly -
python requests SSLError with Heroku certificate setup
Is there anything special I need to do with my requests in python when connecting to an API if the API is requiring your to be on HTTPS to create an SSL handshake? I have looked here: and here: but none of it worked my ACM Certificate from Heroku seems to be valid to me. I need some help since I am continuously getting this error here: current error appearing in New Relic: // Error logs Error message requests.exceptions:SSLError: HTTPSConnectionPool(host='api.konnektive.com', port=443): Max retries exceeded with url: /landers/clicks/import?pageType=leadPage&ipAddress=73.160.94.162&campaignId=1&requestUri=https%3A%2F%2Fwww.workoutwarriors.com%2Fcontact%2F&loginId=**********&password=********** (Caused by SSLError(SSLError("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')],)",),)) Sample stack trace Traceback (most recent call last): File "/app/.heroku/python/bin/gunicorn", line 11, in <module> File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 74, in run File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/base.py", line 203, in run File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/base.py", line 72, in run File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 202, in run File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 544, in manage_workers File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 611, in spawn_workers File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 578, in spawn_worker File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 131, in init_process File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/sync.py", line 124, in run File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/sync.py", line 68, in run_for_one File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/sync.py", line 30, in accept File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/sync.py", line 135, in handle File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/sync.py", line 176, in handle_request File "/app/.heroku/python/lib/python3.6/site-packages/newrelic/api/web_transaction.py", line 1280, in _nr_wsgi_application_wrapper_ File "/app/.heroku/python/lib/python3.6/site-packages/newrelic/api/web_transaction.py", line 807, in … -
DRF: Api endpoint does not output all data
My api endpoint created using django rest framework does not output all the serialized data. InstagramGeograficsSerializer class InstagramGeograficsSerializer(serializers.ModelSerializer): city = InstagramGeoCitySerializer(read_only=True) class Meta: model = InstagramGeograficsAnalitics fields = ('city', 'percentage',) InstagramEthnicSerializer class InstagramEthnicSerializer(serializers.ModelSerializer): class Meta: model = InstagramEthnicAnalitics fields = ('language', 'percentage',) InstagramDemographicsSerializer class InstagramDemographicsSerializer(serializers.ModelSerializer): class Meta: model = InstagramDemographicsAnalitics fields = ('age_group', 'gender', 'percentage', 'full_percentage',) InstagramSerializer class InstagramSerializer(serializers.HyperlinkedModelSerializer): geographics = InstagramGeograficsSerializer(many=True, read_only=True) demographics = InstagramDemographicsSerializer(many=True, read_only=True) ethnic = InstagramEthnicSerializer(many=True, read_only=True) class Meta: model = Instagram fields = ('id', 'userid', 'username', 'full_name', 'avatar', 'bio', 'website', 'media_count', 'follows_count', 'subscriber_count', 'engagement_rate', 'approval_rate', 'discussion_rate', 'male_percentage', 'female_percentage', 'geographics', 'demographics', 'ethnic',) my views.py class InstagramDetail(generics.RetrieveAPIView): permission_classes = (permissions.IsAuthenticatedOrReadOnly,) queryset = Instagram.objects.all() serializer_class = InstagramSerializer And in the end api gives only the data on ethnic, and doesn't contain data on geographics and demographics -
Celery Active Task lost on worker shutdown
I am using celery=4.0.0, when a task runs for a longer period and worker shutdown in between that, i lost all those task. How to re-initiate all the lost task. Thanks in advance. celery = 4.0.0 redis = 2.10.5 -
Make the same date format between Django and Javascript on update
For a Form I have a data field, for which I created a custom widget calendar. The calendar has a JavaScript part, which sets the date as: Wed Jul 04 2018 To gather the date in this format in python, the corresponding form field is set as: date = forms.DateField(input_formats=['%a %b %d %Y'], widget=Calendar) Everything works ok, on create, but on update, Django shows the date formatted as: 2018-07-12 If I try to update without modifying the date(using the widget calendar) I get the error: Enter a valid date. How, do I make that on Update to receive the correct date format ? -
Can You Assign Varaibles to Underscore In Django
It's always struck me a weird that Django uses the underscore as an operator, given that the underscore is normally used to for assignment to variables that you don't want to reference later. E.g. _, file_name = os.path.split(file_path) Does this mean that you can't assign a unwanted variable to _ in the same namespace as you want to use the _("column_name") notation? -
Why does django model work weird?
I have a problem where the list of posts are showed wrong I have a pretty simple model for a post(question) class Post(models.Model): subject = models.ForeignKey(Topic, on_delete=models.CASCADE) topic = models.CharField(max_length=50) text = models.TextField(max_length=5000) grade = models.ForeignKey(Grade, on_delete=models.CASCADE) created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts') created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.text That's how it looks this is an image, click here here's my views.py def questions(request): posts = Post.objects.all().order_by('-created_by') args = {'posts': posts} return render(request, 'news/questions.html', args) So does anyone know why it doesn't show the latest object on the top of the list -
AttributeError: 'DatabaseWrapper' object has no attribute 'set_schema_to_public' (tenat_schemas)
I am using Django+tenant_schemas, and my local version of my app works fine. However, when i try to push it to staging (Heroku+Docker), I get the following error: AttributeError: 'DatabaseWrapper' object has no attribute 'set_schema_to_public' (tenat_schemas). The code points to: tenant_schemas/middleware.py in process_request at line 46: connection.set_schema_to_public() I can't figure out why I'm getting this error. Any advice will be greatly appreciated. Thanks -
Advanced search in Django
I am working on a social blogging site using Django and I need to create an advanced search bar with filters like location and authors. I do have a basic one working as of now. Can someone help me with the concept on how to add filters to it. couldn't find much related stuff with django. Thanks -
django get_or_create int() argument must be a string, a bytes-like object or a number, not 'tuple'
I'm getting this error when I try to user get_or_create int() argument must be a string, a bytes-like object or a number, not 'tuple' for ubc in Ubc.objects.all(): professional_grade, created = ProfessionalGrade.objects.get_or_create(ubc=ubc) if created: professional_grade.category=0, professional_grade.category_name="BRUTA" professional_grade.experts = 0 professional_grade.coordinators = 0 professional_grade.seniors = 0 professional_grade.researchers = 0 professional_grade.plenos = 0 professional_grade.experience = 0 professional_grade.masters = 0 professional_grade.doctors = 0 professional_grade.save() -
Does anyone know how to solve Cross-origin problems?
Does anyone know how to solve Cross-origin problems? I'm using Angular 6 to make Http requests on localhost:8000.And i've got this after sending a requst (I have no headers added yet btw): zone.js:2969 Cross-Origin Read Blocking (CORB) blocked cross-origin response http://localhost:8000/test/ with MIME type application/json. See https://www.chromestatus.com/feature/5629709824032768 for more details. -
how to save images from a multiple input in django
That is in templates, I have the following code. the file input has a multiple attribute in the end so that I can select multiple images. <form method='POST' action="{% url 'method' %}" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="img" multiple /> <input type="submit" /> </form> <br /> Then I am having trouble to save the image to my model. I tried to print request.FILES, and I got this <MultiValueDict: {'img': [<InMemoryUploadedFile: 1.jpg (image/jpeg)>, <InMemoryUploadedFile: 2.jpg (image/jpeg)>, <InMemoryUploadedFile: 3.jpg (image/jpeg)>]}> There are 3 items in 'img', I also used request.FILES.getlist('img'), doesn't really work out. How am I suppose to access the content in the 'img' like accessing several individual request.FILES. Thanks!!! -
django rest single thread / blocking view
Is it possible to block a code in view from execution by all users accessing the view while it is being executed by a single user? Kind of single-thread view. I need it because i generate the python executable with pyinstaller in this view and passing a username into the executable through the config file. For example: class CliConfig(APIView): def get(self, request, format=None): try: config['DEFAULT']['username'] = request.user #make a build with pyinstaller bin_file = open(*generated filepath *, 'rb') response = Response(FileWrapper(bin_file), content_type='application/octet-stream') response['Content-Disposition'] = 'attachment; filename="%s"' % '*filename*' return response finally: config['DEFAULT']['username'] = '' So, basically what i want is to generate a python executable which will have a unique username it it's settings, in django rest framwork APIView. I don't see other approach except passing the username through the settings file. If there is a way - would appreciate an advise. python 3.6.5, djangorestframework==3.8.2, pyinstaller==3.3.1 -
Storing template language in database and have it rendered django
I am using a template to email plugin (django-templated-mail) and am passing the email content to the template from the database via context such as : {{ context.emailtitle }} {{ context.main_text }} I want to include other field tags in the main_text database entry so that i can for instance place the a users name in the email Your name is {{ user.name }} Is there a way I can include another field name in the database text so that it is rendered, or am I thinking about this wrong? I have tried the above way and the output is "Your name is {{ user.name }}" rather than "Your name is John" Thanks! -
Return annotated queryset against graphql queries on django graphene
class Project(models.Model): name = models.CharField(max_length=189) class Customer(models.Model): name = models.CharField(max_length=189) is_deleted = models.BooleanField(default=False) project = models.ForeignKey(Project, related_name="customers") class Message(models.Model): message = models.TextField() customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name="messages") created_at = models.DateTimeField(auto_now_add=True) I am using the following queryset to get all customers under a certain project ordered by who had messaged last. qs = Customer.objects.filter(messages__isnull=False) \ .annotate(last_message=Max('messages__created_at')).order_by('-last_message') Now I want to use a basic graphene query (NOT relay) to get a project and the customers associated with this project according to the annotated queryset. I may also have a second use-case where I would need to filter the project.customers.all() queryset according to a field in the Customer table (e.g. the customers which have is_deleted=False). Currently in my graphql schema i have, class ProjectNode(DjangoObjectType): class Meta: model = Project class CustomerNode(DjangoObjectType): class Meta: model = Customer class Query(graphene.ObjectType): project = graphene.Field(ProjectNode, id=graphene.Int(), token=graphene.String(), ) top_chat_customers = graphene.Field(CustomerNode, project_id=graphene.Int()) def resolve_project(self, info, **kwargs): pk = kwargs["id"] return Project.objects.filter(id=pk).first() def resolve_top_chat_customers(self, info, **kwargs): project = Project.objects.filter(id=kwargs["project_id"]).first() return Customer.objects.filter(project=project, messages__isnull=False) \ .annotate(last_message=Max('messages__created_at')).order_by('-last_message') Here when I try to get the list of customers separately by providing the project Id, It shows error: "Received incompatible instance..." Any ideas on how I should get the list of customers from … -
Neomodel cypher query `_pre_action_check() missing arg: 'action'`
I'm trying to query my Employee model with .cypher within my Django view. I've used this query elsewhere, so I know that part works. query_string = "MATCH (n)-[r:REPORTS_TO|BRANCH_OF|OVERSEEN_BY]->() RETURN n, r" query_results = Employee.cypher( self = Employee, query = query_string, params = None) *** ERROR _pre_action_check() missing 1 required positional argument: 'action' This error points to line 204 here: https://github.com/neo4j-contrib/neomodel/blob/master/neomodel/core.py I've tried: action=cypher action='cypher' self=neomodel self=django-neomodel self=cypher Also, if I try to follow the documentation by defining the cypher call within the model and then calling it in the view... I still get the same error https://neomodel.readthedocs.io/en/latest/cypher.html -
Using dynamic configurations with modelfield form validation in django
I have setup a model called Configuration, which contains configurable details, such as maximum_stake, and registered this in admin.py so that an admin can change them on the fly. Most of my validation is done through the natural ModelForm validation, but when I tried to do this with the dynamically changing constraints from the Configuration model, Postgre complained about the relation not existing (so I was unable to create a migration to build or edit the Configuration model table). However, even after making these changes the database is unhappy. Is there another way to do this? # models.py class Investor(models.Model): stake = models.DecimalField(max_digits=4, decimal_places=2, default=0.00) class InvestorForm(forms.ModelForm): stake = forms.DecimalField(help_text="The income stake as a percentage (0.00% - 8.00%)", validators=[ MinValueValidator(0, f'Stake must be between 0.00%% and {getConfig(ConfigData.MAXIMUM_STAKE)}.00%%'), MaxValueValidator(getConfig(ConfigData.MAXIMUM_STAKE), f'Stake must be between 0.00%% and {getConfig(ConfigData.MAXIMUM_STAKE)}.00%%') ]) class Meta: model = Investor fields = '__all__' -
How to print something to user in Django?
When a Django website goes live, I know it is a bad idea to use Python's print function... However, I want to print output (maybe through a terminal/command line) that the users of my website can see when the Django website goes live. Is there any way to do this? -
How to render default values in django-ajax_select field
I am using ajax_select for my m2m and foreign key fields, its working fine but it is not rendering default value of that field, it is rending empty value ("|"). I am not using ajax_select in my admin panel, so when I open that form in admin panel, fields are having default values already. That means their is no problem in default values but in ajax_select field. As I searched at documentation of ajax_select but nothing found related to it, does anyone know how to render default values in ajax_select field. -
Django-Ajax: Is this the most pythonic to return data to Ajax request?
html_as_template is just a queryset which gets displayed in article_cards.html, which I am refreshing (with updated data from database) via Ajax. Two questions: Is this the most "efficient" way to do so? I thought render_to_string should also work? if request.is_ajax(): html = render_to_string('article_cards.html', context=html_as_template) payload = {'success': True, 'html': html} return HttpResponse(json.dumps(payload), content_type='application/json') -
Django 2.0 upgrade caused Wagtail (2.1) admin to disappear.
I was in the process of upgrading my wagtail app to Django 2.0. After resolving the on-delete errors I thought I had a working app until I went to the /admin page. The standard Wagtail admin interface has disappeared and has been replaced by the default Django admin interface. Can anyone help? https://github.com/timcknowles/wagtailcmsdemo/tree/django2 Many thanks in advance