Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get user information in template
I'm trying to retrieve data from user. The form where i want to show the user information is also the same that i use to update this information. I have my model like this: from django.db import models from django.contrib.auth.models import User # Create your models here. class informacionFacturacion(models.Model): usuario = models.ForeignKey(User) apellidos = models.CharField(max_length=100) nombres = models.CharField(max_length=100) telefono = models.CharField(max_length=100) email = models.EmailField(null=False) direccion_1 = models.CharField(max_length=100) direccion_2 = models.CharField(max_length=100, null=True, blank=True) provincia = models.CharField(max_length=100) ciudad = models.CharField(max_length=100) codigoPostal = models.CharField(max_length=100) empresa = models.CharField(max_length=100) def __str__(self): return self.usuario My form for update user information: from .models import informacionFacturacion class informacionFacturacionForm(ModelForm): class Meta: model = informacionFacturacion fields = [ "usuario", "apellidos", "nombres", "telefono", "email", "direccion_1", "direccion_2", "provincia", "ciudad", "codigoPostal", "empresa", ] And in my view I have my query like this from django.contrib.auth.decorators import login_required from .models import informacionFacturacion from .forms import informacionFacturacionForm @login_required def datosPersonales(request): form = informacionFacturacionForm(request.POST or None) if form.is_valid(): instance = form.save(commit=False) instance.save() query = informacionFacturacion.objects.filter(usuario=request.user) context = { "titulo": "Datos personales | Co", "body_class": "class= sidebar_main_open sidebar_main_swipe", "form": form, "infoFacturacion": query, } template = "micuenta/datosPersonales.html" return render(request, template, context) In my HTML file I populate my form in this way: {% for x in infoFacturacion %} … -
Django implementation of default value in database
I had a field on a model with was: class SomeModel(models.Model): some_field = models.CharField(max_length=10, null=True, blank=True) Then I changed my model to: class SomeModel(models.Model): some_field = models.CharField(max_length=10, default='') When I ran django-admin sqlmigrate somemodels somemigration to check my migration I found the following changes: ALTER TABLE "somemodels" ALTER COLUMN "some_field" SET DEFAULT ''; UPDATE "somemodels" SET "some_field" = '' WHERE "some_field" IS NULL; ALTER TABLE "somemodels" ALTER COLUMN "some_field" SET NOT NULL; ALTER TABLE "somemodels" ALTER COLUMN "some_field" DROP DEFAULT; I am not understanding why the Django apply a DROP DEFAULT in the table since I am creating a default value. If this is correct, how does Django implement the default values? Information about my tools: Postgresql 9.5; Django 1.11b1; -
Reuse same "block" of html in multiple django templates
Currently, I have two html template that extends from a base.html: page1.html: {% extends 'dashboard/base.html' %} {% block tittle %} Dashboard1 {% endblock %} ... code ... Code_block_1 {% endblock %} page2.html: {% extends 'dashboard/base.html' %} {% block tittle %} Dashboard2 {% endblock %} ... code ... Code_block_1 {% endblock %} Both html share the same Code_block_1. I was thinking about about creating another html called Code_block_1.html to consolidate this repeating piece of code. Then, insert Code_block_1.html into page1.html and pag2.html. Django only lets you extend once. How do I get around this problem? Thanks. -
How to do complex join in Django
I have Custom user model and two models, both with ForeinKey to two users at once: class Feature1(models.Model): user1 = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='u1') user2 = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='u2') some field.... percentage = models.FloatField() class Feature2(models.Model): user1 = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='us1') user2 = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='us2') some fields... property = models.PositiveIntegerField() and then I retrieve all pairs for particular user with queryset queryset = Feature1.objects.filter(u1=self.request.user).all().order_by('-percentage') but what I need, to have in this queryset data from Feature2 model too (for each particular pair of users, if exists) and to be able order queryset by 'property' from Feature2 How to do it? I've researched django docs, but without result. -
getattr with django models, where db_column is in use
I have django model: class A_Model(model.Models): a_Column=models.IntegerField(default=0,db_column='a Column', verbose_name='a Column'), and in views: aObject = A_Model.objects.filter(pk=1) x = getattr(aObject, 'a Column') I've thought it should work, but it get exception [...] "object has no attribute 'a Column'" Anybody know what is the reason and know how to fix it? -
cleaned_data.get('department') returning <company.models.Service> in django
Hei, I am really clueless on this error I am getting. Basically, I need to display list of service a loggedin user can register clients to. Now, a user can have the right to register to all services in the company or to a single service. So, I came up with this in my forms.py file: def __init__(self,request,*args,**kwargs): super(NewPatientForm, self).__init__(*args,**kwargs) receptionistFor=receptionisttype(request) self.receptionistFor=receptionistFor if receptionistFor==0: services=Service.objects.filter(serviceNature='Clientel',kind='internal',active='yes').only('id','name') else: services=Service.objects.filter(active='yes',serviceNature='Clientel',kind='internal',pk=receptionistFor).only('id','name') self.fields['department']=forms.ModelChoiceField(required=True,queryset=services,widget=forms.Select()) Where receptionisttype is a method in a package, which is working fine. I see only allowed services per logged in user in my template through this: {% render_field form.department|add_class:"form-control select2" %} Now my problem is when reading back the value of the HTML element in my forms.py clean method, I get a model instance: def clean(self): ''' Grouped cleaning ''' cleaned_data=super().clean() selectedDepartment=cleaned_data.get('department') print(str(type(selectedDepartment))) #gives <class 'company.models.Service'> What am I doing wrong exactly? I get values of other controls that are not created in init pretty well except this one. -
get_fields function not getting called
I am working on a django project in which I want to display the admin fields according to a condition. I have used ModelAdmin.get_fields(request, obj) admin.py class UserAdmin(admin.ModelAdmin): readonly_fields = ('is_enabled',) list_display=['name','area_field', 'is_enabled'] list_filter = ['city', 'is_enabled'] fields = ('city', 'name', 'is_enabled') form = UserForm def get_fields(self, obj=None): key = Condition.objects.get(meta_key='SHOW_AREA_FIELD') area_flag = long(key.meta_value) if area_flag is not 0L: return self.fields + ('area_field') What I am trying to achieve here is that when area_flag is not equal to 0L I want to show one more field(area_field) in the admin page.But this approach is not working, I have even used a debugger but it seems this function is not at all called. If this is the right way to do this what is the problem or there is a better way of doing it? -
Reload Django Website Without 500 Server Error?
I have a Django/Gunicorn/Nginx website which I build using an Ansible playbook. I'm currently in the process of tagging those tasks in my playbook that need to run whenever I add a new feature or fix a bug and want to reload my Django code. My goal is to be able to push any such changes to production as soon as I've tested them on my staging server without having to take my production server down. My playbook is currently set up so that whenever I want to push changes to production, it will delete the entire website directory and rebuild the Pip virtual environment so that there's no leftover "cruft". The problem is that when I run the Ansible playbook, I get a momentary 500 server error at the point at which it deletes the website directory. Then, as soon as the next task that checks out the code from Github runs, the error goes away. Clearly, whenever I reload my code base, if any user is hitting my website at the moment that task runs, they'll get this 500 error too. I've been thinking that once Gunicorn is started and my Django code is loaded into memory, I … -
Adding robots.txt plugin to django
I'm trying to include a robots.txt in my django project and am running into quite a bit of trouble. I'm at the point of throwing my hands up and screaming. :) I have been trying to use this plugin https://github.com/nkuttler/django-robots-txt and have followed all the steps. But I keep receiving 502 bad gateways. So there is something I am missing, but I have no idea what. I have installed the plugin via pip pip install django-robots-txt Gone to my root url.py and added from django.conf.urls.defaults import patterns, include, url from robots_txt.views import RobotsTextView urlpatterns = patterns('', url(r'^robots.txt$', RobotsTextView.as_view()) ) and tried adding it to my installed Apps INSTALLED_APPS = ( 'robots_txt' ) What am I missing? Please save me from this 502. -
Django/Mezzanine: CSS "@import url()" not work properly
I have built the default mezzanine site. However, in the admin page of the site, only part of the styles are applied to the site. And I see some error logs [18/Apr/2017 00:03:47] "GET /admin/login/?next=/admin/ HTTP/1.1" 200 4251 [18/Apr/2017 00:03:47] "GET /static/grappelli/css/base.css/reset.css HTTP/1.1" 4 04 1709 [18/Apr/2017 00:03:47] "GET /static/grappelli/css/base.css/typography.css HTTP/1 .1" 404 1724 [18/Apr/2017 00:03:48] "GET /static/grappelli/css/base.css/modules.css HTTP/1.1" 404 1715 [18/Apr/2017 00:03:48] "GET /static/grappelli/css/base.css/tables.css HTTP/1.1" 404 1712 [18/Apr/2017 00:03:48] "GET /static/grappelli/css/base.css/forms.css HTTP/1.1" 4 04 1709 [18/Apr/2017 00:03:48] "GET /static/grappelli/css/base.css/widgets.css HTTP/1.1" 404 1715 [18/Apr/2017 00:03:48] "GET /static/grappelli/css/base.css/webkit-gradients.css HTTP/1.1" 404 1742 [18/Apr/2017 00:03:48] "GET /static/grappelli/css/img/grappelli-icon.png HTTP/1. 1" 404 1721 It seems paths of some css files are wrong. The path shouldn't be /static/grappelli/css/base.css/xxxx.css but /static/grappelli/css/xxxx.css When I dig into the /static/grappelli/css/base.css file, I see this file imports those wrong path css files like this ... @import url('reset.css'); @import url('typography.css'); @import url('modules.css'); @import url('tables.css'); @import url('forms.css'); @import url('widgets.css'); ... How to fix it? -
'max_user_connections' in django web application
i have developed a Django web application for a chatbot that acts as s store's customers service. At first i was using Sqlite3 foe my databases, i was working fine but some times it causes the (Data Base is Locked error).So, i switch to Mysql for the application backend and the other databases. to be clear i have 5 DB all are under the user eman_saad: 1.db. 2.chating_log. 3.female_brain. 4.male_brain. 5.orderss. But now i have this error: django.db.utils.OperationalError: (1203, "User eman_saad already has more than 'max_user_connections' active connections") PS: I am using django10, Python3.5,webfaction shared server,Mysql -
Issue with adapting Django REST Framework tutorial to Heroku application using Gunicorn
I've been working to create a basic API for a website concept I'm working on and am currently implementing step 5 (Relationships & Hyperlinked APIs) in the Django REST Framework tutorial. The code is located at this GitHub repo. Admittedly, this is my first time deploying stuff on Heroku, and not all of the DRF tutorial is relevant to my needs. When trying to access the site, I get the application error screen. My logs show the following: 2017-04-17T15:47:57.229168+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 126, in init_process 2017-04-17T15:47:57.229169+00:00 app[web.1]: self.load_wsgi() 2017-04-17T15:47:57.229167+00:00 app[web.1]: Traceback (most recent call last): 2017-04-17T15:47:57.229169+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 148, in load_wsgi 2017-04-17T15:47:57.229170+00:00 app[web.1]: self.reloader.add_extra_file(exc_val.filename) 2017-04-17T15:47:57.229171+00:00 app[web.1]: AttributeError: 'NoneType' object has no attribute 'add_extra_file' 2017-04-17T15:47:57.405030+00:00 app[web.1]: [2017-04-17 15:47:57 +0000] [4] [INFO] Shutting down: Master 2017-04-17T15:47:57.236765+00:00 app[web.1]: [2017-04-17 15:47:57 +0000] [9] [INFO] Worker exiting (pid: 9) 2017-04-17T15:47:57.405172+00:00 app[web.1]: [2017-04-17 15:47:57 +0000] [4] [INFO] Reason: Worker failed to boot. 2017-04-17T15:47:57.675763+00:00 heroku[web.1]: State changed from up to crashed 2017-04-17T15:47:57.659354+00:00 heroku[web.1]: Process exited with status 3 What is needed to fix this issue? It seems to be something with the starting of the gunicorn webserver. Sorry if it's light on diagnostic information; I'm not exactly sure what I'm looking at but can … -
Django and real time data from serial port
I have a little project and want to ask for some help. I have an raspberry pi, an other microcontroller, these connected through serial, and the Pi getting data every sec from microcontroller. I want to publish a webpage with real time data displaying. Is django recommended? Or what could be the best? The data processing made with pyserial, so I have the raw data which could be published. I just have problems with the web displaying. -
Django - User and User Profile not saving together
When I submit a sign up form which contains information for the user (username, email, password) and the user profile (first name and last name) and call save like form.save() and profileform.save() in my views.py then all seems to be fine and I get no errors. However, when I go into the Django Admin then I see that the user profile and the profile have saved separately. So there's two different profiles, one containing the username I entered into the form, and the other with first and last name (as the image displays). Here's my views.py: def signup(request): if request.method == 'POST': form = UserRegistrationForm(data=request.POST) profileform = UserRegistrationProfileForm(data=request.POST) if form.is_valid() and profileform.is_valid(): user = form.save() profileform.save() if user is not None: if user.is_active: user_login(request, user, backend='django.contrib.auth.backends.ModelBackend') return redirect('/dashboard/') else: form = UserRegistrationForm() profileform = UserRegistrationProfileForm() return render(request, 'signup-user.html', {'form': form, 'profileform': profileform}) Forms.py (for the profile part of the form): class UserRegistrationProfileForm(forms.ModelForm): user_fname = forms.CharField(#) user_lname = forms.CharField(#) class Meta: model = UserProfileModel fields = ['user_fname', 'user_lname'] def clean(self): #... def save(self, commit=True): profile = super(UserRegistrationProfileForm, self).save(commit=False) if commit: profile.save() return profile Models.py (for the profile, which includes the receiver signal): class UserProfileModel(models.Model): # For the Company Employees user = … -
Failed to deploy My second Django project under IIS
I have two web applications developped with Django1.6/python2.7. To deploy my applications, I'm using Windows Server-2008-R2 && IIS. My first project deployed with success under IIS. (I folloowed this tutorial: Tuto) Now when I'm trying to deploy my second project, I have the 500.0 Error (Error code 0x00000001). Locally my application works fine and the differences between the two projects are: In the first I have used the default website of the IIs server (like the tuto) In the second project I have grouped my applications under a folder named "apps" and serving my statistics file on assets. I don't know if that can affect the process of deployment on IIS. What can be the source of the problem ?? and how can I resolve it? -
Exception: 403 Forbidden when using soaplib.client from django
I get this error when i call the methode say_hello from WSDL : Traceback (most recent call last): File "", line 1, in File "/usr/lib/pymodules/python2.7/soaplib/client.py", line 172, in call raise Exception('%s %s'%(response.status,response.reason)) Exception: 403 Forbidden this is my url.py : url(r'^hello_world/', hello_world_service ,name='hello_world_service'), url(r'^hello_world/service.wsdl',hello_world_service,name='hello_world_service'), my views.py : from soaplib_handler import DjangoSoapApp, soapmethod, soap_types class HelloWorldService(DjangoSoapApp): __tns__ = 'http://my.namespace.org/soap/' @soapmethod(soap_types.String, soap_types.Integer, _returns=soap_types.Array(soap_types.String)) def say_hello(self, name, times): results = [] for i in range(0, times): results.append('Hello, %s'%name) return results hello_world_service = HelloWorldService() my soaplib_handler.py from soaplib.wsgi_soap import SimpleWSGISoapApp from soaplib.service import soapmethod from soaplib.serializers import primitive as soap_types from django.http import HttpResponse class DjangoSoapApp(SimpleWSGISoapApp): def __call__(self, request): django_response = HttpResponse() def start_response(status, headers): status, reason = status.split(' ', 1) django_response.status_code = int(status) for header, value in headers: django_response[header] = value response = super(SimpleWSGISoapApp, self).__call__(request.META, start_response) django_response.content = "\n".join(response) return django_response And this is my test it with a soaplib client: >>> from soaplib.client import make_service_client >>> from foo.views import HelloWorldService >>> client = make_service_client('http://localhost:8000/hello_world/service.wsdl', HelloWorldService()) >>> client.say_hello('John', 2) Any Help please !! -
how to design Django url pattern to avoid 301
I have a project called blog, the url pattern shows below. I want to make the app "posts" to route all the traffic. Url patterns of them shows below: #blog/urls.py from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('posts.url', namespace='posts')), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) #posts/url.py from django.conf.urls import url from django.contrib import admin from .views import ( home, down, get_data_by_post, ) urlpatterns = [ url(r'^$', home, name='down'), url(r'^api/$', ins_down, name='api'), url(r'^p/(?P<slug>[-\w]+)/$', get_data_by_post, name='slug'), ] When enter into home page, the home function in posts.views will generate some links with local data to render index.html. def home(request): final = get_local_suggest() return render(request, "index.html", final) Some of the code in index.html template likes below: <a href="p/{{ results.code }}?From=homepage" class="portfolio-link" target="_blank"> So in home page , some links will show there: "http://example.com/p/code?From=homepage But the tricky question here is that: when I click the url , the console of Django will print 301 like below. In browser, it will redirect from "/p/code" to "/p/code?From=homepage". Not Found: /p/code [17/Apr/2017 15:05:23] "GET /p/code?From=homepage HTTP/1.1" 301 0 There are must be something wrong with url pattern design, how to … -
Add filter automatically if get parameters in url is updated for every time
I have Post model that has multiple foreignkey. class Post(models.Model): category = models.ForeignKey(Category) location = models.ForeignKey(Location) price = models.DecimalField(max_digits=10, decimal_places=2) title = models.CharField(max_length=255) text = models.CharField(max_length=255) objects = PostQuerySet.as_manager() def __str__(self): return self.title class Category(models.Model): parent = models.ForeignKey('Category', related_name='children', null=True, blank=True) name = models.CharField(max_length=255) slug = models.SlugField() @property def dispatch(self): if not self.parent: return self else: return self.parent def __str__(self): return self.name class Location(models.Model): parent = models.ForeignKey('Location', related_name='children', null=True, blank=True) name = models.CharField(max_length=255) @property def dispatch(self): if not self.parent: return self else: return self.parent def __str__(self): return self.name class PostQuerySet(models.QuerySet): def filter_category(self, category): if not category.parent: return self.filter(category__in=category.children.all()) else: return self.filter(category=category) def filter_location(self, location): if not location.parent: # first return self.filter(location__parent__in=location.children.all()) else: if not location.dispatch.parent: # second return self.filter(location__in=location.children.all()) else: # third return self.filter(location=location) And I have filtering system like so: <p>[ Category ]</p> <ul> {% if request.GET.category %} <li><a href="{% url_remove request 'category' %}">All Categories</a></li> {% endif %} {% if big_cat %} <li><a href="?{% url_replace request 'category' big_cat.pk %}">{{ big_cat.name }} | {{ big_cat.pk }}</a></li> {% for small_cat in big_cat.children.all %} <li>---<a href="?{% url_replace request 'category' small_cat.pk %}">{{ small_cat.name }} | {{ small_cat.pk }}</a></li> {% endfor %} {% else %} {% for big_cat in big_cats %} <li><a href="?{% url_replace … -
how to cast the output of Count() in django to FloatField in django 1.8
I am using django 1.8 I have two models Query:- class Query(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) title = models.TextField() details = models.TextField() pub_date = models.DateTimeField('date published') post_score=models.FloatField(default=0.0) .... class Tags(models.Model): """docstring for Tags""" tagname=models.TextField() grouppostlist=models.ManyToManyField(Query,through='GroupPostsTag',through_fields=('tag','query')) and another model(it stores tags for a query) class GroupPostsTag(models.Model): query=models.ForeignKey('Query') tag=models.models.ForeignKey('Tags') Now I want to sort queries based on the sum of "number of tags" and query's "post_score". I am looking for something like this:- tagged_user_posts=Query.objects.filter(Q(tags__id__in=tags_list)).annotate(num_tags=Cast(Count('tags'),models.FloatField())).annotate(post_scores=F('num_tags')+F('post_score')).order_by('-post_scores') Cast is provided in django 1.10. So what alternative I can use? -
Sending email with attached file in Django
I am trying to send and email in Django forms with attached file, but i cant figure out how to send the file(uploaded by user) without saving it locally. I have my form: class PrintForm(forms.Form): contact_name = forms.CharField(required=True) contact_email = forms.EmailField(required=True) supervisor = forms.ChoiceField( choices=[(str(sup.email), str(sup.name)) for sup in Supervisors.objects.all()] ) file = forms.FileField() content = forms.CharField( required=True, widget=forms.Textarea ) and my view: def print(request): # context = dict() # context['printers'] = Printer.objects.all() # return render(request, 'threeD/print.html', context) if request.method == 'POST': form = PrintForm(data=request.POST, request = request) if form.is_valid(): contact_name = request.POST.get('contact_name', '') contact_email = request.POST.get('contact_email', '') form_content = request.POST.get('content', '') supervisor = form.cleaned_data['supervisor'] template = get_template('threeD/email/contact_template_for_printing.txt') context = Context({ 'contact_name': contact_name, 'supervisor': supervisor, 'contact_email': contact_email, 'form_content': form_content, }) content = template.render(context) subject = "New message" try: email = EmailMessage( subject, content, contact_email, [supervisor], headers={'Reply-To': contact_email} ) #email.attach(...) email.send() except: return "Attachment error" messages.success(request, "Thank you for your message.") return redirect('/index/print/') else: form = PrintForm(request=request) context_dict = {} context_dict['printers'] = Printer.objects.all() context_dict['form'] = form return render(request, 'threeD/print.html', context_dict) So in my view, when i am sending an email, is there a way to call email.attach(file) which would attached file to a mail and just send it, without locally saving … -
NoReverseMatch at /product/pussyes/ Reverse for 'basket_adding' not found. 'basket_adding' is not a valid view function or pattern name
NoReverseMatch at /product/pussyes/ Reverse for 'basket_adding' not found. 'basket_adding' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/product/pussyes/ Django Version: 1.11 Exception Type: NoReverseMatch Exception Value: Reverse for 'basket_adding' not found. 'basket_adding' is not a valid view function or pattern name. error with ajax and jquery this is my url in folder orders url(r'^basket_adding/$', basket_adding, name="basket_adding"), this is my views.py of prodcuts def product_view(request, slug=None): instance = get_object_or_404(Product, slug=slug) title = instance.name session_key = request.session.session_key if not session_key: request.session.cycle_key() forms = SubscribersForm(request.POST or None) if forms.is_valid(): instance = forms.save(commit=False) instance.save() return redirect("/") context = { "instance": instance, "title": title, "forms": forms, } return render(request, 'product.html', context) this is my views.py of orders def basket_adding(request): return_dict = {} session_key = request.session.session_key data = request.POST product_id = data.get('product_id') product_price = data.get('product_price') new_product = ProducInBasket.objects.get(session_key=session_key, product_id=product_id, product_price=product_price, quantity=quantity) return JsonResponse(return_dict) this is my models of orders class ProducInBasket(models.Model): session_key = models.CharField(max_length=128, default=None) order = models.ForeignKey(Order, blank=True, null=True, default=None) product = models.ForeignKey(Product, blank=True, null=True, default=None) count_of_goods = models.IntegerField(default=1) price_per_item = models.DecimalField(max_digits=10, decimal_places=2, default=0) total_price = models.DecimalField(max_digits=19, decimal_places=2, default=0) is_active = models.BooleanField(default=True) publish = models.DateField(auto_now=False, auto_now_add=True) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) def __str__(self): return "{0}:|:{1}".format(self.price_per_item,self.order) class Meta: ordering = ["-timestamp"] … -
Python2/Python3 selection django app at Ubuntu VPS
If there is VPS with system wide installed python2 and django virtualenv has python3, where is set which python to use? There is a pre-installed nginx/gunicorn configuration -
Heroku Database Irregularity
I am using the PostGres Hobby Dev plan. I've deployed my Django application (it's a social network). However, when the user interacts with the application, e.g. user x to follow user y. This changes the database, obviously, to record that x follows y. However, when I check the profile page, it sometimes says that x does not follow y. But then if I refresh the page, it changes back to x follows y. Is this a performance issue due to the fact that I am on the hobby dev plan? Thanks -
UnicodeEncodeError / python3
Can't solve typical issue with encodings. Cyrrlic text is received via post and error is raised 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128) The text key itself has a look and it must cyrillic text in russian: u'\u043f\u0440\u043e' After that error tried this way and some others: key = key.decode('ascii').encode('utf8') or : key = key.decode('ascii') Localy it works, error is raised in production only. Python system encoding in production is utf8 -
How to do Group by and count in Django rest framework
I am using Django==1.10.6 djangorestframework==3.6.2 I have tried so far but i am getting key error views.py from django.db.models import Func, F, Sum, Count from django.db.models.functions import TruncMonth class SalesReportViewSet(viewsets.ModelViewSet): queryset = imodels.Sales.objects.all() serializer_class = iserializers.SalesReportSerializer def get_queryset(self): data = imodels.Sales.objects.annotate(month=TruncMonth('date')).values('month').annotate(c=Count('id')).values('month', 'c') return data models.py class Sales(models.Model): orig_quantity = 0 product = models.ForeignKey(Product) sold_to = models.ForeignKey(Merchant) quantity = models.PositiveIntegerField() desc = models.CharField(max_length=255) date = models.DateTimeField() created_at = models.DateTimeField(default=datetime.now) serializers.py class SalesReportSerializer(serializers.ModelSerializer): class Meta: model = models.Sales #fields = ['id', 'quantity', 'total'] fields = '__all__' error i am getting KeyError at /sales-report/ "Got KeyError when attempting to get a value for field quantity on serializer SalesReportSerializer.\nThe serializer field might be named incorrectly and not match any attribute or key on the dict instance.\nOriginal exception text was: 'quantity'.