Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Creating a multiple choice form for each primary key in model with Django
I am trying to create a class registration app in Django. To simplify my problem, I have a model for students, blocks (time periods), and classes (lessons). There are multiple classes for each block, and students must register in exactly 1 class for each block. There will be some customization allowed, so it is not known in advance how many blocks there are or which classes are available for each block. I want to generate a form with radio buttons that looks like this: Block A (9:00 - 11:00) Django class for beginners Some other class Yet another class Block B (11:00 - 13:00) Class for something How to math Placeholder class ... Block E (16:00 - 17:30) Choice 1 Choice 2 Choice 3 Choice 4 Currently, my models look something like this: class Student(models.Model): first_name = models.CharField() [...] class Block(models.Model): block = models.CharField( primary_key=True, choices=(('A', 'Block A'), ('B', 'Block B'), ('C', 'Block C'), ('D', 'Block D'), ('E', 'Block E'))) start_time = models.DateTimeField() [...] class Class(models.Model): title = models.CharField() block = models.ForeignKey('Block') [...] So far, I have something like this in my forms.py: class ClassForm(Form): class_choice = ModelChoiceField( queryset=Class.objects.all(), widget=RadioSelect, empty_label=None) And I can serve that form in my views.py, … -
get decimal input in django_filters.FilterSet
how will filter decimal value using django-filter. I need to input decimal value using the filter form. height_lesser = django_filters.NumberFilter(name='height',lookup_expr='lte', widget=forms.NumberInput(attrs={'class': 'form-control'})) I need to change the widget to DecimalInput but it is not supported. In the model i have used DecimalField. -
How to create a docx file using django framework for begginers?
Hi everyone I want to create a docx file using django. I have already installed python-docx on my laptop, I used this command pip install python-docx and I even created a .docx file on my desktop but I do not how to use this on my django project. First of all, do I need modify settings.py from my project in order to import python-docx to django? by the way I want to create these files when someone visit my urls app I have an app called 'planeaciones' and these are my main files: views.py from django.http import HttpResponse from django.shortcuts import render def index(request): return render(request, 'planeaciones/index.html') urls.py from django.conf.urls import url, include from . import views urlpatterns = [ url(r'^$', views.index, name='index'), ] index template {% extends 'base.html' %} {% block title %}Planeaciones{% endblock %} {% block content %} <h3 class="text-center">Mis planeaciones</h3> <p></p> {% if user.is_superuser %} <p>Hola Administrador</p> {% endif %} {% endblock %} -
Django ImageField in RestFramework
I'm new at Django. my project is in DjangoRestFramework This project has a user: models.py: class Users(models.Model): name = models.CharField(max_length=20, null=True) lastName = models.CharField(max_length=50, null=True) phone = models.IntegerField(unique=True, null=False, default='phone') password = models.CharField(max_length=25, null=True) natNum = models.IntegerField(unique=True, null=True) degImage = models.ImageField(upload_to='Images/degrees/', null=False, blank=False,default='Images/degrees/None/no-img.jpg') natImage = models.ImageField(upload_to='Images/nationalCards/', null=False, blank=False,default='Images/nationalCards/None/no-img.jpg') sex = models.CharField(null=True, max_length=1) province = models.CharField(null=True, max_length=20) city = models.CharField(null=True, max_length=40) job = models.CharField(null=True, max_length=20) code = models.CharField(max_length=4, null=True) last_seen = models.DateTimeField(default=django.utils.timezone.now) points = models.IntegerField(null=False, default=0) scorers = models.IntegerField(null=False, default=0) and in views.py I made a function for registeration but for degImage and natImage there is a problem. views.py @api_view(["POST"]) @parser_classes((MultiPartParser, JSONParser)) def register(request): user_data = request.data if user_data: serializer = UserSerializers(data=user_data) if serializer.is_valid(): phone_number = serializer.validated_data["phone"] try: found_user = Users.objects.get(phone=phone_number) except Users.DoesNotExist: found_user = None if found_user: return Response({ "code": 211, "status": "successfull", "message": "user already exists, try to login" }) else: destination = serializer.validated_data['phone'] message = str(random.randint(1000, 9999)) url = "https://panel.asanak.ir/webservice/v1rest/sendsms/?Username=0216463&Password=123456&Source=02100064636463&Destination={}&message={}" url = url.format(destination, message) r = requests.get(url) r.json() registerInfo = { 'name': serializer.validated_data['name'], 'lastName': serializer.validated_data['lastName'], 'phone': serializer.validated_data['phone'], 'natNum': serializer.validated_data['natNum'], 'password': serializer.validated_data['password'], 'degImage': serializer.validated_data['degImage'], 'natImage': serializer.validated_data['natImage'], 'sex': "", 'province': "", 'city': "", 'job': "", 'code': message } serializer.save(registerInfo) return Response({ "code": 200, "status": "successfull", "message": "code was sent try … -
python website for highlights generation
Hi Actually I am working on a python website cricket video highlights generator in which user will upload cricket match and as an output he will get the highlights but I am totally stuck and I dont know from where to start which libraries to use I'll be thankfull if anybody can help -
Django static css not loaded?
So my app has the following structure: base.html, which contains the nav and the links to the stylesheets and the home.html file, which loads the nav via extends. However, i can't really modify the css inside my home.html file, any suggestions whats wrong? base.html: {% load staticfiles %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>App</title> <link rel="shortcut icon" href="{% static 'img/favicon.png' %}"> <link rel="stylesheet" href="{% static 'css/app.css' %}"> ...## navbar etc. <div id="body"> <div class="container"> {% block page %} {% endblock %} </div> </div> home.html: {% extends 'base.html' %} {% load staticfiles %} {% block page %} <div class="row"> <div class="col-md-12"> <img src="{% static 'img/banner.gif'%}" class="banner"> </div> {% endblock %} As you can see in the base.html file, i load the app.css file via static method. However, changing for example the banner class in the home.html isn't working at all: #body .banner { width: 100%; margin-bottom: 150px; } No errors in the terminal / console. The app.css file works for the base.html by the way. -
Django application how to use tls1.2 to connect sql server
Using pymssql to connect sql server without TLS1.2 now. But how can I use TLS1.2 to connect sql server?Is there any way to use TLS1.2 to connect sql server in Django Project? Thanks in advance for you inputs. -
Loading form from URL in Bootstrap 3 (Django)
I have a form in a url. I want to load it in an existing page. I'm following this tutorial https://www.abidibo.net/blog/2014/05/26/how-implement-modal-popup-django-forms-bootstrap/ This is the form template {% load i18n widget_tweaks %} <div class="modal-dialog modal-lg" role="document"> <form action="{% url 'flag_post' %}" method="post" id="flag-form" class="form">{% csrf_token %} <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> <span class="sr-only">Close</span> </button> <h4 class="modal-title">Report Post</h4> </div> <div class="modal-body"> {{ form.media }} {% render_field form.reason class="form-control" %} </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <input type="submit" class="btn btn-primary" value="Save changes" /> </div> </div><!-- /.modal-content --> </form> </div><!-- /.modal-dialog --> <script> var form_options = { target: '#modal', success: function(response) {} }; $('#flag-form').ajaxForm(form_options); </script> This is my link that is supposed to load the form <a class="fa fa-pencil" data-toggle="modal" href="{% url 'flag_post' node.uid %}" data-target="#modal" title="edit item" data-tooltip></a> | I have the following script tag embedded <script src="http://malsup.github.com/jquery.form.js"></script> When I call the url directly the form is displayed, but when I try clicking the button form is not loaded. What is wrong with my code? Is this the right way to load a form from an external URL? -
ImportError Exception Value: No module named urls Exception Location: /home/pradeep/.local/lib/python2.7/site-packages/rest_framework/routers.py
https://tests4geeks.com/django-rest-framework-tutorial/ Above Tutorial URL I am following for djangorestframework API implementatuion My admin site is working perfectly, I can add Student and Universities successfully and after that while I moved to "Django REST framework-based api" steps I did same as given still getting error Can anybody suggest what to do for fix. -
Users are not being authenticated after login
This is my first time working with Django and I'm trying to create a simple login page. I would like the login page to be located at the base URL (index) of the site and then redirect to "assignments/" with "assignments/" and all other pages on the site only being accessible if the user is logged in. When I try to view if the user is authenticated (using "request.user.is_authenticated"), the view handles the user as if he/she is not logged in. views.py from django.contrib.auth import login as dj_login def login(request): return render(request, 'mainapp/login.html') def assignments(request): if request.user.is_authenticated: assignment_list = Assignment.objects.all() context_dict = {'assignments': assignment_list} return render(request, 'mainapp/assignments.html', context_dict) else: return HttpResponse("You must login first") def show_assignment(request, assignment_name_slug): try: context_dict = {} assignment = Assignment.objects.get(slug=assignment_name_slug) context_dict['assignment'] = assignment except Category.DoesNotExist: context_dict['assignment'] = None return render(request, 'mainapp/projectpage.html', context_dict) def user_login(request): information. if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user: if user.is_active: dj_login(request, user) return HttpResponseRedirect(reverse('assignments')) else: return HttpResponse("Your account is disabled.") else: print("Invalid login details: {0}, {1}".format(username, password)) return HttpResponse("Invalid login details supplied.") else: return HttpResponse("You must login first") application urls.py urlpatterns = [ url(r'^$', views.assignments, name='assignments'), url(r'^(?P<assignment_name_slug>[\w\-]+)/$', views.show_assignment, name='show_assignment') ] project urls.py urlpatterns … -
NoReverseMatch django Reverse for 'profilepk' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['account/profile/(?P<pk>\\d+)/$']
NoReverseMatch at /home/ this is error m not able to solve this pop on screen account/profile/(?P\d+)/$' is there any error in below code viwes.py,urls.py,models.py Error during template rendering In template C:\Users\shubham\Desktop\app1\account\templates\basic.html, error at line 24 Reverse for 'profilepk' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['account/profile/(?P\d+)/$'] urls.py from django.conf.urls import url from home import views app_name = 'home' urlpatterns = [ url(r'^$', views.home.as_view(), name='home'), url(r'^connect/(?P<operation>.+)/(?P<pk>\d+)/$', views.Create, name='create') ] views.py from django.contrib.auth.models import User from django.shortcuts import render, HttpResponse, redirect from django.views.generic import TemplateView from home.forms import RegiForm from home.models import Datastrore, Friendlist class home(TemplateView): template_name = 'home/home.html' def get(self, request): forms = RegiForm() datastore = Datastrore.objects.all().order_by('-created') users = User.objects.exclude(id=request.user.id) friend = Friendlist.objects.get(current_user=request.user) friends = friend.user.all() args = {'form': forms, 'post': datastore, 'user': users,'friend': friends} return render(request, self.template_name, args) def post(self, request): froms = RegiForm(request.POST) if froms.is_valid(): post = froms.save(commit=False) post.user = request.user froms.save() text = froms.cleaned_data['post'] args = {'form': froms, 'text': text} return render(request, self.template_name, args) def Create(request, operation, pk): friends = User.objects.get(pk=pk) if operation == 'add': Friendlist.Create_list(request.user, friends) elif operation == 'remove': Friendlist.Remove_list(request.user, friends) return redirect('home:home') models.py from django.contrib.auth.models import User from django.db import models # Create your models here. class Datastrore(models.Model): post = models.CharField(max_length=100) user … -
Error Incorrect type. Expected URL string, received dict
I am using volley to post data to django server.This is the format I need to Post the data { "no_people": 9, "entry_time": "2018-01-02T15:00:00Z", "predicated_time": "2018-01-02T16:00:00Z", "status": "W", "foodie": "http://localhost:9500/api/users/99/" } The foodie field consist of URL. When I am sending post request I am getting error as POST /api/restqueue/ - 400 {'content-type': ('Content-Type', 'application/json'), 'allow': ('Allow', 'GET, POST, HEAD, OPTIONS'), 'vary': ('Vary', 'Accept')} b'{"foodie":["Incorrect type. Expected URL string, received dict."]}' [23/Jan/2018 05:15:41] "POST /api/restqueue/ HTTP/1.1" 400 66 How to resolve this and send Post Request? -
how do I get that entire object instead of the foreign key. please see below code and output so you can understand
my question is how do I get that entire object instead of the foreign key. please see below code and output so you can understand my question These are my models.py class Professor(models.Model): professor_id = models.AutoField(primary_key=True, auto_created=True) name = models.CharField(max_length=256) email = models.CharField(max_length=256) mobile = models.CharField(max_length=256) created_at = models.DateTimeField() updated_at = models.DateTimeField() class Preference(models.Model): preference_id = models.AutoField(primary_key=True, auto_created=True) professor = models.ForeignKey('Professor', on_delete=models.CASCADE) rank = models.IntegerField() created_at = models.DateTimeField() updated_at = models.DateTimeField() These are my views.py class CreateListMixin: def get_serializer(self, *args, **kwargs): if isinstance(kwargs.get('data', {}), list): kwargs['many'] = True return super().get_serializer(*args, **kwargs) class PreferenceViewSet(CreateListMixin, viewsets.ModelViewSet): queryset = Preference.objects.all() serializer_class = PreferenceSerializer This is my serializers.py class PreferenceSerializer(serializers.ModelSerializer): class Meta: model = Preference I'm getting the output as [ { "preference_id": 1, "rank": 1, "professor": Eshwar "created_at": "2018-01-13T00:00:00Z", "updated_at": "2018-01-13T00:00:00Z" } ] what to do if I have to get professor details as object: [ { "preference_id": 1, "rank": 1, "professor": { professor_id = 1 name = Eshwar email = .... mobile = .... created_at = ... updated_at = .... } "created_at": "2018-01-13T00:00:00Z", "updated_at": "2018-01-13T00:00:00Z" } ] my question is how do I get that entire object instead of foreign key Any help is appreciated. -
Obtain the display value of a choice Field from a function within the own model
I have a method inside a model class, and I want to get the display value of a choice field in such model, but I get a weird value. This is the code: class Actor(models.Model): PERSON = '0' ROLE = '1' AUTO = '2' TYPE_CHOICES = ( (PERSON, 'Person'), (ROLE, 'Role'), (AUTO, 'Auto'), ) alias = models.CharField(max_length=10, default='', unique=True) name = models.CharField(max_length=255, default='') email = models.EmailField(null=True, blank=True) actor_type = models.CharField(max_length=1, choices=TYPE_CHOICES, default=PERSON) long_description = models.TextField(max_length=long_description_max_length, default='', null=True, blank=True) def get_list_fields(self): list_fields = { 'id' : self.id, 'name' : self.alias, 'description' : self.name, 'extra_fields' : "[{}][{}]".format( self.email, getattr(self, 'get_actor_type_display') ) } return list_fields And this is the result i get: {'id': 1, 'name': 'hugo', 'description': 'Hugo Luis Villalobos Canto', 'extra_fields': '[hugo@utopia-software.net][functools.partial(>, field=)]' } I don't know what that functools.partial(>, field=)stands for, and I don't know how to get the result I want: the display value of the current content of the field. Thanks for your help. -
I cannot get my PIP 9.0.1 to work properly
I'm working with a Hostgator Shared package to install and run my Django projects, I followed all the steps from here http://support.hostgator.com/articles/django-with-fastcgi#shared-reseller (section: Setup Django Using Virtualenv) I get stuck in step 3 (Install Django): ~/mydjango/bin/pip install django I get this output: Exception: Traceback (most recent call last): File "/home2/belldentjc/mydjango/lib/python2.7/site- packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/home2/belldentjc/mydjango/lib/python2.7/site- packages/pip/commands/install.py", line 272, in run with self._build_session(options) as session: File "/home2/belldentjc/mydjango/lib/python2.7/site- packages/pip/basecommand.py", line 72, in _build_session insecure_hosts=options.trusted_hosts, File "/home2/belldentjc/mydjango/lib/python2.7/site- packages/pip/download.py", line 329, in __init__ self.headers["User-Agent"] = user_agent() File "/home2/belldentjc/mydjango/lib/python2.7/site- packages/pip/download.py", line 93, in user_agent from pip._vendor import distro File "/home2/belldentjc/mydjango/lib/python2.7/site- packages/pip/_vendor/distro.py", line 1050, in <module> _distro = LinuxDistribution() File "/home2/belldentjc/mydjango/lib/python2.7/site- packages/pip/_vendor/distro.py", line 594, in __init__ if include_lsb else {} File "/home2/belldentjc/mydjango/lib/python2.7/site- packages/pip/_vendor/distro.py", line 933, in _get_lsb_release_info raise subprocess.CalledProcessError(code, cmd, stdout) CalledProcessError: Command 'lsb_release -a' returned non-zero exit status 3 Traceback (most recent call last): File "/home2/belldentjc/mydjango/bin/pip", line 11, in <module> sys.exit(main()) File "/home2/belldentjc/mydjango/lib/python2.7/site- packages/pip/__init__.py", line 233, in main return command.main(cmd_args) File "/home2/belldentjc/mydjango/lib/python2.7/site- packages/pip/basecommand.py", line 251, in main timeout=min(5, options.timeout)) as session: File "/home2/belldentjc/mydjango/lib/python2.7/site- packages/pip/basecommand.py", line 72, in _build_session insecure_hosts=options.trusted_hosts, File "/home2/belldentjc/mydjango/lib/python2.7/site- packages/pip/download.py", line 329, in __init__ self.headers["User-Agent"] = user_agent() File "/home2/belldentjc/mydjango/lib/python2.7/site- packages/pip/download.py", line 93, in user_agent from pip._vendor import … -
How create recursive loop for parsing the json?
I use Nestable2 plugin in my Django project to create tree. When user change the order of tree nodes, plugin return me JSON which I send by Ajax to server. Nestable2 return me JSON: [{"id":1},{"id":2},{"id":3,"children":[{"id":4},{"id":5,"foo":"bar"}]}] In Django view I take this JSON but I want to parse it to list of ids. For example: [1, 2, 3, 4, 5, ...] It seems to me I need to create recursive loop for this task, so I am little bit confused. Can someone say the best way to make this task? views.py: class NodeOrderView(CsrfExemptMixin, JsonRequestResponseMixin, FormView): def post(self, request, *args, **kwargs): print(self.request_json) # JSON return self.render_json_response({'saved': 'ok'}) -
AJAX Success Response Button Not Opening Modal
I'm creating an activity feed of communications, notes, and tasks. Each one has buttons for editing and deleting, which opens up a modal for either changing information or confirming the delete. The modals work fine. Once I load the data after a successful AJAX response, the buttons click (and the call is successfully made to the view) but the modal does not open. I've tried making the buttons "live" and appending the button, but the modal still won't open. This is the origin AJAX -- $(document).ready(function(){ $('.task_completed').click(function() { var id = $(this).attr('id'); var type_id = $('#contactID').attr('value'); $.ajax({ method: "POST", url: "{% url 'communications:task_completed_activity' %}", data: {'id': id, 'type': 'Contact', 'type_id': type_id}, beforeSend: function (xhr) { xhr.setRequestHeader("X-CSRFToken", '{{ csrf_token }}'); }, success: function(response) { $('.infinite-container').html(response); } }); }); }); This is an example of the modal that's failing to open -- $(document).ready(function(){ $(".task-delete").click(function(){ $("#taskDelete").modal(); }); }); This is the AJAX for the button -- $(document).ready(function(){ $('.task-delete').click(function() { var id = $(this).attr('id'); $.ajax({ method: "POST", url: "{% url 'communications:delete_confirm' %}", data: {'id': id, 'type': 'task'}, beforeSend: function (xhr) { xhr.setRequestHeader("X-CSRFToken", '{{ csrf_token }}'); }, success: function(response) { document.getElementById("task-object").innerHTML = response.object; document.getElementById("task-description").innerHTML = response.description; $('#task-id').val(response.id); } }); }); }); Let me know if … -
django models retrieving data
i m new to django.this is my model class . how can i retrieve data from depertment and doctor in my template plz write urls and view. from django.db import models class Hospital(models.Model): name=models.CharField(max_length=300) location=models.CharField(max_length=1000) def __str__(self): return self.name class Department(models.Model): hospital=models.ForeignKey(Hospital,on_delete=models.CASCADE) name=models.CharField(max_length=300) def __str__(self): return self.name class Doctor(models.Model): department=models.ForeignKey(Department,on_delete=models.CASCADE) name=models.CharField(max_length=300) designation=models.CharField(max_length=300) qualification=models.CharField(max_length=500) image=models.ImageField(default='default.png',blank=True) address=models.CharField(max_length=550) def __str__(self): return self.name -
How to filter a filed when it is Null or null character string?
How to filter a filed when it is Null or null character string? I can only to check when it is null: DataDictionary.objects.filter(parentlevel__isnull=True) How about Null or null character string? -
Validating a signed cookie set by Django in the browser
Django sets a signed cookie in the client's browser, and I have the following settings for managing cookie sessions: SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies' SESSION_COOKIE_AGE = 86400 SESSION_SAVE_EVERY_REQUEST = False When I set the cookie value in the request headers and use this code to validate the cookie, I get this error message: raise BadSignature('Signature "%s" does not match' % sig) BadSignature: Signature "REDACTED"" does not match This is how I validate the signed cookie from the request payload (taken from the docs here https://docs.djangoproject.com/en/1.11/topics/signing/#using-the-low-level-api): cookie = '"blahhh:1redacted:redactedk"' from django.core.signing import Signer signer = Signer() signer.unsign(cookie) I even stripped out the " at the beginning and end of the cookie value, and that didn't work either. I also included the cookie key like this: session_id="blahhh:1redacted:redactedk". Is my understanding of how signed cookies work wrong? Am I using the API wrong? What is going on here? -
python merge two query sets and addition of matching records
I have a need to merge two querysets together with simalar data. Set 1 (stats) has a list of teams, total points for that team and the division the team is in. Set 2 (spares) has a list of teams that have had a member spare for them which includes the teams and points (no division for this set). What I would like to do is merge the querysets into one and when the teams match, just add the spares points to the team total, keeping the team name and division. The code i am using below will sort of do what i am looking for except it does not include the teams that never had a spare on it. Consider the following data. Stats List Team 1 : 8 Points : Division A Team 2 : 3 Points : Division B Team 3 : 7 Points : Division A Team 4 : 5 Points : Division B Team 5 : 4 Points : Division A Spares List Team 1 : 3 points Team 3 : 6 Points So what I want to do is merge these two lists where the teams match but total their points. In this case … -
Django field validator not working at all
So im trying at add a simple validator that checks against a postcode and returns a validation error if the user inputs non alphanumberics. But after trying i cant seem to get even the most basic validation message to show up. Here is my form i used the example field validation just to try get it to show up but it doesn't class CartAddShippingDetailsForm(forms.Form): first_name = forms.CharField(max_length=100) last_Name = forms.CharField(max_length=100) email = forms.EmailField() address1 = forms.CharField(max_length=100) town = forms.CharField(max_length=100) postcode = forms.CharField() country = LazyTypedChoiceField(choices=countries) additional_note = forms.CharField(max_length=100, required=False) def clean_postcode(self): data = self.cleaned_data['postcode'] if "fred@example.com" not in data: raise forms.ValidationError("You have forgotten about Fred!") else: return postcode This my views.py def shipping_details(request): cart = Cart(request) shipping_form = CartAddShippingDetailsForm() if request.method == 'POST': shipping_form = CartAddShippingDetailsForm(request.POST) if shipping_form.is_valid(): return redirect(reverse('test_order')) else: return render(request, 'shippingdetails.html', {'cart': cart, 'shipping_form': shipping_form}) and the html {% extends "base.html" %} {% load static %} {% block title %}Shipping{% endblock %} {% block content %} <form action="{% url 'test_order' %}" method="post"> <div class="colcontainer"> {% csrf_token %} {{ shipping_form }} <input type="submit" name="Submit"> </div> </form> {% endblock %} i have also tried using the validator because i just want to check that the field contains only alphanumeric … -
Django Foreign Key not registering in serializer
I am trying to overwrite the create method in my view. In my Child Serializer Class, I have the parent model as a foreign key. From the view, I am only provided the parent_id. I have to get the parent model instance first. After I get the parent model instance, I want to pass that into the serializer. However in my API view, I'm getting "parent": null. Why is that? Here is what my code looks like: class ChildList(generics.ListCreateAPIView): queryset = Child.objects.all() serializer_class = ChildSerializer def create(self, request, *args, **kwargs): parent_id = request.data.get('parent_id') parent = Parent.objects.get(id=hh_id) serializer = self.get_serializer(data={'parent':parent}) if serializer.is_valid(): self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class ChildSerializer(serializers.ModelSerializer): class Meta: model = HandHistoryObject fields = ('parent',) -
Django admin userlinks is not showing up
I extended base_site.html template and it's working correctly. {% extends "admin/base.html" %} {% load i18n %} {% block title %} {% trans 'Test Admin' %} {% endblock %} {% block userlinks %} {{ block.super }} {% endblock %} {% block nav-global %}{% endblock %} And now I've created a template for my submit form which looks like this. {% extends "admin/base_site.html" %} {% load i18n static %} {% block userlinks %} {{ block.super }} {% endblock %} But no userlinks is showing up. -
What is the correct way to organize Django apps when serving data to multiple graphs?
I am currently working on a site that displays warehousing information, but am having trouble wrapping my head around Django's app concept when it applies to serving data for multiple pages of graphs. I currently have 3 apps: Authentication - handles registration pages and user profiles Notifications - manages alerts to the users when there are changes in the data Warehousing - all of the other data is served from here onto the templates The "warehousing" app has grown way too large, since it provides data for the rest of the site (4 different templates), each of which has several graphs and also includes a map of warehouse locations and a log of warehousing equipment. I understand that each Django app is supposed to have a single focus, but what is the proper way to structure them when dealing with an application like this where a majority of the site is pages of interactive graphs?