Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create a Django model instance concurrent with the creation of another Django model instance
I'm creating a simple record keeping app in Django 1.11 that keeps track of what happens in games turn by turn. What I'd like to do is when I create an instince of Game automatically create the first dependent Turn instance. class Game(models.Model): name = models.Charfield(param) active = models.BooleanField(param) def __init__(self, *args, **kwargs): super(Game, self).__init__(*args,**kwargs) Turn(game=self, turn=1).save() class Turn(models.Model): turn = models.IntergerField(param) please suggest a better method becuase I get ValueError on the save method. -
Django form httpresponse
I want to submit form and return to topics page,but it doesn't work.Here is the page before submit. page before submit I enter something and click the button,it does't return to the page I want.Error shows as follow: error page It seems like the views.py can't find the right url,how can I fix it? view.py: def new_topic(request): if request.method != "POST": form = TopicForm() else: form = TopicForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('leraning_log:topics')) context = {'form':form} return render(request,'learning_logs/new_topic.html',context) urls.py: urlpatterns = [ url(r'^topics/$',views.topics,name='topics'), url(r'^topics/(?P<topic_id>\d+)/$',views.topic,name='topic'), url(r'^new_topic/$',views.new_topic,name='new_topic'), ] -
How to join table in django?
Assumes, I have two tables below : enter image description here I've made the models.py: class Score(models.Model): Student_Id = models.CharField(max_length=20, primary_key=True) Grade = models.CharField(max_length=30) Status= models.CharField(max_length=3) class Meta: db_table ='T_Score' class Student(models.Model): Student_Id = models.CharField(max_length=20, primary_key=True) Student_Name = models.CharField(max_length=30) Student_Class = models.CharField(max_length=3) def __str__(self): return { "id" : self.Student_Id, "name" : self.Student_Name, } class Meta: db_table ='T_Student' Is it possible to join the table if Student.Student_Id just as primary key (not as foreign too)? And how should I make the view.py and template which represent Student ID, Student Name, and Grade? Thank you in advance. -
Web analytic with python
I want to build a web analytic as google analytic. My requirement for this system that is high throughput,scalability, low latency and efficient ETL. And If it's ok, can we use django to develop. But I don't know which technique is suitable with my case. For detail, I need to answer these questions: With Django, which open source is the best for: 1) Which framework can help me build high throughput,scalability, low latency service? 2) Which database is better for realtime as google's analytic: High Performance, Security & Permissions, Low Latency Storage, Fully Managed, Redundant Autoscaling Storage, Seamless Cluster Resizing, HBase Compatible. 3) Which Framework for ETL with high performance? Without Django/python, which language is the best and which is suitable question for these question above Thanks & Best Regards, Phuong Hoang -
Django Rest Framework Token authentication with Social auth login
In my Django Rest Framework application, a Token is generated for every user that logs in for the first time into the application using signals. Now I can use this token (By manually going to database and grabbing the token) to make API calls to the view that have authentication_classes = (TokenAuthentication,). Can someone explain me how can I provide this token to the user securely when the (OpenID) login was successful. Django Rest Framework supports something like: from rest_framework.authtoken import views urlpatterns += [ url(r'^api-token-auth/', views.obtain_auth_token) ] But, this obtain_auth_token view only supports post request which takes username and password, which is not the case with my application. Please correct me if there are any flaws in my workflow. -
Can't find any modules in Django project
I've been following a Django tutorial and initially had created virtualenv and a requirements file in it. Project was halfway and in working state. Today I activated virtualenv successfully and tried python manage.py runserver to get error ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? I realized it's not finding Django and just to be sure checked my requirements.txt file (which confirmed right Django version). Tried to reinstall it from the file using pip3 install -r requirements.txt (tried using just pip too) to get another error -- ModuleNotFoundError: No module named 'pip' It seems the environment is unable to find any of the modules. I tried to reinstall pip also just to be sure, but then it couldn't find apt-get command. OS: Mac OSX El Capitan 10.11.6 Python: 3.6.2 Django: 1.10.3 (in requirements file) -
Integrate oscar to existing app
Is there a way I can integrate Oscar to an existing app? I installed oscar, created an app in my existing folder. I changed the settings in my shop app according to Oscar. Then I added the new shop to my existing app's settings in the installed app. It said no module name shop. Is this right way to go about it? -
Send template form data to view via URL
I'm trying to build a wiki search app in django and am having trouble creating a MVC link with a template that has a form with POST method. Essentially, my search form, search_form.html looks like this: {% extends 'layout.html' %} {% block title %}Wiki Search | Search {% endblock title %} {% block content %} <form action = "{% url 'search_results' search_term %}" method="post"> Search for:<br> <input type="text" name="search_term" value=""> <br> <input type="checkbox" name="is_date" value="date">I'm searching for a date (e.g. 02/10) <br><br> <input type="submit" value="Search"> </form> {% endblock content %} The end view needs to evaluate the checkbox value (name=is_date) and the text input (name=search_term). I am passing it to URL named 'search_results' which is defined in my urls.py: from django.conf.urls import url from . import views urlpatterns = [ url(r'search/(?P<search_term>[.\-\_\w\d\s]+)/$', views.search_results, name='search_results'), url(r'search/$', views.search_form, name='search_form'), url(r'^$', views.index, name='index'), ] my search_results url has a regex with a named capture of search_term. I am assuming that this is filled by me referencing the template's form's text input (named search_term). Finally, this URL references views.py's search_results function which is: from django.shortcuts import render from django.http import HttpResponse, HttpRequest from .models import Search # Create your views here. def index(request): #return render(request, … -
New user registration cannot be done
New user registration cannot be done. I wrote in views.py def regist(request): regist_form = RegisterForm(request.POST or None) context = { 'regist_form': regist_form, } return render(request, 'registration/regist.html', context) @require_POST def regist_save(request): regist_form = RegisterForm(request.POST) if regist_form.is_valid(): user = form.save() login(request, user) context = { 'user': request.user, } return redirect('detail') context = { 'regist_form': regist_form, } return render(request, 'registration/regist.html', context) in forms.py class RegisterForm(UserCreationForm): class Meta: model = User fields = ('username', 'email','password1','password1',) def __init__(self, *args, **kwargs): super(RegisterForm, self).__init__(*args, **kwargs) self.fields['username'].widget.attrs['class'] = 'form-control' self.fields['email'].widget.attrs['class'] = 'form-control' self.fields['password1'].widget.attrs['class'] = 'form-control' self.fields['password2'].widget.attrs['class'] = 'form-control' in regist.html <div class="heading col-lg-6 col-md-12"> <h2>New account registration</h2> <form class="form-horizontal" action="regist_save/" method="POST"> <div class="form-group-lg"> <label for="id_username">username</label> {{ regist_form.username }} </div> <div class="form-group-lg"> <label for="id_email">email</label> {{ regist_form.email }} </div> <div class="form-group-lg"> <label for="id_password">password</label> {{ regist_form.password1 }} </div> <div class="form-group-lg"> <label for="id_password">password(conformation)</label> {{ regist_form.password2 }} <p class="help-block">{{ regist_form.password2.help_text }}</p> </div> <div class="form-group-lg"> <div class="col-xs-offset-2"> <button type="submit" class="btn btn-primary btn-lg">SUBMIT</button> <input name="next" type="hidden"/> </div> </div> {% csrf_token %} </form> </div> No error happens and when I put SUBMIT button,it send detail.html,so it is ok.But when I see admin site,no user is registered. I really cannot understand why this happens.I cannot understand what is wrong.I read Django tutorial,so I think this way of … -
Django production get Service Unavailable
I'm trying to setup my app with django but unfortunately I can't I just got a Service Unavailable message. I'm using vestacp The apache configuration works in the same ubuntu 14 without vestacp but using vestacp I can not achieve to work. settings.py # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] it suppose to work using "*" apache2.conf <VirtualHost 172.31.2.45:80> ServerName ip-172-31-2-45.us-west-1.compute.internal ServerAlias www.ip-172-31-2-45.us-west-1.compute.internal ServerAdmin info@ip-172-31-2-45.us-west-1.compute.internal DocumentRoot /home/admin/web/ip-172-31-2-45.us-west-1.compute.internal/public_html ScriptAlias /cgi-bin/ /home/admin/web/ip-172-31-2-45.us-west-1.compute.internal/cgi-bin/ Alias /vstats/ /home/admin/web/ip-172-31-2-45.us-west-1.compute.internal/stats/ Alias /error/ /home/admin/web/ip-172-31-2-45.us-west-1.compute.internal/document_errors/ #SuexecUserGroup admin admin CustomLog /var/log/apache2/domains/ip-172-31-2-45.us-west-1.compute.internal.bytes bytes CustomLog /var/log/apache2/domains/ip-172-31-2-45.us-west-1.compute.internal.log combined ErrorLog /var/log/apache2/domains/ip-172-31-2-45.us-west-1.compute.internal.error.log <Directory /home/admin/web/ip-172-31-2-45.us-west-1.compute.internal/public_html> AllowOverride All Options +Includes -Indexes +ExecCGI php_admin_value open_basedir /home/admin/web/ip-172-31-2-45.us-west-1.compute.internal/public_html:/home/admin/tmp php_admin_value upload_tmp_dir /home/admin/tmp php_admin_value session.save_path /home/admin/tmp </Directory> <Directory /home/admin/web/ip-172-31-2-45.us-west-1.compute.internal/stats> AllowOverride All </Directory> <IfModule mod_ruid2.c> RMode config RUidGid admin admin RGroups www-data </IfModule> <IfModule itk.c> AssignUserID admin admin </IfModule> IncludeOptional /home/admin/conf/web/apache2.ip-172-31-2-45.us-west-1.compute.internal.conf* </VirtualHost> <VirtualHost 172.31.2.45:80> ServerName mensajeriadf.com ServerAlias www.mensajeriadf.com ServerAdmin info@mensajeriadf.com DocumentRoot /home/admin/web/mensajeriadf.com/public_html WSGIDaemonProcess sampleapp python-path=/var/www/sampleapp/sampleapp:/var/www/sampleapp/env/python2.7/site-packages WSGIProcessGroup sampleapp WSGIScriptAlias / /var/www/sampleapp/sampleapp/sampleapp/wsgi.py ScriptAlias /cgi-bin/ /home/admin/web/mensajeriadf.com/cgi-bin/ Alias /vstats/ /home/admin/web/mensajeriadf.com/stats/ Alias /error/ /home/admin/web/mensajeriadf.com/document_errors/ #SuexecUserGroup admin admin CustomLog /var/log/apache2/domains/mensajeriadf.com.bytes bytes CustomLog /var/log/apache2/domains/mensajeriadf.com.log combined ErrorLog /var/log/apache2/domains/mensajeriadf.com.error.log <Directory /home/admin/web/mensajeriadf.com/public_html> AllowOverride All Options +Includes -Indexes +ExecCGI php_admin_value open_basedir /home/admin/web/mensajeriadf.com/public_html:/home/admin/tmp php_admin_value upload_tmp_dir /home/admin/tmp php_admin_value session.save_path /home/admin/tmp </Directory> <Directory /home/admin/web/mensajeriadf.com/stats> AllowOverride All </Directory> … -
Getting AttributeError at /gitstack/ 'str' object has no attribute 'resolve' in Django 1.11
I am modifying Gitstack, a 32bit Python2.7-based Git Web Application (available here) for my 64bit Python installation. In the process, I also had to modify all the Django codes e.g. urlpatterns, etc. While I managed to adapt it to my Apache/PHP environment, I ended up with this Django issue. The error is as below while trying to access /gitstack location AttributeError at /gitstack/ 'str' object has no attribute 'resolve' Request Method: GET Request URL: https://localhost/gitstack/ Django Version: 1.11.6 Exception Type: AttributeError Exception Value: 'str' object has no attribute 'resolve' The traceback below seems to be useless Environment: Request Method: GET Request URL: https://localhost/gitstack/ Django Version: 1.11.6 Python Version: 2.7.13 Installed Applications: ('django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'gitstack') Installed Middleware: ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware') Traceback: File "C:\Python27\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _legacy_get_response 249. response = self._get_response(request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response 172. resolver_match = resolver.resolve(request.path_info) File "C:\Python27\lib\site-packages\django\urls\resolvers.py" in resolve 364. sub_match = pattern.resolve(new_path) Exception Type: AttributeError at /gitstack/ Exception Value: 'str' object has no attribute 'resolve' Below is my modified app\urls.py: from django.conf.urls import url, include from django.contrib.auth.views import login # Uncomment the next two lines to enable the admin: # from django.contrib import admin … -
how to use ajax with graphql using get method?
I am trying to follow this documentation about django and graphql https://www.techiediaries.com/django-graphql-tutorial/graphene/ I am only half way to where we can do testing with the graphql view and make our queries. Then I stopped and trying to do some front end work to make query with ajax been reading https://blog.graph.cool/how-to-use-graphql-with-jquery-51786f0a59cb Even though in that blog, it's using post. I believe using get shouldn't be too much different. So I tried making query into a string then JSON.stringify them to pass it over to the backend django but I keep on getting error this is the error I have XMLHttpRequest cannot load localhost:8000/graphql/?{"query":"query { allProducts {id sku title description } }"}. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https. this is the html + jquery <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <button class="graphql-test">CLICK</button> </body> <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script> <script> $(function(){ $('.graphql-test').on('click', function(e){ e.preventDefault(); var query = "query { allProducts {id sku title description } }"; $.ajax({ method: 'get', url: 'localhost:8000/graphql/', data: JSON.stringify({"query": query}), contentType: 'application/json', success: function(data){ console.log(data); }, error: function(data){ console.log(data); } }) }) }); </script> </html> -
How to define a subclass of ListBlock with fixed contents?
Is there a better way than this to make a subclass of ListBlock with fixed contents? class MixedMediaCarouselBlock(blocks.ListBlock): """ A hghly streamlined CarouselBlock which displays only Images and/or Videos. """ def __init__(self, child_block=None, **kwargs): child_block = blocks.StructBlock([ ('image', ImageChooserBlock(required=False)), ('video', EmbedBlock( label="Video URL", help_text="Paste the video URL from YouTube or Vimeo." " e.g. https://www.youtube.com/watch?v=l3Pz_xQZVDg" " or https://vimeo.com/207076450.", required=False ) ), ]) super(MixedMediaCarouselBlock, self).__init__(child_block, **kwargs) class Meta: template = 'core/blocks/mixed_media_carousel_block.html' label = 'Mixed Media Carousel' icon = 'media' It feels really hacky to do it this way, but I can't find any other obvious method, because ListBlock requires that child_block argument to its constructor, while other block types do not. The reason I want a ListBlock subclass is to use it as the single block type in a StreamField in one of my Pages: class News(Page) assets = StreamField( MixedMediaCarouselBlock(), help_text='Pick one or more images/videos to place in the sidebar of this article.' ) Maybe I'm just doing this wrong? -
Access related ManyToManyField data pre-save in the Django Model.save method
We would like to access related ManyToManyField data pre-save within the Model.save method, however the data isn't available yet via the Django ORM because it's related ManyToManyField data and doesn't get set until post-save of the primary record. Here's some example code of the relationship and where the related ManyToMany records are accessed in Model.save class Friend(models.Model): name = models.CharField(max_length=50) class Person(models.Model): name = models.CharField(max_length=50) friends = models.ManyToManyField(Friend) def save(self, *args, **kwargs): friends = self.friends.all() # 'friends' is an empty QuerySet at this point # I'd like to do something with friends here, # but it gets set after save super(Friend, self).save(*args, **kwargs) Example use case where friends are passed in on save: friend = Friend.objects.all()[0] friend2 = Friend.objects.all()[1] friends = [friend, friend2] Person.objects.create(friends=friends) -
django unit testing with fixtures - object matching query does not exist
I am trying to set up unit testing in django using fixtures. I can successfully load my fixtures, but when I attempt to retrieve data from them I get the error: DoesNotExist: BlogIndexPage matching query does not exist. Here is my code for the test (I'm using the Wagtail CMS, which extends unittest with a few additional methods): class BlogTests(WagtailPageTests): fixtures = ['demosite.json'] def test_can_create_blog_entry(self): blog_index_page = BlogIndexPage.objects.get(pk=5) self.assertCanCreate(blog_index_page, BlogPage, { 'title': 'Post 2', 'date': '2017-10-11', 'intro': 'Post 2', 'body': '<p>Test Post</p>' }) And this is my fixture: [ { "pk": 1, "model": "wagtailcore.page", "fields": { "title": "Root", "draft_title": "Root", "numchild": 1, "show_in_menus": false, "live": true, "seo_title": "", "depth": 1, "search_description": "", "content_type": [ "wagtailcore", "page" ], "has_unpublished_changes": false, "owner": null, "path": "0001", "url_path": "/", "slug": "root" } }, { "pk": 2, "model": "wagtailcore.page", "fields": { "title": "Home page", "draft_title": "Home page", "numchild": 5, "show_in_menus": true, "live": true, "seo_title": "", "depth": 2, "search_description": "", "content_type": [ "home", "homepage" ], "has_unpublished_changes": false, "owner": null, "path": "00010002", "url_path": "/home-page/", "slug": "home-page" } }, { "pk": 5, "model": "wagtailcore.page", "fields": { "title": "Blog index", "draft_title": "Blog index", "numchild": 3, "show_in_menus": true, "live": true, "seo_title": "", "depth": 3, "search_description": "", "content_type": [ "blog", "blogindexpage" … -
Iterating over Django QuerySet without pre-populating cache
I want to iterate over all the objects in a QuerySet. However, the QuerySet matches hundreds of thousands if not millions of objects. So when I try to start an iteration, my CPU usage goes to 100%, and all my memory fills up, and then things crash. This happens before the first item is returned: bts = Backtrace.objects.all() for bt in bts: print bt I can ask for an individual object and it returns immediately: bts = Backtrace.objects.all() print(bts[5]) But getting a count of all objects crashes just as above, so I can't iterate using this method since I don't know how many objects there will be. What's a way to iterate without causing the whole result to get pre-cached? -
Generating action, kwargs confused, django-activity-stream
I'm trying to use django-activity-stream in my application, but this actor, target,verd etc. really confused me. My use case is like Below, Bob creates a purchase requirement, John creates an order with reference to this requirement. I want Bob to track this requirement's status in his timeline while john's actions are beeing seen by others. 1- I did get Bob follow the requirement when he created and add an action. "Bob created Purchase requirement req-0001". so far so good, this is visible to anyone who follows Bob and bob himself. 2- Then John created an order with reference to this requirement, the action I created, "John(actor) placed an order(verb) Order-0002(action object) to req-0001(target)" I know I did that wrong , Bob cant see the req-0001 has been converted to be an order, since requirement is an target in this second action. Should I make the requirement an actor itself? and get bob to follow it? Or this usecase is simple not supported? I think I can get desired behaviour using this keyworkd argument's and templating, but I dont want to get too far from concept. Thanks -
developing django projects using git sub-modules
I have a DJango project that uses menus as part of the application For example: MENU: CUSTOMER VENDOR EMPLOYEE I would like each area to be assigned to a developer for creation and modification: one for Customer, one for Vendor, one for Employee. How could one do this? My thoughts would be that the DJango project would be as follows: Main (which is the project) Main => CustomerApp => VendorApp => EmployeeApp Main would be assigned to a Git repository CustomerApp, VendorApp and EmployeeApp would be assigned to Git Sub-Modules. The person working on CustomerApp would ~only~ have access to CustomerApp (and not the other areas: EmployeeApp, VendorApp) One developer could not "step on" or "see" the work of another developer. Could this be a valid approach? TIA -
Django 1.11 - ModelForm: change default form widget for DateTimeField
I need some help in rendering a datetime picker in my form insead of the default text field that is displayed. I am using Django 1.11 and have followed the recent solution posted here: Django 1.11 - forms.Models: change default form widget for DateTimeField however I receive errors when using the same code. The first error I receive is: cannot import name 'widget'. I can pass this error by importing 'widgets' instead. Has this been renamed? The second error I receive after renaming to widgets is: NameError: name 'forms' is not defined. I can pass this error by changing the code to: Class DateInput(widgets.DateInput):Is this the correct treatment for this error? The third error I receive is: NameError: name 'Date_Input' is not defined I can pass this error by changing the final piece of code (removing underscore in Date_Input) above to: widgets = { 'missing_date': DateInput() } After these changes I no longer get any errors however the date field in my form is still rendering as a text field and not as a date picker. Can anyone shed any further light on the solution above and why it possibly isnt working for me? Additonly I would like to modify … -
Convert two arrays to Arrays of Arrays Using Python
I am New on python and I want to make Arrays of array . this.tblData: Array(2) 0: (header)0:["A-100"B-101", "C-11", "D"] (data_values)1:["0E-11,"GERBER", "CA", "960350E-110.0215.500000000"] 1: (header)0:["E-100"B-101", "C-11", "D"] (data_values)0:["0AE-11,"GERBER", "DA", "960350E-110.0215.500000000"] Currently i have 2 separate Arrays 1.For header ["A-100"B-101", "C-11", "D"] ["E-100"B-101", "C-11", "D"] 2.Array for Data Values ["0E-11,"GERBER", "CA", "960350E-110.0215.500000000"] ["0AE-11,"GERBER", "DA", "960350E-110.0215.500000000"] Thanks In Advance -
Running tests in django / wagtail to create sub pages under pages
I'm trying to get a grasp on how to write tests for my own wagtail site. I read the documentation: http://docs.wagtail.io/en/v1.3/advanced_topics/testing.html#wagtail.tests.utils.WagtailPageTests.assertCanCreate and now I want to create a test to see whether I can create a Blog (entry) page under a Blog Index Page. So I have a few tests set up that run successfully, but the last does not: from __future__ import unicode_literals from django.core.exceptions import ValidationError from django.test import TestCase, SimpleTestCase, Client from wagtail.tests.utils import WagtailPageTests, WagtailTestUtils from wagtail.wagtailcore.models import Page # Create your tests here. from blog.models import BlogIndexPage from blog.models import BlogPage class BlogTests(WagtailPageTests): def test_parent_child_relationships(self): # A Blog page can only be created under a blog index page self.assertAllowedParentPageTypes( BlogPage, {BlogIndexPage}) # It should not be possible to create a blog index page under a blog page self.assertCanNotCreateAt(BlogPage, BlogIndexPage) self.assertCanCreate(BlogIndexPage, BlogPage, { 'title': 'Post 2', 'date': '2017-10-11' }) When I attempt the assertCanCreate test, I get the error: `'cached_property' object has no attribute 'allowed_subpage_models' I suspect the problem is that I am loading two models, and attempting to create a page under another page, but I am not actually grabbing a specific page by ID. Versus in the wagtail documentation: def test_can_create_content_page(self): # Get the … -
Django- Login not working
I am trying to make a page that registers users and then logs them in immediately after. It then redirects them to their profile which is a url that contains their id. There is a model called person, and it has a one-to-one field with User. This is the code for my post method (when someone fills out the register form). def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit = False) username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.set_password(password) user.save() newperson = person(user=user) newperson.save() user.save() if user is not None: if user.is_active: login(request, user) return redirect('/profiles/' + str(user.person.id)) return render(request, self.template_name, {'form': form}) It then runs this function: def loadprof(request, profile_id): print(request.user) try: user = person.objects.get(id=profile_id) user_schedules = user.schedules_set.all() except person.DoesNotExist: raise Http404("The profile you are looking for does not exist.") if request.user.person.id == profile_id: return render(request, 'profile.html', {'user': user, "user_schedules": user_schedules}) return render(request, 'profile.html', {'user': user, "user_schedules": user_schedules}) It raises a 'AnonymousUser' object has no attribute 'person' error when it runs "if request.user.person.id == profile_id:" in the loadprof function. What is happening? I assume because it is an AnonymousUser, the login function didn't work? I imported the login function correctly and everything, I am very lost. Thank … -
How to join two tables in Django Admin system
I have two models connected to Django Admin system. And would like to have a possibility to , using dropdown list, choose a specyfic value from the first model in a second model. What do you think, is this possible ? Thanks in advance -
Comparing and delete api data
I have a django project that takes in some data from another app of ours. The data looks like this: {u' updated': u'2017-04-03T22:30:53.760278 Z', u'added': u'2017-04-03T22:30:53.760197 Z', u'name':u'Jean Bacon, 1942- ', u' authority':{ u'id':2, u'added_by':2, u'name':u'VIAF' }, u'local_identifier':u'85363862', u'concept_type':{ u'id':5, u'identifier': u'viaf:personal', u'name':u'', u'description':None }, u'identifier': u'http://viaf.org/viaf/85363862', u'identities':[ { u'part_of':{ u'id':1, u'added_by':2, u'name': u'builtin:Conceptpower' }, u'added': u'2017-04-03T22:33:20.476637 Z', u'name':u'Jean Bacon', u'confidence':1.0, u'updated': u'2017-04-03T22:33:20.476699 Z', u'concepts':[ u'http://viaf.org/viaf/85363862', u'http://www.digitalhps.org/concepts/CONpeSHC70qxNC0' ], u'id':208, u'added_by':{ u'username':u'erickpeirson', u'email':u'erick.peirson@asu.edu' } }, { u'part_of':{ u'id':1, u'added_by':2, u'name': u'builtin:Conceptpower' }, u'added': u'2017-04-03T22:35:02.546054 Z', u'name':u'Jean Bacon', u'confidence':1.0, u'updated': u'2017-04-03T22:35:02.546116 Z', u'concepts':[ u'http://viaf.org/viaf/85363862', u'http://www.digitalhps.org/concepts/CONpeSHC70qxNC0' ], u'id':209, u'added_by':{ u'username':u'erickpeirson', u'email':u'erick.peirson@asu.edu' } }, Right now I have a function that goes through and compares the concepts in in the identities. What I want to do is delete the duplicate concepts. The nesting of the dictionaries and lists are throwing me off. What I have been trying is: del results[i]["identities"][z]["concepts"] Any ideas as to why this does not work? Here is my loop incase anyone is interested: while (i != di): test = results[i]["identities"] if results[i]["identities"]: z = 0 while (z != len(results[i]["identities"])): con1 = results[i]["identities"][z]["concepts"] print "this is con1: %s", con1 if z != len(results[i]["identities"]): z = z + 1 else: break if … -
How to make an multiple image upload best practice Django
What is the best practice for making an multiple image upload in Django ? How can I reach this <input type="file" name="img" multiple> in my forms.py ? So the user can select many images not only one ? image = models.ImageField(upload_to="", default="", null=True) Some kind of that but with multiple selection. The next question is, how do I handle or even get all the image urls and save them in my database ? Would I do this with Ajax ? For example getting all the urls and save them in my database ? What is the best way or flow of doing it ?