Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
String Variables in XML
In Python 3 you can insert string variables into a string like so: print("Hi %s how are you?" % name) How would you do the same thing in an XML string in a view? Something like: <Response><Message>Hi %s how are you?</Message></Response> % name Note that I'm doing this in a view (as a response to a Twilio request) rather than a template, so I can't simply insert a template variable. -
Exact field search in the Django admin
I'm trying to configure the Django admin bindings for a specific model so that I can quickly filter by the exact value of a specific field. I know I can manually tamper with the GET parameters to do this: ?fieldname__exact=foobar What I can't seem to do, is get the sidebar to display a small form where I can enter this value. I know I can add fieldname to list_filter, but that doesn't scale well beyond tens of unique values. I looked into django-advanced-filters for a bit, but it doesn't seem to be compatible with Django 1.11. How can I implement exact search for a specific field in the Django admin? -
Type error detailed view
Hello I get an type error (takes 2 arguments but only 1 given.) in /taskoftheday. I don't know what I should do to fix it. What argument am I missing? I want the create a detailed view for each guide ID. Here is my code: Views: from django.http import Http404 from django.http import HttpResponse from django.shortcuts import render from models import Guide, Step, Sub_step def taskoftheday(request, guide_id): try: guide = Guide.objects.get(pk=guide_id) except Guide.DoesNotExst: raise Http404("Guide does not exist") return render(request, 'taskoftheday/taskoftheday.html', {'guide': guide}) def detail_taskoftheday(request): return render(render, 'taskoftheday/detail_taskoftheday.html') urls: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.taskoftheday, name="taskoftheday"), url(r'(?P<guide_id>[0-9]+)/$', views.detail_taskoftheday, name='detail_taskoftheday'), ] Thanks! :) -
Return all data from two tables with FK
I develop web server with Django project but I can't generate query with all statements of tables. I explain this. class A(models.Model): i = models.ForeignKey('I', blank=True, null=True) j = models.ForeignKey('J', blank=True, null=True) k = models.ForeignKey('K', blank=True, null=True) date = models.DateTimeField(blank=True, null=True) class Meta: unique_together = (('i', 'j'),) class B(models.Model): z = models.ForeignKey('Z', on_delete=models.CASCADE) a_id = models.ForeignKey('A', on_delete=models.CASCADE) class Meta: unique_together = (('z', 'a_id'),) In this moment I realize these queries, start and end are okay b_result=B.objects.all().values('a_id') print "b_res -> ", b_result I obtain this, a_result=A.objects.filter(date__range=[start, end]).filter(st_work__in=st) They work fine but when I print a_result.query, I obtain only data from class A and a IN statement from SQL SELECT "A"."id", "A"."i_id", "A"."j_id", "A"."k_id", "A"."date" FROM "A" INNER JOIN "B" ON ("A"."id" = "B"."a_id_id") WHERE ("A"."date" BETWEEN 2009-04-23 18:25:43.511000+00:00 AND 2017-09-29 18:25:43.511000+00:00 AND "B"."id" IN (SELECT U0."a_id_id" AS Col1 FROM "B" U0)) I can't return all data, I need statements_class_A | statements_class_B related by your FK. -
I am trying to maths on a django object and failing. any help appreciated
My model class Credits(models.Model): creds = models.IntegerField(default=0) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) My view def addjobdata(request): n = JobInfo.objects.create(title=request.POST['title'], start_date=timezone.now(), end_date=timezone.now() + datetime.timedelta(days=int(request.POST['days'])), rate=request.POST['rate'] ) if int(Credits.objects.get(user_id=request.user).creds) > int(request.POST['days']): Credits.objects.get(user_id=request.user).creds -= int(request.POST['days']) Credits.objects.get(user_id=request.user).creds.save() return HttpResponseRedirect(reverse('datedisplay:infos', args=(n.id,))) else: return render(request, 'datedisplay/menu.html') In the if loop I am trying to take a number from an integer field and save the result but am failing to do so. Any ideas where I've messed up? -
How Django adds trailing slash
Working with the Django-powered project that would automatically put a trailing slash at the end. So: foo.com/bar would become a foo.com/bar/ I have read that there is a CommonMiddleware class which has an APPEND_SLASH attribute with which trailing slash can be controlled. My project import CommonMiddleware indeed: MIDDLEWARE_CLASSES = ( ... 'django.middleware.common.CommonMiddleware', ) However APPEND_SLASH is never set anywhere. And the project keeps adding trailing slash. Question: does APPEND_SLASH get set to True by default if you import CommonMiddleware? Are there any ways to control the trailing slash? -
Django - name a Model field with a number
I would like to name the fields of my Django model with integers. I found the way to do it in MySQL but the same seems not applicable in Django. If I write something like: class WidgetContributionDevelopment(models.Model): site = models.ForeignKey(Site, db_column='site_id', default=None) `1` = models.FloatField(default=0.0) `2` = models.FloatField(default=0.0) `3` = models.FloatField(default=0.0) I get a syntax error. Is there a way to do it? Thanks. -
When To Use A View Vs. A New Project
This is a non-specific question about best practice in Django. Also note when I say "app" I'm referring to Django's definition of apps within a project. How should you go about deciding when to use a new view and when to create an entirely new app? In theory, you can have a simple webapp running entirely on one views.py for an existing app. So how do you go about deciding when to branch off to a new app or just add a new function in your views.py? Is it just whatever makes the most sense? -
Can't load statics, Django rest_framework on Apache, Windows
So, i'm trying to learn django as well as trying to make an app with Angular and Django REST backend on Apache server via mod_wsgi. Currently, i got a problem with static files. Everyhing is ok when app runs with Django tools on 127.0.0.1:8000, but when i load it via Apache - i'm missing statics, so output looks very raw: I tried to collect statics with manage.py collectstatics, tried to define a dir with statics in python dirs - got nothing: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'DjangoApp/static/') STATICFILES_DIRS = [ 'C:/Users/<user>/AppData/Local/Programs/Python/Python36-32/Lib/site-packages/rest_framework/static', ] Can you suggest a solution? -
change date format in django logs
This is my formatter in django logging in settings.py 'standard': { 'format' : "django: %(levelname)s [%(asctime)s] %(module)s %(process)d %(thread)d %(message)s", 'datefmt' : "%Y-%m-%dT%H:%M:%S +05:30" }, I expect the logs' timestamp to be formed in the format something like this, [2017-07-21T20:50:47 +0530]. But still the logs are in the default format. 2017-07-24 12:01:02,790 Am I doing this correctly ? -
getting Error=redirect_uri_mismatch from google trying to exchange auth_code for access_token using django-rest-auth
I am building a rest api that gets authorization code from Android app and send id my server. It aims to provide registration with google. I am using for it two libraries: djangorestframework-oauth==1.1.0 django-rest-auth==0.9.1 This is implementation of my login/register class class GoogleLogin(SocialLoginView): adapter_class = GoogleOAuth2Adapter client_class = OAuth2Client callback_url = 'http://localhost:8000/v1/accounts/google/login/callback/' I set everything in https://console.developers.google.com/apis/credentials?project=testserwusapp I created Id client 0Auth for web applicatio. I added http://localhost:8000 to authorized javascript sourced and http://localhost:8000/v1/accounts/google/login/callback/ to Authorized redirect URI. I tried many variations of those links. Both with slash and without slash in the end. I set both client id and client secret key in my django app. However, I get Error=redirect_uri mismatch trying to exchange auth_code for access_code. What is more I tried to use ngrok to publish my ip. I though that maybe google won't work with localhost but it didn't help. -
Using function into template (Django/Python)
I'm trying to use a function that compare the keys from headers and datas of a form. If the keys aren't similar, this function adds an empty field. It works perfectly fine in my views.py : #Entries define all the datas taken from the fobi forms. headers = json.loads(entries{0}.saved_data) headers = headers.items() for key, value in headers: for data in entries: data = json.loads(data.saved_data) formatted[value] = data.get(key, '') print(entries) formatted = formatted.items() Then i pass formatted into the context and in my template i did : <tr> {% for key, valeur in headers %} <th> {{ key }} </th> {% endfor %} </tr> </thead> <tbody> <tr> {% for key, valor in headers %} {% for cle, valeur in formatted %} {%if cle == valor%} <td> {{valeur}}</td> {% endif %} {% endfor %} {% endfor %} </tr> </tbody> The result is perfect, such as every header is aligned with the datas. And if there are some datas missing such as picture, there is an empty sace in this column. I only printed one form through my loop ( the last saved from the formatted dict). And i want to print all my forms. But it seems impossible in the views.py. How … -
django geocoder to find near by coordinates
I'm using geocoder, I have database of coordinates, I want to fetch the coodinates within the radius of 5 km using geocoder. In rails I could do that as followed: Venue.near([40.71, -100.23], 20) # venues within 20 miles of a point how to do this django geocoder???? -
Operrational Error: No such table :
I have a database file I downloaded online and i am trying to get the contents from that database and display it on a template Here is the code from my view. "getAllTeamNames() is the call to a method that connects to the database and gets the contents and returns a list from django.shortcuts import render from myTest.models import * databaseFile ="C:/Users/Joe Malebe/Documents/Python Scripts/envSite/sampleSite/database.sqlite" def index(request): return render(request,'myTest/home.html') def teams(request): teamsList = getAllTeamNames(databaseFile) context = { 'obj':teamsList, } return render(request,'myTest/teams.html',context) Here is the method that gets the data and returns a list of objects def getAllTeamNames(databaseFile): print(databaseFile) conn = create_connection(databaseFile) cur = conn.cursor() cur.execute("SELECT id,team_long_name FROM Team") rows = cur.fetchall() teamList = [] for row in rows: team = Team(row[0],row[1]) teamList.append(team) # print(team) return teamList This is the response I get If I run my view on the console, I will get all the objects but when I run it on the server I get the error -
Django rest framework group based permissions for individual views
I am using DRF for writing API's. I would like to give different permissions for each view in my Modelviewsets. I have two groups(customers and staff). I have filtered them as Isstaff and Iscustomer in permissions.py. class Iscustomer(permissions.BasePermission): def has_permission(self, request, view): if request.user and request.user.groups.filter(name='customers'): return True return False class Isstaff(permissions.BasePermission): def has_permission(self, request, view): if request.user and request.user.groups.filter(name='staff'): return True return False I am trying to overide using get_permissions method. When I put a single group in self.permission_classes, it works fine. class cityviewset(viewsets.ModelViewSet): queryset = city.objects.all() serializer_class = citySerializer def get_permissions(self): if self.request.method == 'POST' or self.request.method == 'DELETE': self.permission_classes = [Isstaff] return super(cityviewset, self).get_permissions() But, when i try to put multiple groups in self.permission_classes, it fails. def get_permissions(self): if self.request.method == 'POST' or self.request.method == 'DELETE': self.permission_classes = [Isstaff,Iscustomer,] return super(cityviewset, self).get_permissions() -
Web Development - Should social login be performed on frontend or handled on the backend of and application?
I am building a social login based application using Django on the backend and I want to know whether it is a good practice to do Social Auth(facebook, google, github, twitter etc.) on the front end or the backend of an application? For example, If I want to allow a user to signup using their facebook account, is it a good idea to handle that using JavaScript on the front end or using Django on the backend(e.g, using something like social_auth_app_django)? -
i wanna build a webapp with angular2 and django
settings.py ANGULAR_APP_DIR = os.path.join(BASE_DIR, 'front/dist') STATICFILES_DIRS = [ os.path.join(ANGULAR_APP_DIR), ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') Context: I am getting error like this:- ..File "C:\Python27\lib\site-packages\django\core\files\storage.py", line 397, in listdirfor entry in os.listdir(path):WindowsError: [Error 3] The system cannot find the path specified: u'C:\Users\admin\ backend \front\dist\*.* how i need to give path to connect Angular 2 app with Django app.. i tried above code in Django app to link Front end angular 2 app..?? I want to integrate Angular 2 with Django.. what i wanna do please help me with good source. -
Add dynamically new fields to createview - django
I want to add new fields to form used in CreateView. model is, class X(): name = '' dob = '' some_random_field = '' CreateView, from django.views.generic import CreateView class XX(CreateView): model = X This view will generate form with 3 fields. I want to show two dynamic fields in place of some_random_field say random1 and random2. And based on these 2 fields I have to save some_random_field without creating ModelForm for class X. Any help or guidance would be greatly appreciated -
django datetime field customized update
created_at = models.DateTimeField(auto_now_add=True, auto_now=False) updated_at = models.DateTimeField(auto_now_add=False, auto_now=True) My table contains the following fields: | id | created_at | updated_at | Longitude | Latitude | I am manually inserting some values in Longitude and Latitude column and hoping created_date and updated_date fields get updated whenever i insert new record. These record are inserted from excel sheet. Simply, I am taking the value from excel and putting into the the table using mysqldb I am able to do this without django database with the following code. import MySQLdb #For database operations import xlrd #For reading excel file import time book = xlrd.open_workbook('my_data.xlsx') s1 = book.sheet_by_name('prasad') db = MySQLdb.connect(host = 'localhost', user = 'root', passwd = 'lmtech123', db = 'server_db') cur = db.cursor() query = "insert into eyeway_devicedata(Longitude, Latitude) values(%s, %s)" for r in range(1,s1.nrows): ln = str(s1.cell(r,8).value) lt = str(s1.cell(r,7).value) values = ln, lt cur.execute(query, values) #insert the data into the table db.commit() time.sleep(5) db.close() But i want to load the data in django database with its datetime field facility. Is it possible? Please help. -
How to get the reverse of a many to many relationship in Django
I have a model for articles with various attributes like author, title, etc. One of the attributes is "comments_on" for all of the articles that the article in question (let's call it "main article" for now) is responding to. I use a reciprocal many-to-many relationship to represent this. I know how to display on a website all of the articles that the main article comments on. I would like to know if it's possible to display all of the articles that have commented on the main article. I assume I don't need to create a separate field in my model for this since the relationship between the main article and other articles that comment on the main article is reflected in the same reciprocal many-to-many relationship. Any idea what the code for this is? Thank you. -
Write a wrapper to expose existing REST APIs as SOAP web services?
I have existing REST APIs, written using Django Rest Framework and now due to some client requirements I have to expose some of them as SOAP web services. I know this is an odd situation but any help would be greatly appreciated. -
Cant figure out right queryset for json in django
i need a help to get django query where my json file should get this data as output. I tried many ways but im getting it in bits and not completely. I'm new to Django and stuck with this for long. Please help. Thanks:) [{ "Group": "Mars", "count": 10, "months": "June" }, { "Group": "Jupiter", "count": 50, "months": "June" }, { "Group": "Mars", "count": 70, "months": "July" }, { "Group": "Jupiter", "count": 60, "months": "July" }, { "Group": "Mars", "count": 30, "months": "August" }, { "Group": "Jupiter", "count": 40, "months": "August" }]; I have possibly tried to get count of mars and jupiter in my views.py as follows which gives json as [{'Group':'Mars','count':10},{'Group':'Jupiter','count':50}] now months is added which is what im not getting. views.py fm_ds=Details.objects.filter(Group='Jupiter',Div='Cross',Shift='Day').count() m_ds=Details.objects.filter(Group='Mars',Div='Cross',Shift='Night').count() Jupiter_dict={} Jupiter_dict['Group']='Jupiter' Jupiter_dict['count']=fm_ds Mars_dict={} Mars_dict['Group']='Mars' Mars_dict['count']=m_ds print Jupiter_dict print Mars_dict details_dict=[Mars_dict,Jupiter_dict] context = {'data_json': json.dumps(details_dict)} -
Django Error ---index() missing 1 required positional argument: 'pk'
I have this error when try to open a path. It requires a pk in my def and i inserted it, but still the issue is there. If someone could help, i would owe you a lot! This is the error i have in browser: TypeError at /batches/ index() missing 1 required positional argument: 'pk' Request Method: GET Request URL: http://127.0.0.1:8000/batches/ Django Version: 1.11.1 Exception Type: TypeError Exception Value: index() missing 1 required positional argument: 'pk' Exception Location: /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py in _get_response, line 185 Python Executable: /Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 Python Version: 3.6.1 Python Path: ['/Users/cohen/Documents/project/sanctions', '/Users/cohen/Documents/project/sanctions', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python36.zip', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/PyObjC'] Server time: Mon, 24 Jul 2017 10:47:02 +0000 My urls in batches from django.conf.urls import url from . import views urlpatterns = [ # /batches/ url(r'^$', views.index, name='index'), # /batches/2 url(r'^(?P<batches_id>[0-9]+)/$',views.detail, name="detail"), # businessname/1 url(r'^(?P<businessname_id>[0-9]+)/$',views.index_businessname, name="detail_businessname"), # individuals/1 url(r'^(?P<individuals_id>[0-9]+)/$', views.index_individuals, name="detail_individuals"), ] And the views: # -*- coding: utf-8 -*- from __future__ import unicode_literals from .models import BusinessName from .models import Individuals from .models import Batches from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request, pk): all_Batches = Batches.objects.all() html = '' for batch in all_Batches: url = '/batches/' + str(batch.id) + '/' html += '<a … -
inline formset factory update view
i want to get in inline formset factory in update view extra=0, if it have more than 1 contact. So this is my code forms.py class ShopForm(ModelForm): class Meta: model = Shop exclude = ['user', 'slug', 'counter'] def __init__(self, *args, **kwargs): super(ShopForm, self).__init__(*args, **kwargs) for field in iter(self.fields): self.fields[field].widget.attrs.update({ 'class': 'form-control' }) def clean_logo(self): logo = self.cleaned_data['logo'] if not logo: raise forms.ValidationError("Логотип обязателен для заполнения", code='no_logo') return logo ShopInlineFormSet = inlineformset_factory(Shop, Contacts, extra=1, fields=( 'published', 'phone', 'address', 'place', 'latitude', 'longitude', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'), can_delete=True) models.py class Shop(PublishBaseModel, Counter): class Meta: verbose_name = 'Магазин' verbose_name_plural = 'Магазины' user = models.ManyToManyField(to=User, verbose_name='Администратор магазина') title = models.CharField(max_length=255, verbose_name='Название магазина') slug = models.CharField(max_length=32, verbose_name='Название на транслите', unique=True) email = models.EmailField(verbose_name='E-mail магазина') short_description = models.TextField(verbose_name='Короткое описание магазина') description = models.TextField(verbose_name='Полное описание магазина') logo = models.ImageField(upload_to='images/shop/logo/', default=settings.DEFAULT_IMAGE, verbose_name='Логотип') class Contacts(PublishBaseModel): class Meta: verbose_name = 'Контакт' verbose_name_plural = 'Контакты' address = models.CharField(verbose_name='Адрес', max_length=255, null=True, blank=True) phone = models.CharField(max_length=255, verbose_name='Телефон', null=True, blank=True) shop = models.ForeignKey(Shop, verbose_name='Магазин', null=True) place = models.ForeignKey('Place', verbose_name='Торговая точка', null=True, blank=True) latitude = models.CharField(max_length=255, verbose_name='Широта', null=True, blank=True) longitude = models.CharField(max_length=255, verbose_name='Долгота', null=True, blank=True) monday = models.CharField(max_length=255, verbose_name='Понедельник', null=True, blank=True) tuesday = models.CharField(max_length=255, verbose_name='Понедельник', null=True, blank=True) wednesday = models.CharField(max_length=255, verbose_name='Понедельник', null=True, blank=True) … -
Crawl news website from rss with scrapy
I want to read some news websites rss feeds for example nytimes.com rss: <item> <title> White House Signals Acceptance of Russia Sanctions Bill </title> <link> https://www.nytimes.com/2017/07/23/us/politics/trump-russia- sanctions.html?partner=rss&emc=rss </link> </item> <item> <title> News Analysis: For Trump and Putin, Sanctions Are a Setback Both Sought to Avoid </title> <link> https://www.nytimes.com/2017/07/23/world/europe/trump-putin- sanctions-hacking.html?partner=rss&emc=rss </link> </item> find new items that i didn't read yet, and for each item store link, title and GET link to crawl some content of it. my question is can i use scrapy for this purpose and if yes, how?