Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
how to rewrite django test case to avoid unpredictable occasional failures
I have a test case that's written exactly like this def test_material_search_name(self): """ Tests for `LIKE` condition in searches. For both name and serial number. """ material_one = MaterialFactory(name="Eraenys Velinarys", serial_number="SB2341") material_two = MaterialFactory(name="Nelaerla Velnaris", serial_number="TB7892") response = self.client.get(reverse('material-search'), {'q': 'vel'}) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data['count'], 2) self.assertEqual(response.data['results'][0]['name'], material_one.name) self.assertEqual(response.data['results'][1]['name'], material_two.name) My error message is : line 97, in test_material_search_name self.assertEqual(response.data['results'][0]['name'], material_one.name) AssertionError: 'Nelaerla Velnaris' != 'Eraenys Velinarys' - Nelaerla Velnaris + Eraenys Velinarys Then when i re-run without changing any code, it becomes successful. This error happens occasionally not always. I was wondering if there's a better way to achieve the objectives of the test case without having that weird failure once in a while. The frequency this error occurs is around 1 every 50 times I run the test. The typical test command I use : python manage.py test app_name.tests --keepdb -
Is there a way to maintain the serializer order?
If I write this order for AddressRegionDetailSerializer and AvailableAreaSerializer: class AddressRegionDetailSerializer(ModelSerializer): """ 地域详情(包含可用区域) """ availableareas = AvailableAreaSerializer(many=True, read_only=True) class Meta: model = AddressRegion fields = "__all__" class AvailableAreaSerializer(ModelSerializer): """ 可用地区 """ class Meta: model = AvailableArea fields = "__all__" There will report NameError issue: NameError: name 'AvailableAreaSerializer' is not defined in this line: availableareas = AvailableAreaSerializer(many=True, read_only=True) So, I must put the AvailableAreaSerializer in the front. But however in my idea, I want to write the Serializer as the Models order, I don't want to break this law. So, is there a simple way to maintain this order? -
Choose where to save the image when you call save_frame() in MoviePy
I'm using MoviePy to save a frame from an uploaded video (the specific function in MoviePy is save_frame() source). This works successfully, however I want the image to save in my media folder (Django's conventional folder for saving uploaded files). At the moment it saves in the project root (where manage.py is). There doesn't seem to be a settings file so I'm not sure how to change this. Any suggestions appreciated. -
Key Error - Synapse Documentation error - Django
I have a Django app and I am trying to integrate the synapse API into my project. I want to verify a user by added a CIP document and a verification or validation source through last 4 of ssn. I am using the api documentation and the github examples to try to get it to work, but I am getting an issue using the Synapse example in the github repo. A user is being created but the real issue is comming after the base document is added. It is sending the request to Synapse and then the error comes up for the day key.... Here is the error I am getting with trace: KeyError at /verify_profile/ 'day' Request Method: POST Request URL: http://127.0.0.1:8000/verify_profile/ Django Version: 1.11.5 Exception Type: KeyError Exception Value: 'day' Exception Location: /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/synapse_pay_rest/models/users/base_document.py in create, line 107 /Users/omarjandali/Desktop/Yap/Yap/general/views.py in ProfileVerification createUserSynapse(request) ... /Users/omarjandali/Desktop/Yap/Yap/general/views.py in createUserSynapse base_document = create_user.add_base_document(**options) ... /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/synapse_pay_rest/models/users/user.py in add_base_document return BaseDocument.create(self, **kwargs) ... /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/synapse_pay_rest/models/users/base_document.py in create birth_day=kwargs['day'], ... Here is my code in the views.py file: args = { 'email':str(currentUser.email), 'phone_number':str(currentProfile.phone), 'legal_name':str(legal_name), 'note': str(note), 'supp_id':str(supp_id), 'is_business':False, 'cip_tag':cip_tag, } create_user = SynapseUser.create(client, **args) print(create_user) # in order to verify the user and transfer money phone = … -
How to create a Event in Django-Scheduler while creating a Product or any Inserting data in any table?
I am a total newbie in Python and new on StackOverFlow. If I am missing something please let me know This is Django-scheduler App:- https://github.com/llazzaro/django-scheduler It giver various options to create events and occurrences Documentation is here:- http://django-scheduler.readthedocs.io/en/latest/ I have a model known as Product in Django. Which is defined as below `class Products(models.Model): product_choice = ( ('1' ,'sightseeing'), ('2','daytour'), ('3','activity'), ('3','experience'), ('4','rentals'), ('3','multidaytrip'), ) product_type = models.CharField(max_length=20,choices=product_choice, null=True) category = models.ForeignKey(Category, null=True) title = models.CharField(max_length=100, blank=True, default='') pic1 = models.ImageField(upload_to='media', default='media/ross-island-2.jpg') pic2 = models.ImageField(upload_to='media', default='media/ross-island-2.jpg') pic3 = models.ImageField(upload_to='media', default='media/ross-island-2.jpg') shared_code = models.BooleanField(blank=True, default=False) age_requirements = models.CharField(max_length=100, blank=True, default='') time_slots = models.CharField(max_length=100 ,blank=True, default='') location = models.CharField(max_length=100 ,blank=True, default='') duration = models.CharField(max_length=100 ,blank=True, default='') affiliated_institutions = models.CharField(max_length=100, null=True) includes = models.TextField(blank=True) excludes = models.TextField(blank=True) medical_requirements = models.CharField(max_length=100, blank=True, default='') perks_included = models.CharField(max_length=100, blank=True, default='') product_detail = models.TextField() vender_name = models.CharField(max_length=100, blank=False) user = models.ManyToManyField(settings.AUTH_USER_MODEL) vendor_id = models.IntegerField(blank=True) about_vender = models.TextField() price = models.IntegerField(default=0) child_price = models.IntegerField(default=0) infant_price = models.IntegerField(default=0) product_detail = models.TextField(blank=True) slug = models.SlugField(unique=True, blank=True) total_slots = models.IntegerField(blank=True, null=True) open_slots = models.IntegerField(blank=True , null=True) cancellation_policy = models.TextField(blank=True) def __unicode__(self): return str(self.title) def __str__(self): return str(self.title) ` I have installed the Django-Scheduler in my Django Application, however it is installed … -
Ideal Architecture for Django Projects
I'm getting into a rather extensive project and it popped into my head that I don't know what the accepted\proper architecture for a Django is these days. I'll describe what prompted this question. I am making a, what I think is a simple web site that, for all intents and purposes, is made for small companies, or even single entity LLC type companies. In this project the front page is a simple sell of the company with some additional access for customers and employees. Employees would log in, change\adjust\add contacts\companies\address etc. I have this part all done, and I was about to move on to the next part which is filling out of reports. This particular company will have two types of reports - consultation reports and service reports. Now with where I am right now, I could continue to build on the current app\template, or I could start another app. Staying within the current app would certainly seem to make things easier, but definetly not cleaner. So what do you all do? How do you structure your projects? What are the general accepted conventions for decisions like this? Thanks! -
Error in django 1.8.7 version with python 2.7.12
`` I am getting the following trackback message when I run command(python3 manage.py runserver) on ubuntu OS: Traceback (most recent call last): File "manage.py", line 10, in execute_from_command_line(sys.argv) File "/usr/lib/python3/dist-packages/django/core/management/init.py", line 354, in execute_from_command_line utility.execute() File "/usr/lib/python3/dist-packages/django/core/management/init.py", line 303, in execute settings.INSTALLED_APPS I am using the following version of django and python: Django 1.8.7 python: 2.7.12 Can someone please help me to resolve this issue? Because I tried it 10 times from google suggestion but didn't get the right answer. -
dot in `django-admin.py startproject myproject .`
I keep the question in mind when read through Django source codes for weeks. Start project with Django, django-admin.py startproject myproject . # a tailed dot in the end manage.py will be created outside the project folder. if without '.', manage.py will be included in project folders. How does the '.' work? -
is there a faster way to write similar test cases for Django views?
Basically I realise that I am writing a lot of test cases for views that are in this format def test_update_with_only_1_field(self): """ Tests for update only 1 field GIVEN the following shape and related are valid WHEN we update only with just 1 field THEN we expect the update to be successful """ shape_data = { 'name': 'test shape', 'name_en': 'test shape en', 'name_zh_hans': 'test shape zh hans', 'serial_number': 'test shape serial number', 'model_name': { 'some_field': '123' } } data = json.dumps(shape_data) response = self.client.post(reverse('shape-list-create'), data, 'application/json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) some_model = response.data['some_model'] new_some_field = '12345' data = json.dumps({'some_field': new_some_field, 'id': response.data['some_model']['id']}) response = self.client.put(reverse('some-model', args=[some_model['id']]), data, 'application/json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(new_some_field, response.data['some_field']) I need to do this for more than 10 times. Which I have already done so. the only difference each time, is the following phrases "some_model", "some-model", and "some_field" I was wondering if there's a faster way to do this. I can think abstractly two ways: create a template in a text editor that somehow can generate the final test case which I then copy and paste. I am using sublime text 3 though I am okay to switch to another text editor There's a way I can write … -
Django, how do you set the value of a field in a model to be a hash of one of the fields?
This is what my model looks like: class Alert(models.Model): hash = models.CharField(max_length=64, unique=True) raw_line = models.TextField() alert_datetime = models.DateTimeField() datetime_dismissed = models.DateTimeField(null=True) and when I create an Alert, I set the hash value as something. But, I read that I can effectively do this: hash = models.CharField(max_length=64, unique=True, default=some_hash_function) def some_hash_function(): ... return some_hash But the hash I want relies on raw_line, is it possible to have the function hash the raw_line and set it by default? -
How to move up and down
I'm trying to make a ship for alien invaders move up and down but can't seem to make it properly work without messing something up. With my code below what would I need to add? alien_invasion.py: import sys import pygame from settings import Settings from ship import Ship import game_functions as gf def run_game(): #Initialize pygame, settings, and screen object pygame.init() ai_settings = Settings() screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption("Alien Invasion") #Draw the ship ship = Ship(ai_settings, screen) #Start the main loop for the game. while True: #Watch for keyboard and mouse events gf.check_events(ship) ship.update() gf.update_screen(ai_settings, screen, ship) run_game() ship.py: import pygame class Ship(): def __init__(self, ai_settings, screen): """Initialize teh ship and set its starting position""" self.screen = screen self.ai_settings = ai_settings #Load teh ship image and get its rect self.image = pygame.image.load('ship.bmp') self.rect = self.image.get_rect() self.screen_rect = screen.get_rect() #Start each new ship at the bottom center of the screen self.rect.centerx = self.screen_rect.centerx self.rect.bottom = self.screen_rect.bottom # Store a decimal value for the ship's center. self.center = float(self.rect.centerx) # Movement flag self.moving_right = False self.moving_left = False def update(self): """Update the ship's postion based on the movement flag""" # Update the ship's center value, not the rect. if self.moving_right and …