Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django how can I get this translated markdown to render correctly on a website?
I've taken text from my models and used markdown python extension to turn it into html... but it renders as html as a string on my site like this: bot: <p><code>62%</code> Not quite. You got this! Appreciate your efforts</p> kaik: <p>ss</p> Rather than showing the html as a string, I'd like it to format it as html. My views.py currently: from django.shortcuts import render from .models import ChatStream from django.http import HttpResponseRedirect import random import markdown from django.template import RequestContext def send(request): message = request.POST.get('userMessage', False) ip = visitor_ip_address(request) response = routes(message, 'website_' + str(ip)) chatItem = ChatStream(ss= markdown.markdown(response), user= markdown.markdown(message), name=ip) chatItem.save() return HttpResponseRedirect('/chattr/') I'm using markdown to convert the text in my models ChatStream into nicely website formattable text, but rather than formatting as html it just prints the html as a string onto the site. my chattr.html: {% for chat_stream in chat %} <p> {% if forloop.last %} {% else %} <b>bot:</b> <br> {{chat_stream.ss}} <br> <b>{{user}}:</b> <br> {{chat_stream.user}} <br> {% endif %} </p> {% endfor %} It should look like this in the website: bot: 62% Not quite. You got this! Appreciate your efforts kaik: ss -
Load Apache-arrow.js to Django project
Learning web development and using Django. My app will consume lot of data and was thinking to integrate Apache-arrow.js I was inspired by the below blog on the apache arrow js website ( https://arrow.apache.org/docs/js/ ) : https://observablehq.com/@theneuralbit/introduction-to-apache-arrow for Django , I have setup the static folder in which I downloaded the es5-umd version. in my html I have the below : Adding type=="module" - doesn't help and console log do not print "test2" or "test1" I copied the example from apache arrow js website just to test. I get the error - " :arrow.js:20 Uncaught TypeError: Cannot read property 'Arrow' of undefined" {% load static %} <html lang="en"> <head> <script src="{% static 'js/apache-arrow/es5-umd/arrow.js' %}" > console.log('test1') </script> <script type="module" src="{% static 'js/apache-arrow/es5-umd/arrow.js' %}"> const LENGTH = 2000; const rainAmounts = Float32Array.from( { length: LENGTH }, () => Number((Math.random() * 20).toFixed(1))); const rainDates = Array.from( { length: LENGTH }, (_, i) => new Date(Date.now() - 1000 * 60 * 60 * 24 * i)); const rainfall = Table.new( [FloatVector.from(rainAmounts), DateVector.from(rainDates)], ['precipitation', 'date'] ); console.log('test2') </script> <script > console.log('test3') </script> Not sure what is issue , next I am thinking of trying browserify. -
Django 3.2.6: Path order in app urls.py related to 404
I have multiple paths in my urls.py file for app communities. Here are the two that are causing issues. path('posts/<str:username>/<slug:slug>',communities_views.viewPostDetail,name="post_detail") path('posts/delete_comment/<int:comment_id>',communities_views.viewDeleteComment,name="delete_comment") For some reason, Django seems to get confused about the order of these two paths. When in the order as shown, Django recognizes that delete_comment is a path (meaning that in templates using something like communities:delete_comment does not throw an error when generating the template), but when attempting to navigate to the url, Django keeps catching the post_detail view and freaks out. However, when I reverse the order of these two urls, everything works fine. Does order matter? If so, that is rather inconvenient for larger projects. If any other information is needed, please let me know. -
How to change the height of the parent div of a plotly_app iframe in python/django?
I am trying to change the height of the parent div of an iframe but cannot find out how to. Here is an image of how the html structure is when I use my Google browser's inspect tool (I did not write this html, it is created by plotly): The highlighted div contains the height that I am trying to change. Currently, the height is set to 0. (padding-bottom is set to 10% since the ratio in the html is set to 0.1 since I have been testing everything I can think of but I have the ratio set to .35 The following shows how I call the plotly_app in the html: Here is how the views.py has the scatter_app layout: I have attempted to add 'height': '90%' the styles of the 'html.Div' and the 'dcc.Graph' but these change the height of the html inside of the iFrame. Therefore, nothing changes since I need to change the height of the parent div. Thank you in advance for all the help. -
Properties that relate to each other as a one to many field problem
Sorry that the title might be confusing but I'm not native english speaker and very new to django terms. I have a scenario like this: A department can have many branches. I have a student model where he has two properties, Department and Branch. When I select his department , I want it to accept (and show in admin panel) only the branches that are related to that department , my code so far is this: class Entity(models.Model): id = models.UUIDField(primary_key=True , default = uuid.uuid4, editable=False) class Department(Entity): name = models.CharField(max_length=100, null=False) class Branch(Entity): name = models.CharField(max_length=100, null=False) dep = models.ForeignKey(Department, related_name='branches', on_delete=models.CASCADE) class Student(Entity): #Some Fields here department = models.ForeignKey(Department, related_name='students', on_delete=models.CASCADE) branch = models.ForeignKey(Branch, related_name='students', on_delete=models.CASCADE) Assuming I have a 2 departments (CE and CS), CE has 2 branches and CS has 3 branches , What I want is, when I choose a student's department, I want the branches to be shown only the one that exists on that department , what I'm getting is 5 branches (in this example). How can I solve this ? NOTE: I haven't played with anything related to the admin panel except registering the models. Thanks in advance and sorry if the … -
How to script interactions with Django POST endpoints?
What is the preferred way of pre-populating database (Model) objects in a Django app? I am inclined to try to script POSTing data to the relevant endpoints, but am being stymied by the CSRF protection. This is not part of the testing framework, this is for setting up demonstration and training instances in a beta testing or production environment. As a notional example, I'd like to populate the the "Player" database with three entries: Alice(sender), Bob(reciever) and Charlie(eavesdropper), and I'd like to script/automate the process of creating these entries after deploying and starting the application. I already have a form based mechanism for creating new Players. By visiting /create via a browser, there is a form that allows a person to type in the name, e.g. "Bob" and a role, e.g. "reciever", and submit the form to create the new Player instance. Thus it makes sense to me to try to try to use the existing web API for this: e.g. make calls like requests.post('0.0.0.0:8000/create', data={'name':'Bob', 'role':'reciever'}) in the script that pre-populates the database. However doing this results in 403 errors due to the CSRF tokens, which I don't want to disable. This problem also occurs if I just try … -
Flutter websockets and connecting to Django channels
having trouble upgrading to a websocket connection: running my server on django (channels) on python manage.py runserver (my ip.. ):8000 and I keep getting this: WebSocket HANDSHAKING /ws/joingroup/0f248bf2-2e98-48a2-a8aa-96dece0bcff0/ WebSocket REJECT /ws/joingroup/0f248bf2-2e98-48a2-a8aa-96dece0bcff0/ WebSocket DISCONNECT /ws/joingroup/0f248bf2-2e98-48a2-a8aa-96dece0bcff0/ in flutter I am using a controller in getx. WebSocketChannel? channel; //initialize a websocket channel bool isWebsocketRunning = false; void startStream() async { if (isWebsocketRunning) return; //check if socket running var url = 'ws://${ip}:8000/ws/joingroup/${Get.parameters['groupid']}/'; this.channel = WebSocketChannel.connect( Uri.parse(url), //connect to a websocket ); channel!.stream.listen( (event) { print(json.decode(event)); }, onDone: () { isWebsocketRunning = false; }, onError: (error) { debugPrint('ws error $error'); } ); my consumers.py file in djagno: class Chatconsumer(AsyncWebsocketConsumer): async def connect(self): print('hi') self.group_id = self.scope['url_route']['kwargs']['groupid'] # gets the room_name from the Urlroute. self.room_group_name = f'group {self.groupd_id}' #this sets the room_group_name (basically creates a group) await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) #consumer receives message from websocket async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message } ) async def chat_message(self, event): message = event['message'] await self.send(text_data=json.dumps({ 'message': message })) Is this a problem with flutter and it being run on a virutal … -
OSError [Errno 22] 'Invalid argument' when use... print() in Django views for local server 127.0.0.1. PyCharm
Suddenly, the mistake appear in Django project, for start in local 127.0.0.1 in views.py that did`t modified for long time, and normally works now on production server. Run from PyCharm OSError at /Nb/ [Errno 22] Invalid argument Request Method: GET Request URL: http://127.0.0.1:8000/Nb/ Django Version: 3.1.2 Exception Type: OSError Exception Value: [Errno 22] Invalid argument Exception Location: C:\Users\shulya403\Shulya403_works\all_gid_2\all_gid_2\marketability\views.py, line 299, in Dict_by_Classes2 Python Executable: C:\Users\shulya403\Shulya403_works\all_gid_2\venv\Scripts\python.exe Python Version: 3.7.4 Python Path: ['C:\\Users\\shulya403\\Shulya403_works\\all_gid_2\\all_gid_2', 'C:\\Users\\shulya403\\Shulya403_works\\all_gid_2', 'C:\\Program Files\\JetBrains\\PyCharm ' '2019.3.4\\plugins\\python\\helpers\\pycharm_display', 'C:\\Users\\shulya403\\AppData\\Local\\Continuum\\anaconda3\\python37.zip', 'C:\\Users\\shulya403\\AppData\\Local\\Continuum\\anaconda3\\DLLs', 'C:\\Users\\shulya403\\AppData\\Local\\Continuum\\anaconda3\\lib', 'C:\\Users\\shulya403\\AppData\\Local\\Continuum\\anaconda3', 'C:\\Users\\shulya403\\Shulya403_works\\all_gid_2\\venv', 'C:\\Users\\shulya403\\Shulya403_works\\all_gid_2\\venv\\lib\\site-packages', 'C:\\Program Files\\JetBrains\\PyCharm ' '2019.3.4\\plugins\\python\\helpers\\pycharm_matplotlib_backend'] Server time: Wed, 24 Nov 2021 19:08:57 +0000 line 299 - is the print(var) function. (There's another one point of this mistake appears in enother code line, and there's print() too) Server and code normally worked for long time in this installation. I did't change any configuration files or environoment parameters... What it`s may be? -
Optimize request in the FOR loop
How can I optimize the following request to eliminate loop? Codes count is several hundred, so I get several hundreds database queries, which is unacceptable. n = 3 result = [] codes = Target.objects.filter(code__in=['ABC', 'CDE', ...]) for code in codes: result.append(Data.objects.select_related('target') .filter(target__code=code) .values('spec', 'spec_type') .order_by('-spec')[:n]) Models: class Data(models.Model): target = models.ForeignKey(Target) spec_type = models.CharField() spec = models.FloatField() class Target(models.Model): code = models.TextField(db_index=True) -
Pylance auto import one level too deep (Django)
As described in the title, the pylance auto-import imports one level too deep for Django. It throws an Error "no module named [module_name]". How can I fix it? My project structure (to the app I want to import from): Warenwirtschaft/BackEnd/BackEnd/warenwirtschaft The pylance import: from BackEnd.BackEnd.warenwirtschaft.models import Ingredient The correct import: from BackEnd.warenwirtschaft.models import Ingredient I just don't want to manually type all imports... -
correct using get_or_create?
To my code, which records a contact from the form and adds it to the db, need to add get_or_create, or write another condition (if there is a contact with such a phone — update, no - add), but i'm do it for the first time, please, I'll be glad to read solution to my problem and a brief explanation ♡ views.py from django.http import HttpResponse from django.shortcuts import render,redirect from django.contrib import messages from .forms import Forms def main(request): form = Forms if request.method == "POST": form = Forms(request.POST) if form.is_valid(): form.save() messages.success(request, 'Form has been submitted') return redirect('/') return render(request, 'app/main.html', { 'form':form } ) forms.py from django.forms import ModelForm from .models import Form class Forms(ModelForm): class Meta: model = Form fields = '__all__' urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('app.urls')) ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) models.py from django.db import models class Form(models.Model): name = models.CharField(max_length=30) phone = models.CharField(max_length=30) admin.py from django.contrib import admin from .models import Form '''from django.contrib.admin.models import LogEntry LogEntry.objects.all().delete()''' '''for delete actions in admin_panel''' admin.site.register(Form) apps.py from django.apps import AppConfig class AppConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = … -
Django avoiding page reload on form submission using HttpResponseRedirect
I wanted to create a chunk of my website so that it does not make the whole page reload once someone subits a form. I tried this previous question: Django How do i Insert data without refreshing or reloading page I used an HttpResponseRedirect as the post suggested In views.py: def displayDict(request): m = '' ip = visitor_ip_address(request) try: m = ChatStream.objects.filter() last = m.latest() last_ss = last.ss last_user = last.user html_smallest_steps = markdown.markdown(last_ss) # html_user = markdown.markdown(last_user) except: html_ss = '' html_user = '' return render(HttpResponseRedirect, 'chatStream.html', {"chat": m, "html_ss": mark_safe(html_ss), "last_user": mark_safe(last_user)}) my html: {% for chat_stream in chat %} <p> {% comment %} {% if != forloop.last %} # Do something here {% endif %} {% endcomment %} {% if forloop.last %} {% else %} <b>ss:</b> <br> {{chat_stream.ss}} <br> <b>{{user}}:</b> <br> {{chat_stream.user}} <br> {% endif %} </p> {% endfor %} <form action="/send/" method = "post">{% csrf_token %} <input type="text" name="userMessage"> <input type="submit" value="Send to ss bot"> </form> AttributeError: type object 'HttpResponseRedirect' has no attribute 'META'``` And in more detail here is the complete error: Internal Server Error: /chattr/ Traceback (most recent call last): File "C:\Users\Kaij\Documents\djangoTests\django_tailwind_project\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Kaij\Documents\djangoTests\django_tailwind_project\env\lib\site-packages\django\core\handlers\base.py", line 181, in … -
Get decimal data from Postgrades database using Django
I use Python and the Django framework to get some decimal data from the PostGress database. My question is that the variable "new_poi_lat" is displayed correctly, but why is the variable "poi_lat" displayed as shown below ?! I want the "poi_lat" variable to be displayed normally. And then I want to use "zip (poi_lat, poi_log)" but it gives an error! My code: poi_lat = [] poi_log = [] for id in IDs: poi_name = end_poi.values_list('lat','log').filter(id=id) new_poi_lat = poi_name[0][0] new_poi_log = poi_name[0][1] print("new_poi_lat:" , new_poi_lat) poi_lat.append(new_poi_lat) poi_log.append(new_poi_log) print("poi_lat:" , poi_lat) coordinates = (zip(poi_lat, poi_log)) output: new_poi_lat: 34.791553 new_poi_lat: 34.804567 poi_lat: [Decimal('34.791553'), Decimal('34.804567')] -
Wrong field value in Django FileField
There are models: class DataFile(models.Model): title = models.CharField( max_length=100, help_text='Краткое наименование данных', verbose_name = 'Наименование' ) file = models.FileField(upload_to ='data/', verbose_name = 'Файл данных', unique=True) .... class Map(models.Model): .......... data_file = models.ForeignKey( DataFile,on_delete=models.CASCADE, verbose_name = 'Файл данных', to_field='file' ) .......... I have an object of class Map. However, when referring to him obj.get().data_file.file.path or obj.get().data_file.file its behavior is different for django-shell and actual work. For Django-shell, a manual request gives the full path, which is what I need (stored in the 'file' field of the DataFile class). But in real work it outputs the value of the 'title' field of the DataFile class). I need the output to be exactly the full path to the file, i.e. what is stored in the file field. -
ModelForm doesn´t validate
I just cant make my modelform to validate. I call it from view, and GET prints it right, but when POST occurs it doesn´t validate. Allways getting ValueError Exception Value: The view gestionPartesMedicos.views.partes_medicos_add didn't return an HttpResponse object. It returned None instead. form´s name attributes correspond to model´s and form´s. This my model: class MedicalList(models.Model): worker= models.ForeignKey(worker, on_delete=models.CASCADE) description=models.CharField(max_length=255) upload=models.FileField(upload_to='media/') created_at=models.DateTimeField(auto_now_add=True) this my form class: class MedicalListForm(forms.ModelForm): class Meta: model = MedicalList fields = ( 'worker', 'description', 'upload', ) description=forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control'})) upload=forms.FileField(widget=forms.ClearableFileInput(attrs={'class': 'form-control'})) def __init__(self, *args, **kwargs): user_id = kwargs.pop('user_id') super().__init__(*args, **kwargs) worker = forms.ModelChoiceField(queryset=None,empty_label=None,widget=forms.Select(attrs={'class': 'form-control'})) worker_id = Trabajador.objects.filter(user_id=user_id) self.fields['worker'].queryset = worker_id self.fields['worker'].empty_label = None And this my view in trouble: def medical_list_add(request): if request.method == "POST": form = MedicalListForm(request.POST,request.FILES,user_id=request.user) if form.is_valid(): form.save() return redirect('medical_list') else: form = MedicalListForm(user_id=request.user) return render(request, 'medical_list_add.html', {'form': form}) Might it be around Model field created_at? just trying to guess, totally lost. thanks in advance -
Django Custom Middleware gets AnonymousUser even for logged in users
I'm using a custom middleware that looks like this: class DisallowLoggedInUsers: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. print("in interceptor before response") print("user: ", request.user) print("is_authenticated?: ", request.user.is_authenticated) response = self.get_response(request) # Code to be executed for each request/response after # the view is called. print("in interceptor after response") print("user: ", request.user) print("is_authenticated?: ", request.user.is_authenticated) return response I also have similar logs inside the get method of the view. Here's the log output: in interceptor before response user: AnonymousUser is_authenticated? False in view user: John Doe/john@test.domain is_authenticated? True in interceptor after response user: John Doe/john@test.domain is_authenticated? True Here is my order of middlewares: MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'userdata.customInterceptor.DisallowLoggedInUsers', ] Even though I've put my custom middleware way down the order (below AuthenticationMiddleware, the request.user object is not set untill the view is processed. I even tried trapping the request at process_view of the middleware but got an AnonymousUser there still. What am I doing wrong? I'm on Django 3.1.7 and djangorestframework 3.12.3. Note: I checked this related question, but it did not help. -
Can't access Django template variable
I have problem and can't see the error here, I want to pass some variables into newly generated template and then access it with javascript. But template is rendering empty value. But I can see in console that variables are not empty. The views.py arguments={'ram_count':ram_count, 'max_ram':max_ram} print(arguments['ram_count']) print(arguments['max_ram']) return render(request,'generated_elements.html',arguments) The template <option value={{ ram_count }}>{{ ram_count }}</option> <option value={{ max_ram }}>{{ max_ram }}</option> this is view from page Any help will be appreciated -
Custom Django form validation to display front end error
Right now I am setting up a range filter in my Django Project that looks like this. What I need to do, is the present the above behavior from happening, not just in the views logic, which is simple, but I need to display a message to use on the front end something along the lines of "Low bound number cannot be higher than High bound", which would appear like this. Heres my forms.py class MultiFilterForm(forms.Form): review_high = forms.IntegerField(validators = [MinValueValidator(0)], min_value=0, label = 'Reviews', required = False, widget = forms.NumberInput( attrs={'id': 'reviewInputHigh', 'name': 'reviewHigh', 'href': '#', 'value': '', 'class': "form-control"})) review_choice_high =(('lte', 'Reviews <='),) reviewsign_high = forms.ChoiceField(choices = review_choice_high, label = 'Reviews <=', required = False, widget = forms.TextInput(attrs={'id': 'reviewSignHigh','class': 'form-control',})) review_low = forms.IntegerField(validators = [MinValueValidator(0)], min_value=0, required = False, widget = forms.NumberInput( attrs={'id': 'reviewInputLow', 'name': 'reviewLow', 'href': '#', 'value': '', 'class': "form-control"})) review_choice_low = (('gte', 'Reviews >='),) reviewsign_low = forms.ChoiceField(choices = review_choice_low, label = 'Reviews >=', required = False, widget = forms.Select(attrs={'id': 'reviewSignLow','class': 'form-control',})) I was thinking of implementing a function into the Form class like so def validate_bounds(review_high, review_low): if review_low.value > review_high.value: raise ValidationError('Low bound number cannot be higher than High bound') And somehow pass the … -
How do I add an event to a formset field?
How do I add an event to a formset? I tried this but it doesn't work, calculos.js var formset_event = document.querySelector("table.table-formset input:nth-child(4)"); formset_event.setAttribute("onchange","multiplicar_formset()"); where I want to add the event onchange is right here: {% render_field formset.empty_form.unit_price class="form-control" %} I leave the html code here presupuestos-forms.html <div class="form-row" id="empty-row"> <table class="table table-bordered table-nowrap align-middle table-formset"> <td> {% render_field formset.empty_form.codigo class="form-control" %} </td> <td> {% render_field formset.empty_form.descripcion class="form-control" %} </td> <td> {% render_field formset.empty_form.quantity class="form-control" %} </td> <td> {% render_field formset.empty_form.unit_price class="form-control" %} </td> <td> {% render_field formset.empty_form.total_price class="form-control" %} </td> <td> {% render_field formset.empty_form.tax_free class="form-check-input" %} </td> </table> </div> -
Django Import Custom Module to Views.py
We have this folder structure: django_app >> views.py django_app >> bot_funcs >> bot.py Both django_app and bot_funcs have blank __init__.py files. We are attempting to import bot.py into views.py. We have tried every combination we can think of, and assumed something like this would work: from .bot_funcs import bot This results in a 500 server error on our website and this traceback in Spyder: Traceback (most recent call last): File "<ipython-input-18-937d4612431c>", line 1, in <module> from .bot_funcs import bot ModuleNotFoundError: No module named '__main__.bot_funcs'; '__main__' is not a package I think this traceback is a red herring, because other imports in views.py (e.g. from .models import Feedback) return the same traceback, but work properly on the website. What is the best way to import from a folder located in the app folder, and why are the usual import methods not working? -
Django Model Fields: Keeping track of list of possible items
I'm creating a Django model, where (as a simplified example) a user group (Users are all assigned to a group) will be able to access files of a certain file type, and which types a group can access will change by group. The list of files can be any of ~10 common file types. This list might change, but that's probably not common. Roughly speaking, I see two ways of doing this. Representing the file types as a list of strings for each user [".jpg", ".txt", ".zip"] or, as a 1:M relationship with some sort of "FileExtension" Object. These are cases in which I imagine the ORM route would be much preferred (Ex: If it's important to keep track of Each file extension's use case as for "image", "text", "audio", etc) But what if there's no other information we really need to consider here but the file extension itself? Is there a reason to create a whole model for just a few strings? In my actual project, I want to avoid the complications of creating and maintaining multiple models and storing those in the DB if I can. Rough Possible Code Examples of each: String/List approach: class UserGroup(models.Model): group_name = … -
My form is not submitting to database in Django
My View with templateView: I am trying to send my forms to database but it is not submitted because of unknown problems. I tried to combine several forms in one view. How can I send files with class based view(with def post function)? class AddFormView(TemplateView): template_name = 'formuz.html' # Define method to handle GET request def get(self, *args, **kwargs): # Create an instance of the formset EducationFormSet = modelformset_factory(Education_uz, form=EducationForm, extra=1) education_formset = EducationFormSet(queryset=Education_uz.objects.none()) my_form = MyForm(prefix="form") return self.render_to_response({'my_form': my_form,'education_formset':education_formset}) # Define method to handle POST request def post(self,request, *args, **kwargs): EducationFormSet = modelformset_factory(Education_uz, form=EducationForm, extra=1) education_formset = EducationFormSet(data=self.request.POST) my_form = self.form_class(request.POST,request.FILES,prefix='form') #check if submitted forms are valid if all([my_form.is_valid(), education_formset.is_valid()]): form = my_form.save() education = education_formset.save(commit=False) education.form = form education.save() # education_formset.save() return redirect(reverse_lazy('dashboard')) else: return HttpResponse("ishlamottiyu", content_type='text/plain') return self.render_to_response({'my_form': my_form,'education_formset':education_formset}) everything is okay with my models and forms.I am combining several forms in one view -
Django how to loop through a model but not inclide the last entry
I'd like to loop through every entry in a django model except the very last item inside of a template. I understand how to do this in python, but unsure of how I might do it inside of a template. Currently my index.html: {% for chat_stream in chat %} <p> <b>bot:</b> <br> {{chat_stream.bot}} <br> <b>{{user}}:</b> <br> {{chat_stream.user}} <br> </p> {% endfor %} The above code loops through entire model how would I not include the last entry (without first processing it in a view.py)? Thank you -
Django's user_passes_test always gets Anonymous User
I'm using the following class-based view and applying the UserPassesTestMixin to it to check some pre-conditions. class SomeTestView(UserPassesTestMixin, APIView): def test_func(self): return check_precondition(self.request.user) def get(self, request): print("inside view") print("user: ", request.user) print("is_authenticated? ", request.user.is_authenticated) return Response({"status": "success"}) Below is my precondition: def check_precondition(user): print("in user_passes_test") print("user: ", user) print("is_authenticated? ", user.is_authenticated) return True Here's the output I am getting: in user_passes_test user: AnonymousUser is_authenticated? False inside view user: John Doe/john@test.domain is_authenticated? True What I'm not able to understand is that why is the request.user anonymous inside the user_passes_test check. I want to run some precondition checks based on the user object. Here is my sequence of middlewares: MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] I'm on Django 3.1.7 and djangorestframework 3.12.3. -
Django Middleware addition breaks on Heroku but works on local
I have a middleware file that I use to identify the SIDE it that I need to use based on the environment I am running my app. #myusermodel/middleware.py from django.utils.deprecation import MiddlewareMixin from django.contrib.sites.models import Site from django.conf import settings class DynamicSiteMiddleware(MiddlewareMixin): # """ # Make all domain names available through request.site # """ def process_request(self, request): print('I am entering the middleware') try: current_site = Site.objects.get(domain=request.get_host()) print('I found the site for this domain and it is', current_site) except Site.DoesNotExist: current_site = Site.objects.get(id=settings.SITE_ID) print('I did not find the site for this domain so I set to the default, which is', current_site) request.site = current_site settings.SITE_ID = current_site.id response = self.get_response(request) return response I then add such middleware to my settings.py #mywebsite/settings.py """ Django settings for mywebsite project. Generated by 'django-admin startproject' using Django 3.2.5. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path import os import django_on_heroku import django_heroku import cloudinary import cloudinary_storage import dj_database_url from decouple import config import cloudinary.uploader import cloudinary.api # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # …