Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python attach list of dict to another dict as new key
I have two lists. First one (list a) contain lists of dicts and every list represent comments from the specific post. They all have the same 'id' value. Second list (list b) contain dicts only and these dicts are posts. Now I need to create new key named 'comments' for every dict in b_list and assign appropriated list from a_list as value. So targeted list is the one where dict['id'] are the same values as post value. a_list=[ [{'id':'123', 'user':'Foo'}, {'id':'123','user':'Jonny'}, ...], [{'id':'456', 'user':'Bar'}, {'id':'456','user':'Mary'}, ...], ... ] b_list=[{'post':'123','text': 'Something'}, {'post':'456': 'Another thing'}, ...] What will be the best and more pythonic way then to do that? -
Get a foreign key details when getting the primary table data in Django rest framework
I am trying out Dajngo rest framework. I am trying to build the student database. I have following data models class MasterSchool(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) country = models.CharField(max_length=100) state = models.CharField(max_length=100) city = models.CharField(max_length=100) pin_code = models.IntegerField(default=0) class StudDetails(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True, blank=True) grade = models.IntegerField(default=0) deleted = models.NullBooleanField(default=0, blank=True, null=True) school_id = models.ForeignKey(MasterSchool, related_name="school_id", null=True, blank=True) So when I do a GET of student details I want to get the details of the school which he/she belongs to for that I have a serialized as shown below. class MasterSchoolSerializer(serializers.ModelSerializer): class Meta: model = MasterSchool fields = ('id', 'name', 'country', 'state', 'city', 'pin_code') class StudDetailsSerializer(serializers.ModelSerializer): school_id = MasterSchoolSerializer(read_only=True) class Meta: model = StudDetails fields = ('id', 'name', 'created_at', 'school_id') depth = 1 which gives all the details of the student along with the school details. But when I have to do a post since I have read_only true in StudDetailsSerializer for school_id, I am not able to provide school id when I am doing a post. What I have done now is I have 2 serializer classes one as shown above and another one as shown below. class StudDetailsSerializer(serializers.ModelSerializer): class Meta: … -
Django : form validation in client side?
I have two questions. I made certain view accept POST request only through ajax(Not general POST request) I'm using Form and realized that If I used ajax, I could not use django built-in form validation. In this case, do I have to make my own validation for all fields in javascript?. I think that it is kinda time-consuming and redundant thing. Any alternatives? 2. Is it ok for view to accept only ajax POST request? I mean, I do something like this: def post(self, request, *args, **kwargs): if request.is_ajax(): # return response else: # give HTTP404 Is it bad practice? Once the view accept ajax request, does it always accept general HTTP request, too? Thanks. -
dropzone.js and django: unable to redirect
I'm using a dropzone to let a user upload a .csv file. Once a POST request is issued, I'm doing something with it and then I want to redirect to the home page. This works perfectly when I use a simple form like this: <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="myfile"> <button type="submit">Upload</button> </form> if request.method == 'POST' and request.FILES['myfile']: myfile = request.FILES['myfile'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) return render(request, 'accounting/home.html') This works, and renders the view I want. However when I use dropzone, a GET request is issued, but doesn't actually render the view. This is the problematic code: <form action="{% url 'accounting:index' %}" method="POST" id="my-dropzone" enctype="multipart/form-data" class="dropzone dz-clickable"> {% csrf_token %} <div class="dz-message">Drag and drop your .csv file here, or click to upload.</div> </form> <button class="btn-margin btn-primary btn center-block" type="submit" id='submit-all'> <i class="glyphicon glyphicon-upload"></i> <span>Upload!</span> </button> if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) # do something here return render(request, 'accounting/home.html') return render(request, 'accounting/home.html') What could possibly be the problem? -
How can I get the current logged in user from a django-oauth-toolkit token?
I'm using Django and django-oauth-toolkit to build a generic OAuth2 Authorization Server for Auth0. I plan to use the Django server to authenticate users to several different services, using Auth0 as an intermediary. I have a view that is called after an application has authenticated, and I need that view to return the details of the currently logged-in user. urls.py: # Return current logged in user (r'^user/current/?$', 'my_app.views.current_user.get_user', {}, 'current_user'), views/current_user.py: import json from django.http import HttpResponse from oauth2_provider.decorators import protected_resource @protected_resource() def get_user(request): user = request.user return HttpResponse( json.dumps({ 'username': user.username, 'email': user.email}), content_type='application/json') request.user is returning AnonymousUser, instead of the user that the token belongs to. How can I access the Django user associated with a token issued by django-oauth-toolkit? -
Correct way to run some code when the is_active field is changed to false on a Django User?
Is this the correct way to run some code when the is_active field is changed to false on a Django User? def check_is_active(sender, instance, **kwargs): if instance.id: old = sender.objects.get(pk=instance.id) if old.is_active != instance.is_active and not instance.is_active: # code goes here pre_save.connect(check_is_active, User) -
Is there any reason to use "if not ***.filter().exists(): ***.create()" instead of "***.get_or_create()"?
I can not find the answer, would it be faster to use: if not Model.objects.filter(*some_data*).exists(): Model.objects.create(*some_data*) then: Model.objects.get_or_create(*some_data*) Does anyone know? -
How work filter__in in Django
I wonder how works django filter in this case. My Post Model contains a tags fields. Post_tags_ids return list tags's id. I filter the published Post with specified id's tags (for example sport, swim). Next serach similar Posts contains the same tag that current Post. So... How first similar_posts return repeated Post in List ?? How look SQL query ? Example my case: first similar_post query for Post1 set up return [Post4,Post4,Post2,Post3] Filter iterate for each single tag ? Post1 - tags: swim, sport Post2 - tags: swim, ski Post3 - tags: run, sport Post4 - tags: swim, sport. class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Roboczy'), ('published', 'Opublikowany'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') objects = models.Manager() published = PublishedManager() tags = TaggableManager() Query def postLis(self): post = get_object_or_404(Post, slug=post, status='published', publish__year=year, publish__month=month, publish__day=day) post_tags_ids = post.tags.values_list('id', flat=True) similar_posts = Post.published.filter(tags__in=post_tags_ids)\ .exclude(id=post.id) similar_posts = similar_posts.annotate(same_tags=Count('tags'))\ .order_by('-same_tags', '-publish')[:4] -
How to run django application in background
I have a Django application that send emails to customers. I want this application to be run in background every certain time, is like a job/quote process. What could be best way to do this with python/Django? -
Using django inline formset for models in an attempted normalized database
I have a pretty simple Address model: class Address(models.Model): city = models.CharField(max_length=50) state = models.CharField(max_length=50) zip_code = models.CharField(max_length=50) address_line_one = models.CharField(max_length=50) address_line_two = models.CharField(max_length=50, null=True, blank=True) contact = models.CharField(max_length=50, null=True, blank=True) phone = models.CharField(max_length=50) fax = models.CharField(max_length=50, null=True, blank=True) created_at=models.DateField(auto_now_add=True) updated_at=models.DateField(auto_now=True) def __str__(self): return self.city I have a group (like a business) that has two types of addresses: Mailing and Billing. Sometimes the group has a billing company, which then would use the address attached to the company. I only wanted to store addresses in one table hence this model. Though it is proving to make designing the UI complicated to me. I think I am wanting an inline formset? Basically I need this: The Group has a form where you can enter its name and all its data, AND it has a space to enter the mailing address, and the billing address. (if the billing address is checked a jquery takes over and lets you instead attach a billing company id). So is this indeed a case for inline formsets? Or a nested formset? I found a tutorial on this, but it seemed complex for what I needed with the BaseLinkFormSet (I guess FormSet)class it created: http://whoisnicoleharris.com/2015/01/06/implementing-django-formsets.html also again … -
Django App Requires Different Version Dependency Than Project
I am currently writing a Django app to integrate into a larger project. For the app, I need some python package (call it 'package-a') with version 1.0. However, the project that I am trying to add the Django app to already requires package-a, but with version 1.2. The functionality that I need in my app is only available in version 1.0. Is there a way to add this app to the project with version 1.0 of package-a while the main project still uses version 1.2? -
Django ["'' value must be either True or False."]
I am having problems with Django. I created models. class CommentLike(models.Model): commentLike = models.ForeignKey(Comment) like = models.BooleanField() Now i am not able to migrate cause it throws me an error: django.core.exceptions.ValidationError: ["'' value must be either True or False."] How to fix this problem? I really need to know how to migrate database. -
FilteredSelectMultiple widget not working in 1.10.1 (Works in 1.8)
I am using a FilteredSelectMultiple widget from django.contrib.admin.widgets for a ModelMultipleChoiceField. This works great in my django 1.8 environment, but when I try it with 1.10.1, it fails to render the addEvent tag after the select. from forms.py class UserCatForm(forms.ModelForm): """Form to select Categories for user""" form_errors = {"required": "You must choose at least one expense category"} cats = forms.ModelMultipleChoiceField( error_messages=form_errors, label="", queryset=Categories.objects.all(), widget=FilteredSelectMultiple("Categories", is_stacked=False, attrs={'class':'form-control'}), ) class Meta: name = 'UserCatForm' model = UserCat fields = "__all__" widgets = {'user':forms.HiddenInput(),} base.html {% load staticfiles %} <html> <head> {% load bootstrap3 %} {% bootstrap_css %} {% bootstrap_messages %} <link rel="stylesheet" href="{% static 'css/budget.css' %}"> <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" /> <link rel="stylesheet" type="text/css" href="/static/admin/css/widgets.css" /> <script type="text/javascript" src="{% static 'js/jsi18n.js' %}"></script> <script type="text/javascript" src="/static/admin/js/jquery.min.js"></script> <script type="text/javascript" src="/static/admin/js/jquery.init.js"></script> <script type="text/javascript" src="{% static 'admin/js/core.js' %}"></script> <script type="text/javascript" src="{% static 'admin/js/SelectBox.js' %}"></script> <script type="text/javascript" src="{% static 'admin/js/SelectFilter2.js' %}"></script> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script> <script> $(function() { $( "#id_nextDueDate" ).datepicker(); $( "#id_endDate" ).datepicker(); }); </script> {% block title %}{% endblock %} </head> <div class="container-fluid"> <div class="row"> <div class="col-xs-12 well well-sm"> <h1 class="center">GreenPrint PayPlanner</h1> <div class="row"> <div class="col-xs-6"> {% if user.is_authenticated %} {% if user.get_full_name %} <p>Welcome {{ user.first_name }}! {% else %} <p>Welcome {{ user }}! {% … -
How to execute code on save in Django User model?
I would like to run some code specifically when the is_active field is changed for a Django User, similar to how the save method works for other models: class Foo(models.Model): ... def save(self, *args, **kwargs): if self.pk is not None: orig = Foo.objects.get(pk=self.pk) if orig.is_active != self.is_active: # code goes here Can this be done through another model that is in one to one relation with the User model? Something like: class Bar(models.Model): owner = models.OneToOneField(User, on_save=?) ... I guess I could duplicate the is_active field on the related model and then set the is_active field on the User when saving the related model. But this seems like a bit of a messy solution. -
Django - modify block from include after extending
Based on Django documentation The include tag should be considered as an implementation of “render this subtemplate and include the HTML”, not as “parse this subtemplate and include its contents as if it were part of the parent”. But I have a base.html and content.html. Base includes content I want to have final pageview.htmlwhich extends base where it modifies the block in content. I have many parts of the sites included in base, so that each are abstracted. Given the constraint stated by documentation, how to workaround and yet have clean abstraction? -
Python: How to piggyback on existing tests when developing third party packages
My PR on django-rest-framework to add in a "hybrid pagination" got rejected reason being better to be in a 3rd party package. So I went ahead and created the package structure but got stuck in creating the test, if you have a look at the PR files changed, my new tests are merely extending the existing tests and changed to use my new pagination class. +class TestCombinedPaginationPageNumber(TestPageNumberPagination): + def setup(self): + class ExamplePagination(pagination.HybridPagination): + page_size = 5 + + self.pagination = ExamplePagination() + self.queryset = range(1, 101) + + +class TestCombinedPaginationLimitOffset(TestLimitOffset): + def setup(self): + class ExamplePagination(pagination.HybridPagination): + default_limit = 10 + max_limit = 15 + + self.pagination = ExamplePagination() + self.queryset = range(1, 101) I am having trouble working out a way to piggyback these tests in my own 3rd party tests, I can't extend it remotely since installing the package doesn't include test files. I tried copying the particular test_pagination.py file but getting a lot of errors. -
Django display html table after POST
I'm a Django beginner. Currently, I'm working on a web app that lets a user upload a .csv file. I then save the data into a SQLite database and compute aggregations on the data using Pandas. I'm using the DataFrame.to_html() function to get the html code of the result table. I now want to show this table on the view. This is what the main page looks like: As soon as the .csv is uploaded, I would like my table to show up below the dropzone without page refresh. A detailed explanation would be very appreciated! I have a form that submits a POST request when the Upload button is clicked. This is what my upload function looks like: def upload(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): results = process_csv(request.FILES['file']) return render(request, 'accounting/upload.html', {'form': form}) else: toastr.error('Something wen\'t wrong. Please try again later.') else: form = UploadFileForm() return render(request, 'accounting/upload.html', {'form': form}) The results variable stores the html code of the result table. This has to be rendered on the view, below the dropzone. -
Django user permission inside template
I created a custom auth permission in django via admin site, and i added that permission to a user (not a group), now i want to ask if the request user in a template has it but nothing works.It's not a duplicate, i already checked similar questions and none of this work: {% if perms.auth.add_something %} {% if 'auth.add_something' in request.user.get_all_permissions %} {% if request.user.has_perm('add_something') %} The idea it's to make it inside template, not to use more code in views. Any ideas ?, thanks in advance. -
linebreaks filter not working in Django template
I have a simple? problem. I am editing my html template to include the linebreaks function into django. However, when using a value such as 'Hello \n World' what returns is exactly Hello \n World. Aka the filter is not replacing the \n. </script> <!-- End of javascript --> <head> <body> <div id="container"> <h2> GREEn Quiz Survey Question {{q.snum}} </h2> <!-- It appears that {{q.snum}} isn't being used--> <div class="question"> <span id = qspan> {{surv.text}} </span> <br> <br> <span id = m_info> {{'Hello \n World'|linebreaks}} </span> </div> <div id="ready_set_go" class "gq"> </div> <div id="Back_Button" class "Back"> </div> <div id="debug" data-gameid="{{g.id}}"></div> </div> </body> </html> Here is the output <p>Hello \n World</p> -
UnicodeEncodeError in django-registration
Installed django-registration according to the instructions https://django-registration.readthedocs.io/. But when I try to register user I get the following error in PyCharm UnicodeEncodeError: 'ascii' codec can't encode characters in position 8-9: ordinal not in range(128) [06/Oct/2016 23:22:38] "POST /accounts/register/ HTTP/1.1" 500 143329 And here is what Debug shows UnicodeEncodeError at /accounts/register/ 'ascii' codec can't encode characters in position 8-9: ordinal not in range(128) Request Method: POST Request URL: http://127.0.0.1:8000/accounts/register/ Django Version: 1.10.2 Exception Type: UnicodeEncodeError Exception Value: 'ascii' codec can't encode characters in position 8-9: ordinal not in range(128) Exception Location: C:\Python3\lib\smtplib.py in send, line 351 Python Executable: C:\Python3\python.exe Python Version: 3.5.1 Python Path: ['D:\x30ruproject', 'D:\x30ruproject', 'C:\Python3\python35.zip', 'C:\Python3\DLLs', 'C:\Python3\lib', 'C:\Python3', 'C:\Users\PC\AppData\Roaming\Python\Python35\site-packages', 'C:\Python3\lib\site-packages'] Server time: Чт, 6 Окт 2016 20:22:38 +0000 In settings.py written ACCOUNT_ACTIVATION_DAYS = 31 AUTH_USER_EMAIL_UNIQUE = True EMAIL_HOST = 'smtp.yandex.ru' EMAIL_PORT = 25 EMAIL_HOST_USER = 'example@yandex.ru' //Of course, I changed my email address) EMAIL_HOST_PASSWORD = '**********' EMAIL_USE_TLS = False DEFAULT_FROM_EMAIL = 'example@yandex.ru' LANGUAGE_CODE = 'ru-RU' USE_I18N = True -
Strategy for writing a simulator in python with a web interface
I mostly use C# and to solve this problem, I would have a pretty good strategy for doing so. But being new to python, I am a bit out of my comfort zone. What I essentially want is to create a simulator which runs a loop (has state) and simulates some random process. On top of this, I want to add a web interface from which i can influence the simulator; ie. change settings, control which values are used in calculation and so on. Can Django be used here or do i need to implement a web server inside my simulator to do this? Thanks in advance -
Should my Django site's main page be an app?
I have finished reading the Django official tutorial which teaches how to create a simple polls app, which is the way they chose to teach beginners the Django basics. My question is, now that I know how to make a simple app and want to create my own website (using Django), should the main (front) page of my website, be an app as well? If so, how do people usually call it and configure it? I mean, it should do nothing but render a html template, so why make it so complicated? I am a bit confused and could use your help. Maybe I misunderstood Django's main use? -
deploying python code to heroku not working
I have added the buildpack for python, it works. But when i do a git push it doesnt work. I get the below error all the time. (venv) D:\Projects\ecommerce\clone\cut_veggies>heroku buildpacks:set heroku/python Buildpack set. Next release on cutveggie will use heroku/python. Run git push heroku master to create a new release using this buildpack. (venv) D:\Projects\ecommerce\clone\cut_veggies>git push heroku master Counting objects: 308, done. Delta compression using up to 4 threads. Compressing objects: 100% (305/305), done. Writing objects: 100% (308/308), 410.14 KiB | 0 bytes/s, done. Total 308 (delta 193), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Failed to detect set buildpack https://codon- buildpacks.s3.amazonaws.com/buildpacks/heroku/python.tgz remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to cutveggie. remote: To https://git.heroku.com/cutveggie.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/cutveggie.git' Can anyone tell what i am missing? -
Nginx + uwsgi + django + odbc - issues with not finding odbc driver, possibly related to wrong user somewhere
I'm trying to connect to teradata through odbc from django under CentOS. The problem is that odbc cannot find teradata driver when run under django. If I run the script from python directly (or through django's ./manage command) it works fine, which makes me to believe that something in the chain above is being run under wrong (possibly "nginx") user, as I assume teradata (odbc?) is unable to locate .odbc.ini in the home directory of the current user. I had similar problem under Debian and solved it by changing uwsgi user to match, though CentOS uwsgi config is slightly different and the same change doesn't help. The error I'm getting: ERROR - ('DRIVER_NOT_FOUND', "No driver found for 'Teradata'. Available drivers: PostgreSQL,MySQL") .odbc.ini with teradata config is located under /home/myuser/.odbc.ini /etc/systemd/system/uwsgi.service [Unit] Description=uWSGI Emperor service [Service] ExecStartPre=/usr/bin/bash -c 'mkdir -p /run/uwsgi; chown myuser:myuser /run/uwsgi' ExecStart=/usr/bin/uwsgi --emperor /etc/uwsgi/sites --logto /home/myuser/log.log Restart=always KillSignal=SIGQUIT Type=notify NotifyAccess=all [Install] WantedBy=multi-user.target uwsgi app.ini config [uwsgi] chmod-socket = 664 chown-socket = nginx #cannot change this to myuser, getting 502 uid = myuser #this is what fixed it on Debian gid = myuser #this is what fixed it on Debian vhost = true plugins = python socket = /home/myuser/app.sock … -
Django: TypeError: int() argument must be a string, a bytes-like object or a number, not
Please help! I tried searching for an answer, but I think this issue is too specific to have a generalized enough solution. It's very difficult for me to pin point when, exactly, it is that this error started. I've Attempted too many changes now to know when the site was last working. I'm very new to this. And entirely self-taught, at that. I can assure you, it will be apparent. when attempting to migrate I receive this error: when attempting to migrate I receive this error: Applying purchaselog.0009_auto_20161005_1524...Traceback (most recent call la File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Users\jdcar\AppData\Local\Programs\Python\Python35-32\lib\site-packag utility.execute() File "C:\Users\jdcar\AppData\Local\Programs\Python\Python35- 32\lib\site-packag self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\jdcar\AppData\Local\Programs\Python\Python35-32\lib\site-packag self.execute(args, *cmd_options) File "C:\Users\jdcar\AppData\Local\Programs\Python\Python35-32\lib\site-packag output = self.handle(args, *options) File "C:\Users\jdcar\AppData\Local\Programs\Python\Python35-32\lib\site-packag fake_initial=fake_initial, File "C:\Users\jdcar\AppData\Local\Programs\Python\Python35-32\lib\site-packag state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_i File "C:\Users\jdcar\AppData\Local\Programs\Python\Python35-32\lib\site-packag state = self.apply_migration(state, migration, fake=fake, fake_initial=fake File "C:\Users\jdcar\AppData\Local\Programs\Python\Python35-32\lib\site-packag state = migration.apply(state, schema_editor) File "C:\Users\jdcar\AppData\Local\Programs\Python\Python35-32\lib\site-packag operation.database_forwards(self.app_label, schema_editor, old_state, projec File "C:\Users\jdcar\AppData\Local\Programs\Python\Python35-32\lib\site-packag field, File "C:\Users\jdcar\AppData\Local\Programs\Python\Python35-32\lib\site- packag self._remake_table(model, create_fields=[field]) File "C:\Users\jdcar\AppData\Local\Programs\Python\Python35-32\lib\site-packag self.effective_default(field) File "C:\Users\jdcar\AppData\Local\Programs\Python\Python35-32\lib\site-packag default = field.get_db_prep_save(default, self.connection) File "C:\Users\jdcar\AppData\Local\Programs\Python\Python35-32\lib\site-packag return self.target_field.get_db_prep_save(value, connection=connection) File "C:\Users\jdcar\AppData\Local\Programs\Python\Python35-32\lib\site-packag prepared=False) File "C:\Users\jdcar\AppData\Local\Programs\Python\Python35- 32\lib\site-packag value = self.get_prep_value(value) File "C:\Users\jdcar\AppData\Local\Programs\Python\Python35-32\lib\site-packag return int(value) TypeError: int() argument must be a string, a bytes-like object or a number, not I'm going insane, …