Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django extra_views - UpdateWithInlinesView: field doesn't exist
I have two models: UserPost and Image - they are in one-to-many relationship. I want to be able to update both of the models in one template so I followed the docs and tried to implement UpdateWithInlinesView from extra_views but I got an error: Unknown field(s) (image) specified for UserPost Anyone knows what's happening? models.py class UserPost(models.Model): user_id=models.ForeignKey(User,on_delete=models.CASCADE) title=models.CharField(max_length=255) ...and some other fields class Image(models.Model): id = models.AutoField(primary_key=True) user_post=models.ForeignKey(UserPost,default=None, on_delete=models.CASCADE) image=models.ImageField(null=True,blank=True,upload_to='images/') def __str__(self): return self.user_post.title def get_absolute_url(self): return reverse('home') forms.py class ImageInline(InlineFormSetFactory): model = myModels.Image fields = ['user_post','image'] views.py class PostUpdate(UpdateWithInlinesView): model=shopModels.UserPost form=myForms.UploadPostForm inlines = [myForms.ImageInline] template_name = 'update_post.html' fields=['image'] def get_success_url(self): return redirect('home') update_post.html {% extends './base.html' %} {% block content %} {% csrf_token %} {{ form }} {% for formset in inlines %} {{ formset }} {% endfor %} {% endblock %} -
Django - CSRF cookie not set when logging in from Axios
I'm trying to use the standard Django authentication system with a separated Vue/Django app, so Vue handles entirely the entire frontend, Django will work as an API on the backend. Both backend and frontend will be deployed on the same server and on the same port, in order to keep Session auth. Right now my backend uses django-allauth (which uses the built-in Django auth under the hood, i think) for everything authentication related and it supports Session authentication from AJAX. I'm trying to login from the Vue SPA app using Axios, but i keep getting the following error: Forbidden (CSRF cookie not set.): /accounts/login/ Here is my frontend code: get_csrf() { axios.get('http://127.0.0.1:8000/get_csrf/') .then(response => { this.csrf_token = response['data']; }); }, authenticate() { this.get_csrf() axios.post('http://127.0.0.1:8000/accounts/login/', { username: 'test', password: 'test123', }, { headers: { 'X-CSRFTOKEN': this.csrf_token }, }) .then(function (response) { console.log(response) }.bind(this)) }, So get_csrf() is used to connect to an API endpoint on the Django backend that will generate the csrf token, i know that security wise this is not the best practice but i still have to find a safer way to use this, and i can also use samesite=Lax and disable the CSRF protection, but i don't … -
Multiple Django apps using django-tailwind
So, I have been trying out a way to use TailwindCSS with django and I luckily found the package that does the right job for me which is django-tailwind. In the docs, the author has specified how to use all the utlity classes of Tailwind in an app. But hasn't mentioned how to use Tailwind in other Django apps. TAILWIND_APP_NAME = <the app name> is the way to specify the Tailwind app So do I specify a list of the other apps I have like TAILWIND_APP_NAME = [<app1>, <app2>] Or some other way? Thanks. -
Update a field of a Django Object
I'm trying to update an object field in django. Usually I would do something like this: # MODEL --- class MyObj(models.model): name: models.CharField(max_length=10) surname: models.CharField(max_length=10) # VIEW --- # [...] myObj = MyObj.objects.get(pk=1) myObj.name = 'John' myObj.save() The problem is that the field to modify (in the example above: "name") is not known and passed as an argument to the post request. So I would have something like this: # VIEW --- # [...] field = self.request.query_params['field_to_modify'] myObj = MyObj.objects.get(pk=1) myObj[field] = 'John' myObj.save() now this triggers the error: myObj[field] = 'John' TypeError: 'MyObj' object does not support item assignment What is the correct way to update an "unknown" field of a django object? -
Different authentications and permissions in ModelViewSet - Django REST framework
This question is similar to this one: Using different authentication for different operations in ModelViewSet in Django REST framework, but it didn't work for me. I've got the following viewset: class UserViewSet(viewsets.ModelViewSet): serializer_class = UserSerializer queryset = UserProfile.objects.none() permission_classes = [SpecialPermission] SpecialPermission looks like this: class SpecialPermission(IsAuthenticated): def has_permission(self, request, view): if request.method == 'POST': return True return super().has_permission(request, view) REST framework settings: "DEFAULT_AUTHENTICATION_CLASSES": ["backend.api.authentication.ExpiringTokenAuthentication"], "DEFAULT_PERMISSION_CLASSES": ["rest_framework.permissions.IsAuthenticated"], I want to everybody to be able to post to UserViewSet but every other method should require Authentication. However, with the code above I get an Unauthorized Response on post. What do I need to change? -
Django not displaying image with correct settings
I'm trying to make a video/thumbnail model for displaying some videos. It shows the video and I can access the video file (FileField) in the browser, however, I get a 404 error for the thumbnail (ImageField). Since I can access the videos, I assume the media settings are working just fine. def get_video_upload_path(instance, filename): name, ext = filename.split('.') return os.path.join(f'videos/{instance.slug}.{ext}') def get_video_thumbnail_upload_path(instance, filename): name, ext = filename.split('.') return os.path.join(f'videos/thumbnail/{instance.slug}.{ext}') class Video(base_model): thumbnail = models.ImageField( blank=True, upload_to=get_video_thumbnail_upload_path) video = models.FileField( upload_to=get_video_upload_path) -
dynamic passing fields and look up types and values in Q objects
this is to filter a competition start date and end date in a the range provided by the user, below is the code that is working for the same but I want to supply field names (here:deadlines__start_date) and look_up types (here: __lte, __gte). and the user supplied range fields self.start_date and self.end_date. return qs.filter((Q(deadlines__start_date__gte=self.start_date) & Q(deadlines__end_date__lte=self.end_date)) |Q(deadlines__start_date__lte=self.start_date) & Q(deadlines__end_date__lte=self.end_date) & Q(deadlines__end_date__gte=self.start_date)) | (Q(deadlines__start_date__lte=self.start_date) & Q(deadlines__end_date__gte=self.end_date)) | (Q(deadlines__start_date__gte=self.start_date) & Q(deadlines__end_date__gte=self.end_date) & Q(deadlines__start_date__lte=self.end_date)) ) this was working fine but now I want to send field names and look_up types and values to be compared dynamically, but not finding any solution. ``` I tried doing it like below: kwargs0 = {str('%s__gte' % (start_field)) : str('%s' % self.start_date)} kwargs1 = {str('%s__lte' % (end_field)) : str('%s' % self.end_date)} kwargs2 = {str('%s__lte' % (start_field)) : str('%s' % self.start_date)} kwargs3 = {str('%s__lte' % (end_field)) : str('%s' % self.end_date)} kwargs4 = {str('%s__gte' % (end_field)) : str('%s' % self.start_date)} kwargs5 = {str('%s__lte' % (start_field)) : str('%s' % self.start_date)} kwargs6 = {str('%s__gte' % (end_field)) : str('%s' % self.end_date)} kwargs7 = {str('%s__gte' % (start_field)) : str('%s' % self.start_date)} kwargs8 = {str('%s__gte' % (end_field)) : str('%s' % self.end_date)} kwargs9 = {str('%s__lte' % (start_field)) : str('%s' % self.end_date)} q_object= Q() q_object.add(Q(**kwargs0), Q.AND) q_object.add(Q(**kwargs1), … -
How to sort events by date intervals Django REST
I'm working on a Django Rest project, building an API, and, since I got to the point to get all the events sorted by users, now I'm stuck on dividing those events by dates. For example, I want to sort between init_date and end_date, and be able to change the dates and display the events that occurred between those. -
How to take value from Django form?
I have a form with one field for choosing a method to sort objects. However, when I refer to this field to get it's value, it equals to HTML code that renders out this form. How do I solve this problem? My form: class sortChoice(forms.Form): CHOICES = [('sbd', 'Сортировать по дате'), ('sbp', 'Сортировать по популярности')] choice = forms.ChoiceField(choices = CHOICES, widget = forms.RadioSelect, label = 'Сортировка по') My view: @login_required(login_url = 'login') def vacancyListView(request): searchQueryNavbar = request.GET.get('search_navbar', '') searchQueryVLpage = request.GET.get('search_vlpage', '') form = sortChoice() print(form['choice']) if searchQueryNavbar or searchQueryVLpage: if searchQueryNavbar: searchQuery = searchQueryNavbar else: searchQuery = searchQueryVLpage if form['choice'] == 'sbp': queryset = Vacancy.objects.filter(Q(name__icontains = searchQuery) | Q(salary__icontains = searchQuery) | Q(competences__icontains = searchQuery)).order_by('-viewsAmount') if form['choice'] == 'sbd': queryset = Vacancy.objects.filter(Q(name__icontains = searchQuery) | Q(salary__icontains = searchQuery) | Q(competences__icontains = searchQuery)).order_by('-creationDate') else: queryset = Vacancy.objects.all().order_by('-viewsAmount') context = { 'objectList':queryset, 'form':form } return render(request, "vacancyList.html", context) Console output of print(from['choice']): <ul id="id_choice"> <li><label for="id_choice_0"><input type="radio" name="choice" value="sbd" required id="id_choice_0"> Сортировать по дате</label> </li> <li><label for="id_choice_1"><input type="radio" name="choice" value="sbp" required id="id_choice_1"> Сортировать по популярности</label> </li> </ul> -
IntegrityError at /update/70 NOT NULL constraint failed: tohome_task.title
I was updating the data in the database by takin the data from an html form when this appeared. I have faced this problem earlier also but I dont remember how to solve it . my views.py part def update(request,pk): task = Task.objects.get(id=pk) context = { 'task':task, } if request.method=="POST": task.title= request.POST.get('taskname' ) task.save() return redirect('/main') return render(request,"update.html",context) models.py file : class Task(models.Model): title = models.CharField(max_length =200) complete = models.BooleanField(default = False , blank=True) created = models.DateTimeField(auto_now=True) my html file : <div class="container"> <div class="jumbotron mt-3"> <form method= "post"> {% csrf_token %} <h1 class="text-center">{{task}}</h1> <input type="text" class="form-control rounded " id="task_name" name="task_name" aria-describedby="emailHelp" placeholder="Add the task !"> <p class="lead text-center" > Do you really want to update ?</p> <button class="btn btn-lg btn-primary" type ="submit" >Update &raquo;</button> </form> </div> </div> -
How to get subordinates, recursively?
I have Django models for Organizational Units (OrgUnit) which can be company, department, team, etc., ie. it is a tree structure: from django.db import models from django.contrib.auth.models import User from treebeard.mp_tree import MP_Node, MP_NodeManager class OrgUnit(MP_Node): # MP_Node adds a .path field name = models.CharField(max_length=120) Employees can be connected to one or more OrgUnits: class OUEmployee(models.Model): user = models.ForeignKey(User, related_name='employers', on_delete=models.CASCADE) orgunit = models.ForeignKey(OrgUnit, on_delete=models.CASCADE) ..and managers can manage several OrgUnits: class OUManager(models.Model): user = models.ForeignKey(User, related_name='+', on_delete=models.CASCADE) manages = models.ManyToManyField(OrgUnit, blank=True) Now I want a queryset of all employees that are subordinates of a given manager, implemented as a method on OUManager, however, the current implementation only gives the employees connected directly to the OrgUnits the manager manages, not to the child-orgunits: def subordinates(self): return OUEmployee.objects.filter( orgunit__in=self.manages.all() ) i.e. given: root = OrgUnit.add_root(name='Acme Corporation') dept = root.add_child(name='Dept. of Anvils and Tunnels') team = dept.add_child(name='QA') emp1 = OUEmployee(user=User.objects.create_user(username='emp1'), orgunit=team) emp2 = OUEmployee(user=User.objects.create_user(username='emp2'), orgunit=dept) mngr = OUManager(user=User.objects.create_user(username='manager')) mngr.manages.add(dept) I would like employees = mngr.subordinates() to return a queryset with both emp1 and emp2 (the above implementation only return emp2). Is there a way to write subordinates so it only requires one db-hit? The best method I have come up with so … -
CKeditor not working on CreateVIew in Django
I've installed CKeditor and apply it to the models.py. I run the migrations and migrate it to DB. I tried to test it by going to the admin page. I can see that CKeditor is showing, but when I render it to my template using CreateView, it does not show. Models.py from django.db import models from django.contrib.auth.models import User from ckeditor.fields import RichTextField class Content(models.Model): title = models.CharField(max_length=250) content = RichTextField(blank=True, null=True) date = models.DateField(auto_now_add=True) website = models.URLField() github = models.URLField() image = models.ImageField(upload_to=get_image_filename, verbose_name='Image') Forms.py class ContentForm(forms.ModelForm): class Meta: model = Content fields = [ 'title', 'content', 'website', 'github', 'image', ] Views.py class CreateContentView(CreateView): form_class = ContentForm template_name = 'appOne/create_content.html' Template <form method="POST">{% csrf_token %} {{ form.text | safe }} {{ form.media }} <input type="submit" value="Save"> </form> The weird thing is, in the Admin Page, the CKeditor works totally fine, but when I passed it to the template, the toolbar and menubar are not showing. -
Google Cloud VideoIntelligence Speech Transcription - Transcription Size
I use Google Cloud Speech Transcription as following : video_client = videointelligence.VideoIntelligenceServiceClient() features = [videointelligence.enums.Feature.SPEECH_TRANSCRIPTION] operation = video_client.annotate_video(gs_video_path, features=features) result = operation.result(timeout=3600) And I present the transcript and store the transcript in Django Objects using PostgreSQL as following : transcriptions = response.annotation_results[0].speech_transcriptions for transcription in transcriptions: best_alternative = transcription.alternatives[0] confidence = best_alternative.confidence transcript = best_alternative.transcript if SpeechTranscript.objects.filter(text = transcript).count() == 0: SpeechTranscript.objects.create(text = transcript, confidence = confidence) print(f"Adding -> {confidence:4.10%} | {transcript.strip()}") else: pass For instance the following is the text that I receive from a sample video : 94.9425220490% | I refuse to where is it short sleeve dress shirt. I'm just not going there the president of the United States is a visit to Walter Reed hospital in mid-july format was the combination of weeks of cajoling by trump staff and allies to get the presents for both public health and political perspective wearing a mask to protect against the spread of covid-19 reported in advance of that watery trip and I quote one presidential aide to the president to set an example for a supporters by wearing a mask and the visit. 94.3865835667% | Mask wearing is because well science our best way to slow the spread … -
unresolved import 'django.urls'
hello im using Django version 3.1.7 and python 3.9.2 and working on visual studio. so I set up a virtual environment with the command prompt and when I try to import django.urls or django.http it says unresolved import from django.shortcuts import render from django.http import HttpResponse # Create your views here. def home(request): return HttpResponse("hello world") -
Django Assigning or saving value to Foreign Key field
can any one help me with assigning value to a foreign key field. Im trying to create user profile where user can add there countries. when creating the models, from django admin page there is no problem adding countries im only having an error in the front end side when adding country select option and I got an error value ValueError: Cannot assign "{'countries': 1}": "RegsModel.nationality" must be a "Country" instance. please see my omitted code. models.py class RegsModel(models.Model): name = models.CharField(blank=True, max_length=64) nationality = models.ForeignKey(Country, on_delete=models.CASCADE) def __str__(self): return self.Employee_ID class Country(models.Models): countries = models.CharField(blank=True, max_length=64) def __str__(self): return self.countries forms.py class RegsForm(forms.ModelForm): class Meta: model = RegsModel fields = '__all__' views.py def register(request): if request.method == "POST": form = RegsForm(request.POST) if RegsFrom.is_valid() form.save(commit=False) form.nationality = request.POST['nationality'] else: form = RegsForm(request.POST) return request('register', views.register, name='register',{'form':form}) register.html <form method='POST'> {{form.as_p}} <button type='submit'>add</button> </form> -
Runtime error after installing Django cms
I was in the process of doing a pip install to integrate payments to my Django website. When I run migrations I had gotten a module error that stated that Django cms could not be found. I fixed the problem by running pip install djangocms-installer I then receive this error when running migrations. Traceback (most recent call last): File "C:\Users\User\Desktop\rahisi-ecom\manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 357, in execute django.setup() File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\payrave\models.py", line 2, in <module> from cms.models import CMSPlugin File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\cms\models\__init__.py", line 2, in <module> from .pagemodel import * # nopyflakes File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\cms\models\pagemodel.py", line 1626, in <module> class PageType(Page): File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py", line 108, in __new__ raise RuntimeError( RuntimeError: Model class cms.models.pagemodel.PageType doesn't declare an explicit … -
I am getting postgresql error while working in django rest framework?
My project was running fine. Then i opened my editor after a while and called my api then they are giving me this error. I don't know what is causing it. Exception Value: could not load library "/Library/PostgreSQL/13/lib/postgresql/llvmjit.so": dlopen(/Library/PostgreSQL/13/lib/postgresql/llvmjit.so, 10): Symbol not found: ____chkstk_darwin Referenced from: /Library/PostgreSQL/13/lib/postgresql/llvmjit.so Expected in: /usr/lib/libSystem.B.dylib in /Library/PostgreSQL/13/lib/postgresql/llvmjit.so enter image description here -
validate django field against another field on loaddata in django
I have a django model class eclipse(Base): type = models.CharField( choices=[1,2,3] default=1, ) daysVisible = models.PositiveSmallIntegerField(default=32767) recurrence = RecurrenceField(null=True, blank=True) and I have a json of eclipse data that I load in with loaddata.py How would I validate that the data loaded in has daysVisible equal to 1 if type is 1? -
How to get the result of a textfield to run python code in django
so i am making a python editor, and i have a model called NewJax. In this model, i have a field called space. The space field executes the python code i typed in there. for example, if i did print('hello') in the space field, it should take me to a detail page, and return the result. Which is hello. but when it takes me to the details page for now, it results in None. Could you someone please let me know, how this should execute? models.py class NewJax(models.Model): title = models.CharField(max_length=60) description = models.TextField(max_length=140) space = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE) date_created = models.DateTimeField(default=timezone.now) class Meta: ordering = ['-date_created'] verbose_name_plural = "New Jax" def __str__(self): return str(self.title) forms.py class CreateNewJaxForm(forms.ModelForm): class Meta: model = NewJax fields = ('title', 'description', 'space') widgets = { "title": forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'name your jax' } ), 'description': forms.Textarea( attrs={ 'class': 'form-control', 'placeholder': 'add a brief description for jax', 'rows': 4, } ), 'space': forms.Textarea( attrs={ 'class': 'form-control', } ) } views.py def create_new_jax(request): if request.user.username == "Assasinator": logout(request) return redirect('banned_user') if request.method == "POST": form = CreateNewJaxForm(request.POST or None) if form.is_valid(): title = form.cleaned_data.get('title') description = form.cleaned_data.get('description') space = form.cleaned_data.get('space') obj = … -
Save Button Not Working with Attribute Error: 'WSGIRequest' object has no attribute 'project'
I checked the other posts on here that have the attribute error that I have, but they seem to be for different reasons. I am currently requesting the information from a form for users to update a project page. Then, if the form is valid, I am saving the form, saving the project, then trying to return redirect to the project page; however, when I click the button, the computer renders the error page. I will attach my forms.py, views.py, models.py, and urls.py: Views.py for the update section: @wraps(function) def wrap(request, *args, **kwargs): user = request.user name = kwargs.get('name') if uProjects.objects.filter(project=Project.objects.get(name=name), user=user, ifAdmin=True).exists(): return function(request, *args, **kwargs) else: return HttpResponseRedirect('/') return wrap @admin_check def update(request, name): project = Project.objects.get(name = name) if request.method == "POST": pr_form = ProjectUpdateForm(request.POST, request.FILES, instance=project) #if is_admin in Member == True: #need to authenticate user, access user permissions, if user has permission: if pr_form.is_valid(): pr_form.save() messages.success(request, f'This project has been updated.') request.project.save() return redirect('project') else: pr_form = ProjectUpdateForm(instance=project) context = { 'pr_form': pr_form } return render(request, 'projects/updateproject.html', context) forms.py for ProjectUpdateForm: class ProjectUpdateForm(forms.ModelForm): class Meta: model = Project fields=['name', 'department', 'department','bPic', 'logo', 'department', 'purpose', 'projectTag', 'lookingFor', 'recruiting'] urls.py from projects import views as p path('project/<str:name>/', … -
Django celery task api call
I build rss aggregation site, and I try to call iframely.com to get images for my rss objects entry(I save every entry in database). But, when I add celery task for this, rss aggregator don't get new entry and just nothing happend, 0 errors. Task don't run. My code: class Post(models.Model): # an entry in a feed source = models.ForeignKey(Source, on_delete=models.CASCADE, related_name='posts') title = models.TextField(blank=True) body = models.TextField() link = models.CharField(max_length=512, blank=True, null=True) ... def save(self, *args, **kwargs): from .tasks import save_thumbnail_url if not self.image_url: self.image_url = save_thumbnail_url.delay(self.id) super(Post, self).save(*args, **kwargs) I try also post_save signal, same effect. Task: def get_thumbnail_from_url(post: Post): if not post.image_url: req = requests.get('https://iframe.ly/api/oembed?url=' + post.link + '&api_key=493c9ebbdfcbdac2a10d6b') thumbnail_url = req.json()['thumbnail_url'] post.objects.filter(id=post.id).update(image_url=thumbnail_url) @shared_task def save_thumbnail_url(post_id: int): get_thumbnail_from_url(Post.objects.get(id=post_id)) -
Getting Foreign Key data in Django Admin Add/Change Form
I am trying to customise the Django admin add/change for a project. I have created a model called "Visit" which contains 3 Foreign Key fields: "Customer", "Pet" and "Doctor". The workflow is as follows: The user creates a customer. The user creates a pet and associates it with a customer. The user creates a visit and associates it with a pet and a doctor. Below is the code for my models.py class Visit(models.Model): customer = models.ForeignKey('customer.Customer', on_delete=models.CASCADE) pet = models.ForeignKey('pet.Pet', on_delete=models.CASCADE) date = models.DateTimeField() doctor = models.ForeignKey( 'configuration.Doctor', on_delete=models.DO_NOTHING, null=True, blank=True) status = models.CharField( choices=PET_STATUS, max_length=3, null=True, blank=True) reason = models.CharField(max_length=255) diagnosis = models.TextField(null=True, blank=True) treatment = models.TextField(null=True, blank=True) comment = models.TextField(null=True, blank=True) prescription = models.TextField(null=True, blank=True) weight = models.DecimalField( max_digits=6, decimal_places=2, null=True, blank=True) class Meta: ordering = ('-date',) My issue is that someone using the Django Admin to create a Visit can wrongly choose a Customer and Pet. Hence, the Customer does not own that Pet. I would like to know how can I customise the Django Admin, so that, when the user selects a Customer, only Pets under that particular Customer is displayed in the dropbox. Below is my admin.py class VisitAdmin(admin.ModelAdmin): change_form_template = 'visit/invoice_button.html' add_form_template = 'visit/add_visit.html' … -
@login_required decorator redirecting back to login, after log in
My web app successfully logs in the user into the home page (pick.html) but however when clicking on a link in the navigation bar ('Home'), the user gets logged out when the @login_required decorator is used in the pick.html view. views.py: def postsign(request): email=request.POST.get('email') passw=request.POST.get('pass') try: user=auth.sign_in_with_email_and_password(email,passw) except: message="Invalid credentials. Try again." return render(request,"login.html", {"msg":message}) session_id=user['idToken'] request.session['uid']=str(session_id) return render(request,"pick.html") @login_required(login_url='login') def pick(request): return render_to_response('pick.html') pick.html {% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>FYP - Is Your Network Safe?</title> <!-- Bootstrap core CSS --> <link href="{% static 'vendor/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet"> <link href="{% static 'vendor/bootstrap/css/loader.css' %}" rel="stylesheet"> <!-- Custom fonts for this template --> <link href="{% static 'vendor/fontawesome-free/css/all.min.css' %}" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Varela+Round" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet"> <!-- Custom styles for this template --> <link href="{% static 'css/grayscale.min.css' %}" rel="stylesheet"> <script src="https://api.mapbox.com/mapbox-gl-js/v1.11.1/mapbox-gl.js"></script> <link href="https://api.mapbox.com/mapbox-gl-js/v1.11.1/mapbox-gl.css" rel="stylesheet" /> </head> <body id="page-top"> <!-- Navigation --> <nav class="navbar navbar-expand-lg navbar-light fixed-top" id="mainNav"> <div class="container"> <a class="navbar-brand js-scroll-trigger" href="#page-top">TestPage</a> <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> Menu <i class="fas fa-bars"></i> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="{% url 'pick' %}">Home</a> </li> <li class="nav-item"> … -
Django i18n prefix_default_language=False can't redirect back to default language
I'm adding support for German on an English default site. I want the German version to add the /de/ prefix to all URLs as Django suggests but want to keep the standard URLs for the English version so it doesn't break the links I already have set up. The prefix_default_languge=False works as expected when you go directly to the URLs. The form that Django supplies switches to German correctly but doesn't allow you to switch back to the default language. This is only a problem with it set to False, When True the form works as expected (adding the /en/ prefix) and if I disable the i18n_patterns and just change the language without the URL changing the form also works. Why is this a problem just when prefix_default_language=False? urls.py: from django.conf.urls.i18n import i18n_patterns from django.contrib import admin from django.urls import include, path urlpatterns = [ path("admin/", admin.site.urls), path("staff/", include("stats.staff_urls")), path("i18n/", include("django.conf.urls.i18n")), ] urlpatterns += i18n_patterns( path("", include("stats.urls")), prefix_default_language=False, ) settings.py LANGUAGE_CODE = 'en' LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) LANGUAGES = ( ('en', 'English'), ('de', 'German'), ) TIME_ZONE = 'Europe/London' USE_I18N = True USE_L10N = True USE_TZ = True form.html {% load i18n %} {% get_current_language as LANGUAGE_CODE %} <form … -
Sorting serialized data - Django - getting keyerror
Version Info: Django: 1.11.2 Python 2.7 In my application, I want to sort by a field in the data that is returned by the serializer, however, it is throwing an error. The resultset is of type rest_framework.utils.serializer_helpers.ReturnList, the data is given below (only sample, actual data is pretty huge). [OrderedDict([(u'id', 941), ('business_location', {'distance': 3.7249839781687317, 'business': 941, u'id': 916}), ('business_detail', {'business_profile': u"Good solutions!", 'website': None}), ('business_images', []), ('business_service', [OrderedDict([(u'id', 1587), ('length_of_slots', 12), ('price', 25.0), ('business_group', None)])])]), OrderedDict([(u'id', 1595), ('business_location', {'distance': 6.376269428282773, 'business': 1595, u'id': 1634}), ('business_detail', {'business_profile': u'A long-term wellness.', 'website': None}), ('business_images', []), ('business_service', [OrderedDict([(u'id', 5361), ('length_of_booking_slot', u''), ('price', 125.0), ('business_group', None)])])])] The error I'm getting is (KeyError('price',), 'price') The views.py, I'm using this code to sort by price. sorted(business_serializer.data, key=lambda k: (k['price'])) Kindly suggest what is that I'm doing wrong. Also, I would want to implement ASC/DESC functionality. Note: I tried to implement order_by in the serializer, since my data has a different category & each of them will have a price it is not getting sorted at the result level.