Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django blank FileField how to serialize without getting error
I have a file field that is defined in my model like this: class Profile(models.Model): ... profile_picture = models.FileField(blank=True) Then, I have a JSON view like this: from django.forms.models import model_to_dict class ProfileView(APIView): def get(self, request, format='json'): profile = ... profile_serialized = model_to_dict(profile) return Response(profile_serialized, status=status.HTTP_200_OK) I am using DRF but DRF is not my concern. model_to_dict converts the model to dictionary, so I can output it as JSON. However, I keep getting validation error: ValueError: The 'profile_picture' attribute has no file associated with it. If the field field is empty, I can't serialize it. How should I do approach solving this? Should I create a @property function in the models that does the checking or is there a better approach to this? Thanks! -
Large increase in client timeouts since moving database to rds
Last week we moved our postgres db off the AWS EC2 it had previously shared our django app and onto an AWS RDS instance. Since then we've seen a large uptick in the number of client timeouts we're experiencing, these take the following form: NGINX returning a '499' status to the client This trio of messages in the django logs: SIGPIPE: writing to a closed pipe/socket/fd (probably the client disconnected) on request /my/web/hook/ (ip 172.18.0.3) !!! Wed Jun 13 09:35:51 2018 - uwsgi_response_writev_headers_and_body_do(): Broken pipe [core/writer.c line 287] during POST /my/web/hook/ (172.18.0.3) IOError: write error The application on the EC2 is deployed using docker with docker-compose and consists of a django and an nginx container in the same network with an additional connected network containing a single container handling the ssl with lets-encrypt. The webhook is only authorised to a single client from it is triggered consistently throughout the day. I was hoping someone could shed some light on what could be causing this, I have already tried addressing it by increasing nginx's keepalive_timeout to 65 and by increasing the CONN_MAX_AGE django database setting from 0 to 600. Each of these measures appeared to fix the problem for about 1-2 … -
Django and Bootstrap: Card only on large devices
What I want to achieve: In my base.html I want to create a card to put the main content on all pages inside a nice border. But however: This border shouldn't appear on smaller than md-Devices to make the content not super small. What I tried: base.html <div class="card d-none d-lg-block"> <div class="card-body d-none d-lg-block"> {% block content %} {% endblock %} </div> </div> <div class="d-md-none"> <div class="d-md-none"> {% block content %} {% endblock %} </div> </div> This of course brings the following error: TemplateSyntaxError at / 'block' tag with name 'content' appears more than once But how could I implement this? Any input is highly appreciated! -
Cross server login and logout in Django
I am working on a project where I am using Angular-5 for front-end and Django for server side back-end. My front-end and back-end both services are running on different machines. Let's say front-end is on "example.com" and back-end is on "api.example.com". How should I use the django login and logout in this scenario? If I use JWT then what to do in case of logout? Is there any good approach I can use? I have read about JWT based authentication but still not sure how to expire an active token if user wants logout before the expiration time? -
Django find items from db by values from list?
I have a list of strings: phrases_filter = json.loads(request.GET['phrases_filter']) ['xx', 'yy'] I need to lookup all phrases in db, that contain xx OR yy I tried it like this: Phrase.objects.filter(name__in phrases_filter) But this gave me only phrases that have in name xx AND yy -
Django vote mod and problems
I installed the Django-vote package for voting on one of my models. Here's the model. I added these two fields to help with voting: class Idea(VoteModel, models.Model): ... vote_for = models.NullBooleanField(choices=ONE_CHOICE) votes = VotableManager() Ideally I just want a user to be able to vote for the model, and have the models vote_score incremented by one. That is where I run into problems. I have a vote form: class VoteForm(forms.ModelForm): class Meta(): model = Vote fields = ('vote_for',) widget = {'vote_for': forms.RadioSelect(choices=ONE_CHOICE)} def __init__(self, *args, **kwargs): super(VoteForm, self).__init__(*args, **kwargs) self.fields['vote_for'].required = True widgets = {'vote_for': forms.RadioSelect} And I have modified the vote model a bit keeping in mind I just need a user to be able to up vote the model, so a PositiveIntegerField doesn't really work: class Vote(models.Model): ACTION_FIELD = { UP: 'num_vote_up', DOWN: 'num_vote_down' } user_id = models.BigIntegerField() content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() action = models.PositiveSmallIntegerField(default=UP) create_at = models.DateTimeField(auto_now_add=True) vote_for = models.BooleanField(choices=ONE_CHOICE) voter = models.ForeignKey(User, on_delete=models.PROTECT, related_name='voter') objects = VoteManager() class Meta: unique_together = ('user_id', 'content_type', 'object_id', 'action') index_together = ('content_type', 'object_id') Here is my view: class IdeaVoteView(LoginRequiredMixin, CreateView): model = Idea form_class = VoteForm required_fields = ('vote_for',) template_name = 'heart/vote_form.html' success_url = … -
Serializer Equivalent of clean for django forms in rest framework Serializers
What is the serializer equivalent of the clean method for django forms. My use case is that I want to do custom model field validation of some fields for a model serializer class. My guess is it could be the run_validators, for the framework. But I am not sure with certainty. Thanks, Best regards, -
Object in django admin for a foreignkey :
I have this object in my django model : class Stock(models.Model): name = models.CharField(null=True,blank=True,max_length=20) def ___str__(self): return self.name def __unicode__(self): return self.name When i see it in the django admin it works well. But in the admin when i want to see this object : class StockData(models.Model): stock = models.ForeignKey(Stock,on_delete=models.PROTECT,null=True,blank=True) date = models.DateTimeField(null=True,blank=True) def ___str__(self): return self.stock+ ":" + str(self.date) def __unicode__(self): return self.stock + ":" + str(self.date) with this admin : from django.contrib import admin from .models import StockData # Register your models here. class StockData_Admin(admin.ModelAdmin): list_display = ( 'date', 'stock', 'interval' ) admin.site.register(StockData,StockData_Admin) but in the admin page the stock object is represented as : Stock object (1) So how to solve this ? My django version : import django django.VERSION (2, 0, 0, 'final', 0) Thanks and regards -
KeyError on get value from select django
i'm try to get the value from select on django but get this error: u"Key 'destino' not found in 'ProcesoForm'" this is my html <select name="destino" id="destino" class="form-control" required> <option disabled selected>Seleccione:</option> {% for directorio in directoriosList %} <option value="{{directorio.ruta_absoluta}}">{{directorio.nombre.1}}</option> {% endfor %} </select> on the views.py form = ProcesoForm(request.POST, request.FILES) print form['destino'].value() on the inspector web: with this method i get the values from others input but dont get from a select..please .. a little suggest !! thanks -
Problems with getting content from mySQL server to webpage via django
This is the first time I am using mySQL and django, and I have some problems with getting my content from the server and show it on my webpage. Here is my codes: This is the index.html {% extends 'test/layout.html' %} {% block content %} <hr> <br> <h1 class="container center-align">{{title}}</h1> <br> <h3 class="center-align blue lighten-3">Webpages</h3> <ul class="collection"> {% for homes in homes %} <li class="collection-item"><a href="test/details.html">{{homes.title}}</a></li> {% endfor %} </ul> {% endblock %} The views.py from django.shortcuts import render from django.http import HttpResponse from .models import Home def index(request): homes = Home.objects.all()[:10] context = { 'title': 'All Home', 'homes': homes } return render(request, 'test/index.html', context) def details(request, id): home = Home.objects.get(id=id) context = { 'Home': home } return render(request, 'test/details.html', context) urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'', views.index, name='index'), url(r'details/(?P<id>\d+)/', views.details, name='details') ] models.py from django.db import models from datetime import datetime class Home(models.Model): title = models.CharField(max_length=100) body = models.TextField() created_at = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.title class Meta: verbose_name_plural = "Home" details.html {% extends 'test/layout.html' %} {% block content %} <hr> <br> <h1 class="container center-align">{{home.title}}</h1> <br> <div class="card"> <div class="card-content"> {{home.body}} </div> <div class="card-action"> {{created_at}} </div> </div> <a href="/test" class="btn">Go Back</a> … -
Where is the httpd.conf for Django's Development Server
I am making an intranet app and I wanted to implement Active Directory on my development server. The main problem I'm having right now is that I don't know where Django puts their httpd.conf file. I'm trying to access this file so I can implement mod_ldap. Also I'm using Windows 10, Django 1.11, and Python 2.7 -
Mac pip install mysql-python unsuccessful
I installed MySQL and Workbench from website. I have a django project whose requirements.txt: Django==1.11.12 djangorestframework==3.8.2 django-cors-headers==2.2.0 drfdocs==0.0.11 mysql-python==1.2.5 django-rest-auth==0.9.3 django-allauth==0.35.0 nltk==3.2.5 django-extensions==2.0.7 pyparsing==2.2.0 pydot==1.2.4 When I run pip install -r requirements.txt I got an error mysql_config not found. To solve this I ran PATH=$PATH:/usr/local/mysql/bin It now throws _mysql.c:44:10: fatal error: 'my_config.h' file not found #include "my_config.h" ^~~~~~~~~~~~~ 1 error generated. error: command 'cc' failed with exit status 1 ---------------------------------------- Command ""/Users/nitish/gitProjects/Vision Backlog/vb_env/bin/python" -u -c "import setuptools, tokenize;__file__='/private/var/folders/ql/_w2_rlvs2351pdcnzhn04sf40000gn/T/pip-install-M4ue9E/mysql-python/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /private/var/folders/ql/_w2_rlvs2351pdcnzhn04sf40000gn/T/pip-record-7OCzf1/install-record.txt --single-version-externally-managed --compile --install-headers "/Users/nitish/gitProjects/Vision Backlog/vb_env/include/site/python2.7/mysql-python"" failed with error code 1 in /private/var/folders/ql/_w2_rlvs2351pdcnzhn04sf40000gn/T/pip-install-M4ue9E/mysql-python/ Why is this happening? -
Is it possible to control url addresses in Django admin page?
In my Django project I want to control url addresses in admin page. Make them inactive when we need or make it active again. Can someone say how to make it? -
How can I handle the error "expected str, bytes or os.PathLike object, not InMemoryUploadedFile' in Python or Django?
Before explaining my problem in detail, here are my codes. models.py class SimilarStore(models.Model): store = models.ForeignKey(Store) domain = models.CharField(max_length=100, blank=True) score = models.IntegerField(blank=True) rank = models.IntegerField(blank=True) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) forms.py class SimilarStoreForm(forms.ModelForm): similarstore_csv = forms.FileField() class Meta: model = SimilarStore fields = ('store', 'similarstore_csv') def save(self, commit=False, *args, **kwargs): form_input = SimilarStoreForm() self.store = self.cleaned_data['store'] csv_file = self.cleaned_data['similarstore_csv'] with open(csv_file) as data: reader = csv.reader(data) for line in reader: self.domain = line[0] self.score = line[1] self.rank = line[2] form_input.save() data.csv roolee.com,100,125225 piperandscoot.com,29.3,222166 calledtosurf.com,23.8,361542 cladandcloth.com,17.9,208670 neeseesdresses.com,9.6,251016 ... I'm trying to upload data.csv to DB. I need each column data in the file to go into domain, score, rank in SimilarStore model. This is what I'm trying to do with the above codes. However, when I upload the file and submit it, an error shows up, saying expected str, bytes or os.PathLike object, not InMemoryUploadedFile I've done some research about it, but nothing worked for my case. Can anyone figure out anything wrong? -
Docker machine's database persists after docker-machine rm | How do I remove the db?
Whenever I break the database on my local development instance I am able to easily run 'docker-machine rm dev-instance'. This works, and I can just recreate a new docker-machine with 'docker-machine create --driver virtualbox dev'. This approach works fine when on Mac OS. However, on my Ubuntu machine, when I run 'docker-machine rm -f dev-instance' it deletes the dev instance and I think all is fine. I go through the usual process of recreating my dev instance. It builds successfully, but way too fast -- it's not creating a new machine it doesn't look like.. It seems to be caching the last docker machine. I confirm this when I run 'docker-compose -f local.yml up'. This isn't very helpful though, because I still run into the same errors I had with my DB before -- I was hoping to nuke my instance of everything and start fresh, but I can't quite get it to work on Ubuntu. Any suggestions would be greatly appreciated, please let me know what other details would be useful to provide. Thanks in advance! -
Ranking of users in django
I am trying to assign rank to bloggers based on the sum of total blogs and total likes. Sum - 1-10 : Rank 1, 2-30 : Rank 2 and so on.Can someone suggest how to achieve that. thanks. models.py class Blog(models.Model): author = models.ForeignKey(User, on_delete = models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() def __str__(self): return self.title def count_blogs_of(user): return Blog.objects.filter(author=user).count() def total_likes_received(user): return user.blogs.aggregate(total_likes=Count('likes'))['total_likes'] or 0 views.py class BlogListView(ListView): model = Blog context_object_name = 'blog_list' def get_queryset(self): return (Blog.objects.filter(published_date__lte=timezone.now()) .order_by('-published_date') .annotate(author_total_likes = Count('author__blogs__likes')) ) -
Django: form: not showing validators messages
I am working with DJango 2.0 I am trying to understand how field validators work in DJango. I want a field in a model to only have a 6 digit value. SO i tried the below. I have model: class Test(models.Model): sample = models.CharField(blank=True, null=True, max_length=6, validators=[RegexValidator(r'^\d{6}$',message=_('Sample shoud be of 6 digits. Not less or more than 6'))]) My Form class TestForm(forms.ModelForm): class Meta: model = Test fields = ['sample'] Now when i post sample = "097" I am expecting the form to display the error "Sample shoud be of 6 digits. Not less or more than 6" But i found it shows Nothing and cleaned_data shows None How to ensure it show the failure message also so that we know why its failed. -
Accessing Parent of Inline Form Sets in template?
I am wondering how to access the parent of the inline form set in Django. Here is what I am currently doing: views.py def upload(request): [Code Ommitted] formSet = inlineformset_factory(Tombstone, Tank, form = TombstoneForm) form = formSet(instance=t) return render(request, 'edit_form2.html', {'form': form}) In this instance I want to access the Tombstone object in my template. -
Django: How to get and display shorted url stats?
So, I have a Url Shorter with django but now I want to add stats to it so when a user logs in he can see the stats of the link he just shorted. Any documentation on how I can do that? -
Django websockets with Redis
I'm using django-websocket-redis (http://django-websocket-redis.readthedocs.io/en/latest/) I can send messages to the global channel but not to a specific user. Following the docs: http://django-websocket-redis.readthedocs.io/en/latest/usage.html Message to the global channel (WORKING): Client code: WS4Redis({ uri: '{{ WEBSOCKET_URI }}foobar?subscribe-broadcast, receive_message: function(data){alert(data)}, heartbeat_msg: {{ WS4REDIS_HEARTBEAT }} }); Server code: redis_publisher = RedisPublisher(facility='foobar', broadcast=True) message = RedisMessage('Hello World') redis_publisher.publish_message(message) Message to a specific user (NOT WORKING): Client code: WS4Redis({ uri: '{{ WEBSOCKET_URI }}foobartwo?subscribe-user, receive_message: function(data){alert(data)}, heartbeat_msg: {{ WS4REDIS_HEARTBEAT }} }); Server code: redis_publisher = RedisPublisher(facility='foobartwo', users=['user1']) message = RedisMessage('Hello World') redis_publisher.publish_message(message) No error occurs, simply the user's message never captures it. Why? -
using mailchimp in django
I am trying to redirect the user to home page when they click on subscribe. I have tried the below method but its not working, I think because of the mailchimp link in the form action. How can I do that: adding the user to mailchimp list and redirecting them to home page. html <form action="https://trajectorE.us14.list-manage.com/subscribe/post?u=9511e91b4b591328ba1176666&amp;id=8d427209e8" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate> <div class="clear"><a href="{% url 'home' %}"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></a></div> views.py class Subscribe(TemplateView): template_name = 'subscribe.html' redirect_field_name = 'blog/home.html' -
Django "server error occured"
In short words: Even though im following tutorial perfectly, and get no errors when starting server I get "a server error occured. Please contact the administrator" error when i open the site. Here is prompt i get in pycharm: "C:\Program Files\JetBrains\PyCharm 2018.1.4\bin\runnerw.exe" C:\Users\Username\Downloads\WinPython-64bit-3.6.2.0Qt5\python-3.6.2.amd64\python.exe "C:\Program Files\JetBrains\PyCharm 2018.1.4\helpers\pycharm\django_manage.py" runserver C:/Users/Username/PycharmProjects/strona2 Tracking file by folder pattern: migrations Performing system checks... System check identified no issues (0 silenced). June 14, 2018 - 18:27:17 Django version 2.0.6, using settings 'strona2.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Full story: I'm a total newb in a subject so please forgive if my problem is trivial. I'm following this tutorial: first app in Django using Pycharm, and up to the point of "performing administrative functions" everything went well. I added superuser, performed migrations, opened server, and even though i get no errors in pycharm somehow an error occurs on site. The previous parts of tutorial work. For example 127.0.0.1:8000/polls works just as it should while 127.0.0.1:8000/admin doesn't. Any ideas? -
Is Flask starting to dominate Django?
I just got an official position into software this year (switching from hardware), and have been working with python scripting. I am now learning full stack development on the side and working with Django. I have been told by peers that Flask is the "up and coming" and may potentially be more of a standard than Django for years to come? Is this necessarily true or is it arbitrary and based on preference? Thanks and peace. -
Javascript vs Python for DynamoDB & Django
New to all of the above, Which would be the better choice. I would like to store form entries into a DynamoDB with Django. The form responses are collected in Javascript. Use javascript dynamoDB calls to update the table. Make an ajax call in my Javascript to a python method which updates the table. I see the difference being that the request is made client side in case 1, where server side in case 2. Perhaps case 2 is more Model-View-Template? -
Django get the name of related model doesn't recognize `rel` attribute
I am trying to create a dictionary with some attributes of model fields, so I followed the answer to this question to get the name of the model referenced by ForeignKey fields, but I get an error AttributeError: 'ForeignKey' object has no attribute 'rel'. This is my code: def get_fields(model, fields): fields_meta = [] for field in fields: field_meta = {} field_meta['name'] = field field_meta['title'] = force_text(model._meta.get_field(field).verbose_name) field_meta['type'] = model._meta.get_field(field).get_internal_type() if field_meta['type'] == 'ForeignKey': field_meta['rel_model'] = model._meta.get_field(field).rel.to field_meta['null'] = model._meta.get_field(field).null field_meta['max_legth'] = model._meta.get_field(field).max_length fields_meta.append(field_meta) return fields_meta I can't find what I am missing.