Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: How to delete child row and remove relationship from Foreign key
What I want I have two Models. I want the following outcomes: When the RecordModel is deleted - The BookingModel remains the same but removes relationship to RecordModel. When the BookingModel is deleted - RecordModel is not deleted. What I've tried When trying to delete RecordModel. I receive error: MySQLdb._exceptions.IntegrityError: (1451, 'Cannot delete or update a parent row: a foreign key constraint fails (`cdt_dashboard`.`emissions_dashboard_bookingmodel`, CONSTRAINT `emissions_dashboard__record_id_f8312a32_fk_emissions` FOREIGN KEY (`record_id`) REFERENCES `emissions_dashboard_recordmodel` (`i)') Models class RecordModel(models.Model): created = models.DateTimeField(blank=True, null=True) started = models.DateTimeField(blank=True, null=True) finished = models.DateTimeField(blank=True, null=True) class BookingModel(models.Model): booker = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) record = models.OneToOneField(RecordModel, blank=True, null=True, on_delete=models.DO_NOTHING) -
raise DatabaseError('ORDER BY term does not match any column in the result set.')
list=Model1.objects.filter( reservation__in=Model.objects.filter(resource__in=resources).union( Model2.objects.filter( reservation__in=Model.object.filter(resource__in=resources).defer('col4','col5','col6'), Model3.objects.filter( reservation__in=Model.objects.filter(resource__in=resources),\ Model4.objects.filter( reservation__in=Model.objects.filter(resource__in=resources).defer('col4') I have 4 models with not equal number of columns.The query is working fine.But facing this error when i am trying to return in get_initial_queryset in django datatables raise DatabaseError('ORDER BY term does not match any column in the result set.') django.db.utils.DatabaseError: ORDER BY term does not match any column in the result set. -
Django DateField with only month and year choice
I have a question for you. I have the following model: class Budget_Vendite(models.Model): product=models.ForeignKey() income=models.DecimalField() date=models.DateField() I have an algo in my django app that split my income based on month as following: for product_id, year, month, totale in(Budget_Vendite.objects.values_list('prodotto__name', 'date__year', 'date__month'). annotate(totale=ExpressionWrapper(Sum(F('income')),output_field=FloatField())) All works perfectly but now I have the need to give the possibility to choose only month and year and not also the day. In other words is it possible to set DateField in this manner without modifying my algo structure? -
Modify model generated by django-activity-stream
I am creating a project which needs an audit in the database about all kind of actions performed by user. For this objective, i m using 'django-activity-stream' which create its model properly. I want to change type of one parameter in the model generated by this library but i m not sure how to do it. PD: This is my first time with Django and have seen the documentation of both but im not really sure. If i explained something wrong or you need more info about it ask me without any problem. -
Fetching user details in React from django-rest-auth gives back 403 (Forbidden) - Using authtoken
In my project, I have Django Rest Framework managing the backend and React on the frontend. I am currently implementing the authentication system, so I have just switched the REST_FRAMEWORK settings for the DEFAULT_PERMISSION_CLASSES from rest_framework.permissions.AllowAny to rest_framework.authtoken (before everything worked just fine). Just to make things clearer, here is my settings.py (from INSTALLED_APPS): INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Custom Apps 'rest_framework', 'assessments', 'corsheaders', 'accounts', 'rest_framework.authtoken', 'rest_auth', 'django.contrib.sites', 'allauth', 'allauth.account', 'rest_auth.registration', 'allauth.socialaccount' # needed for delete user ] 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', ] ROOT_URLCONF = 'api.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'api.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ STATIC_URL = '/static/' REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ # … -
Unexpected keyword argument when working with several objects
I'm trying to work with severals objects to achieve an action. My models.py class LogBook(models.Model): name = models.CharField() class LogMessage(models.Model): logbook = models.ForeignKey(LogBook, on_delete=models.CASCADE) class LogDone(models.Model): logmessage = models.ForeignKey(LogMessage) done_status = models.BooleanField(default=False) My view : def logmessage_done(request, logmessage_id, log_id, token ): log = get_object_or_404(LogBook, pk=log_id) logmessages = LogMessage.objects.filter(logbook=log) logdone = LogDone.objects.get_or_create(logmessage=logmessages) logdone.done_status = True logdone.update() My url : "done/<int:logmessage_id>/<int:log_id>/<str:token>" What I want to achieve : I want to change the status of the logdone object which is link to the logmessage object but I am not sure I have access object correctly. What error I have : logmessage_done() got an unexpected keyword argument 'logmessage_id' -
How to Connect Django running in GCP App Engine to an external Microsoft SQL Server?
I have a Django App running in GCP App Engine, it has his own database in Cloud SQL.I need to connect to an external Microsoft Mysql Server that i have in a private server with static public IP Address for consult some data that i need. How can i do it? How can i know the public address of my django App Engine GCP to give access from my private Microsoft SQL Server? Is it possible? I tried doing some research, but I have only found, the solution to the reverse problem. To connect from external app to Cloud SQL. Thanks. -
Djago - How can I set restrictions on an input based on a db item (better explanation inside)
I want to know which should be the good way of: Having the following model: AmountModel(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) project = models.ForeignKey(Project, on_delete=models.CASCADE) amount = models.PositiveIntegerField(validators=[MinValueValidator(0), ]) And having already the first object which have a user and a project assigned and 100.000 amount, I want to let this same user add more users on the same project and distribute his 100.000 amount between all of them. The user should be able to delete the extra objects, and so the amount of those should be added to it's own object. That's not a problem. So: The SUM of the amounts of all the users must be always 100.000. The new objects should be editable, so the main user can change the amounts in case of error. In this case if he adds more amount to the user, this should be rested from it's own. In case of decreasing the amount, it should be added to it's own object. I'm having three views for that: The one to create the object, the one to edit the object and the one to delete it. For the delete view is easy, I just have to delete and sum the amount of the … -
Django password reset function view
Using class based views kinda hide all the complexity in the django code so i prefer using the function based view then afterwards move to class based views. Is there by anychance you can write a custom password reset view to change user's password either than using django's class based views. I am able to do it with class based views but understanding it, is a problem since all the complexity is hidden. If anyone has a link to an article explaining that in detail i would be glad since google is giving me nothing Muchas gracias in advance -
Don't know why Django queryset prefetch sorting does not work?
In a ModelViewSet, I'm using this queryset with complex prefetching : queryset = ( Device.objects .prefetch_related( Prefetch( 'scopes', queryset=Scope.objects .select_related('variable') .prefetch_related('values', 'values__project') ), Prefetch( 'groups', queryset=Group.objects .order_by('-priority') # not working don't know why.... .prefetch_related( Prefetch( 'scopes', queryset=Scope.objects .select_related('variable') .prefetch_related('values', 'values__project') ) ) ) ) ) when using the data in Device model i'm using the group objects ordered in the same manner: groups = self.groups.order_by('-priority') for group in groups: print(str(group)) This is were it's not working. I'm getting a N+1 problem : Number of SQL requests follow the number of device in DB. ... SELECT "burritos_group"."id", "burritos_group"."name", "burritos_group"."priority", "burritos_group"."group_type_id" FROM "burritos_group" INNER JOIN "burritos_group_devices" ON ("burritos_group"."id" = "burritos_group_devices"."group_id") WHERE "burritos_group_devices"."device_id" = 8402 ORDER BY "burritos_group"."priority" DESC SELECT "burritos_scope"."id", "burritos_scope"."object_id", "burritos_scope"."content_type_id", "burritos_scope"."variable_id", "burritos_variable"."id", "burritos_variable"."name", "burritos_variable"."tag" FROM "burritos_scope" INNER JOIN "burritos_variable" ON ("burritos_scope"."variable_id" = "burritos_variable"."id") WHERE ("burritos_scope"."content_type_id" = 2 AND "burritos_scope"."object_id" IN (24, 1, 10, 19, 25)) SELECT "burritos_value"."id", "burritos_value"."json", "burritos_value"."state", "burritos_value"."project_id", "burritos_value"."scope_id" FROM "burritos_value" WHERE "burritos_value"."scope_id" IN (18167, 18158, 18157) SELECT "burritos_project"."id", "burritos_project"."name", "burritos_project"."finished" FROM "burritos_project" WHERE "burritos_project"."id" IN (NULL) # of Queries: 5318 As you can see ordering by group priority is done device by device : WHERE "burritos_group_devices"."device_id" = 8402 ORDER BY "burritos_group"."priority" DESC if I remove the ordering … -
DataError: numeric field overflow
DETAIL: A field with precision 2, scale 2 must round to an absolute value less than 1. I am trying to deploy a Django app to Heroku. My Django application uses Sqlite3 and it works perfectly on my system. If you click 'like' on product it will update the ratings parameter by 1. Here is the snippet of the Product model class Product(models.Model): image = models.CharField( max_length= 500, blank = True, help_text= 'Image link' ) title = models.CharField( max_length= 200) description = models.TextField(blank = True) price = models.DecimalField(max_digits= 10, decimal_places= 2, blank = True, ) ratings = models.DecimalField(max_digits=10, decimal_places=2, blank= True, default = 0) Before clicking 'like' the ratings on the product is 4 After clicking 'like' the ratings increases to 5 without any error Result This is how I'm updating the ratings: if request.method == 'POST': obj = Product.objects.get(id = i) obj.ratings += Decimal(1) obj.save() However, after deploying to Heroku, when i click 'like' I get this error. DataError at /home/1/ numeric field overflow DETAIL: A field with precision 2, scale 2 must round to an absolute value less than 1. (/home/1/ is the route) I don't get why precision 2, scale 2? I get that heroku might be … -
Django - Accept username in front of id on a form with user as FK
I want to create an object that have the user as FK, and for that I want to make users fill the username on a textfield and validate if that user exist. If I use a selector it shows me each user on the platform, but what I want is to make them write the user manually, but the textfield is just receiving the user id as valid. Now I have this working: View: @login_required def partners_view(request, pk): project = Project.objects.get(pk=pk) if request.method == 'POST': form = CreateProjectPartnerForm(request.POST) if form.is_valid(): # todo work on this to make the movement of tokens from the entrepreneur to partners. form.instance.project = project form.instance.creation_date = timezone.now() form.instance.history_change_reason = 'Project Partner invited' form.save() messages.success(request, 'Partner Successfully created!') return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/')) else: messages.error(request, 'Please correct the error below.') else: form = CreateProjectPartnerForm() return render(request, 'tokenmanagement/project_partners.html', { 'form': form, 'project': project, }) Form: class CreateProjectPartnerForm(forms.ModelForm): class Meta: model = TokenTransaction fields = ('user', 'amount') widgets = { 'user': forms.Textarea(), } def __init__(self, *args, **kwargs): # first call parent's constructor super(CreateProjectPartnerForm, self).__init__(*args, **kwargs) # evade all labels and help text to appear when using "as_crispy_tag" self.helper = FormHelper(self) self.helper.form_show_labels = False Template form: <form id="my_form" action="{% url 'project-partners' … -
Django not looking in correct template folder when changing initially loaded app
in an Django project I have two apps named file-management and docs. As I first created the file management app my base urls.py looks like this: from django.contrib import admin from django.urls import include, path urlpatterns = [ path('', include('file_management.urls')), path('admin/', admin.site.urls), path('file_management/',include('file_management.urls')), path('docs/',include('docs.urls')), ] In the file_management folder I then have an urls.py that defines where to look for templates: from django.urls import include, path from .views import index urlpatterns = [ path('', index, name="file_management"), path('<int:file_id>/', index), ] And in the docs folder the urls.py looks like this: from django.urls import include, path from .views import index urlpatterns = [ path('', index, name="docs"), path('<docs_page>/', index), ] Like this everything works fine and I can use the links {% url 'docs' %} and {% url 'file_management' %} and the admin page can be accessed via /admin. Now if I change the base urls.py so that it points to docs.urls instead of file_management.urls for '' I land on the correct docs page when loading the project. But if I click on a link I get a TemplateDoesNotExist at /file_management/. It seems Django is looking for the template in the wrong folders: django.template.loaders.app_directories.Loader: /home/fiedler/anaconda3/envs/ct_env/lib/python3.7/site-packages/django/contrib/admin/templates/docs/file_management.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/fiedler/anaconda3/envs/ct_env/lib/python3.7/site-packages/django/contrib/auth/templates/docs/file_management.html (Source does … -
Django REST API RemoteUserBackend
I'm fairly new at using Django. I'm building a REST api using Django for an application I built for our company. I've already completed deploying the API using IIS; however, when I enable the windows authentication for single sign on (which is a requirement) the api no longer allows me to make a request and throws me this error HTTP Error 401: Unauthorized. I read the document in the rest_framework for using Remote User Authentication; however, I'm having difficulty understanding the steps I need to take. Here is my current settings.py --> which was mentioned needed to be added REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.RemoteUserAuthentication',]} MIDDLEWARE = [ .... .... 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.RemoteUserMiddleware',] AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.RemoteUserBackend',] Here is one of my requests in views.py @api_view(['GET']) def SuSngLoginDirectoryGet(request): queryset = SngSuLoginDirectory.objects.all() serializer = SuSngLoginDirectorySerializer(queryset, many=True) return Response(serializer.data) I'm stuck and I don't know how to make the authentication after this. I tried using the @authentication_classes and @permission_classes on my views request but to no success. Here is how I test it using IDLE: requests.get('http://lngsydappp023:83/api/example_view/') then throws me this error: <Response [401]> I've been doing lots of research since last night. Please help. -
Validation error on modify slug with date
i'm trying to modify the slug on save to add a date at the end of it if the same slug already exists. Here is the code that i got: import datetime as dt class BlogPage(...): def save(self, **kwargs): now = dt.datetime.now() if self.slug: self.slug = f"{self.slug}-{now.isoformat()}" super().save(self, **kwargs) Once i try to save i get a Validation error: {'slug': ['Enter a valid “slug” consisting of Unicode letters, numbers, underscores, or hyphens.']} Thank you -
How can I deliver a HTML form created by Django or DRF to React?
I'm using React, Django, and DRF. I wanna send a form consisting of HTML that is auto-generated in Django to React in JSON. Below is a simple example. [ { "html": "<tr><th><label for="id_writer">Writer:</label></th><td><input type="text" name="writer" maxlength="20" required id="id_writer"></td></tr>" } ] Django forms are really convenient to me so I wanna make the most of it. So I have a few questions I'd like to ask you about. Is this possible? If possible, do you think this is a proper way? I mean, in terms of the philosophy of each framework and library. -
cant load static files all settings are correct as far as i checked and added load static in templates but still its not getting the static files
cant load static files at all and when I inspect on the template in the network it says 404 not found and in the network, it's not picking the correct path even though everything in settings and template seems to be correct! Please help tried whatever I could but the issue isn't resolved tried few solutions given in the past regarding such issue but didn't work. **settings.py** STATIC_URL = '/static/' # the path in url STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static_files"), ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') **base.html** <!DOCTYPE html> <html> {% load static %} <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1, maximum-scale=1, user-scalable=0"> <script src="{% static 'pludo/js/jquery.min.js' %}"></script> <link rel="stylesheet" href="{% static 'pludo/css/bootstrap.min.css' "> <script src="{% static 'pludo/js/bootstrap.min.js' %}"> </script> <link rel="stylesheet" href="{% static 'pludo/css/main.css' %}"> <script src="{% static 'pludo/js/main.js' %}"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> {% block content %} {% endblock %} </body> </html> **index.html** {% extends 'base.html' %} {% block content %} <!-- {% load static %} --> <div id="header"> <div id="companyheader" class="headerdiv"> <div class="logoDiv"> <img class="logoImg" onclick="goToHome();" src="{% static 'pludo/images/drawable-xhdpi/PluudoLogo.png' %}"> </div> <div class="search-back-button" style="display:none;"> <img onclick="backPage();" src="{% static 'pludo/images/drawable-xhdpi/BACKBUTTON.png' %}"> </div> <div class="searchDiv"> <img class="searchIcon" src="images/drawable-xhdpi/VIEWTEXT.png"> </div> <div> <label id="updateText" style="position: absolute; … -
I am able to fetch data of only 4 fields in my model but why I am not able to fetch data of fields (Business_name,Mobile) in django
Can you please help me Forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class Registrationform(UserCreationForm): first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30) mobile=forms.CharField(max_length=12,min_length=10) Business_name=forms.CharField(max_length=64) email=forms.EmailField(required=True) password2=None class Meta: model = User fields = ['username','first_name','last_name','mobile','email','password1','Business_name'] def save(self,commit=True): user=super(Registrationform,self).save(commit=False) user.first_name=self.cleaned_data['first_name'] user.last_name=self.cleaned_data['last_name'] user.mobile=self.cleaned_data['mobile'] user.email=self.cleaned_data['email'] user.Business_name=self.cleaned_data['Business_name'] if commit: user.save() return user views.py @login_required def home(request): return render(request,'users/home.html',{'user':request.user}) home.html {% block content %} <p> {{ user.Business_name }} {{ user.first_name}} {{ user.last_name}} {{ user.email }} {{user.username}} {{ user.mobile }} </p> {% end block %} I don't understand why i am not able to fetch data even though doing the right thing.Please help me as i am newbie in Django.............................................................................. -
Prevent get_object frim hitting DB multiple times in DRF
Question is about getting get_object method in DRF. Thing is when I need to get object in view or in serializer via serializer contex, each time I call get_object it sends new set of queries to DB and this is not acceptable as this behavior puts overhead on DB. Seems like DRF does not cache get_object result at all or does not save it in instance as well, at least I haven’t found any tracks of this in source code. In order no not send same queries to DB multiple times I do following: def get_object(self): obj = super().get_object() setattr(self, 'obj', obj) return obj And then use self.obj in my code lately when I need it. From my point ow view doing so in each and every generic DRF view class where I need to use get_object more the onсe – it’s kind of something is really wrong. Either my logic or DRF source code. Realistically first assumption has more odds to be true. Question is -what is wrong in my approach in saving get_object result in attribute and if its any more generic or pythonic way to do so. Thanks. -
Django setting a transaction for class-based redirect view
I have the following class-based view with simple likes-toggling mechanics: class PostLikeToggle(RedirectView): def get_redirect_url(self, *args, **kwargs): post_id = kwargs.get('pk') post = get_object_or_404(Post, id=post_id) user = self.request.user if post.likes.filter(id=user.id).exists(): post.likes.remove(user) else: post.likes.add(user) url_redirect = post.get_absolute_url(post_id) return url_redirect I think of making this method as an atomic transaction, but not sure about the proper way to do that. Am I on the right track? class PostLikeToggle(RedirectView): @transaction.atomic def get_redirect_url(self, *args, **kwargs): -
How to save multiple object in DRF
I am having one issue ..... I want to save multiple object in a single post request .... Here is my view class MovieTicketCreateView (CreateAPIView): queryset = models.Ticket.objects.order_by('id').all() serializer_class = TicketSerializer def perform_create(self, serializer): details = self.request.data.get('details') movie_id = self.kwargs.get('movie_id') query = get_object_or_404(Movie, object_id=movie_id) for each in details: if each['seat']: seats = Seat.objects.get(id = each['seat']) serializer.save(movie=query, question= seats ,start_time = each['start_time]) In this view if I am creating ticket for one person its saving successfully.... But if I am creating ticket for more than one person only last details is saving ....How to save multiple object in this case -
unsupported operand type(s) for +: 'method' and 'method' [closed]
I'm trying to get the sum of my methods then display them on my templates..here is what I have tried and the error I got. Models.py class Organization(models.Model): # Section1 - ORGANIZATIONAL BACKGROUND exist = models.BooleanField(default="False", help_text='Does organization exist physically?') accessibility = models.BooleanField(default="False", help_text='Indicate if State, Province, District or County of operation is a hard to reach area (desert, flooded, mountainous region, etc.)') @classmethod def exist_score(self): if Organization.exist == True: exist_score=0.1 return exist_score #The higher score else: exist_score=0.1 return exist_score #The lower score @classmethod def accessibility_score(self): if Organization.accessibility == True: accessibility_score=5 return accessibility_score else: accessibility_score=0 return accessibility_score @classmethod def previous_implementations(self): previous_implementations = Organization.exist_score + Organization.accessibility_score return previous_implementations Error: unsupported operand type(s) for +: 'method' and 'method' -
Django matching query does not exist but I get prints
models.py class SessaoAtividade(models.Model): # Activity_Session id = models.AutoField(db_column='ID', primary_key=True) atividadeid = models.ForeignKey(Atividade, models.DO_NOTHING, db_column='AtividadeID') class Atividade(models.Model): id = models.AutoField(db_column='ID', primary_key=True) code in a view.py for a in atividades: #print(a.id) sessao_atividade = SessaoAtividade.objects.get(atividadeid=a.id) So, basically I am using this queryset to get SessaoAtividade objects. It returns me "SessaoAtividade matching query does not exist." But if I print with "print(a.id)" I get prints in the console Why is this happening ? -
Django Javascript Ajax - Submitting form does nothing
I have a form with which I would like to send data to my backend view. <form class="modal-content animate" method="POST" id="make_admin"> {% csrf_token %} <!-- List users to make admin --> <div class="container"> <label for="uname"><b>User: </b></label> <select id="select_user"> {% for employee in users %} {% if not employee.is_admin %} <option value="{{ employee.id }}">{{ employee.first_name }} {{ employee.last_name }}</option> {% endif %} {% endfor %} </select> <button type="submit">Make Admin</button> </div> </form> Javascript: $(document).on('submit', '#make_admin' ,function(e){ e.preventDefault(); $.ajax({ type:'POST', url:'{% url 'cerberus_mvp:make_admin' %}', data:{ id: $('#select_user').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), action: 'post' }, success:function(response){ $(".update").html(response) }, error : function(xhr,errmsg,err) { console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console } }); }); My problem is that when the submit button is clicked nothing happens, the page just seems to refresh. It seems like the javascript code is never reached. Any ideas why? Thanks in advance. -
user.is_authenticated DetailView is coming as True
I have a Users model and exposing the user details via DetailView. In the template navbar section, currently use is_authenticated to render url as below. if {% user.is_authenticated %} my_account {% else %} login_url Now I am exposing the User details via DetailView like // views.py class ProfileView(DetailView): model = User template_name = 'account/user_profile.html' // account/user_profile.html shows the links(```my_account``` or ```login_url```) and user details viz. username,email & location(via separate ProfileModel) // models.py import django.contrib.auth.models import User def Profile(models.Model) user = models.OnetoOneField(User) location = models.CharField(max_length=200) but this results in showing my_account url on user_profile.html page which I understand is due to the auth context user= self.request.user To change this behaviour I tried changing the DetailView as follows. class ProfileView(DetailView): model = User template_name = 'account/user_profile.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) if self.request.user.is_authenticated: print("context:",context['user'].is_authenticated) return context else: context['user'] = None return context Is this a recommended way or there are other recommendations,