Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"{"detail":"Error decoding signature."}" Angular 2 + Django + ionic 2
i am using django + angular 2 + ionic2 i am using rest_framework_jwt with a url like this url(r'^api/api-token-auth/', obtain_jwt_token), url(r'^api/settings/?$', views.Settings.as_view()), url(r'^updsettings/?$', views.SettingsUpdate.as_view()), My view class Settings(generics.ListAPIView): serializer_class = SettingsSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,) def get_queryset(self): queryset = Settings.objects.all() queryset = queryset.filter(user=self.request.user.id) return queryset class SettingsUpdate(generics.UpdateAPIView): queryset = Settings.objects.all() serializer_class = SettingsSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,) My service is: private headers = new Headers({ 'Content-Type': 'application/json', 'Accept': 'application/json', }); .... getSettings() : Promise <SettingsV> { let currentUser = JSON.parse(localStorage.getItem('currentUser')); this.headers.append('Authorization', 'JWT ' + currentUser.token); return this.http.get('/api/settings', { headers: this.headers }) .toPromise() .then(response => response.json() as SettingsV); } updateSettings(settings: Settings): Promise <SettingsV> { let currentUser = JSON.parse(localStorage.getItem('currentUser')); this.headers.append('Authorization', 'JWT' + currentUser.token); return this.http .put('/api/updsettings', JSON.stringify(settings), { headers: this.headers }) .toPromise() .then(() => settings); } My Component for update settings.. save(): void { this.settingsService.updateSettings(this.settings) .then(() => this.navCtrl.push(somepage)); } My html <ion-content padding> <form> <div *ngFor="let setting of settings"> <ion-list> <ion-item> <ion-label> boolean 1</ion-label> <ion-toggle [(checked)]="setting.boolean1" color="secondary"> </ion-toggle> </ion-item> <ion-item> <ion-label> boolean 2</ion-label> <ion-toggle [(checked)]="setting.boolean2" color="primary"></ion-toggle> </ion-item> <ion-item> <ion-label> boolean 3</ion-label> <ion-toggle [(checked)]="setting.boolean3" color="danger"></ion-toggle> </ion-item> <ion-item> <ion-label floating>string 1</ion-label> <ion-input type="text" value={{setting.string}} ></ion-input> </ion-item> </ion-list> </div> </form> <button ion-button (click)="save()">Save</button> </ion-content> My login is working fine, Settings return fine but i cannot save them/update … -
Can PostgreSQL query external Microsoft Dynamics REST API directly?
Our most up-to-date client information is stored in Microsoft Dynamics 365 CRM and would like to query it anytime information related to it is needed to make sure the internal PostgreSQL database has the most current information. I read through the documentation and am pretty familiar with the Web API for CRM. What I am wondering is can PostgreSQL itself, which I am fairly new to, request against an external API? That way I was thinking I could make a trigger to request the necessary data from it. If not, I'll just do it via Django, put it into a temporary table, and UPDATE/INSERT into the auth_user table. -
How to replace form field with custom layout in Django?
I have a model form field which is a choice field. Instead of having the default widget: I would like to have a grid of cards like so: With each of the choices that would have been in the default widget in a card. How do I edit the python form to achieve this? Here is my form: from django import forms from . import models class PostJobForm(forms.ModelForm): class Meta: model = models.Job fields = [ 'title', 'description', 'pay', 'category' ] -
Djnago making fields unique together even if field values are swapped
Django unique_together does not allow the repetition of (Apple, Fruit) as field values again but how to restrict (Apple, Fruit) and (Fruit, Apple) -
Diff between api and REST api in django
I am very confuse in api and rest api. what is the difference between them. I am a django developer and works on both but don't know the difference between them . and is soap api and api same thing?? -
Django execute class in script
I have problem with executing script in Django application. This script must serve for job in crontab. So ill provide example of my script: Specification: Python:3.5.x Django:1.10.5 my_script.py class SayHello(object): def print_args(self, arg1, arg2): print (arg1, arg2) if __name__ == "__main__": foo = SayHello() foo.print_args(sys.argv[1], sys.argv[2]) But the main problem is when i want to include models in this script i got error: ImportError: No module named "app" Folder structure: say_hello (main folder) -> init.py -> my_script.py How to run script but don't get errors from import statement into this script. Any advice would be great. -
How to access class variable in Python?
I'm new to Python programming and wondering how can I access to variables I have declared in one file to another? I'm working on Django and have two files: forms.py class ContactForm(forms.Form): full_name = forms.CharField(max_length=100) email = forms.EmailField() message = forms.CharField(max_length=1000) views.py from .forms import ContactForm def contact(request): e = ContactForm() toPrint = e.get(email) print(toPrint) I'm just testing it to print on terminal to help me learn how to access those variables to use them in views.py Thanks -
Default ViewSet behaviour in detail_route
I am working on a Django Rest Framework view that enables creating/getting a user's profile at /users/{user_id}/profile I got it to work the following way, except for a bug in test_post_profile_for_unexisting_user where it returns a 201 and throws an IntegrityError (weird): views.py: class UserViewSet(mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = (IsUserOrReadOnly,) def create(self, request, *args, **kwargs): self.serializer_class = CreateUserSerializer self.permission_classes = (AllowAny,) return super(UserViewSet, self).create(request, *args, **kwargs) @detail_route(methods=['get', 'post'], permission_classes=[IsUserOrReadOnly]) def profile(self, request, pk=None): if request.method == 'GET': try: profile = Profile.objects.get(user_id=pk) except Profile.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) serializer = ProfileSerializer(profile) return Response(serializer.data) # POST request_data = request.data serializer = ProfileSerializer(data=request_data) if serializer.is_valid(): serializer.save(user_id=pk) return Response(serializer.validated_data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) test_views.py class TestProfileAPI(APITestCase): def setUp(self): self.profile_data = model_to_dict(ProfileFactory.build()) self.user_data = model_to_dict(UserFactory.build()) self.user = User.objects.create(**self.user_data) def test_post_profile(self): url = reverse('user-profile', args=[str(self.user.id)]) response = self.client.post(url, self.profile_data) eq_(response.status_code, 201) response_data = response.json() eq_(response_data['name'], self.profile_data.get('name')) eq_(response_data['role'], self.profile_data.get('role')) eq_(response_data['title'], self.profile_data.get('title')) eq_(len(response_data), 3) def test_post_profile_for_unexisting_user(self): url = reverse('user-profile', args=[str(uuid.uuid4())]) response = self.client.post(url, self.profile_data) eq_(response.status_code, 404) def test_get_profile(self): url = reverse('user-profile', args=[str(self.user.id)]) self.client.post(url, self.profile_data) response = self.client.get(url) eq_(response.status_code, 200) response_data = response.json() eq_(response_data['name'], self.profile_data.get('name')) eq_(response_data['role'], self.profile_data.get('role')) eq_(response_data['title'], self.profile_data.get('title')) eq_(len(response_data), 3) def test_get_unexisting_profile(self): url = reverse('user-profile', args=[str(self.user.id)]) response = self.client.get(url) eq_(response.status_code, 404) urls.py router = … -
How to accept upper and lower case in django restframework Charfilter
I have a filter for my model, but when the user enters a value to filter, the results belongs exactly to the string introduced by the user. Is there any way that Charfilter accepts upper and lower case? Is it in the argument "lookup_expr"? I've been googling with no suscess. This is my filter class: class ArticuloFilter(filters.FilterSet): clave = CharFilter( name="clave", lookup_expr="contains" ) clave_jde = CharFilter( name="clave_jde", lookup_expr="contains" ) descripcion = CharFilter( name="descripcion", lookup_expr="contains" ) class Meta: model = Articulo fields = [ 'clave', 'descripcion', 'tipo', 'clave_jde', 'estado', ] -
How can i override create method in serializer with multiple nested fields in django?
I'm trying to create a writable nested serializer. I read django rest documents but in my case i have multiple nested fields and don't know how can solve that i get this error: TypeError at /api/v1/libraries/ 'tel_number' is an invalid keyword argument for this function models.py: class RegisterRule(models.Model): picture = models.BooleanField(default=False) passport = models.BooleanField(default=False) education_rule = models.CharField(max_length=255) class SpecificInformatin(models.Model): specific_name = models.CharField(max_length=255) description = models.TextField(max_length=255) def __unicode__(self): return self.specific_name class District(models.Model): district = models.CharField(max_length=2) def __unicode__(self): return self.district class Address(models.Model): district = models.ForeignKey(District, on_delete=models.CASCADE) square = models.CharField(max_length=20) master_street = models.CharField(max_length=20) slave_street = models.CharField(max_length=20) plaque = models.CharField(max_length=3) def __unicode__(self): return self.slave_street class Library(models.Model): name = models.CharField(max_length=30) address = models.OneToOneField(Address, on_delete=models.CASCADE, related_name='address') reading_room = models.BooleanField(default=False) reading_room_start_time = models.CharField(max_length=10, default='8:00') reading_room_end_time = models.CharField(max_length=10, default='20:00') library_start_time = models.CharField(max_length=10, default='8:00') library_end_time = models.CharField(max_length=10, default='20:00') specific_information = models.ManyToManyField(SpecificInformatin) register_rules = models.ManyToManyField(RegisterRule) gender_days_in_week = models.CharField(max_length=100, default='mens') manager_of_library = models.CharField(max_length=50, default='shahrdari') tel_number = models.CharField(max_length=11, null=True) email = models.EmailField(max_length=40, default="@.com") from_user = models.BooleanField(default=False) def __unicode__(self): return self.name serializers.py: class LibrarySerializer(serializers.ModelSerializer): address = AddressSerializer() specific_information = SpecificSerializer(many=True) register_rules = RegisterRulesSerialzers(many=True) class Meta: model = Library fields = ('id', 'name', 'address', 'reading_room', 'reading_room_start_time' , 'reading_room_end_time', 'library_start_time', 'library_end_time' , 'specific_information', 'register_rules', 'gender_days_in_week' , 'manager_of_library', 'tel_number', 'email', 'from_user') def create(self, validated_data): address_data = … -
Django restframework getting WSGIRequest instead of rest_framework.request.Request
i'm creating a rest api with django 1.8 and djangorestframework and also creating the client side using extjs 6.2, i'm getting this error when i send an ajax request to the server 'WSGIRequest' object has no attribute 'query_params' my view is recieving a WSGIRequest object instead of the Request object, what bothers me is that i'm getting this error now when creating any view, all other(previously created) work fine, here are my MIDDLEWARE_CLASSES MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', 'corsheaders.middleware.CorsMiddleware',) and here are both the django view and extjs ajax request django view api_view(["GET"]) def testView(request): print(request.__class__) req = json.loads(request.query_params['array'])# here it gives the error lolo = {"response":"data"} return JsonResponse(data, safe=False) var data = 'insert':{idlineapresupuesto_id:1, idusuario_id:1, nombre:"aaaaaa"} extjs Ajax request Ext.Ajax.request({ url :"http://127.0.0.1:8000/editarConcGastosView/?format=json", method: 'GET', dataType: 'json', params: {array: Ext.JSON.encode(data)}, success : function(response){ var jsonResp = Ext.util.JSON.decode(response.responseText);//Guarda en jsonResp la respuesta de la peticion -
Anonymus user Django + Angular 2
i am using django + angular 2 i am using rest_framework_jwt with a url like this url(r'^api/api-token-auth/', obtain_jwt_token), url(r'^api/settings/?$', views.SettingsValues.as_view()), My view is class SettingsValues(generics.ListAPIView): serializer_class = SettingsSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,) def get_queryset(self): queryset = Settings.objects.all() queryset = queryset.filter(user=self.request.user.id) print self.request.user return queryset My service is: getSettings() : Promise <SettingsValues> { return this.http.get('/api/settings', { headers: this.headers }) .toPromise() .then(response => response.json() as SettingsValues); } My login is working fine, but i cannot return the settings from django.. The print inside def get_queryset shows AnonymousUser. Any idea what i am doing wrong ? EDIT private headers = new Headers({ 'Content-Type': 'application/json', 'Accept': 'application/json', }); -
Configuring memcached with django
I'm working with an ubuntu 16.04 VPS, where I have a django 1.8 app running using uwsgi and nginx. I want to install memcached for django , so I've been looking at https://docs.djangoproject.com/en/1.8/topics/cache/. I want to use pylibmc as my memcached client. Based on this, I've added: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache', 'LOCATION': '/tmp/memcached.sock', } } to my settings.py. But when I run (myenv) deploy@server:~$ sudo systemctl status memcached ● memcached.service - memcached daemon Loaded: loaded (/lib/systemd/system/memcached.service; enabled; vendor preset Active: active (running) since Fri 2017-02-17 11:21:07 EST; 5s ago Main PID: 5562 (memcached) CGroup: /system.slice/memcached.service └─5562 /usr/bin/memcached -m 64 -p 11211 -u memcache -l 127.0.0.1 How can I configure memcached to use the django socket backend? -
Django get the sum of votes per post
I have two models, Post and Vote. Users can upvote and downvote posts. models.py: class Post(models.Model): poster = models.ForeignKey('auth.User') question = models.ForeignKey('self', null=True, blank=True) post_title = models.CharField(max_length=300) post_content = models.TextField(null=True, blank=True) is_published = models.BooleanField(default=True) is_locked = models.BooleanField(default=False) is_question = models.BooleanField(default=True) is_deleted = models.BooleanField(default=False) created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) date_modified = models.DateTimeField( blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.post_title class Vote(models.Model): user = models.ForeignKey('auth.User') post = models.ForeignKey('Post') vote_type = models.SmallIntegerField()#-1, 0, 1 date_voted = models.DateTimeField( default=timezone.now) def __str__(self): return self.user I use the following code in my view to return the posts to templates: views.py: def index(request): posts = Post.objects.filter(created_date__lte=timezone.now( ), is_question=1, is_published=1).order_by('-created_date') #removed the paging stuff here for simplification return render(request, 'homepage/index.html', {'posts': posts}) This just returns the posts, but I also want the sum of the vote_type column for each post which is the total number of votes for the post. Currently I use template tags for each post to check for each post's votes. My index.html sample code: {% for post in posts %} {{ post|total_votes|default:"0" }} {% endfor %} Is there any way to query everything in the views.py and then in the template I could check like … -
Django : ValueError at form submission, returned none
I'm working on password change form where take old password, new password and confirm new password. If old password does not match with current user's password, it display error message. Also, if new password and password confirm does not match each other, it displays error message. So far I keep getting error messages and I want to know which part went wrong. Why does it return none? error message ValueError at /blog/password_change/blue/ The view blog.views.password_change didn't return an HttpResponse object. It returned None instead. urls.py url(r'^password_change/(?P<username>[-\w.]+)/$', views.password_change, name='password_change'), url(r'^password_change_done/$', views.password_change_done, name='password_change_done'), forms.py class PasswordChangeForm(SetPasswordForm): error_messages = dict(SetPasswordForm.error_messages, **{ 'password_incorrect': ("Your old password was entered incorrectly. Please enter it again."), }) oldpassword = forms.CharField( label=("Old password"), strip=False, widget=forms.PasswordInput(attrs={'autofocus': True}), ) field_order = ['oldpassword', 'password1', 'password2'] def clean_oldpassword(self): oldpassword = self.cleaned_data["oldpassword"] if not self.user.check_password(oldpassword): raise forms.ValidationError( self.error_messages['password_incorrect'], code='password_incorrect', ) return oldpassword views.py @login_required def password_change(request, username): if request.method == 'POST': form = PasswordChangeForm(data=request.POST, user=request.user) if form.is_valid(): oldpassword = form.cleaned_data.get('oldpassword') password1 = form.cleaned_data.get('password1') password2 = form.cleaned_data.get('password2') if password1 == password2: update_session_auth_hash(request, form.username) form.save() return HttpResponseRedirect('/blog/password_change_done/') else: return render(request, 'blog/detail.html', {'error_message': 'password mismatch'}) else: form = PasswordChangeForm(user=request.user) return redirect(reverse('blog:profile', args=[form.user.get_username()])) -
how to solve error 500 on django-registration-redux
Good afternoon I got a problem with django-registration-redux after deploy on heroku, it's getting 500 error when I try to register but locally it is working fine could someone give me a hint of what can be this is my settings for it. #DJANGO REGISTRATION REDUX SETTINGS REGISTRATION_OPEN = True ACCOUNT_ACTIVATION_DAYS = 7 REGISTRATION_AUTO_LOGIN = True SITE_ID = 1 LOGIN_REDIRECT_URL = '/' LOGIN_URL = '/accounts/login/' -
How does UserPassesTestMixin in django work?
views.py class ProfileEdit(UserPassesTestMixin, UpdateView): model = User form_class = ProfileForm template_name="profile/profile_new.html" def test_func(self): x = self.request.user.id print (x) y = self.kwargs['pk'] print (y) a = True b = False if self.request.user.id == self.kwargs['pk']: print (a) else: print (b) return redirect ('/login/') enter image description here as you can see in the output image the test condition actually satisfies.. but why does it print "False" if it's true. -
How to pass value from html file to views.py file?
after user enter 10 digits number automatically python function will call. i need to send text box value to python function (views.py). How to get value in views.py? i don't want when user click on submit button to get value in text box. base.html <input type="text" name="vat" id="vat1" placeholder="Please Enter 10 digits number"> script var Value = document.getElementById('vat1').value; alert(Value); -
Serving Static content from Nginx but handling error pages in Django
My static and media files are served by Nginx and other requests are served by Django. I have a custom 404 page which is served by Django. Since Nginx is handling static content any requests to /static/* which throws 404 is also handled by Nginx. I can set static custom 404 page in Nginx but I want Django to handle any 404. Is it possible to serve static content from Nginx but in case of 404, the request get forwarded to Django? -
Send HttpResponse(status=200) without "returning" - where to send?
I am using the Slack Events API to record conversations with my slackbot. The Events API pushes the messages to my Django server with an HTTP POST. Slack expects an HTTP 200 response within 3 seconds, or else they will re-POST the message. I want to store / process the Event, but I'm not sure that the processing will complete in 3 seconds. I want to send the HTTP Status 200 back to Slack and then continue the process, but I don't know where to send it. Usually, I return HttpResponse(status=200) and python manages the destination / sending. How do I identify the response URI? Can I send the HTTP Status 200 w/ urllib2? import json import urllib2 from django.http import HttpResponse def processEvent(event): # do some stuff that takes longer than 3 seconds return def incomingEvent(request): event = json.loads(request.body) url = request.????? req = urllib2.Request(url, HttpResponse(200)) processEvent(event) -
Django reduce queries
I have two models, Post and Vote. Users can upvote and downvote posts. models.py: class Post(models.Model): poster = models.ForeignKey('auth.User') question = models.ForeignKey('self', null=True, blank=True) post_title = models.CharField(max_length=300) post_content = models.TextField(null=True, blank=True) is_published = models.BooleanField(default=True) is_locked = models.BooleanField(default=False) is_question = models.BooleanField(default=True) is_deleted = models.BooleanField(default=False) created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) date_modified = models.DateTimeField( blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.post_title class Vote(models.Model): user = models.ForeignKey('auth.User') post = models.ForeignKey('Post') vote_type = models.SmallIntegerField()#-1, 0, 1 date_voted = models.DateTimeField( default=timezone.now) def __str__(self): return self.user I use the following code in my view to return the posts to templates: views.py: def index(request): posts = Post.objects.filter(created_date__lte=timezone.now( ), is_question=1, is_published=1).order_by('-created_date') #removed the paging stuff here for simplification return render(request, 'homepage/index.html', {'posts': posts}) This just returns the posts, but I also want to check if the current user has voted or not (and possibly the sum of the vote_type column for each post which is the total number of votes for the post). Currently I use template tags for each post to check if the current user has voted or not. This creates a lot of queries. (Currently 50 queries with 40 duplicates). My index.html sample code: {% for post … -
Send Output from javascript to html DIV in Django
I have an HTML page in Django where I send my input from the form to javascript and which will inturn will send it to the views, get processed and the output will come to javascript. Now I want to display this output back in the same html page in one particular DIV. My form is <form id="form_id" method = "POST" action = "/your_Value/"> {% csrf_token %} <label for="your_Value">Sentence: </label> <input id="your_Value" type="text" name="your_Value"> <input type="submit" value="Compare"> </form> <div class="details"> </div> My javascript is <script type="text/javascript"> $(function() { $(".details").hide(); $("#form_id").submit(function(event) { event.preventDefault(); var friendForm = $(this); var posting = $.post( friendForm.attr('action'), friendForm.serialize() ); posting.done(function(data) { $(".details").show(); }); posting.fail(function(data) { alert("Fail") }); }); }); </script> Where the values from posting.done() should go to 'details' div. Kindly let me know how to send the values from javascript to HTML DIV and display it. Thanks in advance!! -
Submitting form data from angularjs to django
The issue I am using Angular to submit form data as JSON to my Django view. However, after creating the form instance passing the POST data, my form will not validate. When printing out the form instance the following data is displayed. <tr> <th><label for="id_department">Department:</label></th> <td> <ul class="errorlist"> <li>This field is required.</li> </ul><select class="input-element" id="id_department" name="department" required=""> <option selected="selected" value=""> --------- </option> <option value="1"> CS </option> <option value="4"> Racing Data Customer Support </option> <option value="2"> Racing Ops </option> <option value="3"> Racing Transmissions </option> </select> </td> </tr> <tr> <th><label for="id_notification_type">Notification type:</label></th> <td> <ul class="errorlist"> <li>Select a valid choice. Leased Line Failures is not one of the available choices.</li> </ul><select class="input-element" id="id_notification_type" name="notification_type" required=""> </select> </td> </tr> <tr> <th><label for="id_notification_name">Notification name:</label></th> <td> <ul class="errorlist"> <li>Select a valid choice. AMRAC LL is not one of the available choices.</li> </ul><select class="input-element" id="id_notification_name" name="notification_name" required=""> </select> </td> </tr> <tr> <th><label for="id_notification_contacts">Notification contacts:</label></th> <td> <ul class="errorlist"> <li>Select a valid choice. 2 is not one of the available choices.</li> </ul><select class="input-element" id="id_notification_contacts" multiple="multiple" name="notification_contacts" required=""> </select> </td> </tr> <tr> <th><label for="id_subject">Subject:</label></th> <td><input class="input-element" id="id_subject" name="subject" required="" type="text" value="Test"></td> </tr> <tr> <th><label for="id_body">Body:</label></th> <td> <textarea class="input-text-area" cols="40" id="id_body" name="body" required="" rows="10">Hello world.</textarea><input id="id_notification_id" name="notification_id" type="hidden" value="11"></td> </tr> </table> … -
How to Query DB using .object in Django
I have few categories. Say Electronics and Toy. and i have mutiple shops in a mall. A shop is saved with a foreign key(category). Now in the navigation bar.. i want to list stores based on their categories. Thanks in anticipation models.py class ShopCategories(models.Model): category = models.CharField(max_length=50, unique=True,) def __str__(self): return self.category class NewShop(models.Model): category = models.ForeignKey(ShopCategories) name = models.CharField(max_length=100, unique=True) tagline = models.CharField(max_length=50, default='Enter tagline here2') description = models.TextField(default='enter shop description') def __str__(self): return self.name views.py def basefile(request): shop_cat = NewShop.objects.filter(category_id=1) shop_name = NewShop.objects.filter(name=shop_cat) return render_to_response('base.html', {'Shopname':shop_name, 'Shopcat':shop_cat}) base.html {% for category_id in Shopcat %} <li><a href="#">{{ Shopname }}</a></l> {% endfor %} -
django modeling and load JSON input as tables
Have to make django models and take a JSON file to feed all the data for a student and classes display webapp. JSON file is what going to drive my modeling, it looks like this (truncated to couple of data points)... { "students": [ { "first": "John", "last": "Smith", "email": "johnsmith@mailinator.com", "studentClasses": [ { "id": 1, "grade": 4 }, { "id": 2, "grade": 3 }, ]}, {...#truncated data, this follows with more students "classes": { "1": "Math 101", "2": "English 101", "3": "Science 101", #total 8 classes declared, truncated } I have my data models as..... class Student(models.Model): first = models.CharField(max_length=200) last = models.CharField(max_length=200) email = models.EmailField() class Classes(models.Model): student = models.ForeignKey(Student) class_name = models.CharField(max_length=50) Here are my questions... (1) How can I model in a way that takes in studentClasses:[{id:1, grade:4}] type relational input from JSON file and populates my database tables ? It seems I might have to declare serializer, why and how? (2) Getting confused by ID in classes table and not ID in students table, do I explicitly have to declare primary key in modeling with ID in classes but not students models ? (3) It seems I can load tables with "python manage.py load data …