Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django checkboxes: pass value to another page (search -> search results)
I have a google-like searchbar on my homepage. index.html <form method="get" action="/search/" id="searchbarform"> <div id="searchbargroup" class="form-group"> <input id="homejs" type="text" class="form-control large input-medium search-query" name="q" placeholder='"Computer Science", "Web Analytics", "2INC0"'> <input type="submit" class="btn btn-default btn-main" id="searchbarbutton" value="Search!"> </div> <!-- form-group --> <label><input type="checkbox" name="checkbox" value="summariesbox" checked>Summaries</label> <label><input type="checkbox" name="checkbox" value="examsbox" checked>Exams</label> <label><input type="checkbox" name="checkbox" value="coursesbox" checked>Courses</label> <label><input type="checkbox" name="checkbox" value="majorsbox" checked>Majors</label> </form> The searches work fine, but I want to use the values of the checkboxes to limit the search results based on the values. The problem is that I cannot find a way to pass the values to the searchresultpage. Other people on stackoverflow used the values of the checkboxes on the same page. this is the view that gets called when you search something: views.py def search(request): if request.method == "POST": form = UserForm(request.POST) if form.is_valid(): new_user = User.objects.create_user(**form.cleaned_data) login(request, new_user) return redirect('index') else: form = UserForm() query = request.GET['q'] results = Resource.objects.filter(title__icontains=query) courses = Course.objects.filter(name__icontains=query) summaries = Resource.objects.filter(title__icontains=query) .filter(resourcetype = "Summary") exams = Resource.objects.filter(title__icontains=query) .filter(resourcetype = "Exam") return render(request, 'main/searchresults.html', {'courses': courses, 'summaries': summaries, 'results': results, 'exams': exams, 'query': query}) Other threads (Django check if checkbox is selected), write code in the view function that is associated with … -
Integration of django authentication system with Facebook API
I am integrating Django authentication and login system with Facebook Login API. The problem is that once Facebook username will be the same as existing in my project's database so the only solution to the problem is to catch Facebook username and add numbers or something to the string to make it unique ? Is it correct ? How is it normally handled ? -
the user who logined by python-social-auth can't access the page that is only logined user.(Django)
the user who register my homepage directly, he can access the homepage which is need logined. but the user who register by python-social-auth, he can login. but he can't access homepage which is need logined. what is problem? could you help me -
How to join tables in django
Please excuse me for this silly question, I'm a beginner and I can't find my way through documents. I have two models: class Student (models.Model): name = models.CharField(max_length=40) family = models.CharField(max_length=40) school = models.ForeignKey(School) class School (models.Model): name = models.CharField(max_length=40) rate = models.IntegerField(default=-1) I want to have a list of students which includes all data of school in it: [ { "name": "John", "family": "Doe" "school": { "name": "J.F.K", "rate": 1 } } ... ] How can I do this with django ORM? -
Django static media not showing picture
after searching for a solution for hours which did not resolve my problem,I am posting this. The image from my media root is not showing up on my html. In chrome's console i get a 404 file not found.Even though the image is there. I am using Python 3 ,Django 1.10 in Pycharm. This is the model which is where i upload images to: from django.db import models class Post(models.Model): username = "anonymous" post = models.ImageField(upload_to='anon') creation_date = models.DateTimeField(auto_now_add=True) def __str__(self): return Post.username views.py: from django.shortcuts import render,get_object_or_404 from .models import Post def home(request): return render(request,"base.html",{}) def post_detail(request,id=None): instance = get_object_or_404(Post,id=id) context = { "post": instance.post, "instance": instance } return render(request,"post_detail.html",context) post_detail.html(here the image isnt showing): <body> <img src = "{{ instance.post.url}}" height="520" width="500"><br> {{ instance.creation_date }}<br> {{ instance.username }}<br> </body> Parts of setting.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Post', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'Post.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, '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', ], }, }, ] WSGI_APPLICATION = 'Post.wsgi.application' # Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': … -
Url reverse error
I've got a url with two fields user_id and code: url(r'^account_completion/(?P<user_id>d+)$/(?P<code>[-w]+)$', confirm_verification, name="confirmation_link"), I've tried getting the link from the shell got an error In [2]: reverse('confirmation_link', args=(123,'aaaaaaa'))/home/samuel/Documents/code/kazi/django_project/django_project/urls.py:34: t = url(prefix=prefix, *t) --------------------------------------------------------------------------- NoReverseMatch Traceback (most recent call last) ... ... NoReverseMatch: Reverse for 'confirmation_link' with arguments '(123, 'aaaaaaa')' and keyword arguments '{}' not found. 1 pattern(s) tried: ['register/account_completion/(?P<user_id>d+)$/(?P<code>[-w]+)$'] -
Generating download link in djano
I have referred to multiple django question regarding file download and this was the solution suggested. {% for task in tasks %} <tr><td><strong> name {{task.name}}</strong></td> <td><strong> date {{task.date_created}}</strong></td> <td><strong> status {{task.status}}</strong></td> <td><strong> id {{task.id}}</strong></td> <td><strong> input file {{task.input_file_path}}<td> <td><a href="{{task.output_file_path}}" download>output file</td></tr> {% endfor %} The solution suggested is <a href="{{task.output_file_path}}" download> However, when i check my django request. It shows up this in console. GET /adv_filters/check/download/download/download/download/download/download/download/download/download/download/download/download/download/download/download/download/download/download/download/download/input_files/input_files/input_files/input_files/input_files/task4 HTTP/1.1" 200 2524 For testing purposes. I have set the location of the output file to be the location of the input file. My relevant views.py document.input_file_path = 'input_files/' + document.name document.output_file_path = 'input_files/' + document.name Is there anymore information i would need. -
Updating MLab document in Python views but cannot find id
In my previous code, I am passing a geojson file directly. But this time, I modified the code that directly gets all objects from my Mlab DB through python models. models.py from mongoengine import * class Route(Document): type = StringField(required=True) route_id = StringField(required=True) geometry = LineStringField() properties = DictField() meta = {'collection':'routes'} views.py def index(request): features = [r._data for r in Route.objects.all()] geojson = {'type': 'FeatureCollection', 'features': features} return render(request, settings.TEMPLATES[0]['DIRS'][0] + '/load-map.html', { 'routes' : jsonpickle.encode(geojson) }) I'll be passing this to render in a Leaflet map thus the code above (jsonpickle.encode(geojson)) to make it a Geojson Feature Collection. I was expecting it to work the same way however, there seems to be a problem when it comes to obtaining the Object it... Instead of the usual code below to update a document: line = json.loads(request.body) _id = line['id'] try: Route.objects(id=ObjectId(_id.get('$oid'))).update(set__geometry=geometry, set__properties=properties) return HttpResponse("Success!") except: return HttpResponse("Error!") I couldn't get it to work because of the format that I found when printing out line trying to get the ObjectId: {u'py/object': u'mongoengine.base.datastructures.SpecificStrictDict', [... u'id': {u'py/object': u'bson.objectid.ObjectId', u'py/state': {u'py/b64': u'WC/JW7er55Q/GkhL\n'}}} How can I resolve this? -
Update javascripts that are cached in the Chrome browser
I have a Django + Guicorn + Nginx project. My problem is that every time after I had deployed a new change on EC2, the new change wouldn't get updated in the browser unless I deleted the cache locally. I don't really have a clue as of why this is the case and how I am supposed to implement my project to prevent this problem. -
MySQL: django.db.utils.OperationalError: (1366, "Incorrect integer value: 'Category object' for column 'category_id' at row 1")
Using MySQL with Django, I have changed a model from using strings for "category" to using a FK. It is now broken with django.db.utils.OperationalError: (1366, "Incorrect integer value: 'Category object' for column 'category_id' at row 1") Initially, it looked like: class ItemRecord(models.Model): catalog_id = models.IntegerField() name = models.CharField(max_length=250) price = models.DecimalField(max_digits=7, decimal_places=2) active = models.BooleanField(default=True) # is the item being sold at all? (carried) in_stock = models.BooleanField(default=True) # is the item currently in stock? banned = models.BooleanField(default=False) category = models.CharField(max_length=250, null=True, blank=True) class Meta: abstract = True class FermentableRecord(ItemRecord):#record of each item pass class HopRecord(ItemRecord): pass class YeastRecord(ItemRecord): pass Then, I use FK: class Category(models.Model): name = models.CharField(max_length=250) banned = models.BooleanField(default=False) class ItemRecord(models.Model): catalog_id = models.IntegerField() name = models.CharField(max_length=250) price = models.DecimalField(max_digits=7, decimal_places=2) active = models.BooleanField(default=True) # is the item being sold at all? (carried) in_stock = models.BooleanField(default=True) # is the item currently in stock? banned = models.BooleanField(default=False) category = models.ForeignKey(Category, related_name="items") class Meta: abstract = True class FermentableRecord(ItemRecord):#record of each item pass class HopRecord(ItemRecord): pass class YeastRecord(ItemRecord): pass This broke from using the same related name on 3 different Record models. Now I have: class Category(models.Model): # TODO: install "category = models.ForeignKey(Category, related_name='item_records')" in the ItemRecord model. # this … -
Django REST Framework serializer with different models
I have three different models that I want to gather in a feed type page. They do all contain different types of things but for simplicity, the models are the same in this instance. class ObjectA(models.Model): text = models.TextField() pub_date = models.DateTimeField('date published',auto_now_add=True) ... class ObjectB(models.Model): text = models.TextField() pub_date = models.DateTimeField('date published',auto_now_add=True) ... class ObjectC(models.Model): text = models.TextField() pub_date = models.DateTimeField('date published',auto_now_add=True) ... What would be the general idea to serialize lists of all three objects into one list ordered by pub_date using the Django REST Framework. I just have experience using the meta version below but it can only deal with one model I am assuming. Thanks in advance. class ObjectAListSerializer(serializers.ModelSerializer): class Meta: model = ObjectA fields = [ 'text', 'pub_date' ] Pretty much trying to create something that would work like this: class AllObjectsListSerializer(serializers.ModelSerializer): -
How to sort list dictionaries by two nested keys?
{'AvailableOffers': (d7b000a:Order {Amount:1000,Name:"000091",OfferedC:"JD",SeekingC:"Taobao",UserName:"xalima",ValidTill:"2019-11-30"}), 'Participants': 2, 'OrderID': ['000089', '000091', '000089']} {'AvailableOffers': (d7b000a:Order {Amount:1000,Name:"000091",OfferedC:"JD",SeekingC:"Taobao",UserName:"xalima",ValidTill:"2019-11-30"}), 'Participants': 2, 'OrderID': ['000089', '000091', '000089']} {'AvailableOffers': (b222004:Order {Amount:1000,Name:"000093",OfferedC:"JD",SeekingC:"China Airline",UserName:"yunis",ValidTill:"2017-11-11"}), 'Participants': 3, 'OrderID': ['000089', '000093', '000090', '000089']} {'AvailableOffers': (d7b000a:Order {Amount:1000,Name:"000091",OfferedC:"JD",SeekingC:"Taobao",UserName:"xalima",ValidTill:"2019-11-30"}), 'Participants': 5, 'OrderID': ['000089', '000091', '000096', '000095', '000090', '000089']} {'AvailableOffers': (d7b000a:Order {Amount:1000,Name:"000091",OfferedC:"JD",SeekingC:"Taobao",UserName:"xalima",ValidTill:"2019-11-30"}), 'Participants': 6, 'OrderID': ['000089', '000091', '000096', '000097', '000093', '000090', '000089']} THAT IS THE LIST DICTIONARY I WANT TO SORT, what i can do now is to sort ListData_by_Participants = sorted(ListData, key=itemgetter("Participants")) What i want to get help is ListData_by_Validity = sorted(ListData, key=itemgetter("AvailableOffers")("ValidTill")) is there a way to manage this ? -
Using django widgets with the django form builder
See here: https://github.com/stephenmcd/django-forms-builder and here: https://github.com/furious-luke?tab=overview&from=2017-01-01&to=2017-01-15 I am trying to have a field for a users street address on a django form. This input needs to be validated by google maps. I'm at a loss at how to combine the django address widget into the forms builder. I know it involves these two settings fields: FORMS_BUILDER_EXTRA_FIELDS = and FORMS_BUILDER_EXTRA_WIDGETS = but nothing I have put in either has allowed me to access the field (but I do get an assortment of errors). Any ideas or input would be greatly appreciated. -
Trouble setting up Django-Assets / Webassets and directory locations
Was looking for a Python package for Django to manage assets, using Sass to compile CSS, and also cache busting, and Django-Assets / Webassets was recommended. Having trouble getting it setup though with my directory structure. By default it looks for assets.py in each installed app. I want to set it up so that it sits in the same directory as settings.py and compiles app specific assets from each app directory into /static/js and /static/css. I have django_assets in INSTALLED_APPS. According to the docs it looks like I needed to add this to settings.py: ASSETS_MODULES = [ 'project_dir', ] Or: ASSETS_MODULES = [ os.path.join(BASE_DIR, 'project_dir'), ] Or: ASSETS_MODULES = [ PROJECT_ROOT ] At any rate, it just returns No asset bundles were found. If you are defining assets directly within your template, you want to use the --parse-templates option. Even moving the assets.py into one of the app directories, it is looking in BASE_DIR/scripts which is where I keep my manage.py. Again, changing ASSETS_ROOT doesn't really same to be doing anything. ~/portal-client project_dir apps account templates account login.html forms.py urls.py views.py home templates home home.html urls.py views.py results assets.py settings.py urls.py scripts manage.py static templates base.html footer.html title.html -
How to deploy my python machine learning code in website form
Can somebody point me in the right direction on how I can set up my machine learning code into a user friendly website for example using the famous University of California Irvine data for breast cancer ready to be used for researchers. A researcher can simply enter the values and get the result for the tumor another good example there are a lot of sentiment analysis websites using NLTK you just paste your text and a positive or negative result will appear. I want my code to be user friendly on a website a simple Q&A and get your result. I am new to the world of programming and coding but I think it's very important to mention that the website will have one page for K-means and one page for SVM and users can push a button and calculate average between the two result of K-means -
How to delete all data from a table in django inside a scrapy spider
I have this scrapy spider that populates a table, 10 to 20 records maximum get scraped and inserted into the table. So I figured instead of seeing if a record exists and update it, it would be faster just to get rid of them and scrape new ones to take their place, what would you think is the better option seeing as how I practically have no data in my table? Also what is the django orm command to delete with the help of a where clause, e.g delete all records that have "cat" as name? Thank you very much -
Django: Page Not Found
I'm getting a 404 from Django and none of the previous posts on the subject (of which there are many) seem to have helped. views.py from django.views.generic.detail import DetailView, SingleObjectMixin from app.models import MyModel class MyDetails(DetailView, SingleObjectMixin): template_name = "app/my_view.html" model = MyModel urls.py from django.conf.urls import include, url from django.contrib import admin from app.views import MainList, post_form_upload, MyDetails urlpatterns = [ url(r'^$', MainList.as_view(), name="main_list"), url(r'^add_something$', post_form_upload, name="add_something"), url(r'^my_details/(?P<pk>\d+)$', MyDetails.as_view(), name="my_details"), ] app/urls.py from django.conf.urls import url from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ (r'^$', include('app.urls')), url(r'^admin/', include(admin.site.urls)), ] when I enter the URL: http://localhost:8000/my_details, I get the following error: Using the URLconf defined in app.urls, Django tried these URL patterns, in this order: ^$ [name='main_list'] ^add_something$ [name='add_something'] ^my_details/(?P<pk>\d+)$ [name='my_details'] The current URL, my_details, didn't match any of these. The other two URLs (/ and /add_something) work fine. -
How to I send an Id After creating a new record Django?
Good evening I'm doing an application with django and I need that after creating a record I address with HttpresponseRedirect taking the id of this new record to a new view and a different template. url.py urlpatterns = [ url(r'^$', beneficiario, name='beneficiario'), url(r'^beneficiario_create/(?P<id>\d+)/$', beneficiario_create, name='beneficiario_create'), ] wiews.py def datosBasicos(request): if request.method == 'POST': beneficiario = Beneficiario() beneficiario.numeroDocumento = request.POST['numeroDocumento'] beneficiario.nombreUno = request.POST['nombreUno'] beneficiario.save() ben = Beneficiario.objects.get(id=beneficiario.id) messages.success(request, validator.getMessage()) return HttpResponseRedirect('/beneficiario/beneficiario_create/%d/'%ben.id) return render(request,'datosBasicos.html', informacion) def beneficiario_create(request, id): beneficiario = Beneficiario.objects.get(id = id) return render(request,'beneficiario_create.html') -
Django error during template template rendering because URL tag
The error is on this line: <li><a href="{% url 'app:detail' college.id %}">{{ college.college_name }}</a></li> Here is the whole template (index.html): {% if latest_college_list %} <ul> {% for college in latest_college_list %} <li><a href="{% url 'app:detail' college.id %}">{{ college.college_name }}</a></li> {% endfor %} </ul> {% else %} <p> No colleges available </p> {% endif %} The view: from django.shortcuts import get_object_or_404, render from .models import College # Create your views here. def index(request): latest_college_list = College.objects.order_by('college_name') context = {'latest_college_list': latest_college_list} return render(request, 'app/index.html', context) def detail(request, college_id): college = get_object_or_404(College, pk=college_id) return render(request, 'app/detail.html', {'college':college}) urls.py: from django.conf.urls import url from . import views app_name = "app" urlpatterns = [ # campusarchitecture.com/ url(r'^$', views.index, name="index"), # /college_name url(r'^(?P<college_id>[0-9]+)/$', views.detail, name="detail") ] Anyone know what the problem is? -
Need Help Matching Paypal API Return URL with regex in django
I am looking for help making a regex url for this paypal api return url in django. https://www.example.com/?paymentId=PAY-3893HFBFBAF&token=ECAA320327QHGNAAFBLA2&PayerID=6R7EUHSHGAQY6 I need to capture the paymentID, token, and the payerID into my url regex function. I have this which I know is really really wrong. url(r'^confirm/?P<paymentId>[a-z][0-9]&?P<token>$[a-z][0-9]&?P<PayerID>[a-z][0-9]',views.complete_payment, name="complete_payment") -
After moving to a new server, the website failed to load...socket error
I was working on a website for a school project. Recently the website was moved to a new server by the IT people from school. And I found that the website could not load anymore. I am new to django and python, so I am very lost at this point... I will really appreciate any suggestions or comments! Thanks a lot! The error log shows that: Traceback (most recent call last): File "application.fcgi", line 19, in runfastcgi(method="threaded", daemonize="false") File "/home/spatialtest/Envs/django1.6/lib/python2.7/site-packages/django/core/servers/fastcgi.py", line 182, in runfastcgi WSGIServer(get_internal_wsgi_application(), **wsgi_opts).run() File "/home/spatialtest/Envs/django1.6/lib/python2.7/site-packages/flup/server/fcgi.py", line 114, in run ret = ThreadedServer.run(self, sock) File "/home/spatialtest/Envs/django1.6/lib/python2.7/site-packages/flup/server/threadedserver.py", line 84, in run clientSock, addr = sock.accept() socket.error: [Errno 22] Invalid argument -
How to manage email from within AngularJS + Django?
I am working on a web app with AngularJS (1.x) and Django on the back-end, using the Django Rest Framework as API. I want to be able to manage any email account that's connected through IMAP/POP/SMTP protocols from within the app. So once you log in, you can view your email, receive, and send emails without - for example - having to go the gmail website. No idea where to start really, as most of the information I find online is only for automated registration and welcome emails. Do I need to set up a separate server? Should this live in Angular or mostly on Django? Etc... Any help would be greatly appreciated. -
Django View Does Not Populate In Template
I am following this book for some Django tutorials: https://www.packtpub.com/web-development/django-example I run into problems when trying to run the code for Chapter 1. Namely, everything works except for the Blog entries stored in database. They do not show up on the rendered page. Initially, I thought that I had made a mistake somewhere, so I downloaded the code that comes with the book and gave it a go. It behaves the same way. Could this be a version issue for Django? I installed the one recommended by the book. In case there is a code issue, I include some pertinent files below. Any help of suggestion is welcome. 1) views.py from django.shortcuts import render, get_object_or_404 from .models import Post # Create your views here. def post_list(request): posts = Post.published.all() return render(request, 'blog/post/list.html', {'posts': posts}) def post_detail(request, year, month, day, post): post = get_object_or_404(Post, slug=post, status='published', publish__year=year, publish__month=month, publish__day=day) return render(request, 'blog/post/detail.html',{'post': post}) 2) urls.py from django.conf.urls import url from . import views urlpatterns = [ # post views url(r'^$', views.post_list, name='post_list'), url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/'r'(?P<post>[-\w]+)/$', views.post_detail, name='post_detail'), ] 3) models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.core.urlresolvers import reverse # Create your models here. class PublishedManager(models.Manager): … -
Django csrf_exempt not working
I'm using Django Rest Framework to build a webapp with user registration/login. I'm trying to exempt the user sign up view from needing a CSRF token. This is what my view looks like right now: class UserSignUpView(generics.CreateAPIView): permission_classes = [] # FIXME: doesn't seem to be working serializer_class = UserSerializer @method_decorator(csrf_exempt) def post(self, request, *args, **kwargs): super().post(self, request, *args, **kwargs) def get_permissions(self): if self.request.method == 'POST': return (permissions.AllowAny(), TokenHasReadWriteScope()) return False My settings.py looks like this: REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ] } I still get this on my backend output Forbidden (CSRF cookie not set.): /users/ and in the front end the classic CSRF verification failed. Request aborted. Why wouldn't this work? Could it have something to do with the fact that I never manually set the CSRF cookie? -
CentOS6 Django Project on CentOS7
I have projects made on CentOS6 and when I try to use manage.py on CentOS7 (I tried editing the manage.py file to have execute_from_command_line and copying manage.py from a new project made on CentOS7) and get ImportError: Could not import settings 'PROJECTNAMEHERE.settings' (Is it on sys.path? Is there an import error in the settings file?): No module named PROJECTNAMEHERE.settings Can I use manange.py commands without rewriting all my Django projects? Similar to: python manage.py run server return ImportError