Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What to return to django admin if user has not username or something else
In short i am doing online store and in django admin i display authenticated users 'username' but there not authenticated users. So if authenticated users will order something it's okay i have their data. But if unauthenticated users will order? What to show in django admin? If i will request from user only his name from this no result. Because we know django need full authorization models.py class Cart(models.Model): user = models.ForeignKey(User, null=True, blank=True) products = models.ManyToManyField(Product, through=CartProduct) class Meta: verbose_name = 'Cart' verbose_name_plural = 'Cart' def __str__(self): return self.user.username # That for authenticated users views.py class CartView(View): def get(self,request,*args,**kwargs): cart_id = request.session.get('cart_id') if cart_id == None: cart = Cart() cart.save() request.session['cart_id'] = cart_id cart = Cart.objects.get(id=cart_id) product_id = request.GET.get('product') delete_product = request.GET.get('delete') if product_id: product_instance = get_object_or_404(Product, id=product_id) amount = request.GET.get('amount') cart_product = CartProduct.objects.get_or_create(cart=cart, product=product_instance)[0] if delete_product: cart_product.delete() else: cart_product.amount = amount cart_product.save() return HttpResponseRedirect('/') -
@monthly cron job is not reliable
Our customer wants us to create a report every month. In the past we used a @monthly cron job for this task. But this is not reliable: The server could be down in this minute. Cron does not re-run those jobs If the server is up, the database could be unreachable in this moment. If the server is up and DB is up, there could be a third party system which is not reachable There could be software bug. What can I do, to be sure that the report gets created monthly? It is a django base web application -
I return Response with `status=HTTP_404_NOT_FOUND` but find the 201
In the views.py, I return Response with status=HTTP_404_NOT_FOUND: class CloudServerCreateAPIView(CreateAPIView): serializer_class = CloudServerCreateSerializer permission_classes = [] queryset = CloudServer.objects.all() def perform_create(self, serializer): return Response(data="There is no data left.", status=HTTP_404_NOT_FOUND, exception=Exception()) serializer.save() But when I request the API, I get HTTP 201 Created, not the 404: POST /api/user_productmanage/cloudserver/create/ HTTP 201 Created Allow: POST, OPTIONS Content-Type: application/json Vary: Accept { "expiration_time": "2017-12-11T11:11:11+08:00", "profile": "asdas", "buytime": 1, "availablearea": 2 } -
Celery beat process allocating large amount of memory at startup
I operate a Django 1.9 website on Heroku, with Celery 3.1.23. RabbitMQ is used as a broker. After restarting the beat worker, the memory usage is always around 497Mb. This results in frequent Error R14 (Memory quota exceeded) as it quickly reaches the 512Mb limit. How can I analyze what is in the memory at startup? I.e. how can I get a detail of what is in the memory when restarted? Here is a detail of memory consumption obtained with the beta Heroku log-runtime-metrics: heroku/beat.1: source=beat.1 dyno=heroku.52346831.1ea92181-ab6d-461c-90fa-61fa8fef2c18 sample#memory_total=497.66MB sample#memory_rss=443.91MB sample#memory_cache=20.43MB sample#memory_swap=33.33MB sample#memory_pgpgin=282965pages sample#memory_pgpgout=164606pages sample#memory_quota=512.00MB -
When I execute “python manage.py runserver",the following error occurs。Even a new project。
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x03DB6540> Traceback (most recent call last): File "C:\Users\cb229\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Users\cb229\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\commands\runserver.py", line 149, in inner_run ipv6=self.use_ipv6, threading=threading, server_cls=self.server_cls) File "C:\Users\cb229\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\servers\basehttp.py", line 164, in run httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=ipv6) File "C:\Users\cb229\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\servers\basehttp.py", line 74, in __init__ super(WSGIServer, self).__init__(*args, **kwargs) File "C:\Users\cb229\AppData\Local\Programs\Python\Python36-32\lib\socketserver.py", line 453, in __init__ self.server_bind() File "C:\Users\cb229\AppData\Local\Programs\Python\Python36-32\lib\wsgiref\simple_server.py", line 50, in server_bind HTTPServer.server_bind(self) File "C:\Users\cb229\AppData\Local\Programs\Python\Python36-32\lib\http\server.py", line 138, in server_bind self.server_name = socket.getfqdn(host) File "C:\Users\cb229\AppData\Local\Programs\Python\Python36-32\lib\socket.py", line 673, in getfqdn hostname, aliases, ipaddrs = gethostbyaddr(name) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc4 in position 0: invalid continuation byte -
django: UnboundLocalError local variable referenced before assignment
I'm trying to make a social web app with django. I made a form that a user can use to answer a question. Everything worked fine but when I submit form without any content (empty form), I got an error (Unbound Local error "local variable 'new_answer' referenced before assignment". I'm new to django and I don't know much about this so any help will be very kind. here is my view code: def question_detail(request, pk): question=get_object_or_404(Question, pk=pk) #list of active answers for this question answers = question.answers.filter(active=True) answer_form = AnswerForm() if request.method=='POST': #a comment was posted answer_form = AnswerForm(data=request.POST or None) if answer_form.is_valid(): new_answer= answer_form.save(commit=False) new_answer.question = question u=request.user new_answer.name = u new_answer.save() else: answer_form = AnswerForm() new_answer = False question_tags_ids = question.tags.values_list('id', flat=True) similar_questions = Question.objects.filter(tags__in = question_tags_ids)\ .exclude(id=question.id) similar_questions = similar_questions.annotate(same_tags=Count('tags'))\ .order_by('-same_tags','-created')[:4] return render(request,'dashboard/post/detail.html', {'question':question, 'answer_form':answer_form, 'new_answer': new_answer, 'similar_questions':similar_questions}) -
Django how to build my query?
I have a form where there is an HTML tag <select> and 2 <option> : True or False. In my view, I built a simple query according to the value returned., for exemple for in the case of returning True : Test = Relation.objects.filter(field=True) It's working fine for True or False because this is a boolean field in my model. Now I would like to make a new <option> to filter True and False, to return all results. Off course I could make : Test = Relation.objects.all() But for a technical reason and because it's just a simple exemple here, I'm looking for a synthax like : Test = Relation.objects.filter(field=*) or : Test = Relation.objects.filter(field=all) This kind of synthax does exist ? Thank you -
How to save objects in django directly to data base?
I'm using django 1.11 python 3.5 and postgresql on ubuntu 16. I'm trying to build something like sports event website. It's consist of 2 parts: Django app. Python script that inserting new objects to django database with events. Code for inserting: get information about max primary key, pk = z INSERT INTO events_event VALUES pk = z, event_name = name .... In this part, everything works correctly. But, when I trying to save objects from django admin, I see an error: IntegrityError at /admin/events/event/add/ duplicate key value violates unique constraint "events_event_pkey" DETAIL: Key (id)=(7) already exists. What is an issue with this problem? How should I organize my code so I can save a lot of objects to a database? -
Django- URLs Regex UUID & Phone numbers
How to support both uuid and phone numbers having +- signs in Django URLs? Currently, for uuid, I've url(r'^(?P<uuid>[0-9A-Fa-f-]+)/$', view_name.as_view()), And for phone number, url(r'^(?P<msisdn>[0-9A-Fa-f-]+)/$', view_name.as_view()), How to have a regex supporting both uuid and phone numbers? PS:- One option is to support every character (.*), but that's a bad practise. -
Django - Deserializing JSONField in DRF
I've a JSONField in model, lets say x. I'm using DRF to save the model instance. Serializer:- class ABCSerializer(serializers.ModelSerializer): class Meta: model = ABC fields = ('x', ) def create(self, data): instance = ABC.objects.create(**data) instance.x = {'key': 'value'} instance.save() When I POST the data, the response returned by creating the object is correctly deserialized, ie { 'id': 1, 'x': { 'key': 'value' } } However, when I GET the data using the id, it return x as str, ie { 'id': 1, 'x': "{\"key\": \"value\"}" } How can I properly deserialize the data back to json? -
Django unable to create instance
so I am trying to problematically create instances but I keep getting this error. The error occurs on the last line rec.save() while I try to makemigrations. It works fine without rec.save() line. I have tried Users.objects.create_user(username="xy",password="password123") and also flushing the database having taken out the rec.save() line. django.db.utils.IntegrityError: NOT NULL constraint failed: catalog_company.modif ied_by_id here is my code from django.db import models from django.contrib.auth.models import User, UserManager from datetime import date import datetime from django.urls import reverse #Used to generate URLs by reversing the URL patterns from django.core.validators import MaxLengthValidator from simple_history.models import HistoricalRecords from simple_history import register register(User, inherit=True) class Company(models.Model): """ Model representing a company invested in. """ name = models.CharField(max_length=200) #details group=models.CharField(max_length=15, default='EQD') stake = models.CharField(max_length=50, blank=True) partners = models.CharField(max_length=50, blank=True) #user details modified_by = models.ForeignKey(User,related_name='Project_modified_by') modified_date = models.DateTimeField(auto_now=True) #to keep records history = HistoricalRecords(inherit=True) def __str__(self): """ String for representing the Model object. """ return self.name def get_form_url(self): """ Returns the url to access the form to change model attributes. """ return reverse('forms', args=[str(self.id)]) def attrsetter(self,attr,value): """ set attribute of an instance """ return setattr(self, attr, value) @property def _history_user(self): #to track who modified return self.modified_by @_history_user.setter #to track what was modified def _history_user(self, value): … -
Linking multiple model relationships with views in django
I have a project with a custom user model, users can login and create a company, this all works fine. Now I want everything else in the project linked to the company they created, ie leads for that company. THe first layer linking the user to the company works great, but now combining the third layer seems to be not working. Here is the code and then what I want it to do follows. The link from my template <li><a href="{% url 'nodiso:leadlist' pk=company.id %}">Sales</a></li> The URl url(r'^leads/(?P<pk>\d+)/$', views.LeadListView.as_view(), name='leadlist'), The View class LeadListView(LoginRequiredMixin, generic.ListView): login_url = '/scrty/login/' template_name = "nodiso/leadslist.html" model = models.Leads def get_queryset(self): return models.Leads.objects.filter(company=self.pk) The Model class Leads(models.Model): company = models.ForeignKey(Company) name = models.CharField(max_length=265) email = models.EmailField(max_length=265) tel = models.IntegerField() dateenq = models.DateField() So basically I am trying the create a list view for leads, but it should only be the leads linked to the company, I also would like to somehow display information regarding the company in the views for leads. Basically linking but also combining bot the views with each other. Not sure if my approach is correct at all. -
How to show the chart made by C3PyO through django to html?
when I ran this function the chart will show on ie browser not result.html. There isn't anything info about C3PyO in internet so I came here to ask. How to show the chart on result.html? views.py import C3PyO as c3 def chart(nominal_data): chart = c3.PieChart() chart.plot((nominal_data['男']/nominal_data['男']+nominal_data['女']), label='man') chart.plot((nominal_data['女']/nominal_data['男']+nominal_data['女']), label='woman') chart.show() return render(request, 'result.html',{'nominal_data': nominal_data,"chart":chart}) result.html <!DOCTYPE html> <html> </script> <head> <title>I come from template!!</title> <style> body { background-color: pink; } em { color: white; } </style> </head> <body> <h1>Hello World!</h1> {{chart}} <h1><em>{{nominal_data}}</em></h1> </body> </html> -
The logic in GenericView verbose Serializers
I browse the Rest Framework: In the Generic Views : When create there is a perform_create method: def perform_create(self, serializer): serializer.save(user=self.request.user) And in the Serializer: class UserSerializer(serializers.ModelSerializer): profile = ProfileSerializer() class Meta: model = User fields = ('username', 'email', 'profile') def create(self, validated_data): profile_data = validated_data.pop('profile') user = User.objects.create(**validated_data) Profile.objects.create(user=user, **profile_data) return user There is also create method. they all can give us chance to do other logic. But however, we do our logic in which one is better? -
Django rest with cross domain
I have two projects. One of them Django rest api and its includes my APIs and the other one is pure html project. I simply want to connect to my APIs from the html page using javascript. For example; i try to login my APIs with that javascript code: function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); $.ajax({ type: "POST", url: "http://0.0.0.0:8001/api-auth/login/", data: { username : 'admin', password : 'admin123', }, sucess: function() { console.log("Success!"); }, contentType: "application/json; charset=utf-8", dataType: "json", crossDomain:false, beforeSend: function(xhr, settings) { xhr.setRequestHeader("X-CSRFToken", csrftoken); }, }); and here it is my cors customization in settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', … -
Can django field access model class's meta information?
Question: Can Django field in model class access model's meta information? like this: # fields.py from django.db.models import Field class CustomField(Field): def check(self, **kwargs): # Here, can I get Post model's meta information? # models.py from django.db import models from fields import CustomField class Post(models.Model): title = CustomField() When CustomField is called in model class, it'll call check method in CustomField, then can I get Post class's Meta information (usually Post._meta)? I would like to distinct what database is used when CustomField is used. I can get all the list of connections through django.db, but I'd like to know model class's DATABASE connection information not all the connections. -
Django: Generics with different serializer and deserializer
I have a feeling that I'm thinking about this in the wrong way. Say we wanted to make a request with an integer and then a response with a charField. Would I need to use two serializers, one for the input, and then one for the output? -
ReactJS send POST/PUT request and get CSRF token missing or incorrect
I'm new to learn ReactJS and Django. I set CSRF_COOKIE_HTTPONLY:True, and get CSRF token missing or incorrect message after sending POST/PUT from my front-end(developed by ReactJS). The reason is I can not get CSRF-token from cookie. By searching related topics, the solutions are all used document.cookie('csrftoken') to get token. My question is ... how to get token without cookie? This DFX problem stocks me for a long time. Thanks :) -
How to filter list of values from Table?
Consider I have model called DemoModel which consists of field named demo_field of type Char Field. Now i have to query on the demo_field which has null values and 'demo'. Example: Class DemoModel(models.Model): demo_field = models.CharField(max_lenght=20) I have tried to query like DemoModel.objects.filter(demo_field__in=[None,"demo"]) but i am able to get only records which having value as "demo". I want to query it in single line is it possible? or anyother ways -
CRITICAL WORKER TIMEOUT error on gunicorn django
I am trying to tarined word2vec model and save it and then create some cluster based on that modal, it run locally fine but when I create the docker image and run with gunicorn, It always giving me timeout error, I tried the described solutions here but it didn't workout for me I am using python 3.5 gunicorn 19.7.1 gevent 1.2.2 eventlet 0.21.0 here is my gunicorn.conf file #!/bin/bash # Start Gunicorn processes echo Starting Gunicorn. exec gunicorn ReviewsAI.wsgi:application \ --bind 0.0.0.0:8000 \ --worker-class eventlet --workers 1 --timeout 300000 --graceful-timeout 300000 --keep-alive 300000 I also tried worker classes of gevent,sync also but it didn't work. can anybody tell me why this timeout error keep occuring. thanks Here is my log Starting Gunicorn. [2017-11-10 06:03:45 +0000] [1] [INFO] Starting gunicorn 19.7.1 [2017-11-10 06:03:45 +0000] [1] [INFO] Listening at: http://0.0.0.0:8000 (1) [2017-11-10 06:03:45 +0000] [1] [INFO] Using worker: eventlet [2017-11-10 06:03:45 +0000] [8] [INFO] Booting worker with pid: 8 2017-11-10 06:05:00,307 : INFO : collecting all words and their counts 2017-11-10 06:05:00,309 : INFO : PROGRESS: at sentence #0, processed 0 words, keeping 0 word types 2017-11-10 06:05:00,737 : INFO : collected 11927 word types from a corpus of 1254665 raw words … -
Mysql not connecting with Django 1.11.7 using python 3.6
I am using python 3.6 and install django 1.11.7. Its working fine with Oracle and Sqlite3. But not working with mysql. To connect with mysql tried to install package Mysql-python but it showing error: ***Collecting MySQL-python Using cached MySQL-python-1.2.5.zip Complete output from command python setup.py egg_info: Traceback (most recent call last): File "", line 1, in File "/tmp/pycharm-packaging168/MySQL-python/setup.py", line 13, in from setup_posix import get_config File "/tmp/pycharm-packaging168/MySQL-python/setup_posix.py", line 2, in from ConfigParser import SafeConfigParser ModuleNotFoundError: No module named 'ConfigParser' ----------------------------------------*** I guessed that i should download ConfigParser. But configparser itself showing error: Collecting configparse No matching distribution found for configparse equirement configparse (from versions: ) Now i am stuck. Please Help -
How to pass information about the field data type to the frontend when using Django Rest Framework?
Am using django rest framework 3.6 The frontend library I am using is x-editable, it requires knowledge of the datatype of the field. I am currently fetching my data using Django Rest Framework and Serializers. I have googled about Serializer Field but I have difficulty understanding if it fits my requirements. Also I have no idea how to go about testing if it fits. Basically I have a endpoint that attempts to fetch a single instance of SomeModel and its 5 related models. /api/v1.0/shape/2508 This works okay and I get back a data structure that's like this: { "data": { "art_numbers": [], "collection": "", "extra_number": "", "some_related_model1": { "finished_capacity": null, "finished_weight": null, "finished_width": null, "id": 3 }, "has_associated_product_variant": false, "id": 2508, "another_related_model": { "bar_height": null, "bar_number": "", "id": 3, } } } Is there a way for django restframework to also pass in some metadata about the related model fields? like data type? -
Django-graphene mutation error: unexpected argument
I'm learning graphene-python with django-graphene and I have a problem with a mutation. I defined a mutation class: class CreateLink(graphene.Mutation): id = graphene.Int() url = graphene.String() description = graphene.String() class Input: url = graphene.String() description = graphene.String() @staticmethod def mutate(root, input, context, info): link = Link( url=input.get('url'), description=input.get('description') ) link.save() return CreateLink( id=link.id, url=link.url, description=link.description, ) And this a screenshot in GraphiQL with my query and response with error. I don't understand why keyword 'url' is unexpected if I defined it in Input subclass of the mutation? -
Chat Application in Django
I'm trying to create a messaging app. This is what I did so far. Here's my model, class Message(models.Model): sender = models.ForeignKey(User, related_name="sender") receiver = models.ForeignKey(User, related_name="receiver") msg_content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) Now I can filter the messages between request.user & any user but couldn't re-order the messages based upon the fact that if request.user sends someone a message the person whom he send a message his name should appear at the top or if some send a message to request.user his name should appear at the Top. As we see on social networks. This is what I tried, users = User.objects.filter(Q(sender__receiver=request.user) | Q(receiver__sender=request.user)).annotate(Max('receiver')).order_by('-receiver__max') This code is working fine only when request.user sends someone a message, whom request.user sends a message his name re-orders at the Top but It's not changing the ordering of messages in case if someone sends a message to request.user. I also tried, users = Message.objects.filter(sender=request.user, receiver=request.user).order_by("created_at") But, I could't filter out the distinct users. It's showing equal number of users as messages. How can I solve this issue? Thank You! -
How to get datetime_difference with django queryset?
I have 3 models: class Store(models.Model): title = models.CharField(u'Store_Title', max_length=100) class OrderExtra(models.Model): order = models.OneToOneField(Order, verbose_name=u'Order') store = models.ForeignKey(Store) class Order(models.Model): code = models.IntegerField(u'Order_Code') datetime_begin = models.DateTimeField(null=True) datetime_end = models.DateTimeField(null=True) I also have a queryset that returns me all of my stores with count of orders in each store: qs = Order.objects.values('orderextra__store__title').annotate(orders_count=Count('code')) As a result I get: qs[0] = {'orders_count': 500, 'orderextra__store__title': u'MyTestStore 1'} qs[1] = {'orders_count': 200, 'orderextra__store__title': u'MyTestStore 2'} What I want is an orm queryset or native sql query for doing something like this: For 'MyTestStore 1' there are 500 orders, each of that orders has datetime_begin and datetime_end. For each of that 500 orders I want to calculate difference: diff = datetime_end - datetime_begin. As a result I will get 500 diff's. Next step is to calculate this: diff1 + diff2 + diff3 + diff500 / 500 (get average from all diff's). And as final result of queryset I want to get: qs[0] = {'orders_average_diff': 7.3 (minutes), 'orderextra__store__title': u'MyTestStore 1'} qs[1] = {'orders_average_diff': 4.2 (minutes), 'orderextra__store__title': u'MyTestStore 2'} Is there a way to accomplish this ? Thank you.