Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get a related objects queryset through multiple levels of reverse foreignkeys in django?
I have a model of the sort: class Publisher(models.Model): ... class Author(models.Model): publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE) class Article(models.Model): author= models.ForeignKey(Author, on_delete=models.CASCADE) Now I'm trying to get all the articles from a given publisher 'pub'. I've tried doing the following: pub.article_set() pub.authot_set().article_set() As well as other failed tentatives. So how can I retrieve a Queryset of all articles of a given publisher without hitting the database too many times? Whats the most efficient way? Thanks in advance! -
Rename the column inside csv file.
Check for me whats wrong with my renaming command it nothing change on csv file. The code that i have tried below renaming header. df = pandas.read_csv('C:/JIRA Excel File.csv') df.rename(columns=({'Custom field (Implemented Date)':'Custom field (Verified Date)'})) df.set_index('Custom field (Verified Date)').to_csv("C:/JIRA Excel File/Done.csv", index=None) I want column Custom field (Implemented Date) CHANGE to Custom field (verified Date), but It the column still doesn't change anything -
Django 'dict' object has no attribute 'set_cookie'
Browser send OPTIONS request and I get this strange error. What is possible wrong? Tested on django 1.10 and 1.11 ERROR Internal Server Error: /cc_login/ Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 249, in _legacy_get_response response = self._get_response(request) File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.5/dist-packages/django/utils/decorators.py", line 167, in _wrapped_view return middleware.process_response(request, response) File "/usr/local/lib/python3.5/dist-packages/django/middleware/csrf.py", line 328, in process_response self._set_token(request, response) File "/usr/local/lib/python3.5/dist-packages/django/middleware/csrf.py", line 192, in _set_token response.set_cookie( AttributeError: 'dict' object has no attribute 'set_cookie' [06/Sep/2017 10:50:45] "OPTIONS /cc_login/ HTTP/1.1" 500 12601 -
Django + Scrapy: Apps aren't loaded
I tried to follow this (outdated) guide to use django models for my scrapy items. Sadly it's not working as soon I add my models to the crawler items.py. http://ruddra.com/2016/01/03/django-1-7-scrapy/ Python: 3.6 Django: 1.11.4 Scrapy: 1.4.0 scrapy-djangoitem: 1.1.1 I assume the problem is in my crawslers settings.py, which u can see here: import os import sys # C:\Users\kv\AtomProjects\example_project DJANGO_PROJECT_PATH = os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) DJANGO_SETTINGS_MODULE = 'example_project.settings' sys.path.insert(0, DJANGO_PROJECT_PATH) os.environ['DJANGO_SETTINGS_MODULE'] = DJANGO_SETTINGS_MODULE BOT_NAME = 'example_bot' SPIDER_MODULES = ['example_bot.spiders'] NEWSPIDER_MODULE = 'example_bot.spiders' ITEM_PIPELINES = { 'example_bot.pipelines.ExPipeline': 1000, } Stacktrace: kv@KV-PC ~/AtomProjects/example_project/example_bot/example_bot/spiders (master) $ scrapy runspider example.py c:\Users\kv\AtomProjects\example_project Traceback (most recent call last): File "c:\python\python36-32\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "c:\python\python36-32\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "c:\Python\Python36-32\Scripts\scrapy.exe\__main__.py", line 9, in <modul e> File "c:\python\python36-32\lib\site-packages\scrapy\cmdline.py", line 148, in execute cmd.crawler_process = CrawlerProcess(settings) File "c:\python\python36-32\lib\site-packages\scrapy\crawler.py", line 243, in __init__ super(CrawlerProcess, self).__init__(settings) File "c:\python\python36-32\lib\site-packages\scrapy\crawler.py", line 134, in __init__ self.spider_loader = _get_spider_loader(settings) File "c:\python\python36-32\lib\site-packages\scrapy\crawler.py", line 330, in _get_spider_loader return loader_cls.from_settings(settings.frozencopy()) File "c:\python\python36-32\lib\site-packages\scrapy\spiderloader.py", line 61 , in from_settings return cls(settings) File "c:\python\python36-32\lib\site-packages\scrapy\spiderloader.py", line 25 , in __init__ self._load_all_spiders() File "c:\python\python36-32\lib\site-packages\scrapy\spiderloader.py", line 47 , in _load_all_spiders for module in walk_modules(name): File "c:\python\python36-32\lib\site-packages\scrapy\utils\misc.py", line 71, in walk_modules submod = import_module(fullpath) File "c:\python\python36-32\lib\importlib\__init__.py", line 126, in import_mo dule return … -
Django 1.11 use template from an app as admin template
as the title said i am having a problem using a template in an admin view here is my worktree project |-- project/ |-- myapp/ |-- templates/ |-- admin/ |-- file.html settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'myapp/templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] ModelAdmin.py class ModelAdmin(admin.ModelAdmin): actions = ['export'] def export(self,request, queryset): paragraphs = ['first paragraph', 'second paragraph', 'third paragraph'] pdfkit.from_file('file.html', 'out.pdf', paragraphs) admin.site.register(Model, ModelAdmin) but i am getting "No such file: file.html" error -
Wagtail - adding blogs to the homepage when not using home_page.html
Instead of using Wagtail for all pages, I added Wagtail to an existing site based on Edge v2. I have customized the install of wagtail by creating a news app (instead of blog app) and changing the names of pages to NewsIndexPage, etc. This means I don't have a models.py in the main app folder. For some reason it also means the news page is at pages/news instead of /news. I want to display posts on this home page but having changed the name(s) to news from blog, and not using the HomePage model I'm confused on how to make that happen. I'm thinking I should be able to add to the "context" in the views.py to make this happen but whatever I tried didn't seem to work. Being new I'm sure I've missed something, but I'm having a ton of fun learning this stuff, and would appreciate any guidance in making this work. Here's the news/models.py: from django import forms from django.db import models # New imports added for ClusterTaggableManager, TaggedItemBase, MultiFieldPanel from modelcluster.fields import ParentalKey, ParentalManyToManyField from modelcluster.contrib.taggit import ClusterTaggableManager from taggit.models import TaggedItemBase from wagtail.wagtailcore.models import Page, Orderable from wagtail.wagtailcore.fields import RichTextField from wagtail.wagtailadmin.edit_handlers import FieldPanel, InlinePanel, … -
Passing token headers in my OAuth2WebServerFlow django
So in my /auth endpoint it needs to have a authorization URL; after clicking 'accept' in auth url user get redirected to another endpoint called /complete, how would I pass in header from user and authenticate my user in my first call 'auth', so the /complete endpoint works because it is authenticated. I tried passing header; like how I would to get the token, but it doesn't seem to be working. def auth(self,request, *args, **kwargs): client_id = '' client_secret = '' flow = OAuth2WebServerFlow(client_id=client_id, client_secret=client_secret, scope='https://www.googleapis.com/auth/calendar', headers = {'Authorization' :'Token TOKEN HERE'}, redirect_uri='http://localhost:8001/api/google_auth/complete') auth_uri = flow.step1_get_authorize_url() get_user = self.request.user get_user.google_access_token = get_user.username get_user.save() return Response(status=200, data=str(auth_uri)) -
Write to a csv file. Python
I want to read the content from a csv file and remove 1 column. date location price 1/1/2016 FL 300000 1/1/2016 NY 400000 1/1/2016 UT 150000 import pandas, sys pandas.read_csv('C:/ExcelFile.csv').set_index('location').to_csv(sys.stdout, index=None) The code above working on removing the location column. My Question - How to create a new csv file and pass the output after removing the column to a new csv file. Code that i have tried. import pandas, sys df1 = pandas.read_csv('C:/ExcelFile.csv').set_index('location').to_csv(sys.stdout, index=None) df = df1.DataFrame(df1) df.to_csv('C:/JIRA Excel File/Done.csv') Thank you :D -
Only last excel data is put in model
I wanna parse excel and put data in the model(User). However now,only last excel data is put in model and the number of the data is 4.4 is the number of all excel rows like Now db.sqlite3 is |10|Karen||| |10|Karen||| |10|Karen||| |10|Karen||| My ideal db.sqlite3 is 1|1|Blear|40|false|l 2|5|Tom|23|true|o 3|9|Rose|52|false|m |10|Karen||| all data wanna be put in there. Why does such result happen? views.py is #coding:utf-8 from django.shortcuts import render import xlrd from .models import User book = xlrd.open_workbook('../data/data.xlsx') sheet = book.sheet_by_index(1) for row_index in range(sheet.nrows): rows = sheet.row_values(row_index) print(rows) def build_employee(employee): if employee == 'leader': return 'l' if employee == 'manager': return 'm' if employee == 'others': return 'o' for row in rows: is_man = rows[4] != "" emp = build_employee(rows[5]) user = User(user_id=rows[1], name_id=rows[2], name=rows[3], age=rows[4],man=is_man,employee=emp) user.save() When i print out rows in print(rows) ,result is Blear Tom Rose Karen so I think rows has all data in excel. models.py is class User(models.Model): user_id = models.CharField(max_length=200) name_id = models.CharField(max_length=200) name = models.CharField(max_length=200) age = models.CharField(max_length=200) man = models.BooleanField() TYPE_CHOICES = ( ('m', 'manager'), ('l', 'leader'), ('o', 'others'), ) employee =models.CharField(max_length=1, choices=TYPE_CHOICES) How can i fix this? -
Save variable from function into model with python and django
I have created a model and imported it in my views.py file: from app.models import User next I am receiving a message from a user on telegram: def get_message_from_request(request): received_message = {} decoded_request = json.loads(request.body.decode('utf-8')) if 'message' in decoded_request: received_message = decoded_request['message'] received_message['chat_id'] = received_message['from']['id'] return received_message class tbotview(generic.View): @method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): return generic.View.dispatch(self, request, *args, **kwargs) def post(self, request, *args, **kwargs): TELEGRAM_TOKEN = '' message = get_message_from_request(request) send_messages(message, TELEGRAM_TOKEN) return HttpResponse() what I would like to do is to save the 'id' of the user in my sqlite database. Kind of: u = User(userid='id') u.save() So right now I am just saving the string 'id' obviously. My question is how can I access the 'id' from the received_message and save this one in my database. Thanks a lot! -
Add page child buttom need to be effective only on firts level
On click "Add page child" I want to be able to add a page only when I'm on the first level(homepage). the pagemodel dont need to be selected. -
excluded field in model form still required
I have the following form: class PostForm(forms.ModelForm): post_type = forms.ChoiceField(widget=forms.RadioSelect(attrs={'name': 'radioInline'}), choices=POST_CHOICES) class Meta: model = Post fields = ('title','desc','image','url',) I have the following model: @python_2_unicode_compatible class Post(models.Model): entity = models.ForeignKey('companies.Entity') title = models.CharField('Post Title', max_length=128, unique=True) desc = models.TextField('Description', blank=True, null=True) post_type = models.IntegerField(choices=POST_CHOICES) image = models.ImageField('Post Image', upload_to='post', blank=True, null=True) url = models.URLField(max_length=255, blank=True, null=True) slug = models.SlugField(blank=True, null=True, unique=True) created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) When I submit the form, I get the error: post_type field error: This field is required. I want to populate this field after form.is_valid method. Since this field is not in the required fields tuple, shouldn't it not be required? I have also tried adding: post_type = models.IntegerField(choices=POST_CHOICES, blank=True) Though I get the same error. Is there something else going on? -
Press Tab to get in and out of field
I have this form (HTML below): I want to be able to Tab focus into the box, type immediately, Enter to select an option, and Tab into the next field. Because of this issue I added this so that I can type immediately when the box is focused (rather than first opening the menu before typing): $(document).on('focus', 'span.select2', function () { $(this).prev('select:not([multiple])').select2('open'); }); but now once I've entered a value, I can't Tab out of the box into the next field; instead Tab just reopens the dropdown menu. Is there a way I can both Tab in and out of the box? <form method="POST"> <input type='hidden' name='csrfmiddlewaretoken' value='8wD3gvqLeBDetM19MnvdVFGxGmzy27T6BGukPuHCOEZiagBoLtnUQQFm1qv6kyVu' /> <input type="hidden" name="record_set-TOTAL_FORMS" value="2" id="id_record_set-TOTAL_FORMS" /><input type="hidden" name="record_set-INITIAL_FORMS" value="0" id="id_record_set-INITIAL_FORMS" /><input type="hidden" name="record_set-MIN_NUM_FORMS" value="0" id="id_record_set-MIN_NUM_FORMS" /><input type="hidden" name="record_set-MAX_NUM_FORMS" value="1000" id="id_record_set-MAX_NUM_FORMS" /> <table id="id_data_table"> <input type="hidden" name="record_set-0-id" id="id_record_set-0-id" /> <link href="/static/autocomplete_light/vendor/select2/dist/css/select2.css" type="text/css" media="all" rel="stylesheet" /> <link href="/static/autocomplete_light/select2.css" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/static/autocomplete_light/jquery.init.js"></script> <script type="text/javascript" src="/static/autocomplete_light/autocomplete.init.js"></script> <script type="text/javascript" src="/static/autocomplete_light/vendor/select2/dist/js/select2.full.js"></script> <script type="text/javascript" src="/static/autocomplete_light/select2.js"></script> <thead><tr> <th>Full name</th> <th>Score</th> </tr></thead> <tr> <td> <select name="record_set-0-full_name" minimumInputLength="2" data-placeholder="Full name" id="id_record_set-0-full_name" data-autocomplete-light-url="/app/name-autocomplete" data-autocomplete-light-function="select2"> </select><div style="display:none" class="dal-forward-conf" id="dal-forward-conf-for-id_record_set-0-full_name"><script type="text/dal-forward-conf">[{"type": "const", "val": ["Jane Smith", "James Dill"], "dst": "full_name_choices"}]</script></div> </td> <td> <input type="number" name="record_set-0-score" id="id_record_set-0-score" /> </td> </tr> <input type="hidden" … -
django forms - how to update user data from previous comment when user posts a new comment
I feel like I'm really close, but not quite there yet. Please bear with me as I am very much so in the beginner stages of learning django. I have a feature where users can comment on each blog post. I want to display the total number of comments each user has next to his name. If that user has left 4 comments on 4 different posts, I want it to show "4 total comments" next to his name on each one of his individual comments throughout my website. I have made a model method that I put in my view, which automatically updates the total comments for each user. The only problem is that if the user has left two comments, only his latest comment will show "2 total comments". His previous one shows only "1". My question is, how do I make the previous entry update when the user has left a new comment? models.py class Comment(models.Model): ... post = models.ForeignKey(Post, related_name="comments") user = models.ForeignKey(User, related_name="usernamee") email = models.EmailField(null=True, blank=True) picture = models.TextField(max_length=1000) ... review_count = models.IntegerField(default=0) class UserProfile(models.Model): ... def user_rating_count(self): #This is what adds "1" to the user's total post count user_ratings = Comment.objects.all().filter(user_id=self.user.id).count() user_ratings += … -
Using plotly with django
I was looking to use plotly in a django project and found @samcheuk explanation here: plotly in django But the solution doesn't seem to work any more because of an update of plotly. The result is argument of type 'bool' is not iterable It seems as if the _plot_html function changed but I can't understand how. Does any one run into the same problem and manage to fix it? The current signature is: _plot_html(figure_or_data, config, validate, default_width, default_height, global_requirejs) But the solution suggests using: plot_html = plot_html, plotdivid, width, height = _plot_html( figure_or_data, True, 'test', True, '100%', '100%') Which would use True as the default_width I'm using plotly version 2.0.11 with conda. Thank you for your help. -
Why does csrf verification fail after validation error in Django admin?
I have a Django site that has an admin site associated with it. One of the models that is registered with the admin is called Article, and it has a field called content that is required. If the user leaves this field blank, it will show them a validation error saying that the field is required. However, if they get this validation error and then click the save button again, they will be given a csrf_verification failed error. I have checked, and the csrf token is being passed, and a different csrf token is passed when the user makes the request that generates the validation error from when the user makes the request that generates the csrf_token error. Any ideas why the csrf_token error is happening? Is this normal Django behavior, or is it specific to my site? What are the next steps I should take to resolve this issue? -
How to syle django rendered radio buttons?
I have a django form from which I am displaying radio button choices to the user on my template. But these radio buttons are very bland and hence I would like to style them, something on these lines: https://codepen.io/manabox/pen/raQmpL Here's my form: class SampleTicketForm(forms.Form): queue = forms.ChoiceField( widget=forms.RadioSelect(), label=_('What do you need help with?'), required=True, choices=() ) The choices are filled in my views because they may change based on user. In my template, I have: <form role="form" method='post'> {% csrf_token %} {{form.queue.0}} </form> {{form.queue.0}} renders as <label for="id_queue_0"><input id="id_queue_0" name="queue" value="0" type="radio"> Order Issues</label> In the template's <style> tag, I have CSS code from that codepen, but it seems to have no effect. Is it not possible to style django radio buttons by using CSS on the file? Should I include my CSS externally? -
Using django-maintenance-mode to set maintenance mode; is it possible to not redirect?
I'm using the django-maintenance-mode package to handle maintenance mode for my django app, but instead of redirecting to a maintenance page, I want to leverage the context and use {% if maintenance_mode %} in my templates to show a toast message IF it's in maintenance mode. I looked over the doc over at https://github.com/fabiocaccamo/django-maintenance-mode and it doesn't seem like this is possible (maybe I missed it). Are there any alternatives to this? -
Prevent Django from re-creating default permissions
Is there a way I can remove all the permission that Django creates by default and prevent it from creating them again? Currently I have a migration that runs a Permission.objects.all().delete() and I also have added default_permissions = () to the Meta class of all my models, and yet once I run the migration, the permissions disappear for a second, and then Django recreates them (I know it's a genuine recreation because the ID of each permission increases each time I run the migration). So, is there a way I can completely disable automatic permission creation? Note that I'm saying disable creation, not hiding permissions (which I already know how to do). -
Custom validators on Wagtail fields
I have a TextField I would like to add a min_length to. According to the Django docs there are built in validators you can use to enforce this (https://docs.djangoproject.com/en/dev/ref/validators/#minlengthvalidator). I tried to add this to my model with this code: class MyPage(Page): ... introduction = models.TextField( null=True, blank=False, validators=[MinLengthValidator(240, message="Must be at least 240 chars.")] When publishing this page with a value lower than 240, however, I did not get the expected validation error, but instead hit a TypeError: unorderable types: str() < int(). Is there a way to have a min_length on a TextField? -
Passing Related Row to Django Database Function
Is it possible to pass rows of related fields into django database functions and if so how can i accomplish this? When I try, I end up getting an integer (the id column) instead of the row. Models: class ModelA(models.Model): pass class ModelB(models.Model): pass class ModelC(models.Model): model_a_rel = models.ManyToManyField( ModelA, related_name='m2mrelatedobj' ) fkobj = models.ForeignKey( ModelB ) Desired Queryset: ModelA.objects.annotate( my_annotation=DatabaseFn('m2mrelatedobj_fkobj') ).filter(my_annotation=True) My goal is to pass rows of fkobj into DatabaseFn so that the join is done once over the queryset and not inside each annotation. Is this even possible in django? Right now, I get an error from my postgres function saying that it received an integer instead of a row, which communicates that django is not doing the additional join. Any insight would be much appreciated, thanks. environment: Django v1.10.3, python 2.7, postgresql 9.5 -
Python + Django: Get aware datetime string from aware datetime
I have an aware datetime-object and want to return an aware datetime-string. However when I do obj.strftime("%e %b %Y %H:%M:%S") it returns a UTC-based string (even though TIME_ZONE-setting is set right). How can I get a localised datetime-string? -
Different form fields for add and change view in Django admin
I want to display different form fields for add and change view in Django admin. If it is add then I am showing the form field file_upload and if it is change then I am showing model fields cname and mname Code from admin.py class couplingAdmin(admin.ModelAdmin): list_display = ('cname','mname') form = CouplingUploadForm #upload_file is here def get_form(self, request, obj=None, **kwargs): # Proper kwargs are form, fields, exclude, formfield_callback if obj: # obj is not None, so this is a change page kwargs['exclude'] = ['upload_file',] else: # obj is None, so this is an add page kwargs['exclude'] = ['cname','mname',] return super(couplingAdmin, self).get_form(request, obj, **kwargs) If it is add then it's fine but if it is change view then I am getting all the fields ie cname,mname,upload_file. Please suggest how can I remove upload_file from change view in admin. Any help is highly appreciated. Thanks in advance. -
Retrieving a user's ID when trying to add a friend with Django
Okay so I'm making a friend system for a website, it's going pretty well. I've been able to create a relationship between two users (friendship) when I manually enter the proper URL. However that's the problem, I need to manually enter it, here's my urls.py: url(r'^profile_test/connect/(?P<operation>.+)/(?P<pk>\d+)/$', views.change_friends, name='change_friends') Here's the views.py: def change_friends(request, operation, pk): #this view will manage a user's friends other_user = User.objects.get(pk=pk) if operation == 'add': Friend.objects.add_friend( request.user, other_user, message='Hi, I would like to add you') elif operation == 'remove': Friend.objects.remove_friend(request.user, other_user) return HttpResponse(Friend.objects.friends(request.user)) As you can see the view takes the arguments operation and pk, the operation will be adding or removing a friend and the pk will be the primary key of the user that you want to add as a friend. I'm trying to find a way to dynamically generate the ID of the user that is being added, so I can put it in a URL. So this HTML code would need to do it but I don't know how: <a href='http://localhost:8000/profile_test/connect/add/dynamically-generated-pk/'> Click </a> How should I go about this? I'm using the django-friendship package btw -
JSON request response type error - Django
I have a Json request that i am sending for a django project. I am sending the request and I am getting a a response as I am expecting. But I think the response is coming back as a string and not as a file or iterable file. I am not sure how to ensure the response is the correct format to be processed. Here is the request that I am sending from the django views.py file... def createUserSynapse(request): data = { "logins":[ { "email":"test@test.com", } ], "phone_numbers":[ "123.456.7890", "test@test.com", ], "legal_names":[ "Test name", ], "extras":{ "supp_id":"asdfe515641e56wg", "cip_tag":12, "is_business":False, } } req = urllib.request.Request('http://uat-api.synapsefi.com') req.add_header('X-SP-GATEWAY', 'client_id_asdfeavea561va9685e1gre5ara|client_secret_4651av5sa1edgvawegv1a6we1v5a6s51gv') req.add_header('X-SP-USER-IP', '127.0.0.1') req.add_header('X-SP-USER', '| ge85a41v8e16v1a618gea164g65') req.add_header('Content-Type', 'application/json') print(req.headers) response = urllib.request.urlopen(req, json.dumps(data).encode('utf8')) print(response) return render(reqest, 'tabs/create_user_synapse.html', response) also, the second to last time is supposed to print the response and it is not printing anything.... can anyone help me... Here is the full error: TypeError at /setup_profile/ POST data should be bytes, an iterable of bytes, or a file object. It cannot be of type str. Request Method: POST Request URL: http://127.0.0.1:8000/setup_profile/ Django Version: 1.8.6 Exception Type: TypeError Exception Value: POST data should be bytes, an iterable of bytes, or a file object. It …