Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django admin returning whole object not just the FK field
I have searched and found a few answers however all the questions relate to the use of str etc... Im using the django admin module as it is interesting to play with and saves times, im having slight issues with my foreign keys in the sense they are returning all the field values not just the foreign key value. relevant models: class Order(models.Model): Order_ID =models.AutoField(primary_key=True) Dept_ID =models.ForeignKey(Department) Status =models.ForeignKey(Order_Statu) Order_Total =models.DecimalField(decimal_places=2, max_digits=5) def __str__(self): return '%s %s %s %s' % (self.Order_ID, self.Dept_ID, self.Status, self.Order_Total) class Order_Item(models.Model): Order_ID =models.ForeignKey(Order) Itm_Name =models.ForeignKey(Item) Quantity =models.IntegerField() def __str__(self): return '%s %s %s' % (self.Order_ID, self.Itm_Name, self.Quantity) and an example of what i mean: Screenshot im willing to admit that it is probably something i have overlooked in the documentation or it is something simple and obvious. -
How to query fields through an intermediate many to many field?
I use django 1.8 and python 2. What I have I have a model similar to this: from django.db.models import Model class Person(Model): name = models.CharField() class Unit(Model): unit_name = models.CharField() class PersonUnitRelType(Model): relation=models.CharField() class PersonUnitRelation(Model): person = models.ForeignKey(Person) unit = models.ForeignKey(Unit) I have a form similar to this: from django import forms from ceres.persons.models import Person, PersonUnitRelType, Unit class MForm(forms.Form): persons = forms.ModelMultipleChoiceField(Person.objects) units = forms.ModelMultipleChoiceField(Unit.objects) relations = forms.ModelMultipleChoiceField(PersonUnitRelType.objects) I have a view similar to this: from django.http import HttpResponseRedirect from django.shortcuts import render from .forms import MessageForm from ceres.persons.models import Person, PersonUnitRelType, Unit def messages(request): if request.method == 'POST': form = MessageForm(request.POST) if form.is_valid(): persons = form.cleaned_data['persons'] persons_list = [p.name for p in persons] relations = form.cleaned_data['relations'] for relation in relations: #TODO: Add all persons in 'relation' to persons_list units = form.cleaned_data['units'] for unit in units: #TODO: Add all persons in a unit witch have a 'relation' to persons_list. return HttpResponseRedirect("./") else: form = MForm() context = { 'form': form } return render(request, 'foo.html', context) What I want I want to add all names of persons to a list, whether they are selected direct, by a relation, or by a unit witch has a relation. How can I … -
Django admin add_view - prefill data with pk passed through URL
How to pre-fill Django NestedModelAdmin(inheriting from this class , not admin.ModelAdmin ) add_view with a model Object, I am passing Pk of that object in url. I can fetch the model object and prefill the fields but problem is ManyToManyRel and ManyToOneRel and OneToOneRel, some one please help me how I can solve this. I am using nested_inline Package for managing the Admin . No where it is mentioned how to handle these cases. I am using Django 1.9 and Python 2.7 -
Is there a way to exclude template url keyword arguments from view function definition?
I have a url in my template that's routed in this way: workoutcal/templates/calendar.html: <a href="{% url 'workoutcal:add' year=table.0 month=table.1 day=element.0 %}" class="add">Add workout</a> workoutcal/urls.py: url(r'^add/(?P<year>[0-9]+)/(?P<month>[0-9]+)/(?P<day>[0-9]+)/$', views.add, name = 'add'), #Adding a workout for the date in question. workoutcal/views.py: def add(request,year,month,day): return HttpResponse("This is the add page) If I replace add() with this: def add(request): return HttpResponse("This is the add page) I get an error: Traceback (most recent call last): File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) TypeError: add() got an unexpected keyword argument 'year' Meaning views.add had an unexpected keyword argument sent to it. Let's say that I want to pass these keyword arguments to the url in calendar.html because they're needed to get the correct url, but that I don't want to use these arguments in my view. Is there a way to exclude the arguments from the view function definition without getting this error? -
Type Error when using date from a Django form, I get: combine() argument 1 must be datetime.date, not tuple
I send a data dictionary to an external SOAP API using Zeep. I did this, and it was working: my_date = (form.cleaned_data['my_date']) #This comes from a Django form data2 = { "CashBookEntryData": { "Type" : "FinanceVoucher", "CashBookHandle" : { "Number" : 1 }, "AccountHandle" : { "Number" : 5820 }, "Date" : my_date, "VoucherNumber" : 100, "Text" : "Dagenssalg", "AmountDefaultCurrency" : 0, "CurrencyHandle" : { "Code" : "DKK" }, "Amount" : beloeb_salg, "DepartmentHandle" : { "Number" : 1 } } } To be able to better control how the dict is constructed, I have changed it to this: data1 =collections.OrderedDict() data1["CashBookEntryData"] = {} data1["CashBookEntryData"]["Type"] = "FinanceVoucher" data1["CashBookEntryData"]["CashBookHandle"] = { "Number" : 1 } data1["CashBookEntryData"]["AccountHandle"] = { "Number" : 5820 }, data1["CashBookEntryData"]["Date"] = my_date, data1["CashBookEntryData"]["VoucherNumber"] = 100, data1["CashBookEntryData"]["Text"] = "Dagenssalg", data1["CashBookEntryData"]["AmountDefaultCurrency"] = 0, data1["CashBookEntryData"]["CurrencyHandle"] = { "Code" : "DKK" }, data1["CashBookEntryData"]["Amount"] = 9999, data1["CashBookEntryData"]["DepartmentHandle"] = { "Number" : 1 } But now I get a Type Error: combine() argument 1 must be datetime.date, not tuple Any help is very appreciated! Best Regards Kresten Buch -
How to let a User upload an image in Django
Hi Guys I started coding in Django and i just wanted to make an 9gag-Clone. I followed some Tutorials and acctualy made a Blog. But when i "upload" Images it allways take the default value. So here is my Html: {% extends "posts/post_base.html" %} {% load bootstrap3 %} {% block post_content %} <h3 class="title">Poste Some Memes here</h3> <form action="{% url 'posts:create' %}" method="POST"> {% csrf_token %} {% bootstrap_form form %} <input type="submit" value="posten" class="btn btn-primary btn-large"> </form> {% endblock %} Here is my Views.py: class CreatePost(LoginRequiredMixin, SelectRelatedMixin, generic.CreateView): fields = ('title','picture','group') model = models.Post def form_valid(self, form): self.object = form.save(commit=False) self.object.user = self.request.user self.object.save() return super().form_valid(form) and at least my models.py: class Post(models.Model): user = models.ForeignKey(User,related_name='posts') created_at = models.DateTimeField(auto_now=True) title = models.CharField(max_length=30,default='Titel') picture= models.ImageField(upload_to=settings.MEDIA_ROOT, default='/static/img/default.png') title_html = models.CharField(max_length=30,default='Titel', editable = False) group = models.ForeignKey(Group,related_name='posts',null=True,blank=True) def __str__(self): return self.title def save(self,*args,**kwargs): self.title_html =misaka.html(self.title) super().save(*args,**kwargs) def get_absolute_url(self): return reverse('posts:single',kwargs={'username':self.user.username,'pk':self.pk}) class Meta: ordering = ['-created_at'] #unique_together = ['user','title','bild'] urls.py and other htmlfiles work correctly. everything was makemigrated and migrated I just need to know why it dont save the Images, or dont upload it. -
How can I access 'user_id' is in model?
I got an error ,KeyError: 'user_id'. I wrote from app.models import User class UserPropriety(): def __init__(self, sheet_path): self.file = glob.glob(sheet_path) self.user_propriety = {} def read(self): for x in self.file: if "$" not in x: book = xlrd.open_workbook(x) sheet = book.sheet_by_index(0) cells = [ ('corporation_id', 0, 4), ('name', 5, 3), ('age', 6, 3), ('work', 7, 3), ] user_propriety_origin = OrderedDict() for key, rowy, colx in cells: try: user_propriety_origin[key] = sheet.cell_value(rowy, colx) except IndexError: user_propriety_origin[key] = None if user_propriety_origin['corporation_id'] in self.user_propriety: self.user_propriety[user_propriety_origin['user_id']].update(user_propriety_origin) continue self.user_propriety[user_propriety_origin['user_id']] = user_propriety_origin def save(self): for row_number, row_data in self.user_propriety.items(): user = User.objects.filter(user_id=self.user_propriety['user_id']) ) is_work = self.convert_symbol_to_int(self.user_propriety[row_number]['job']) is_age = self.convert_symbol_to_int(self.user[row_number]['age']) if user: user.update( work=is_work, age=is_age, ) def convert_symbol_to_int(self, arg): if arg == '△': return 2 elif arg == '○': return 1 elif arg == '×': return 0 else: return -1 y = UserPropriety('./data/*.xlsx') y.read() y.save() I really cannot understand why I cannot access 'user_id' because I imported from app.models import User,so I think 'user_id can be used.How can I fix this?What should I write it?Is this caused the way of calling value? -
TypeError: list indices must be integers, not str (the for loop method works, the lambda expression method doesnt)
Hey I have a working code which is this : # two_days_ago_chatted_visitors = None # yesterdays_chatted_visitors = None # chat_count = None # for x in apichat_data_bydate: # if x["date"] == two_days_ago.strftime("%Y-%m-%d"): # two_days_ago_chatted_visitors = x['visitors_with_conversation_count'] # else: # yesterdays_chatted_visitors = x['visitors_with_conversation_count'] # chat_count = x['conversation_count'] But I have been instructed to make my code simpler, and use something like this: two_days_ago_str = two_days_ago.strftime("%Y-%m-%d") data_for_two_days_ago = filter(lambda data_for_day: data_for_day['date'] == two_days_ago_str, apichat_data_bydate) two_days_ago_chatted_visitors = data_for_two_days_ago['visitors_with_conversation_count'] yesterday_str = two_days_ago.strftime("%Y-%m-%d") data_for_yesterday = filter(lambda data_for_day: data_for_day['date'] == yesterday_str, apichat_data_bydate) yesterdays_chatted_visitors = data_for_yesterday['visitors_with_conversation_count'] chat_count = data_for_yesterday['conversation_count'] But now the new code does not work and gives an error. TypeError: list indices must be integers, not str -
Type error field_contents_foreign_linked in django suit
I have django 1.8 project where I'm using django-suit==0.2.25. When I want to add a new item, I get an error: TypeError at /admin/tours/tour/add/ unsupported operand type(s) for -: 'NoneType' and 'int' This code is highlighted in path ...venv/lib/python3.5/site-packages/suit/templates/admin/includes/fieldset.html, error at line 44: <span class="readonly"> {{ field|field_contents_foreign_linked }} </span> Please for any hint. I tried already this: https://github.com/darklow/django-suit/issues/638 but without success. -
How to build a system to handle MQTT broker and Django
I am planning to build a home automation system where IoT devices communicate with the MQTT broker.The system also involves a Django web server that serves API for ios/android devices. I will describe an example of what I want to implement. An API call is made from mobile app to Django server to turn ON a device. When such API request is made to Django, it should psuh 'Turn ON' data to IoT device via MQTT protocol. Also, IoT devices send some real time data to the MQTT broker. Upon receiving such data I want to send push notifications to a mobile app via apns/fcm. How can I implement this?. Will Django channels serve the purpose or should I code my Django server to act as an MQTT client?. Or is there any other methods to implement this. Any advice will be helpful. -
location settings for Django Uwsgi Nginx Configuration for production
Django settings STATICFILES_DIRS = [STATIC_DIR, ] STATIC_DIR = os.path.join(BASE_DIR, 'static') STATIC_ROOT = '/home/sandyman/production/django_project/assets/' STATIC_URL = '/assets/' local machine example file /home/sandyman/development/django_project/css/bootstrap.min.css Template {% load staticfiles %} href="{% static "css/bootstrap.min.css" %}" Production environment ran python manage.py collectstatic this succesfully created all files in sub directories of **/home/sandyman/production/django_project/assets/** e.g. /home/sandyman/production/django_project/assets/css/bootstrap.min.css ** NGING configuration **server { server_name sandyman.xyz www.sandyman.xyz ; location /static { alias /home/sandyman/production/django_project/assets/; } }** ** GET Request ** Request URL:http://www.sandyman.xyz/static/css/bootstrap.min.css Request Method:GET **Status Code:404 NOT FOUND** file bootstrap is located in /home/sandyman/production/django_project/assets/css/bootstrap.min.css Please assist me .. Ive tried many iterations of values for nginx location but no success -
How to query the bilaminar data in Django ORM?
I have two models: class AddressRegion(models.Model): name = models.CharField(max_length=8) class AvailableArea(models.Model): name = models.CharField(max_length=8) addressregion = models.ForeignKey(AddressRegion, default=1) In the template I want expediently to use the query models. If now I query the datas I only knows use a for-loop: addressRegions = models.AddressRegion.objects.all() for ar in addressRegions: availableArea = models.AvailableArea.objects.filter(availablearea = ar) Then do some method to gather them. Is there some simple method to do that? because I believe Django is kind to users. -
Model itself and nested Meta use the same list
Django 1.11.5 The problem with this code is that I have already created a list in the model (comment "Field list created"). Then in Meta nested class I'd like to use the same list. Is it possible not to create the list twice? utils.py def get_distinctive_fields(): """ By these fields a people can be distinguished from one another. """ field_list = ['last_name_ru', 'premarital_surname_ru', 'first_name_ru', 'patronymic_name_ru', 'nickname_ru', 'year_of_birth', ] return field_list models.py class Person(LoginRequiredMixin, models.Model): def get_composed_string(self): composed_string = "" field_list = get_distinctive_fields() # Field list created. for field in field_list: composed_string += value def __str__(self): return self.get_composed_string() class Meta: unique_together = get_distinctive_fields() # Failed to use already created list. -
Pycharm Debugger - Django - Frames Not Available
If I run the Debugger without running the server everything looks ok. If I connect to the server, in the window I have the message "Connected" . If I run an url in the browser it works as usual, ignoring the breaking points. I followed the steps from the Pycharm video: https://blog.jetbrains.com/pycharm/2017/08/develop-django-under-the-debugger/ -
How to Filter in DRF Serializer using a Self Referencing Recursive Field
Using Python 3.x and the Django Rest Framework. I have a serializer with a Recursive Field (on self) which works as expected. However, I need a way to initially filter the nested children it returns by active = True. I've tried different ways to filter children by active=True, but I'm unable to get this working on the nested children that are returned in the serializer. Here is what I have. class MenuListSerializer(serializers.ModelSerializer): url = serializers.HyperlinkedIdentityField(view_name='menu_detail') children = RecursiveField(many=True, required=False) class RecursiveField(serializers.Serializer): """ Self-referential field for MPTT. """ def to_representation(self, value): serializer = self.parent.parent.__class__(value, context=self.context) return serializer.data Model class Menu(MPTTModel, TimeStampedModel): name = models.CharField(max_length=100) active = models.BooleanField(default=1) parent = TreeForeignKey('self', null=True, blank=True, related_name='children') This is what I have tried with ListSerializer' object has no attribute 'queryset' However, I'm not even sure this would work. class MenuListSerializer(serializers.ModelSerializer): def __init__(self, *args, request_user=None, **kwargs): # try and filter active in chrildrend before query set is passed super(CatalogueListSerializer, self).__init__(*args, **kwargs) # print(self.fields['children'].parent) self.fields['children'].queryset = self.fields['children'].queryset.filter(active=True) url = serializers.HyperlinkedIdentityField(view_name='menu_detail') children = RecursiveField(many=True, required=False) 2nd, I have also tried filtering on the view changing the query set method, but this does not seem to take when it's a child! It runs on the parent only! def get_queryset(self, … -
How to save POST data with multiple checkboxes using Django ?
Django version=1.10.2 and python 2.7 Im learning django and trying to clone to-do list item like this Here is the models file for todo:- class Todo(models.Model): title = models.CharField(max_length=200) # text = models.TextField() completed = models.BooleanField(null=False,default=False) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title #this makes djangoadmin page show title inthe list The views file from django.shortcuts import render from models import Todo def index(request): todos = Todo.objects.all() context = { 'todos':todos } if request.method == 'POST': title = request.POST['title'] todo = Todo(title=title) todo.save() return render(request,'index.html',context) else: return render(request,'index.html',context) def show_completed(request): #show completed task only todos = Todo.objects.filter(completed=True) context = { 'todos': todos } return render(request, 'index.html', context) def show_active(request): #show active task list todos = Todo.objects.filter(completed=False) context = { 'todos': todos } return render(request, 'index.html', context) def clear_completed(request): #Delete the completed tasks Todo.objects.filter(completed=True).delete() todos = Todo.objects.all() context = { 'todos': todos } return render(request, 'index.html', context) def save_state(request): pass The template file "index.html" <!DOCTYPE html> <html lang="en"> <head> </head> <body> <h3>Todo List:</h3><hr> <form method="post" action="{% url 'index' %}"> {% csrf_token %} <input type="text" name="title" id="title"/> <input type="submit" value="submit" /> </form> <hr><br> <form method="post" action="{% url 'save_state'%}"> {% csrf_token %} <ul>{% for todo in todos %} <li> <input type="checkbox" name="completed" value="True" … -
Duplicate key error in django-treebeard using MP and node_order_by
I have an account system that has a nested group structure per account. Each Account consists of multiple users that each can have permissions based on the groups they are in (a User has the permissions of the group they are in and of all the children of that Group. My Group model looks as follows. It is basically coupled to an Account has a title and contains Users. Each Account has one "main"/root-level Group linked to it so we can easily access the tree for an Account class Group(MP_Node): node_order_by = ['title'] account = models.ForeignKey(Account, related_name='groups', verbose_name=_('account')) title = models.CharField(_('title'), max_length=255) users = models.ManyToManyField(User, related_name='groups', verbose_name=_('users')) When adding a new Account and corresponding "main"/root-level group for that Account I sometimes get the following error: IntegrityError: duplicate key value violates unique constraint "accounts_group_path_key" DETAIL: Key (path)=(003A) already exists. It looks like it has something to do with the title of a Group. When adding "LLL-MIDDLE" the error shoots, when adding "ZZZ-END" it does not. I can't seem to figure out what I'm doing wrong that is leading to this error popping up from time to time. Can anybody help me? -
Is it a good practice to use serializer as query parameters validators?
Serializer would not be used for its intended purpose of creating some django model but it would be used for query parameters validation, creation of filtering query to elasticsearch, swagger documentation describing API. from rest_framework import views, serializers, fields from rest_framework.response import Response class TestQueryParams(serializers.Serializer): id = fields.IntegerField(min_value=0) date = fields.DateField(format='%Y%m%d') class TestView(views.APIView): def get(self, request): qp = TestQueryParams(data=request.query_params) qp.is_valid(raise_exception=True) # parameters would not be used to create some model # but they would be used to get data return Response({'some': 'data'}) -
How does default_token_generator store tokens?
I recently built a Django-based authentication system using a tutorial. Within this System I created a token within a forms.py. This Token is then send (as a link) in an activation activation mail. from django.contrib.auth.tokens import default_token_generator token = default_token_generator.make_token(user) The view which receives the get request matches the token and the user-id supplied in this link and checks the token using: default_token_generator.check_token(user, token) This verifies that the token was sent though my site. But I don't understand the process. The token is unique but I don't seem to save the token somewhere? So how does check_token()verify the token? Also - is there any setting for the token_generator to set, how long the token should be valid? -
Unit test form with ImageField in django
I have model with ImageField. I am trying to write unit test to my form but it always raise error. Can someone say me where is my mistake? From error I understand that form is not valid. print str(form.errors) return me this: <ul class="errorlist"><li>image<ul class="errorlist"><li>This field is required.</li></ul></li></ul> Error: Traceback (most recent call last): File "/home/nurzhan/CA/slider/tests.py", in test_form_valid self.assertTrue(form.is_valid()) AssertionError: False is not true tests.py: def test_form_valid(self): self.image_file = open( os.path.join(BASE_DIR, 'static/images/test.jpg'), "rb" ) data = { 'image': self.image_file } form = ArticleForm(data=data) self.assertTrue(form.is_valid()) print data return me: {'image': <open file '/home/nurzhan/CA/static/images/test.jpg', mode 'rb' at 0x7efe24b47b70>} Also I tried to use this: data = { 'image': SimpleUploadedFile( self.image_file.name, self.image_file.read() ) } In this case print data return me {'image': <SimpleUploadedFile: test.jpg (text/plain)>} forms.py: class ArticleForm(forms.ModelForm): class Meta: model = Article fields = ('image',) def __init__(self, *args, **kwargs): super(SlideForm, self).__init__(*args, **kwargs) self.fields['image'].widget.attrs = { 'accept': 'image/png, image/jpeg, image/gif', 'id': 'image', } models.py: from django.db.models.signals import pre_save from django.dispatch import receiver class Article(models.Model): image = models.ImageField( upload_to='article/images/%Y/%m/%d/', blank=False, ) @receiver(pre_save, sender=Article) def delete_old_slide_image(sender, instance, *args, **kwargs): if instance.pk: article = article.objects.get(pk=instance.pk) if instance.image and article.image != instance.image: article.image.delete(False) -
Invoke a Javascript function in HTTPResponse
Following up on this SO answer, I am trying to run a JS on the page in HTTPResponse return HttpResponse("<script>alert('Yep, JS running.');window.location.href='/path/to/original/url'; parent.show_modal_form('" + json.dumps(my_list) + "');};</script>") But the js function is defined in the page referenced above and it tries to execute the script before loading (and not after loading) the page, and hence fails to find the function. Any ideas on how to make it execute after the window.location.href has loaded the page, so that it can find the js function being called ($(document).ready won't work because JQuery is also not loaded yet. I tried window.load but that also does not work (i.e it fails to find the javascript function) My use case is that the user performs an action in the Django Admin page, and as a result the user needs to see a modal dialog form on the same page (after executing some logic back in the view) -
How to connect Django to external DB without migrations
I would like to connect my DjangoApp to an external MySQL database. I don't want to make migrations to this table, I mean I don't want to create new tables ,just pull data. And my question is - how to do this ? If i add this table to DATABASES in my settings file then the console shows an error about mandatory migration. What can you recommend me ? Thanks in advance, -
Compute multiple model properties in one call
I have Django Model which have two properties: class M(Model): @property def p1(self): return process_result(SomeModel.objects.filter(val_gt=1)) @property def p2(self): return process_result(SomeModel.objects.filter(val_lt=1)) And both used in Django Admin list_lisplay = ('p1','p2',) I want to replace 2 database queries with 1, something like this class M(Model): def some_hook(self): res = SomeModel.objects.all() self.p1 = process_result(filter(lambda l:l.val > 10, res)) self.p2 = process_result(filter(lambda l:l.val < 10, res)) PS: problem with >10 or <10 is just an example for simplification, I only want to find a way how to define multiple properties with performing one common database query -
Django Best way to store price history of millions of products?
I am running a web scraping spider that scrapes nearly 1 million products on a daily basis. I am considering 2 approaches: 1) store all products prices history in one table product_id, date, price but this would yield a multi million records in this table. 2) store data in multiple tables & make separate table for each product. Table1: product_id, current_price Table_product_id: date, price Table_product_id: date, price Table_product_id: date, price But I will have nearly 1 million tables! -
NameError: name 'convert_symbol_to_int' is not defined
I got an error,NameError: name 'convert_symbol_to_int' is not defined when I run this code. I wrote class ReadData(): def __init__(self, sheet_path): self.book = xlrd.open_workbook(sheet_path) self.sheet = self.book.sheet_by_index(1) self.users = [] def read(self): for row_index in range(2, self.sheet.nrows): rows = self.sheet.row_values(row_index) if rows[1] != '' and rows[2] != '' and rows[4] != '': woman = convert_symbol_to_int(row[8]) man = convert_symbol_to_int(row[9]) def convert_symbol_to_int(self,arg): if arg == '○': return 2 elif arg == '×': return 1 elif arg == '△': return 0 else: return -1 x = ReadData('./data/excel1.xlsx') x.read() I really cannot understand why this error happens. Why can't I access convert_symbol_to_int?How should I fix this?