Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot add CSS class to my CharField with .widget.attrs.update
I'm learning django widgets documentation https://docs.djangoproject.com/en/2.2/ref/forms/widgets/ I created new class like in sample: class CommentForm(forms.Form): name = forms.CharField() url = forms.URLField() comment = forms.CharField() And then tried to add CSS class to name: name.widget.attrs.update({'class': 'special'}) But django crushes and VSCode sends me error: Class 'TextInput' has no 'attrs' member What is the problem? -
How to fix db-mailer sending email?
I'm using db_mailer to send emails from by backend. NOTE The have created Mail template with slug="user-signup". I don't know exactly what should I do, i've repeated the docs installation steps but with no positive results. send_db_mail( slug="user-signup", recipient="aahmedsamy.as@gmail.com", first_name="first name value" ) I expected the send_db_mail() send mails as i followed in the db_mailer docs, but i got that error. TypeError: __init__() got an unexpected keyword argument 'username' -
How to add custom view to django admin interface?
My django admin interface looks like this: Now I would like to add a view which does not correspond to a model. I could overwrite the template of above page and add a custom link. But I think this would look ugly But maybe there is an official way to do add a custom view to the admin interface? In my case I want to provide a form which can execute tcptraceroute to a remote server. The admin of my app needs this. -
Signature Doesnt match
"The request signature we calculated does not match the signature you provided. Check your key and signing method." This is what iam getting when i tries to upload a file to S3. It works fine for me in local with the same bucket.But when coming to heroku in production it shows the above error.Any helps are appreciated s3_path = 'zips' + '/' + str(user_id) + '.zip' zipdata = open(zip_file_path, 'rb').read() file = default_storage.open(s3_path, 'wb') file.write(zipdata) file.close() return s3_path i guess the problem is with file.write(zipdata).. bucket = s3.Bucket(settings.AWS_STORAGE_BUCKET_NAME) key = 'media/zips/' + str(self.request.user.id) + '.zip' objs = list(bucket.objects.filter(Prefix=key)) if len(objs) > 0 and objs[0].key == key: print("Exists!") return JsonResponse({'status': 'success'}) else: print("Doesn't exist") return JsonResponse({'status': 'failed'}) same issue with the list operation also.. so will that be any issue with the bucket or something else?Iam using celery and redis in heroku.i had configured the environment variables with aws cli.. -
How to do an equivalent of "overlap" keyword of Django 2.2 in Django 1.11?
Suppose I have a model "Books" which has a field named "locations_available". This field stores a list of locations in which a book is available. Now, I have a query_list = ['US', 'Germany', 'Italy']. To find all the books which are available in any of these locations, I would do in Django 2.2 like this: books.objects.filter(locations_available__overlap=query_list) Since Django 1.1 had no overlap feature, how would I do the same functionality there? >>> Books.objects.create(name='X', locations=['India', 'Japan']) >>> Books.objects.create(name='Y', locations=['US', 'Korea']) >>> Books.objects.create(name='Z', locations=['Italy', 'Germany']) >>> Books.objects.create(name='A', locations=['US', 'Germany', Italy]) Consider the above data, the following datas should be returned: name='Y', locations=['US', 'Korea'] name='Z', locations=['Italy', 'Germany'] name='A', locations=['US', 'Germany', Italy] Note that the book with name='X' is not returned as it has no overlapping with any of the locations in the query_list. Check out this for more details: https://docs.djangoproject.com/en/2.2/ref/contrib/postgres/fields/#overlap -
Django query set filtering: filter with nested, nullable foreign keys
I have a relationship as follows: class A(Model): b = FK(B) class B(Model): c = FK(C) class C(Model): name = models.CharField() I'm writing the following query to filter rows by some value. queryset = A.objects.all().filter(b__c__name=someValue); I can run the same query in SQL and it works just fine. However, from django, it returns an empty queryset. Also, these foreign keys are nullable. Can someone explain this strange behavious of django querysets? -
How to serialize generic relations in DRF?
I have an Administrator model associated with three other models through generic relationship. A = 'Active' D = 'Disabled' status = ( (A, 'Active'), (D, 'Disabled') ) limit_choices = (models.Q(app_label='core', model='track') | models.Q(app_label='core', model='company') | models.Q(app_label='core', model='member') ) content_type = models.ForeignKey(ContentType, limit_choices_to=limit_choices, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') status = models.CharField(max_length=7, choices=status, default=D) class Track(models.Model): name = models.CharField(max_length=70) class Company(models.Model): partner_id = models.ForeignKey(Track, related_name='companies', on_delete=models.CASCADE) name = models.CharField(max_length=70) class Member(models.Model): carrier_id = models.ForeignKey(Track, on_delete=models.CASCADE) name = models.CharField(max_length=70) For serialization, I use the sample code from the official documentation. serializer.py class AdministratorSerializer(serializers.RelatedField): class Meta: fields = ('id', 'status', ) model = Administrator def to_representation(self, value): if isinstance(value, Track): return value.id elif isinstance(value, Member): return value.id elif isinstance(value, Company): return value.id raise Exception('Unexpected type of tagged object') But I got an error TypeError at /administrator/ __init__() takes exactly 1 argument (3 given) Please help me to solve this task/ -
I am reading a xlsx file to get some data using pandas but, the file is getting read when the project is in development and throwing 500 in production [on hold]
I am reading xlsx using pandas, it is working fine in local but in production it is throwing 500 Internal server error -
how to convert Django 2.0 url() to path()
I am unable to convert URL to path. how can I do that? and how to pass id on it. code is following. urlpatterns =[ url(r'^$',views.index, name="index"), #192.0.0.1/polls/ url(r'^(?p<question_id>[0-9]+)/$',views.detail,name="detail"), #192.0.0.1/polls/1 url(r'^(?p<question_id>[0-9]+)/result$',views.results, name="result"), #192.0.0.1/polls/results url(r'^(?p<question_id>[0-9]+)/votes$',views.vote, name="vote"), #192.0.0.1/polls/results ] -
Why doesn't enter to the get method?
The function does not even enter the get method. urls.py url(r'^activate/complete/$', TemplateView.as_view( template_name='registration/activation_complete.html' ), name='registration_activation_complete'), url(r'^activate/(?P<activation_key>\w+)/$', ActivationView.as_view(), name='registration_activate'), views.py class ActivationView(TemplateView): success_url = 'registration_activation_complete' template_name = 'registration/activate.html' def get(self, *args, **kwargs): activated_user = self.activate(*args, **kwargs) activated_user.email_approval_status = 'done' activated_user.email_success = True activated_user.save(update_fields=['email_success', 'email_approval_status', 'user_status']) activated_user.email_success = False activated_user.save(update_fields=['email_success']) if activated_user: signals.user_activated.send( sender=self.__class__, user=activated_user, request=self.request ) success_url = self.get_success_url(activated_user) if \ (hasattr(self, 'get_success_url') and callable(self.success_url)) else \ self.success_url try: to, args, kwargs = success_url return redirect(to, *args, **kwargs) except ValueError: return redirect(success_url) return super(ActivationView, self).get(*args, **kwargs) def activate(self, *args, **kwargs): activation_key = kwargs.get('activation_key') activated_user = RegistrationProfile.objects.activate_user( activation_key ) user_registration_log = UserRegistration.objects.get(user=activated_user) parent = user_registration_log.get_parent() ref_log = LogReferral.objects.get_or_create( user=parent, enabled=True, created_at__date=now() ) ref_log.count_reg += 1 ref_log.save(update_fields=['count_reg']) activated_user.email_approval_status='done' activated_user.save(update_fields=['email_approval_status']) email_confirmed_status = Status.objects.filter(verification_done=False, identification_done=False, referred=False, email_confirmed=True).last() visitor_status = Status.objects.filter(verification_done=False, identification_done=True, referred=False, email_confirmed=False).last() if not activated_user.user_status or activated_user.user_status == visitor_status: activated_user.user_status = email_confirmed_status activated_user.save(update_fields=['user_status']) return activated_user -
Restframework's .save() method does not save object to the Database but returns an object with new PK
I'm trying to save a validated serializer in my PostgreSQL 11.0 Database using djangorestframework. Restframework's .save() method is returning an object with a unique PK(+1 sequence) but the object is not being saved to the database. I tried debugging the .save() method through the Pycharm's Debugger and it turns out in the end, it does ModelClass.objects.create(**validated_data) if the object is new. I checked the validated_data and everything seemed fine. When I did ModelClass.objects.create(data) manually through the shell with the same validated data, the object was created in the database. It seems that the same code is saving to DB from the shell but not from the view. When I turned on the debugger and went inside the restframework's save() method, turns out in the end it does this for new objects: try: instance = ModelClass.objects.create(**validated_data) except TypeError: #handle error My test data returned the following value for **validated_data: {'strt_day': datetime.date(2000, 1, 24), 'end_day': datetime.date(2000, 1, 28), 'no_of_days': 5} and after that line was executed instance was an object with PK 2077 I opened a shell and did the following: In [1]: from core.models import UsrInDys In [2]: import datetime In [3]: strt_day=datetime.date(2000, 1, 24) In [4]: end_day=datetime.date(2000, 1, 28) In … -
How to redirect google VM external ip address to HTTPS in django with Debial and Apache?
I have successfully installed SSL certificate with certbot and lets encrypt on my debian and apache linux virtual machine on google cloud. the domain is successfully secure with HTTPS. Although on directly accessing the external ip address i am still getting an unsecure version of the website. How to redirect the ip directly to the HTTPS version set up with APACHE and just the "domain.com" towards -->> HTTPs:www.domain.com . I have tried to re-route to port 80 and 443 towards the HTTPS version as in PHP without any luck as shown here : How to redirect from www to https www with htacces? in my 000-default.conf: <VirtualHost *:80> ServerName localhost ServerAdmin webmaster@localhost ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined RewriteEngine on RewriteCond %{SERVER_NAME} =www.bracketline.com [OR] RewriteCond %{SERVER_NAME} =localhost RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] </VirtualHost> and on my 000-default-le-ssl.conf i have: <IfModule mod_ssl.c> <VirtualHost *:443> ServerName localhost ServerAdmin webmaster@localhost Alias /static /var/www/static-root <Directory /var/www/static-root> Require all granted </Directory> Alias /media /var/www/media-root <Directory /var/www/media-root> Require all granted </Directory> <Directory /var/www/venv/src/cfehome> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess cfehome python- path=/var/www/venv/src/:/var/www/venv/lib/python3.5/site-packages WSGIProcessGroup cfehome WSGIScriptAlias / /var/www/venv/src/cfehome/wsgi.py ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined ServerAlias www.bracketline.com SSLCertificateFile /etc/letsencrypt/live/www.bracketline.com/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/www.bracketline.com/privkey.pem Include /etc/letsencrypt/options-ssl-apache.conf </VirtualHost> </IfModule> I am not sure … -
How to throw a messages in django form that it is not changed the data in the form in UpdateView
I have a form that been populated data in Updateview i want to check or throw a message that the form hasn't had changes when clicking the submit button I'm glad that you can help me in this matter I can't understand some logic about this. -
Django Rest API merging delete/get/update/get methond in two class
At first you see my 4 method class in view.py: class ContactList(ListAPIView): queryset = Contact.objects.all() serializer_class = ContactSerializers # This is delete method class ContactDelete(DestroyAPIView): queryset = Contact.objects.all() serializer_class = ContactSerializers lookup_field = 'pk' #below is post method to create new contact class ContactCreate(CreateAPIView): queryset = Contact.objects.all() serializer_class = ContactSerializers #below is put and patch method to update contact class ContactUpdate(UpdateAPIView): queryset = Contact.objects.all() serializer_class = ContactSerializers lookup_field = 'pk' I want ContactList and ContactCreate should be in one class and ContactDelete and ContactUpdate should be in one class i am not getting how to merge it, can anyone tell me how to do it? Note: i dont want APIViewSet -
How to run a python script from django views
How to execute python script passing an argument from html page in django views and want to get output from the python script and display it in the same html page. My views.py file from django.shortcuts import render def index(request): context = {} shortdes = request.GET.get('shortdes') context['shortdes'] = shortdes return render(request, 'webapp/ttgeniehome.html', context) Want to pass shortdes variable as an argument to python script (eg: script.py which is available on the same directory where views.py file exists. -
Connection refused when trying to create a connection
We are using django to call APIs (ubuntu server) that are on 172.20.44.148. Our code is the following: import socket socket.create_connection(('172.20.44.148', 8080), timeout=2) However, the connection refused. This is the error we got from apache: [root@xxx ~]# python /home/something.py Traceback (most recent call last): File "/home/something.py", line 3, in <module> socket.create_connection(('172.20.44.148', 8080), timeout=2) File "/usr/local/lib/python2.7/socket.py", line 571, in create_connection raise err socket.error: [Errno 111] Connection refused We also tried to ping 172.20.44.148 and we got a response. Any ideas? -
Django template loops unwantedly fetching items in random order
I am using Django 2.2 and psql 10.8 on Ubuntu 18.04.1. I have a collection of items that I want to iterate over and render the results in a template. They are expected to be rendered in exactly the order that they have been created in the database (by pk). However, they seem to be rendered in a random order instead. The problem does not occur when using sqlite. I have not found the solution for this problem; reverse iterating through the objects results also not in the desired behaviour. A simple portion of the code would be: <div class="row"> <ul class="tabs"> {% for category in categories %} <li class="tab col s3"><a href="#{{category}}">{{category}}</a></li> {% endfor %} </ul> </div> Say I have created four categories A, B, C, D; when using sqlite in dev, they would be rendered in that order on the frontend page. With psql, I am seeing an unordered result. Any help in the right direction is appreciated! -
Stacktrace of Python is cut in psycopg2 connection.notices
I am overwriting connection.notices of psycopg2. My goal is to send a notice from a PostgreSQL trigger to my application. In python I want to write the current stacktrace to a log file to see which python code is triggering the trigger in the database. It works, but unfortunately I can't extract the whole stacktrace. I only get the lines below psycopg, not the above (lines of the callers). Here is my code: # Overwriting connetion.notices via Django class MyAppConfig(AppConfig): def ready(self): connection_created.connect(connection_created_check_for_notice_in_connection) class ConnectionNoticeList(object): def append(self, message): if not 'some_magic_of_db_trigger' in message: return logger.warn('%s %s' % (message, ''.join(traceback.format_stack()))) def connection_created_check_for_notice_in_connection(sender, connection, **kwargs): connection.connection.notices=ConnectionNoticeList() I see this in the logs: 'NOTICE: some_magic_of_db_trigger: 17909 File "/snap/pycharm-community/128/helpers/pycharm/_jb_pytest_runner....ork/foo/apps.py", line 47, in append logger.warn(\'%s %s\' % (message, \'\'.join(traceback.format_stack()))) ' traceback.format_stack() inside ConnectionNoticeList.append() extracts not the callers. Is there a way to get the lines of the upper methods? -
Filter - How to implement
I need to implement multi-choice filter in my Django software. I have my model (database): models.py class Autor(models.Model): naziv = models.CharField(max_length=30, null=False, blank=True) email = models.EmailField(max_length=75, null=True, blank=True) def __str__(self): return str(self.naziv) class Clanak(models.Model): naslov = models.CharField(null=False, blank=True, max_length=120) datumObjave = models.DateField(null=False, blank=False) autor = models.ForeignKey(Autor, on_delete=models.CASCADE, null=True) def __str__(self): return str(self.naslov) + ', ' + str(self.datumObjave) + ', ' + str(self.autor) My urls.py: urlpatterns = [ path('filtar/',views.filtar, name='filtar'), ] Views.py: def filtar(request): data = Clanak.objects.all() return render(request, 'filtar.html', {'data': data}) My Filtar.html: <!DOCTYPE html> <html> <head> {% extends 'base.html' %} {% block main_content %} <title></title> </head> <body> <table border="1"> <tr> <th>Naslov</th> <th>Datum</th> <th>Autor</th> </tr> {% for x in data %} <tr> <td>{{x.naslov}}</td> <td>{{x.datumObjave}}</td> <td>{{x.autor}}</td> </tr> {% endfor %} </table> </body> </html> {% endblock %} Footer.html: <br> <div>Filter: </div> <form> <fieldset> <legend>Filtar - Thing that is being chosen</legend> <input type="radio" name="Autor" id="Autor" value="Autor"> <label for="Autor">Choice A</label> <input type="radio" name="Datum" id="Datum" value="Datum"> <label for="Datum">Choice B</label> <br> <br> <input type="submit" value="Submit"> </fieldset> </form> <br> <div>Copyright by </div> Screenshot: Now my question is: User can pick one filter or both filters. First filter should be on name ("naslov") and other one should be on year from date (datumObjave). What would be the best … -
How to use a schema as default value of Django JSONField
I would like to use a dict with attributes as default value of my JSONField instead of a simple empty dict. The schema: class FinancialDataSchema(marshmallow.Schema): capital = fields.Float(allow_none=True) # Capital social revenue = fields.Float(allow_none=True) # Chiffre d'affaires revenue_year = fields.Int(allow_none=True) # Année du chiffre d'affaires account_published = fields.Boolean(allow_none=True) # Publication des comptes The model: class ServiceProvider(models.Model): financial_data = JSONField(validators=[MarshmallowValidator(schema=schemas.FinancialDataSchema)], default=dict) Problem: By default the key serviceProvider.finalcial_data.capital does not exist. I would like the key to be created and its value set to None. What I've tried: JSONField(validators=[MarshmallowValidator(schema=schemas.FinancialDataSchema)], default=schemas.FinancialDataSchema) I got: TypeError: Object of type 'FinancialDataSchema' is not JSON serializable -
Uploading Multiple files or images serializers using django
I'm trying to upload multiple files or images in one field. It's returning one image/file but not multiple objects. I've tried passing many=True in the serializer. Only one image/file is being saved in the database. Models: class FoundationImage(models.Model): project_name = models.ForeignKey(Project,on_delete=models.DO_NOTHING) site_clearing = models.ImageField(upload_to='images/%Y/%m/%d/') def __str__(self): return str(self.project_name) Views: class FoundationImageViewSet(DefaultsMixin, viewsets.ModelViewSet): queryset = FoundationImage.objects.order_by('created_at') serializer_class = FoundationImageSerializer serializer class FoundationImageSerializer(serializers.ModelSerializer): class Meta: model = FoundationImage fields = ('__all__') { "id": 2, "setting_site_clearing": "http://127.0.0.1:8000/media/images/2019/05/22/ck.jpeg" } The expected output should include more than one image in that field -
Django Changing existing models once setting is updated
I've got a user model, which has a ManyToMany Field called groups it looks like this: class User(models.Model): groups = models.ManyToManyField(verbose_name="Groups", to='content.Group', limit_choices_to={'is_active': True}, blank=True) Now as you can see the groups model has a field called is_active class Group(models.Model): is_active = models.BooleanField(verbose_name="Active", default=True) Now the thing is that in my settings forms, I can turn on these groups to be active or not. Now let's say I've got them not turned on to be active and a user registers for my page. He then of course has a "None" value for the groups field, but what I want to do now is the following: Groups are not active User registers has None groups I set groups to be active Every User which has None Groups should get all existing groups added to their profile My Question would be, what is the best way to do that, without making to many queries every time I save my settings form? My Settings form looks like this: class InstanceForm(forms.ModelForm): class Meta: model = Instance fields = [ 'is_registration_enabled', 'groups_is_enabled' ] def __init__(self, *args, **kwargs): super(InstanceForm, self).__init__(*args, **kwargs) self.setting = FormHelper() self.setting.form_tag = True self.setting.label_class = 'font-weight-bold' self.setting.layout = layout.Layout( Row( Div('is_registration_enabled', css_class='col-sm-3'), … -
How to use django filter_fields with ArrayField in DRF
I am using a Postgres ArrayField in my models. I am trying to use django filters but I get an error for them. AutoFilterSet resolved field 'flavor' with 'exact' lookup to an unrecognized field type ArrayField. Try adding an override to 'Meta.filter_overrides'. See: https://django-filter.readthedocs.io/en/master/ref/filterset.html#customise-filter-generation-with-filter-overrides Model class Items(models.Model): item = models.CharField(max_length=150, unique=True) matches = ArrayField(models.CharField( max_length=200), blank=True, default=list) category = ArrayField(models.CharField( max_length=200), blank=True, default=list) flavor = ArrayField(models.CharField( max_length=200), blank=True, default=list) special = ArrayField(models.CharField( max_length=200), blank=True, default=list) created_at = models.DateTimeField(auto_now_add=True) ViewSet class CategoryViewSet(viewsets.ModelViewSet): queryset = Items.objects.all() serializer_class = CategorySerializer filter_fields = ('item', 'category') -
How do i send an extra string info OnClick?
I have a for loop creating my main home page cards , i have 3 models Image ,title and body the idea is to get the specific info for each card that I'm pressing on his "view " button . I'be been using django with python , and I'm trying to make like a news website where you see the title on the cards on the home page and when you click them you get a scroll bar with the full info about the arctical , the problem is that because I'm looping trough the database to get all the cards , when I press on the "View" button doesn't mattet which one I get the body of the text that Is last on the List. <div class="row"> {%for job in jobs.all%} <div class="col-md-4"> <div class="card mb-4 shadow-sm"> <img class ="card-img-top" src ="{{job.image.url}}" /> <div class="card-body"> <p class="card-text">{{job.title}}</p> <div class="d-flex justify-content-between align-items-center"> <div class="btn-group"> <button type="button" class="btn btn-outline-primary" data-toggle="modal" data-target="#exampleModalScrollable" > View </button> <div class="modal fade" id="exampleModalScrollable" tabindex="-1" role="dialog" aria-labelledby="exampleModalScrollableTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-scrollable" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalScrollableTitle">Full artical</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> {{job.body}} </div> <div class="modal-footer"> <button type="button" … -
How can I get json from this webpage using requests or other libraries?
How can I get json from this webpage using requests or other libraries? code: request_url = 'http://tour.tmon.co.kr/api/direct/v1/airtktintlapi/api/search/dataList' headers = { 'Accept': 'application/json, text/plain, */*', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'ko-KR,ko;q=0.9,en-US;q=0.8,en;q=0.7', 'Connection': 'keep-alive', 'Content-Length': '1011', 'Content-Type': 'application/json;charset=UTF-8', 'Host': 'tour.tmon.co.kr', 'Origin': 'http://tour.tmon.co.kr', 'User-Agent': ('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ' +'(KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36') } jsonObj = requests.get(request_url, headers=headers).json() error: requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None))