Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pass a non DB object from a template to a view outside the URL with Django ?
I'm fairly new to Django. I'm writing an app that displays articles using RSS. I want users to be able to react to any given article. On the index, I display the latest articles dynamically (they are not stored in the DB). View : class IndexView(generic.ListView): template_name = 'publisher/index.html' def get_context_data(self, **kwargs): context = super(IndexView,self).get_context_data(**kwargs) feeds = feedparser.parse('http://www.foo.com/rss/news.xml') context['feeds'] = feeds return context Template : {% for entry in feeds.entries %} <li> <a target="_blank" href="{{entry.link}}">{{entry.title}}</a> <a href="{% url 'publisher:rss_react' entry %}">I want to react</a> </li> {% endfor %} This works so far. I have a link next to each of these articles that should call the RSSReactView and display the article title, abstract, and a form to react. I don't want the article to be saved anywhere if the reaction is not posted, and thus I don't want any parameter to be included in the URL of the reaction form. URL : app_name = 'publisher' urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^new_rss/react/$', views.RSSReactView.as_view(), name='rss_react'), ] View : class RSSReactView(generic.CreateView): model = ReactionArticle form_class = ReactionForm template_name = 'publisher/react.html' def get_context_data(self, **kwargs): context = super(ReactView,self).get_context_data(**kwargs) entry = self.kwargs['entry'] context['entry'] = entry return context def form_valid(self, form): pass Template : <h1>You are β¦ -
How to use float value in django nvd3 discrete bar chart?
I am trying to fill float values in django nvd3 discrete bar chart with following data. ydata = [0.4, 0.6] xdata = ['Sunday, 27. November 2016', 'Wednesday, 30. November 2016'] The output is not quite good. The float value is truncated and only '0' is shown when hover in the bars. How to get exact float values on the bar? -
Django Authentification Override -> custom AuthenticationForm -> confirm_login_allowed() issues
I'm customizing the Django Authentication and I created a custom CreationForm, ChangeForm and AuthentificatioForm. Almost everything is working properly excepting the confirm_login_allowed(). It seems that Django is "ignoring" this method override or not. If the user is inactive I receive the message: "Please enter a correct email address and password. Note that both fields may be case-sensitive."(default behavior)* If I make the user active everything is ok(same credentials) def confirm_login_allowed(self, user): print('inside') if not user.is_active: raise forms.ValidationError( _("This account is inactive."), code='inactive', ) I thought the problem is the 'user' argument and I tried to set him as user = settings.AUTH_USER_MODEL Not working, no idea why. Forms from django import forms from django.conf import settings from django.contrib.auth.forms import AuthenticationForm, ReadOnlyPasswordHashField from .models import CustomUser class UserCreationForm(forms.ModelForm): """A form for creating new users. Includes all the required fields, plus a repeated password.""" password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) class Meta: model = CustomUser fields = ('first_name', 'last_name', 'email',) def clean_password2(self): # Check that the two password entries match password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords don't match") return password2 def save(self, commit=True): # Save the provided password in hashed β¦ -
Saving OnetoOneField in Django Admin while null=True gives error
I have OnetoOnefield in my model, which is set to null=True and blank=True. Everything is working fine but as soon as I try to save that model's object from admin site I get IntegrityError, saying that the field can't be null. My model is: class Appointment(models.Model): doctor = models.OneToOneField(Doctor) clinic = models.OneToOneField(Clinic, null=True, blank=True) hospital = models.OneToOneField(Hospital, null=True, blank=True) -
Django Models self reference
I need to build a Django Model in which it refers to itself (a list of the same Model type within each instance of this model, sort of like a nested structure), probably within its own definition. I have looked into ManyToManyField or a possible solution with another model with a foreign key to this Model. What's the simplest way to do it ? -
Own context processor in Django 10.1
I try to add own context processor. I try this: django_test/prject/settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, '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', 'blog.context_processors.global_menu', ], }, }, ] django_test/blog/context_processors.py def global_menu(): menu = {'a': 'aaa', 'b': 'bbb'} return {'menu': menu} django_test/blog/views.py def context_processors(request): args = {} args['article'] = 'my article' return render_to_response('context_processors.html', args) django_test/blog/templates/context_processors.html try get menu: {{menu.a}} django_test/blog/urls.py url(r'^context_processors/$', views.context_processors), I just see: try get menu: in browser and i can not understand the reason why it is not work. -
Django-Allauth custom signup ModelForm inheritance: no fields error
I am adding my custom signup form in allauth: ACCOUNT_SIGNUP_FORM_CLASS = 'myApp.forms.SignupDataForm' I have used the code in django 1.6 and allauth 0.18 but when trying it in django 1.8.6 and allauth 0.28 I get: AttributeError: 'SignupForm' object has no attribute 'fields' My SignupForm is a child declared like this: class SignupDataForm(BaseUserDataForm): reg_user_badge = forms.CharField(label="Give Points to a Friend",required=False,widget = TextInput(attrs={'placeholder': 'Username (optional)'}),validators=[validate_friendname]) class Meta(BaseUserDataForm.Meta): model = UserData fields = BaseUserDataForm.Meta.fields + ('terms_conditions',) #terms_conditions is also a model field but not added to the parent definition def __init__(self, *args, **kwargs): super(SignupDataForm, self).__init__(*args, **kwargs) self.fields['terms_conditions'].required = False self.fields['gender'].widget = Select(choices=GENDER_CHOICES,attrs={'class':'signup_select',}) self.fields['password2'].widget.attrs['onblur'] ="check_pass()" self.fields['password1'].widget.attrs['onblur'] ="check_pass()" def clean(self): #clean overwrite def signup(self,request, user): #requested signup function What is weird is that if I feed Allauth with the parent form everything works fine, I get no error. The shortend code for the parent is here: class BaseUserDataForm(forms.ModelForm): url = forms.CharField(max_length = 30, label="Don't type here (anti spam protection)",validators=[validate_name_honeypots]) class Meta: model = UserData fields = ('****model fields named without terms_conditions field****') def __init__(self, *args, **kwargs): super(BaseUserDataForm, self).__init__(*args, **kwargs) Does anybody know what am I doing wrong? -
How to fix - ERROR [django.security.SuspiciousFileOperation:216]?
I am getting following error while running Django 1.9.x on Mac OS [26/Nov/2016 07:33:23] ERROR [django.security.SuspiciousFileOperation:216] The joined path (/static/fonts/DINLight.ttf) is located outside of the base path component (/Users/petermac/python27/erpproject/app/staticfiles) What should I do to resolve this? -
django channels: how to restrict access to a chat room except certain two people?
I'm building a chat app using Django channels. Now the app allow users to watch any chat rooms if they know the urls for them. I wanna restrict access to each chat room except certain two people. How do I realize that on Django channels? How do I allow only certain users to access to a url on Django app in general? Url for chat rooms in my chat app is following. url(r'^(?P[\w-]{,50})/$', views.chat_room, name='chat_room') -
Can one define a separate css file for an extending html template in Django?
Assume that abc.html extends base.html in a django app. I noticed that I have to do the styling of abc.html inside the css file of base.html (say base.css) I was wondering there is a way to define a separate (independent) css file for abc.html and manage the styling using base.css and abc.css files for example? I tried to follow the same steps to use , and tags inside abc.html and define a link to abc.css file, but django was not picking it up. -
I'm having trouble deciding between using a foreign key, many-to-many field, or choicefield
I'm building a video game library and I'm having some trouble structuring my models. I'm not sure if I should use a many-to-many, foreign key, or choices field to do the following: There are game consoles (PC, Playstation 4, etc) and video games (Rocket League, Minecraft, etc). Each game must be on at least one console, but it might be available on more. My idea is to create a game console table which would store the name, logo, and other useful information. The video game table would store the title, cover art, maps, game modes, and so on. Ideally, in the admin dashboard, a user can edit console information or a game. The game section of the dashboard would allow editing of the game and the consoles it's available on. Here's what I've done so far. models.py class GameConsole(models.Model): name = models.CharField( max_length=8, default='PC' ) # console_logo = models.ImageField() def __str__(self): return self.name class Meta: verbose_name = 'game console' verbose_name_plural = 'game consoles' db_table = 'console' ordering = ['-name'] class VideoGame(models.Model): title = models.CharField( max_length=128, default='???' ) # game_cover = models.ImageField() # company_website = models.URLField() # date_published = models.DateField() def __str__(self): return self.title class Meta: verbose_name = 'video game' verbose_name_plural β¦ -
Django: Dynamic link building in edit template for file download with nginx
I have a Django project. I have following setting in NGINX configuration. location /media/protected { internal; root /home/django/django_project/django_project; } With this setting i cannot download the files. How to structure the urls and views.py so that automated download link in Django edit templates allow the file downloads? -
Django Celery socket.error [Errno 61] Connection refused
I'm running Redis, Celery 4.0 and Django 1.10 but receive a [Errrno 61] connection refused error when running task 'test' from shell. This is my project structure: myproj β βββ app1 βββ __init__.py βββ tasks.py myproj βββ __init__.py βββ urls.py βββ settings β βββ __init__.py β βββ base.py β βββ local.py β βββ staging.py β βββ production.py βββ local β βββ __init__.py β βββ celery.py β βββ wsgi.py βββ staging β βββ __init__.py β βββ celery.py β βββ wsgi.py βββ production β βββ __init__.py β βββ celery.py β βββ wsgi.py βββ urls.py βββ wsgi.py myproj/app1/tasks.py: from __future__ import absolute_import from celery import task @task(name='app1.tasks.test') def test(): print('this is a test') myproj/myproj/local/celery.py: from __future__ import absolute_import import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproj.settings.local') app = Celery('myproj_local') app.config_from_object('django.conf:settings') app.autodiscover_tasks() myproj/myproj/local/__init__.py: from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ['celery_app'] I think something is wrong in this init file because the task runs from shell when I move the content to myproj/myproj/__init__.py: from __future__ import absolute_import, unicode_literals from .local.celery import app as celery_app __all__ = ['celery_app'] Celery is running in the myproj directory with command: celery -A myproj.local.celery worker -l info The full error: python manage.py shell β¦ -
Django Querying MongoDB ObjectIds in views from json object
I am currently working on querying MongoDB objects in Python Django and had no trouble in creating queries if it's the other attributes needed. However I need to modify my queries to specifically filter through the ObjectIds returning one or no object found. From my Javascript I am passing a json data to my Django views.py here's how it currently looks like: def update(request): #AJAX data line = json.loads(request.body) _id = line['_id'] print("OBJECT_ID: %s" % (_id)) another_id = line['another_id'] print("ANOTHER_ID: %s" % (another_id)) *Don't confuse the another_id, there are objects that has the same another_id s and unfortunately remain like that that's why I can't query it for update since it will update all duplicates. This is the reason why I need the ObjectId. For checking here's what it prints out: {u'$oid': u'582fc95bb7abe7943f1a45b2'} ANOTHER_ID: LTJ1277 Therefore I appended the query in views.py like this: try: Route.objects(_id=_id).update(set__geometry=geometry, set__properties=properties) print("Edited: " + another_id) except: print("Unedited.") But it didn't return any object. So I was wondering if the query itself can't recognize the $oidin the json body as "_id" : ObjectId("582fc95bb7abe7943f1a45b2")? -
Can't install Django (or set up a virtual environment)
I am a beginner web programmer, and I am trying to start learning web app development on Python. I have Python 3.4 and I am using Windows 10. Python works fine when making a game using the pygame modules. Recently, I wanted to try web dev, and so I tried to install Django (along with creating a virtual environment), neither of which I was able to successfully do. I've already installed pip as shown in the image below. Pip installed But for some reason when I enter into Command Prompt this: C:\Users\Steven>$ pip install Django I get: '$' is not recognized as an internal or external command, operable program or batch file. OR C:\Users\Steven\>pip install django I get: 'pip' is not recognized as an internal or external command, operable program, or batch file. Any kind of help will be greatly appreciated! -
Django - All messed up on a simple form redirect
I've got myself all screwed up following different tutorials/StackOverflow threads, and I can't get this stupid form to work. The idea is the user selects a team in "standings", and "results" displays the team name, plus wins and losses. I can do it by messing with the code, but adding the form has been awful. Here's code, sorry in advance on the newbie errors. forms.py from django.forms import ModelForm from teamsports.models import Teams class SelectTeam(ModelForm): class Meta: model = Teams fields = ('team_name',) urls.py from django.contrib import admin from teamsports import views urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^admin/', admin.site.urls), url(r'^standings/$', views.StandingsView.as_view(), name='standings'), url(r'^results/(?P<team_name>[\w\-]+)/$', views.ResultsView.as_view(), name='results'), ] Models (only applicable) class Teams(models.Model): team = models.AutoField(primary_key=True) team_name = models.CharField(max_length=225, blank=True, null=True) sport_id = models.ForeignKey(Sports, models.DO_NOTHING, blank=True, null=True) division = models.CharField(max_length=225, blank=True, null=True) school = models.ForeignKey(School, models.DO_NOTHING, blank=True, null=True) win = models.IntegerField(blank=True, null=True, default=0) loss = models.IntegerField(blank=True, null=True, default=0) tie = models.IntegerField(blank=True, null=True, default=0) class Meta: managed = True db_table = 'teams' def __str__(self): return self.team_name views def home(request): schools = School.objects.all() return render(request, 'teamsports/home.html', {'schools' : schools}) class StandingsView(FormView): template_name = 'teamsports/standings.html' form_class = SelectTeam def get_team(self, request, team_name): form = self.form_class(request.GET) if form.is_valid(): data= request.GET.get('team_name') return HttpResponseRedirect(reverse('/results/' + data)) else: β¦ -
Django Signal NameError
I am just curious how the django Signals work. I am been playing with it and stuck. This is my code: -app/models.py class TesterModel (models.Model ): name = models.CharField(max_length=200, default = '') class TesterModel2(models.Model): sub_name = models.CharField(max_length = 200, default = '') -app/urls.py from django.conf.urls import url urlpatters = [ url(r'^addnewdataontest/$',addNewDataOnTest,name='add_new_data_on_test'), url(r'^deletenewdataontest/$', deleteNewDataOnTest, name='delete_new_data_on_test'), ] -app/views.py from django.db.models.signals import pre_save, post_save from django.dispatch import receiver def addNewDataOnTest(request): converted_json_to_dict = getJSONObj( request ) r = TesterModel() r.name = converted_json_to_dict['first'] r.save() return HttpResponse(json.dumps({'rs':'okay'}),content_type='application/json') def deleteNewDataOnTest(request): qs = TesterModel2.objects.latest('id') qs.delete() return HttpResponse(json.dumps({'rs':{'message':'success'}}),content_type='application/json') @receiver(pre_save, sender=TesterModel) def my_handler(sender, **kwargs): q = TesterModel2() q.sub_name = 'It is working!' q.save() This code works well. When I send request to ADD record to the TesterModel will trigger my_handler function and add record to the TesterModel2. Deleting record TesterModel2 is also working, but when I delete record using the django admin on TesterModel2 it Raise an NameError. What is really happening? Django version 1.9 Thank you in advance! Sorry for my poor English. -
Adding model to model
In my models.py I have something like this: class RootModel(models.Model): """ Model to store another models """ name = models.CharField(max_length=30) # ..to do... def __str__(self): return self.name class Model1(models.Model): charfield1 = models.CharField(max_length=20) textfield1 = models.TextField() def __str__(self): return self.charfield1 At let's say, few more models like Model2, Model2 etc., with different fields. RootModel is intended to store another models (somethin like django admin). I would like to have a page, that could display all objects in RootModel with buttons add/delete model selected from the list. I found this question useful in this sense, that (I guess) I can create a view (which activates after pressing 'add' button), that lists all available models with something like: for model in get_models(app): model._meta.db_table But how can I programm action in which user choose from available models in this view, clicks 'add selected model' and those are added to RootModel and then displayed on the home page? -
Should I use Redis or Neo4J for the following use case?
I am building a social network where each user has 3 different profiles - Profile 1, Profile 2 and Profile 3. This is my use case: User A follows Users B, C and D in Profile 1. User A follows Users C, F and G in Profile 2. User C follows Users A and E in profile 3. Another question is that any user on each of these profiles would need to see the latest or (say top N) posts of the users they are following on their respective profiles (whether it is profile 1, 2 or 3). How can we best store the above information? Context: I am c using Django framework and a Postgres DB to store userβs profile information. Userβs posts are being stored on and retrieved from a Cloud CDN. Which is the best way to go implementing these use cases i.e. the choice of technologies to best suit this scenario? Scalability is an other important factor that comes into play here. -
'tuple' object has no attribute 'get'
*AttributeError at / 'tuple' object has no attribute 'get' Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 1.10.3 Exception Type: AttributeError Exception Value: 'tuple' object has no attribute 'get' Exception Location: /home/homa/.local/lib/python2.7/site-packages/django/middleware/clickjacking.py in process_response, line 32 Python Executable: /usr/bin/python Python Version: 2.7.12 Python Path: ['/home/homa/project/firstproject', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/home/homa/.local/lib/python2.7/site-packages', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages'] Server time: Fri, 25 Nov 2016 22:49:08 +0000 :::::::::::::::::::::::::::: from django.conf.urls import include, url from django.contrib import admin from ahmed import views as ahmed_views urlpatterns = [ url(r'^$', ahmed_views.home, name='home'), url(r'^admin/', admin.site.urls), ] Why write in views.py I want a solution -
Custom error pages using django 1.10
Hello I'm newbie in Django, I'm looking to creating custom error pages to my app and found this site: http://blog.eliacontini.info/post/118617321553/django-custom-error-pages However the 'render_to_response' is not used in Django 1.10 How do I transcript this code to Django 1.10 With best regards. -
Creating Stackable Search Filters with Django
I'm trying to integrate search filters into a website that I'm building with Django. On the home page of the website, I want to have all of the items (each of which is an instance of a model) displayed initially. I'm going to have buttons at the top of the page that, when clicked, should sort the items. The button value is going to correspond to a particular field that each object has (like a size field to sort clothing items). So if a user clicks a button that says "male", it should display all male clothes items. If a user then clicks a button that says "pants", the website should display all items that are men's clothing and are also pants. I've tried numerous methods using ajax, but I run into issues because on the initial page load, clothes items are displayed 3 per line. If I simply hide items that have a specific class or value, there will be empty spaces in each of the rows. Another issue I've had with ajax is that I can't access the original template variables (specifically, the queryset of clothes items that are visible to a particular user on their own home β¦ -
How to specify order of template loading in Django?
So I have upgraded an old project from Django 1.6 to 1.10, and now all templatse from a specific directory are no longer loading. the location of these templates are in /project/templates/userena these templates should be overriding the templates included with the userena library in /usr/local/bin/python2.7/dist-packages/userena I have read the Django documentation for template loading but it does not make sense to me at all. Currently my settings.py has this TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates'), ], 'APP_DIRS': False, 'OPTIONS': { 'debug': DEBUG, 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], 'loaders': [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ], }, }, ] What do I need to change in my settings.py in order to have Django load templates from /project/templates/userena? -
Serving Media in Production
This is well known topic, on how to setup, serve MEDIA Files, but there is a lot of no no to serving them in production, this is just one example from answered question on SO, Django does not serve MEDIA_ROOT by default. That would be dangerous in production environment. But in development stage, we could cut short. Pay attention to the last line. That line enables Django to serve files from MEDIA_URL. This works only in developement stage Obviously there is a lot of web application that are handling this, I have a field in which I'm expecting a lot of CV to be uploaded, my concern are corrupted files, so is there a common pattern on how to handle this? -
Model with two foreign keys to same model returns only one of the relations?
Below is a simplified version of two models used in my app. Each Payment has a Member which it concerns, and each Payment has a registeree which is another Member. I'm trying to list all Payments in a template, with both to the Member and the registeree for each Payment, and I'm using select_related to join in the necessary information from related tables. However, in the template my payment.registeree is somehow the same object as the payment.member. Any tips? class Member: # name etc user = models.OneToOneField(User) # django.auth.models.User # more fields... class Payment: member = models.ForeignKey('app.Member', related_name='payment_set') registeree = models.ForeignKey('app.Member', related_name='registeree_set') # more fields... class PaymentListView(ListView): def get_queryset(self): return (Payment.objects.all() .select_related('member__user', 'registeree__user')) {{ payment.member.user.first_name }} # returns correct name of member {{ payment.registeree.user.first_name }} # returns the name of the member not the registeree