Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - how to pass model data with for loop and detailview
I couldn't pass model data to detail.html with for loop. ListView can pass datas with for loop but DetailView doesn't let me. I can access datas with object.name etc. but I cant access with for loop. my index.html <tbody> {% for total_amount in receipt_list %} <tr class="active"> <td>{{ total_amount.id }}</td> <td>{{ total_amount.amount }}</td> <td>{{ total_amount.vat }}</td> <td>{{ total_amount.total_amount }}</td> <td><a href="{% url 'detail' total_amount.id %}">Click for the details...</td> </tr> {% endfor %} </tbody> my detail.html <tbody> {% for object in receiptitem_list %} <tr class="active"> <td>{{ object.id }}</td> <td>{{ object.receipt.id }}</td> <td>{{ object.product.id }}</td> <td>{{ object.amount }}</td> <td>{{ object.vat }}</td> <td>{{ object.vat_rate }}</td> <td>{{ object.sub_total }}</td> <td>{{ object.name }}</td> </tr> {% endfor %} </tbody> my views.py class IndexView(ListView): template_name = "index.html" model = Receipt class ReceiptItemView(DetailView): template_name = "detail.html" model = ReceiptItem and my models class Receipt(models.Model): amount = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) vat = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) total_amount = models.DecimalField(max_digits=5, decimal_places=2 , blank=True, null=True) def __str__(self): return str(self.total_amount) def save(self, *args, **kwargs): receipt_items = self.receiptitem_set.all() self.amount = 0 self.vat = 0 self.total_amount = 0 for receipt_item in receipt_items: self.amount += receipt_item.amount self.vat += receipt_item.vat self.total_amount += receipt_item.amount + receipt_item.vat return super(Receipt, self).save(*args, **kwargs) class ReceiptItem(models.Model): receipt = models.ForeignKey('Receipt', on_delete=models.CASCADE … -
Django, celery beat scheduled task running every 1.5 hour, scheduled once 10 minutes
I have specific task that I configure to run every 10 minutes "schedule": crontab(minute='*/10') But it actually runs every 1.5 hours. It's happening in some tenants but in other tenants it work fine, what am I missing? -
Django/Certbot - invalid response from domain/.well-known
I'm trying to set up https on our web page which runs on Django 1.8. I'm very new in this area so I use Certbot. I followed the instructions until ./path/to/certbot-auto certonly. How would you like to authenticate with the ACME CA? 1: Place files in webroot directory (webroot) 2: Spin up a temporary webserver (standalone) I've chosen 1. Then it wants my domain and the next step is: Select the webroot for salix.sk: >>> /home/django/salix which returns error Waiting for verification... Cleaning up challenges Failed authorization procedure. salix.sk (http-01): urn:acme:error:unauthorized :: The client lacks sufficient authorization :: Invalid response from http://salix.sk/.well-known/acme-challenge/some_code: " Page not" IMPORTANT NOTES: - The following errors were reported by the server: Domain: salix.sk Type: unauthorized Detail: Invalid response from http://salix.sk/.well-known/acme-challenge/some_code: " Page not" To fix these errors, please make sure that your domain name was entered correctly and the DNS A record(s) for that domain contain(s) the right IP address. I think that I should somehow set the path in my project but can't figure out how. It created a folder .well-known inside the root of my project without any visible files inside. Do you know what to do? -
Replace Django Templates with ReactJs while Django serves as the API
I am trying to figure out the ideal approach to replace Django templates with ReactJS. When people say - "Let ReactJS entirely replace your Django Templates and let Django be used only as an API", they dont really mean replacing Django Templates (and the way they are served) entirely, right? I mean my assumption is that the html pages will still be "served" through Django (as in, urls.py will still be used and point to an html template), and then in the template html, I can define a DOM node (div etc.) which React could use to populate its stuff in, yeah? -
how do you serialize a method inside a model ?
How to serialize a get_picture(self) method in this model ? I am developing a social network and I need to serialize this method to get a json url for user profile picture to handle it in android app. class Profile(models.Model): user = models.OneToOneField(User) location = models.CharField(max_length=50, null=True, blank=True) url = models.CharField(max_length=50, null=True, blank=True) job_title = models.CharField(max_length=50, null=True, blank=True) class Meta: db_table = 'auth_profile' def __str__(self): return self.user.username def get_url(self): url = self.url if "http://" not in self.url and "https://" not in self.url and len(self.url) > 0: # noqa: E501 url = "http://" + str(self.url) return url def get_picture(self): no_picture = 'http://trybootcamp.vitorfs.com/static/img/user.png' try: filename = settings.MEDIA_ROOT + '/profile_pictures/' +\ self.user.username + '.jpg' picture_url = settings.MEDIA_URL + 'profile_pictures/' +\ self.user.username + '.jpg' if os.path.isfile(filename): return picture_url else: gravatar_url = 'http://www.gravatar.com/avatar/{0}?{1}'.format( hashlib.md5(self.user.email.lower()).hexdigest(), urllib.urlencode({'d': no_picture, 's': '256'}) ) return gravatar_url except Exception: return no_picture -
Get max value from django rest
I am using django rest framework and instead of getting the complete list of an object, I only want to get a specific value, like max(date) for example. Here is the code I am using: My Serializer class MoodSerializer(serializers.ModelSerializer): class Meta: model = Mood fields = ('date', 'rating') def create(self, validated_data): return Mood.objects.create(**validated_data) My View class MoodList(generics.ListCreateAPIView): queryset = Mood.objects.all() serializer_class = MoodSerializer class MoodDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Mood.objects.all() serializer_class = MoodSerializer My URLS url(r'^mood/$', views.MoodList.as_view()), url(r'^mood/(?P<pk>[0-9]+)/$', views.MoodDetail.as_view()), So if fire a GET on "max_mood" I want the latest Mood entry from the db. -
posting formdata with ajax has csrf error in django
I'm new to ajax and django and I'm trying to send a file in a form using formdata and ajax but I'm getting csrf token missing error and I've searched alot but can't solve this problem.Should I use cookies?if so,how?.I really need help.My codes are here: urls.py ... url(r'^administration/library/add_ebook/ajax/$',upload_ebook_ajax, name='upload_ebook_ajax'), ... forms.py class EbookForm(forms.ModelForm): class Meta: model = Ebook fields = ('ebook_title', 'ebook_publisher','ebook_publication_date','ebook_Type','ebook_keywords','ebook_preview','ebook_url','ebook_categories', ) views.py @transaction.atomic() def upload_ebook_ajax(request): if request.method == 'POST': form = EbookForm(request.POST, request.FILES) if form.is_valid(): form.save() data['form_is_valid'] = True else: data['form_is_valid'] = False else: form = EbookForm() context = {'form': form} data['html_form'] = render_to_string('upldebook.html',context,request=request) return JsonResponse(data) upldebook.html {% load crispy_forms_tags %} {% crispy form %} add_ebook.html <div class="c"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <script src="{% static 'js/jquery-file-upload/vendor/jquery.ui.widget.js' %}"></script> <script src="{% static 'js/jquery-file-upload/jquery.iframe-transport.js' %}"></script> <script src="{% static 'js/jquery-file-upload/jquery.fileupload.js' %}"></script> <form method="post" enctype="multipart/form-data" action="{% url 'upload_ebook_ajax' %}" class="js-upload-ebook-form"> {% csrf_token %} <div class="frmclass"></div> <script src="{% static 'uploadebook.js' %}"></script> <button type="submit">Upload</button> </form> </div> uploadebook.js //for showing form $.ajax({ url: '/administration/library/add_ebook/ajax', type: 'get', dataType: 'json', success: function (data) { $(".frmclass").html(data.html_form); } }); //for form submit $(".js-upload-ebook-form").submit( function (e) { e.preventDefault(); var frmdt = new FormData($('form').get(0)); //I don't know what is 'form' :| frmdt.append('csrfmiddlewaretoken', '{{ csrf_token }}'); $.ajax({ url: $(this).attr('action'), type: $(this).attr('method'), data: frmdt, cache: … -
DRF - Join three tables and make a count
I'm just starting using Django and DRF and i some problems my models.py: class Post(models.Model): owner = models.ForeignKey('auth.User', related_name='posts', on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) description = models.CharField(max_length=100, blank=True, default='') ... class Like(models.Model): owner = models.ForeignKey('auth.User', related_name='likes', on_delete=models.CASCADE) post = models.ForeignKey(Post, related_name='likes', on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) ... serializers.py: class LikeSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='owner.id') class Meta: model = Like fields = ('id', 'owner', 'post', 'timestamp') class PostSerializer(serializers.HyperlinkedModelSerializer): owner = serializers.ReadOnlyField(source='owner.id') class Meta: model = Post fields = ('url', 'id', 'description', 'owner', 'timestamp') views.py: class PostViewSet(viewsets.ModelViewSet): queryset = Post.objects.all() serializer_class = PostSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,) def perform_create(self, serializer): serializer.save(owner=self.request.user) class LikeViewSet(viewsets.ModelViewSet): queryset = Like.objects.all() serializer_class = LikeSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,) def perform_create(self, serializer): serializer.save(owner=self.request.user) class UserFeedList(generics.ListAPIView): serializer_class = PostSerializer def get_queryset(self, pk=None): queryset = Post.objects.filter(owner=self.kwargs['pk']) return queryset Routers in Urls.py: router.register(r'posts', views.PostViewSet) router.register(r'users', views.UserViewSet) router.register(r'likes', views.LikeViewSet) urlpatterns = [ url(r'^userfeedlist/(?P<pk>[0-9]+)/$', views.UserFeedList.as_view()), ... ] I'm developing an Instagram like app (academic purposes) and right now I'm working on a Rest API and using DRF. Right now I'm struggling to figure out how to get a list of all the posts from a specific User, making something like a User Feed. With the code I developed so far I'm able to get all the … -
Cannot assign "abc@gmail.com". "Invitation.friend" must be a "Invitation" instance
I am developing a referral program. It is referring a friend to join our community. I have a model called Invitation. I have used two form with same model. In the first form, the user has to fill the form with just his/her email address. When he request for invitation, he/she can now refer to his/her friends. The point will be gained if the referred friend clicks the referred link that is sent by him. My first form, i.e request for invitation is working but when after requesting for invitation, if he/she tries to refer to the friend filling his email adress and his/her friend's email address, i get an error of Cannot assign "abc@gmail.com". "Invitation.friend" must be a "Invitation" instance. How can i save the refered email adress(friend) to database? Here is my models.py class Invitation(models.Model): email = models.EmailField(unique=True, verbose_name=_("e-mail Address")) friend = models.ForeignKey('self', related_name="referral", null=True, blank=True, on_delete=models.CASCADE) invite_code = models.UUIDField(default=uuid.uuid4, unique=True) points = models.PositiveIntegerField(default=0) invite_accepted = models.BooleanField(verbose_name=_('invite accepted'), default=False) request_approved = models.BooleanField(default=True, verbose_name=_('request accepted')) forms.py class ReferForm(forms.Form): sender_email = forms.EmailField(label=_("Your email"), required=True) receiver_email = forms.EmailField(label=_("To email"), required=True) def save(self, sender_email, receiver_email): print('email', sender_email, receiver_email) new_join, created = Invitation.objects.get_or_create(email=sender_email) print ('new_join is', new_join, created) if created: return True return … -
Generic view in Django
I want to create a generic view where I have a list of modules (instructormodules.html with CreateInstructorFormView) and when the user click on a module, it leads to a page that displays module details (instructortest.html with CreateTestFormView). However, currently I am stucked on getting to the page that displays module details due to the following error: Error: Reverse for 'instructormodule' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', MainView.as_view(), name='main'), url(r'^login/$', LoginFormView.as_view(), name='login'), url(r'^register/$', RegistrationFormView.as_view(), name='register'), url(r'^instructormodule/$', CreateModuleFormView.as_view(), name='instructormodule'), url(r'^(?P<pk>[0-9]+)/$', CreateTestFormView.as_view(), name='instructortest'), ] instructormodule.html {% if class_list %} {% for module in class_list %} <div id="action-container"> <a href="{% url 'instructortest' module.classid %}"> <p>{{ module }}</p> </a> </div> {% endfor %} {% else %} <p>There is currently no module.</p> {% endif %} instructortest.html <div id="module-header"> <h2>{{ module.class_name }}</h2> </div> views.py class CreateModuleFormView(FormView): form_class = CreateModuleForm template_name = 'SqlLabApp/instructormodule.html' success_url = '/' def get(self, request, *args, **kwargs): create_module_form = CreateModuleForm class_list = ClassTeacherTeaches.objects.filter(teacher_email_id=request.user.email) class_names = [] for module in class_list: class_names.append(Class.objects.get(classid=module.classid_id).class_name) return self.render_to_response( self.get_context_data( class_list=sorted(class_names), create_module_form=create_module_form, ) ) class CreateTestFormView(FormView): model = Class template_name = 'App/instructortest.html' -
Django allauth - How to know if user is logged in with socialaccount or account?
How to know if user is logged with socialaccount or account? And get this information in the template? -
get OneToOneField data from User models on firsttime save()
i want to extend my User models and add fields to it in another models and i want it to save two of the form at once each form works fine on its own but the problem is that when i combine them the i cant get the username from the User model class Information(models.Model): Username = models.OneToOneField(User, on_delete=models.CASCADE) i tried this views.py RegisterForm = self.form_class(request.POST) InfoForm = self.second_form_class(request.POST) if RegisterForm.is_valid() and InfoForm.is_valid(): username = request.POST.get('username') password = request.POST.get('password') email = request.POST.get('email') first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') User_obj = User(username=username, password=password, email=email, first_name=first_name, last_name=last_name) user = User_obj.save() Username = username PhoneNo = request.POST.get('PhoneNo') Address = request.POST.get('Address') Country = request.POST.get('Country') Info_obj = Information(Username=Username , PhoneNo=PhoneNo, Address=Address, Country=Country) Info_obj.save() forms.py class RegisterForm(forms.ModelForm): username = forms.CharField(max_length=40) password = forms.CharField(widget=forms.PasswordInput()) class Meta: model = User fields = ["username","password", "email", "first_name", "last_name"] class InfoForm(forms.ModelForm): Username = forms.CharField(max_length=40, required=False) class Meta: model = Information fields = ["Username","PhoneNo","Address","Country"] did i miss something here? it can save to the User but it doesn't save to Information model I think the problem is with the Username on InfoForm -
How to prevent the display of admin page in django project
I created a project in python with Django framework. And I hosted the project using heroku. If the project link is like https://abc.herokuapp.com/ When I add admin to the link https://abc.herokuapp.com/admin/ the django administration page will open. I don't want to open that page. How can I prevent the django administration page shown while typing admin to the given link. -
Webpack: "Uncaught SyntaxError: Unexpected token <" in Django
My application runs fine in development, but whenever I deploy it to production I am provided with the error: "Uncaught SyntaxError: Unexpected token <". Whenever I inspect the source of the error, it is due to the webpack bundle loading index.html instead of the anticipated javascript /assets/js/index.js. I deduce that this is Webpack ignoring every request outside of index.html, but nowhere in any configurations do I have it pointing at it as default. I'd like to know how to remedy this issue and have it render what's configured as the entry point. Thanks in advance. webpack.config.js //require our dependencies var path = require('path') var webpack = require('webpack') var BundleTracker = require('webpack-bundle-tracker') module.exports = { //the base directory (absolute path) for resolving the entry option context: __dirname, //the entry point we created earlier. Note that './' means //your current directory. You don't have to specify the extension now, //because you will specify extensions later in the `resolve` section entry: [ './assets/js/index' ], output: { path: path.resolve('./assets/bundles/'), filename: "[name]-[hash].js" }, plugins: [ //tells webpack where to store data about your bundles. new webpack.NoErrorsPlugin(), // don't reload if there is an error new BundleTracker({filename: './webpack-stats.json'}), //makes jQuery available in every module new webpack.ProvidePlugin({ … -
AttributeError at / 'Context' object has no attribute 'request'
I am trying to use django-allauth for facebook login. However, when I have logged in facebook, the user.username still is null. Then, I try to follow the code in django-allauth document, but it keeps throwing the error. AttributeError at / 'Context' object has no attribute 'request' Request Method: GET Request URL: http://localhost:8000/ Django Version: 1.10.6 Exception Type: AttributeError Exception Value: 'Context' object has no attribute 'request' Exception Location: C:\Users\prairie5270\django\lib\site-packages\allauth\compat.py in template_context_value, line 25 Python Executable: C:\Users\prairie5270\django\Scripts\python.exe Python Version: 3.6.0 Python Path: ['C:\\Users\\prairie5270\\Desktop\\website', 'C:\\Users\\prairie5270\\django\\Scripts\\python36.zip', 'C:\\Users\\prairie5270\\django\\DLLs', 'C:\\Users\\prairie5270\\django\\lib', 'C:\\Users\\prairie5270\\django\\Scripts', 'c:\\users\\prairie5270\\appdata\\local\\programs\\python\\python36\\Lib', 'c:\\users\\prairie5270\\appdata\\local\\programs\\python\\python36\\DLLs', 'C:\\Users\\prairie5270\\django', 'C:\\Users\\prairie5270\\django\\lib\\site-packages'] The according code below: 14 {% load socialaccount %} 15 {% providers_media_js %} 16 <a href="{% provider_login_url "facebook" method="js_sdk" %}">Facebook Connect</a> 17 18 {% if user.is_authenticated %} 19 20 <a href="/accounts/logout"> 21 <button class="btn btn-default">Logout</button> 22 </a> 23 {% else %} 24 <a href="/accounts/login"> 25 <button class="btn btn-default">Login</button> Thank you very much in advance! I am happy for any help -
How do I retrieve values of a buttons which I am generating through a Iterator in Django?
<form action="." method="POST" role="form"> {% csrf_token %} <legend>Form title</legend> <div class="form-group"> <label for="">label</label> <input type="text" class="form-control" id="" placeholder="Input field"> </div> {% for item in items %} <button type="button" name="abc" value="2" class="btn btn-default">{{item}}</button> {% endfor %} <button type="submit" class="btn btn-primary">Submit</button> </form> Here I am generating buttons through Iterator.I want to increment value of the button on button click and then submit the final value for all the generated buttons. How do I retrieve the value for each button using Post? -
Retrieve list of objects from Django
I am new to Django. I have a User and Module database. How can I retrieve a list of modules from Modules database based on the user's email and display in html? I have tried the following code but I get empty results: html {% for class in class_list %} <form class="form" id="action-container"> <p>{{ class.class_id }}</p> <ul id="menu"> <li class="sub"><a href="#">Edit</a> |</li> <li class="sub"><a href="#">Delete</a></li> </ul> </form> {% endfor %} models.py class ClassTeacherTeaches(models.Model): class Meta: unique_together = (('classid', 'teacher_email'),) classid = models.ForeignKey(Class) teacher_email = models.ForeignKey(User) form.py class InstructorModuleForm(forms.Form): def getClassList(self, user): return ModuleTeacherTeaches.objects.values_list('classid_id', flat=True).filter(teacher_email=user.email) views.py class InstructorModuleFormView(FormView): form_class = InstructorModuleForm template_name = 'App/instructormodule.html' success_url = '/' def post(self, request, *args, **kwargs): instructor_form = self.form_class(request.POST) class_list = instructor_form.getClassList(request.user) if instructor_form.is_valid(): return HttpResponseRedirect("../instructormodule") else: return self.render_to_response( self.get_context_data( instructor_form=instructor_form, class_list=class_list ) ) -
Django formset creates extra form
My formset that I create always seems to have one extra form and because of that form it always fails the is_valid() function. Why is an extra form being created? I am creating the formset like so with initial data itemList = [] for item in cart: itemList.append(item) CartFormSet = formset_factory(CartForm) formset = CartFormSet(initial=[{'itemId' : item.object_id, 'quantity' : item.quantity, 'name' : item.product.name} for item in itemList]) also when printing itemList it shows the correct amount of objects. There is no empty item object. So why is it adding an additional form? -
How to get attributes from a fetched model. Adding Backbone to Django auth backend
I'm using django auth backend, django rest framework api and backbone in a project. var User = Backbone.Model.extend({ urlRoot: '/api/users/' }); var isAuthenticated = {{ request.user.is_authenticated|yesno:"true,false" }}; // django auth response if (isAuthenticated){ var userID = {{ request.user.id }}; // django user id console.log(userID); // checking value var currentUser = new User({id: userID}); currentUser.fetch(); var username = currentUser.get('username'); console.log(username); // checking value, getting undefined here I don't know what's wrong here, any help? -
Django - safe to store debugging data in request.META
As we know, if there is an error with your django application and you have debug=True, then you will see something like Although I am not sure, I assume that if debug=False, we would still have access to this same thing except django would email this html file to us instead. Following this assumption (someone please confirm), I have been tasked with adding another section to this exception template (USER, GET, POST, FILES, ETC [NEW CUSTOM SECTION HERE]). However, since I dont know how to do that, I thought an easier way would just to set a bunch of custom key values into request.META Would it be safe to do so? Like say an API secret key or something? So when something goes wrong, I would see it in the META of the formatted log? -
How do you pass 'exception' argument to 403 view?
I'm attempting to use UserPassesTestMixin to check which model's edit view is being requested and run a test specific to that model to see if the user should have access. Nothing is working yet, I'm just trying to get a feel for how this mixin operates. Upon returning false in the test_func, the view tries to redirect to /403/, but I get the below error. TypeError at /403/ permission_denied() missing 1 required positional argument: 'exception' view class DeviceUpdate(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Device template_name_suffix = '_update_form' form_class = DeviceUpdateForm def test_func(self): return edit_permission_test(self.get_object()) ... perms.py def edit_permission_test(model_object): possible_models = ['Device',] if isinstance(model_object, Device): print('This is a Device model object') return True else: print('This doesn't look like a Device model object') return False I cant seem to find anything out there on the interwebs that helps with this error. -
Creating New Model Form Fields in Django Admin
I have a product model that has a manytomany relationship to a locations model. I am creating an app for my clients business that has hundreds of products and services, but each product/service have different prices base on the delivery location and can deliver to multiple locations. Right now my client delivers to 4 locations. Solution #1 Hard code all 4 locations into the product model - this works, but is not preferred since they want to expand and hard coding more locations is just gross.. Solution #2 (current solution - code listed below) Create a manytomany relationship to locations - this works, but is getting way out of hand having location options of varying charges an rates for - multiplied by every product.... Solution #3 - This is the help I need, if a solution exists. I would like to build a hybrid of sort of the above two options. Id like to keep the manytomany with the location model so its easy to add locations as they grow, but once added, I would like to have an empty 'price' object that they can fill-in when adding or updating a product, yet remain assigned to that product only. Not … -
Using a dynamic value in the src= attribute of an image in the DJango static folder
I am trying to put {{color}}, which is a context dictionary key in a django file within my html but am having trouble getting {{color}} within the second img's source address to be recognized as a variable.... if that is even possible. My first img tag works fine. The second one receives the variable that I pass into the url (for example /blue as the color) within the alt= as the proper color or whatever color I pass. But it has trouble with my characters used when trying within the {%here%} ! <div id="wrapper"> <img id="logo" src="{% static 'disappear_maker/images/logo.png' %}" alt="Teenage Mutant Ninja Turtles Logo"> <img id="main_pic" src="{% static 'disappear_maker/images/{{color}}.jpg' %}" alt="{{color}} of the ninja turtle's character"> </div> I hope I am explaining this well. If not, my apologies. I basically have an images static folder with images named after colors (red.jpg, blue.jpg, etc) and want them to change depending on the manually typed in url extension that is passed to the browser. Thanks!! -
Django: How to calculate a context value AFTER rendering template?
The documentation for the render() method says that if a value in the context dictionary is callable, the view will call it just before rendering the template. The problem is I have a context value that takes a LONG time to calculate and the next page won't be rendered until that is done. I would like to render the next page immediately (without the value), but show a progress bar. A lame illustration I'm sure there are plenty of ways to do this with AJAX or other solutions, but I would like to do this value calculation with pure Django/python. Is there a way to calculate a value after rendering a page? (I'm not looking for a progress bar solution) -
django - Get user id from token and add it to database model
I'm working on a project using Django Rest Framework, I use token authentication using rest-auth library. A part of the project is to assign a home (from an pre-defined set of homes database) to users. I need the users to send a POST request with the home id, and then the home is assigned to this user in the database. Here is the serializer: class HomeUserSerializer(serializers.ModelSerializer): user_id=serializers.HiddenField(default=0) class Meta: model=models.Home_Users_Link fields=('home_id','user_id',) And the database model: class Home_Users_Link(models.Model): class Meta: unique_together = ("user_id", "home_id") user_id=models.ForeignKey(UserProfile,editable=True) home_id=models.ForeignKey(Saved_Homes) Noting that I have overridden the User model with the UserProfile model. I also learnt that it would be performed using request.user to get the user id, but I still can't implement the right function to add it to the database when the POST request is received