Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get Facebook user's cover photo in django
I couldn't find a good resource to get a facebook user's cover photo. I was able to grab a facebook user's profile photo however. I looked through the following, but couldn't figure out what i was doing incorrectly: Getting Facebooks' Cover Photo via PHP SDK & Graph API models.py class Profile(models.Model): user = models.OneToOneField(user_models.User) created_at = models.DateTimeField(auto_now_add=True) gender = models.TextField() def cover_image_url(self): fb_uid = SocialAccount.objects.filter(user_id=self.user.id, provider='facebook') if len(fb_uid): return "http://graph.facebook.com/{}?fields=cover".format(fb_uid[0].uid) print('GRAVATAR PHOTO') return "http://www.gravatar.com/avatar/{}?s=30".format(hashlib.md5(self.user.email).hexdigest()) template <img src="{{ profile.cover_image_url }}" class = "profile-bubble img-responsive center m-t-2"> -
Custom BaseInlineFormSet not saving
I have subclassed BaseInlineFormSet. I've overridden save() method, and inside it, first I call super save method to get the instances, like: def save(self, convenient_attribute=None, commit=True, *args, **kwargs): instances = super(CustomBaseModelFormSet, self).save(commit=False) for instance in instances: # I do something with each instance if commit: instance.save() return instances From the view: formset.save(convenient_attribute=some_object) If I check the forms in the formset var,it say they are bound and valid. So everything seems fine, but the the formset instances don't get saved in the DB! I've found that when I call the superclass save(), the var instances is a empty list. So there's no instances to commit. Why I don't get them? -
Visual Studio. Publishing a Python project takes so long
I'm developing a Django project for a Raspberry Pi 3 B. The development is being made with Visual Studio 2015 Community edition, and i'm publishing the projecto to the Raspberry binding the "Publish" option at VS with a folder containing the project at the Raspberry using Samba. My problem is that each time i Publish the project it takes about 5 minutes to upload all the files (and it just has 3 views for testing). At the Output window it shows: Connecting to \192.168.1.200\djangoProjects... C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v14.0\Python Tools\Microsoft.PythonTools.Web.targets(803,5): Warning : env (Python 64-bit 3.4) is not natively supported on Microsoft Azure. Add a WebPI reference to install this environment or add the 'SuppressGenerateWebPiReference' property to DjangoRaspiTest and set it to true. C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v14.0\Python Tools\Microsoft.PythonTools.Web.targets(812,5): Warning : Using old configuration tools. Add the Web Role support files to your project to use the updated deployment tools. Copying all files to temporary location below for package/publish: obj\Release\Package\PackageTmp. Publishing folder /... Publishing folder app... Publishing folder app/migrations... Publishing folder app/static... Publishing folder app/static/app... Publishing folder app/static/app/content... Publishing folder app/static/app/fonts... Publishing folder app/static/app/scripts... Publishing folder app/templates... Publishing folder app/templates/app... Publishing folder bin... Publishing folder DjangoRaspiTest... Publishing folder env... Publishing folder env/Lib... Publishing folder … -
block.super returns NoReverseMatch
I'm learning Django and I have problems with templates. I'm trying to add content to extended template. Structure of my code: base.html category -- category_detail.html -- list_content.html category_detail.html {% extends 'base.html' %} {% block title %} {{ category_name }} {% endblock %} {% block description %} {{ category_description }} {% endblock %} {% block content %} <div class="col-md-10 text-center"> <a href="{% url 'charts:category_error_list' category_name %}" id="list-button" class="btn btn-success btn-lg active" role="button" aria-pressed="true">Error list</a> </div> {% endblock %} Simple subpage with button. Button should redirect to another template, hovewer it gives me NoReverseMatch. list_content.html (which is category_error_list defined in view) {% extends 'category/category_detail.html' %} {% block content %} {{ block.super }} <h1 class="page-header"> Some string</h1> {% endblock %} What I'm trying to achieve is displaying "Some string" under button. (I know it should be done better with AJAX for example, but I want to learn the basics). urls.py urlpatterns = [ url(r'^category/$', views.categories_list, name='categories'), url(r'^category/(?P<category_name>\w+)/$', views.category_detail, name='category_detail'), url(r'^category/(?P<category_name>\w+)/list/$', views.category_error_list, name='category_error_list'), ] views.py # ${url}/category/${category} def category_detail(request, category_name): cat_detail = Category.objects.get(name=category_name) return render(request, 'charts/category/category_detail.html', {'category_name': cat_detail.name, 'category_description': cat_detail.description}) #${url}/category/${category}/list def category_error_list(request, category_name): category_with_errors = Category.objects.filter(name=category_name) error_list = Error.objects.get(category=category_with_errors) return render(request, 'charts/category/list_content.html', {'errors_list': error_list}) Problems seems to be related with urls.py, but I … -
dependencies reference nonexistent parent node error when renaming app label
Background I'd like to use the 3rd party Django app "Allauth" to save myself some time. Allauth requires you to add providers in INSTALLED_APPS, and their provider modules' names conflict with my existing apps. So I get the "django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates:.." error. I know how to fix that as per this previous question. The Issue My problem is that renaming my app's label in appconfig causes migrations to fail with "dependencies reference nonexistent parent node". So I assume this is because the parent node has now changed, and now so do the database tables. My Questions My existing app has a ton of data in production already so its not an option to start fresh. My questions are what are my options? Does Django not offer an option to rename the label for 3rd party packages instead? Am I really forced to perform a migration similar to the one discussed here? Thanks -
Way to keep terminal as you left it when you open pycharm back up?
I'm new to programming and I'm working with django. The problem is when I close down Pycharm my terminal also closes. When I open pycharm back up I have to to get my server back up and running each time. Is there an option so that my terminal is exactly how I left it when I closed down Pycharm? -
Python use of 'getattr' for an Update query
The goal of this code is to add 1 to the existing statistics. Statistics are kept by the day and an ongoing monthly tally. The error I am getting is telling me that the attribute name MUST be a string. I am trying to create this using the variable " current_day_field_name ". The database table for the statistics is designed with the day columns being of the fashion day_##. How may I take the value of "current_day_field_name" and present this as a string to the getattr syntax? @transaction.atomic() def add_one_view_for_current_day(blog_entry_reference, language_code): access_date = timezone.now() stats_object = BlogWebsiteViewStats.objects.get_or_create( blog_website_reference=blog_entry_reference, language_iso=language_code, year=access_date.year, month=access_date.month ) current_day_field_name = 'day_' + str(access_date.day) # fetch the data into Python, add +1 in Python, save views_today = getattr(stats_object, current_day_field_name|str) views_month = getattr(stats_object, 'total_month_views') setattr(stats_object, views_month, + 1) setattr(stats_object, current_day_field_name, views_today + 1) stats_object.save() -
Select specific data in Django query and map the result in a table
I've been avoiding this way too many times and I think it's time to ask for some help. First of all, I have the following structure of the relevant parts of my project: # models.py class LocationsProvisioning(models.Model): user = models.CharField(max_length=200) dates = models.CharField(max_length=15) locations = models.CharField(max_length=200) goods = models.CharField(max_length=200) quantities = models.CharField(max_length=200) samples = models.CharField(max_length=200) # forms.py DateInput = partial(forms.DateInput, { 'class': 'datepicker form-control', 'name': 'dates'}) class ReportForm(forms.Form): start_date = forms.DateField(label="Start date", required=True, widget=DateInput(), initial=datetime.date.today() - datetime.timedelta(days=1)) end_date = forms.DateField(label="End date", required=True, widget=DateInput(), initial=datetime.date.today()) locations = forms.ModelMultipleChoiceField(label='Select some locations', queryset=LocationsModel.objects.all().order_by('name'), required=True, widget=forms.SelectMultiple(attrs={ 'class': 'form-control', 'name': 'locations' })) # views.py def reports_view(request): form = ReportForm(request.POST or None) selected_locations = '' all_goods = GoodsModel.objects.all().order_by('name') if request.method == "POST": if form.is_valid(): start_date = str(form.cleaned_data.get('start_date')) end_date = str(form.cleaned_data.get('end_date')) selected_locations = form.cleaned_data.get('locations') else: form = ReportForm() return render(request, 'admin/coffee_app/raport.html', { 'form': form, 'selected_locations': selected_locations, 'all_goods': all_goods # those will be the headers of the table }) So far so good, I have in my template a table which contains as headers, goods, and as the first column the selected_locations. The html looks like this (I've removed some html tags for readability): <form class="form-horizontal" method="post"> {{ form.start_date.label_tag }} {{ form.end_date.label_tag }} {{ form.locations }} <button type="submit" … -
Python 3.5 django 1.10 social_auth doesnt working
Blockquote Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.5/dist- How do I solve this problem? Help I have a django 1.10 python 3.10 -
Django - NOT NULL constraint failed on stockinfo_note.stock_id - ForeignKey error
Purpose and Problem: I want to put two forms in the same template and process them in the one view. I can get the template to display the two forms but not submit them (i.e process the submission). When I submit I get the following error: Exception Value: NOT NULL constraint failed: stockinfo_note.stock_id 'stock' is the ForeignKey. I can't figure out how to get the function stock_new in Views.py to populate the foreign key ID which is what i think i need to do to overcome the above error. Models.py: class Stock(models.Model): ''' Model representing the stock info. ''' user = models.ForeignKey(User) ticker_code = models.CharField(max_length=10, null=True, blank=True) def __str__(self): return self.ticker_code class Note(models.Model): ''' Model representing the note. ''' user = models.ForeignKey(User) text_note = models.TextField() stock = models.ForeignKey(Stock) def __str__(self): return self.text_note Forms.py class StockForm(forms.ModelForm): class Meta: model = Stock fields = ('ticker_code',) class NoteForm(forms.ModelForm): class Meta: model = Note fields = ('text_note',) Views.py def stocknoter(request): stock = Stock.objects.filter(user=request.user) note = Note.objects.filter(user=request.user) context_dict = {'stock':stock, 'note':note} return render(request, "stocknoter/stock.html", context_dict) def stock_new(request): if request.method == "POST": form1 = StockForm(request.POST) form2 = NoteForm(request.POST) if form1.is_valid() and form2.is_valid(): stock = form1.save(commit=False) stock.user = request.user stock.save() note = form2.save(commit=False) note.user = request.user ''' … -
Django Dynamic Widget
I have a model with FileField and I'd like to display a different (and custom) widget for screens with a touch screen. Is this possible with Django (and some JavaScript of course)? -
Pickle and evaluation of sympy expressions
I have the problem that pickling/unpickling of sympy expressions may not return the inital expression, as in the following example >>>with evaluate(False) : x = atan(sqrt(3)) >>>x atan(sqrt(3)) >>> y = pickle.dumps(x) >>> z = pickle.loads(y) >>> z pi/3 Is there a way to avoid the evaluation in the process? The motivation is that I need to add sympy expressions to a request.session object in Django without them being altered in the process. -
How i can Change the default table name in the admin interface in django
I need to change the newss to another name how i can do this ؟ -
Django how I can get all objects to the list from db?
I want to use a "ArticleBlock", and it must have some "Articles" I wrote next models class ArticleBlock(models.Model): class Meta: db_table = "articleblock" articleBlockName = models.CharField(max_length=50) class Articles(models.Model): class Meta: db_table = "articles" articles_titel = models.CharField(max_length=50) articles_text = models.TextField() articles_date = models.DateTimeField() articles_main = models.ForeignKey(ArticleBlock) The first question? Is it correct? if I want bind many articles to one some block? In view.py I have next: def article_theme(request, articleblock_id=2): return render_to_response('article_theme.html', {"ArticleBlock_name": ArticleBlock.objects.get(id=articleblock_id), 'articles_list':list(Articles.objects.filter (articles_articleblock_id=articleblock_id))}) I want get a list() with articles, to sort random them. How I can get the list from db? -
Django - Models 'MultiSelectField' errors in Template and Form
I'm attempting to display a form that will let users create, read and update a model object. I recently used pip install django-multiselectfield to install a Python package that allows multiple choices to be stored in one db column. In the admin panel, I can select the choice boxes in the form without any problems, but in the view it returns the form with a ValidationError above the field like Value [u"[u'Digital Video'", u" u'Direct Marketing']"] is not a valid choice In addition, when the values are saved in the admin and I use a template tag to render the values in the view then the values are like so... Ad Type: [u'Digital Video'] as opposed to what I expected to be just 'Ad Type: Digital Video'. Any ideas why this is 1) Preventing the form from being saved inside the view (but works inside the admin) and 2) Why the template renders the value in the way shown above and how this can be rectified? Thanks Edit: Will show my HTML here as I realized I need to show more code... models.py: ad_types = MultiSelectField(verbose_name='Ad Type', choices=AD_TYPES, max_choices=10, blank=True, null=True) -
Installing django-ldapdb on Windows 10
I am trying to extend an existing LDAP database to allow the users to register WLAN devices. For this I would like to utilize the Django framework. A promising looking plugin is django-ldapdb which I would like to try out. Main problem The issue is with getting this plugin to run on my Windows 10 machine. I am using Python 3.6.1 and would like to develop in JetBrain's PyCharm. Installing the plugin through pip install django-ldapdb results in an error (ellipses indicating left out log): (...) running build_ext building '_ldap' extension creating build\temp.win32-3.6 creating build\temp.win32-3.6\Release creating build\temp.win32-3.6\Release\Modules C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -DHAVE_SASL -DHAVE_TLS -DHAVE_LIBLDAP_R -DHAVE_LIBLDAP_R -DLDAPMODULE_VERSION=2.4.28 -IModules -I/usr/include -I/usr/include/sasl -I/usr/local/include -I/usr/local/include/sasl "-Ic:\program files (x86)\python36-32\include" "-Ic:\program files (x86)\python36-32\include" "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\INCLUDE" "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\ATLMFC\INCLUDE" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\include\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\winrt" /TcModules/LDAPObject.c /Fobuild\temp.win32-3.6\Release\Modules/LDAPObject.obj LDAPObject.c c:\users\j0hj0h\appdata\local\temp\pip-build-j0vdz6mm\pyldap\modules\errors.h(8): fatal error C1083: Cannot open include file: 'lber.h': No such file or directory error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\cl.exe' failed with exit status 2 ---------------------------------------- Command ""c:\program files (x86)\python36-32\python.exe" -u -c "import setuptools, tokenize;__file__='C:\\Users\\j0hj0h\\AppData\\Local\\Temp\\pip-build-j0vdz6mm\\pyldap\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', … -
Django-redis-cache failing to fetch data from redis
I have a question regarding the working of this package. How does it writes to redis db ? This is my settings for redis - CACHES = { 'default': { 'BACKEND': 'redis_cache.RedisCache', 'LOCATION': '/var/run/redis/redis.sock', 'OPTIONS': { 'DB': 2, }, }, } This is my views file, def postview(request): print("Working") #post_list = Post.objects.all() if cache.get("posts") == None: post_list = Post.objects.all() print("going to be cached") a = cache.get("aman") print("aman ", a) cache.set("posts", post_list, timeout=60*100*10) print("cached") else : post_list = cache.get("posts") aman = cache.get("aman") print(aman, " aman's job") print("already present in cache") context = {"post_list" : post_list} print("Problem") return render(request, 'post_list.html', context) @cache_page(60*15*10, key_prefix="cache_redis") def testview(request): post_list = cache.get("posts") print("post_list is", post_list) return render(request, 'post_list.html', {"post_list":post_list}) @cache_page(60*25*10, key_prefix="cache_test") def new(request): print("Hey") print("cache_page is working") return HttpResponse("Hello, I am Mohammed") This is my redis -cli , luvpreet@DHARI-Inspiron-3542:~/test_venv_wrapper/test_redis/cache_redis$ redis-cli 127.0.0.1:6379> select 2 OK 127.0.0.1:6379[2]> set "a" "aman" OK 127.0.0.1:6379[2]> set ":1:a" "theman" OK 127.0.0.1:6379[2]> keys * 1) "a" 2)":1:views.decorators.cache.cache_page..GET.ad00468064711919773512f81be0dbc4.d41d8cd98f00b204e9800998ecf8427e.en-us.UTC" 3) ":1:posts" 4) ":1:a" 5) ":1:aman" 6) ":1:views.decorators.cache.cache_header.cache_test.ad00468064711919773512f81be0dbc4.en-us.UTC" 7) ":1:views.decorators.cache.cache_header..ad00468064711919773512f81be0dbc4.en-us.UTC" 8) ":1:b" 9)":1:views.decorators.cache.cache_page.cache_test.GET.ad00468064711919773512f81be0dbc4.d41d8cd98f00b204e9800998ecf8427e.en-us.UTC" 10) "aman" 127.0.0.1:6379[2]> get ":1:a" "theman" 127.0.0.1:6379[2]> get "a" "aman" This is the corresponding redis-cli monitor luvpreet@DHARI-Inspiron-3542:~/test_venv_wrapper/test_redis/cache_redis$ redis-cli monitor OK 1491412249.001149 [0 unix:/var/run/redis/redis.sock] "INFO" 1491412249.086196 [0 127.0.0.1:44984] "select" "2" 1491412250.001249 [0 unix:/var/run/redis/redis.sock] "INFO" … -
How can I access a Django Form fieldset's legend in the template?
This is what I tried below. The form is being passed to the template from the views.py method, but I am still not seeing the legend. <form id="exam_select"> {%for field in exams_form.fieldsets %} <div class="checkbox"> <label><input type="checkbox" value="" id="tug_checkbox">{{field.legend}}</label> </div> {%endfor%} </form> -
PyCharm cannot map django project
I am trying to use the declaration function in PyCharm, for a django application, however I get the message Cannot find declaration to go to. The project has worked fine without any problems for other users of this project, and there are __init__.py files in each subfolder containing .py files. However for some reason PyCharm doesnt read them properly. My interpreter is a virtualenv created for the project. There isn't much information coming from PyCharm on why this issue is appearing, but I am wondering if there is some trick similar to this. -
How to get time stamp of database update using psycopg2
I am implementing HTTP streaming with Django. When a user opens a webpage, there is a connection made to the server which returns back data when a new entry is made to the postgresql table. Let's call the model "M", the model which when updated returns back the data to the client I have a view get_update which does the timestamp checking and returns back data. How can I go about doing it? -
AWS Elastic Beanstalk throws error cc1plus doesn't exist
I'm currently deploying a fairly simple Django site to AWS Elastic Beanstalk, but my most recent deployment failed with the following: ------------------------------------- /var/log/eb-activity.log ------------------------------------- caused by: Requirement already satisfied (use --upgrade to upgrade): appdirs==1.4.3 in /opt/python/run/venv/lib/python3.4/site-packages (from -r /opt/python/ondeck/app/requirements.txt (line 1)) Requirement already satisfied (use --upgrade to upgrade): beautifulsoup4==4.5.3 in /opt/python/run/venv/lib/python3.4/site-packages (from -r /opt/python/ondeck/app/requirements.txt (line 2)) Collecting blessed==1.14.2 (from -r /opt/python/ondeck/app/requirements.txt (line 3)) Downloading blessed-1.14.2-py2.py3-none-any.whl (64kB) Collecting boto==2.46.1 (from -r /opt/python/ondeck/app/requirements.txt (line 4)) Downloading boto-2.46.1-py2.py3-none-any.whl (1.4MB) Collecting cement==2.8.2 (from -r /opt/python/ondeck/app/requirements.txt (line 5)) Downloading cement-2.8.2.tar.gz (165kB) Collecting colorama==0.3.7 (from -r /opt/python/ondeck/app/requirements.txt (line 6)) Downloading colorama-0.3.7-py2.py3-none-any.whl Requirement already satisfied (use --upgrade to upgrade): Django==1.10.6 in /opt/python/run/venv/lib/python3.4/site-packages (from -r /opt/python/ondeck/app/requirements.txt (line 7)) Collecting django-ses==0.8.2 (from -r /opt/python/ondeck/app/requirements.txt (line 8)) Downloading django-ses-0.8.2.tar.gz Collecting docopt==0.6.2 (from -r /opt/python/ondeck/app/requirements.txt (line 9)) Downloading docopt-0.6.2.tar.gz Collecting future==0.16.0 (from -r /opt/python/ondeck/app/requirements.txt (line 10)) Downloading future-0.16.0.tar.gz (824kB) Requirement already satisfied (use --upgrade to upgrade): html5lib==0.999 in /opt/python/run/venv/lib/python3.4/site-packages (from -r /opt/python/ondeck/app/requirements.txt (line 11)) Requirement already satisfied (use --upgrade to upgrade): nameparser==0.4.0 in /opt/python/run/venv/lib/python3.4/site-packages (from -r /opt/python/ondeck/app/requirements.txt (line 12)) Requirement already satisfied (use --upgrade to upgrade): packaging==16.8 in /opt/python/run/venv/lib/python3.4/site-packages (from -r /opt/python/ondeck/app/requirements.txt (line 13)) Requirement already satisfied (use --upgrade to upgrade): PennSDK==1.5.3 in /opt/python/run/venv/lib/python3.4/site-packages (from -r /opt/python/ondeck/app/requirements.txt (line 14)) Collecting probableparsing==0.0.1 … -
Django: pass data from CBV form view to form CBV
I have Form with a ModelChoiceField, which is being used as the form_class in a FormView. The choice field has to be populated with information bound to the request object. Let's summarize: class MyFormView(FormView): # I need to pass `request.user` and a value # derived from `request.GET['pk']` to the form form_class = MyForm class MyForm(Form): choices = ModelChoiceField(queryset=MyChoice.objects.none()) def __init__(self, user, number, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) self.fields['choices'] = MyChoice.objects(number=number, owner=user) What would I need to do to pass that data to the form when its instance is created? I tried overriding get_form but I am unsure this is the proper way of doing this: def get_form(self, form_class): user = self.request.user number = SomeModel.objects.get(self.GET['pk']).number return form_class(user, number, **self.get_form_kwargs()) -
Merge model subclass with polymorphic base class and drop subclass
In the process of cleaning up a django app I found a model which is the only subclass of its base class which itself derives from polymorphic.PolymorphicModel. Is there a way to merge the subclass with its base class and drop the subclass? The subclass has just one more member than the base class. -
How Can I Write a Django Model To Store Details of Users Who Communicate With My Messenger Bot
I'm currently building a Facebook messenger bot, and I wish to create a Django model to store users who communicate with my bot which is built in Django. The USER API documentation states how to get a user's details, but I don't know how to incorporate it in my Model. Here is a link to the USER API. -
Django localize datetime fields in the queryset and not template
I'm running Django with Postgres, and have USE_TZ=True set. I want timezone-aware datetimes returned from the database, which I get from USE_TZ=True being set. I want all the datetimes in the querysets to be set to the user's locale, not UTC. If USE_TZ=False and set TIME_ZONE='America/New_York', I can get my results back in the user's correct locale, but the dates are all naive. How can I get timezone-aware datetimes in the user's locale returned in my querysets by default? The worst case scenario is I loop through the results and set them all manually, but that seems like a poor/slow solution. I'm not interested in Django's ability to convert the dates to the user's timezone at render time. I need the timezone shifted dates before then for processing. To complicate this scenario, I also need to dynamically set the user's locale based on their settings, which means I can't rely on the TIME_ZONE setting. This I've accomplished with middleware. class TimezoneMiddleware(object): """ Adjust the timezone settings to depend on the account that the user is a part of. """ def process_request(self, request): if hasattr(request, 'pm_user'): # this doesn't do much, except let me manually update datetimes # with timezone.localtime() timezone.activate( …