Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Initial value in queryset field is missed in updateview
I was using this guide to Implement Dependent/Chained Dropdown List with Django. When I try to create the UpdateView, it get the value of Province and City of the instance, but not the Country value. I want to show the initial value as a selected value, just like the others fields. Here's how it looks: forms.py class ProfileForm(ModelForm): country = choices.CountryModelChoiceField( queryset=Country.objects.all()) province = choices.ProvinceModelChoiceField( queryset=Province.objects.all()) city = choices.CityModelChoiceField( queryset=City.objects.all()) class Meta: model = Profile fields = PROFILES_FIELDS def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if 'country' in self.data: try: country_id = Country.objects.get( id=int(self.data.get('country'))).country_id self.fields['province'].queryset = Province.objects.filter( country_id=country_id).order_by('province_name') except (ValueError, TypeError): pass if 'province' in self.data: try: province_id = Province.objects.get( id=int(self.data.get('province'))) self.fields['city'].queryset = City.objects.filter( province_id=province_id).order_by('city_name') except (ValueError, TypeError): pass views.py class edit_profile_page(PanelContextMixin, UpdateView): model = Profile form_class = ProfileForm template_name = 'profiles/profile_edit_form.html' def get_object(self, queryset=None): return self.request.user.profile choices.py class CountryModelChoiceField(forms.ModelChoiceField): def label_from_instance(self, obj): return obj.country_name class ProvinceModelChoiceField(forms.ModelChoiceField): def label_from_instance(self, obj): return obj.province_name class CityModelChoiceField(forms.ModelChoiceField): def label_from_instance(self, obj): return obj.city_name -
Using Gmail API with Python, searching messages return Requested entity was not found
I am working in gmail api using python and django. In this case I need to work in the backend offline authentication. After create the url to auth the backend and create the credentials I need to get specific message with the id message. This the code: state = request.GET['state'] flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( client_secrets_file='credentials.json', scopes='https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/gmail.metadata https://www.googleapis.com/auth/userinfo.email openid https://www.googleapis.com/auth/gmail.readonly https://www.googleapis.com/auth/gmail.compose',state=state) flow.redirect_uri = 'https://domian.com/auth/oauth' authorization_response = request.build_absolute_uri() flow.fetch_token(authorization_response=authorization_response, client_secret='<client_secret>', code=request.GET['code']) request.session['credentials'] = { 'token': credentials.token, 'refresh_token': credentials.refresh_token, 'token_uri': credentials.token_uri, 'client_id': credentials.client_id, 'client_secret': credentials.client_secret, 'scopes': credentials.scopes } service = build('gmail', 'v1', credentials=credentials) results = service.users().messages().get(userId='me', id='<id>', format='minimal').execute() Django return: HttpError at /auth/oauth <HttpError 404 when requesting https://gmail.googleapis.com/gmail/v1/users/me/messages/1273369159314488?format=minimal&alt=json returned "Requested entity was not found."> But the id message exist and is correct. Even I use others endpoints like labels and works good the query. Somene have any suggestions? Regards -
iterator should return strings, not bytes (did you open the file in text mode? ) Django
I have been facing an issue with file upload , so i will be uploading a file on submit , i want to collect the file read the data in it and add it to the database , I am constantly getting this error Traceback (most recent call last): File "/Users/vinaykashyap/opt/anaconda3/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/vinaykashyap/opt/anaconda3/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/vinaykashyap/opt/anaconda3/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/vinaykashyap/opt/anaconda3/lib/python3.7/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/Users/vinaykashyap/Desktop/Deploy-Testing2/annotating/views.py", line 244, in UploadAdmin next(reader) # skips header File "/Users/vinaykashyap/opt/anaconda3/lib/python3.7/csv.py", line 111, in next self.fieldnames File "/Users/vinaykashyap/opt/anaconda3/lib/python3.7/csv.py", line 98, in fieldnames self._fieldnames = next(self.reader) _csv.Error: iterator should return strings, not bytes (did you open the file in text mode?) It will be helpful anyone of you can suggest , how it needs to done . Thanks in Advance Views.py def UploadAdmin(request): if request.method == 'POST': if request.POST.get("action_name") == 'NEXT': # form = request.FILES['my_uploaded_file'].read() reader = csv.DictReader(request.FILES['my_uploaded_file'].file) next(reader) # skips header for row in reader: _, created = NewsItem.objects.get_or_create( headline=row[0], content=row[1], collection=row[2], url=row[3], chunk_id=row[4] ) return render(request,'annotating/uploadDataAdmin.html') -
Making a form field compulsory only for specific users
Is it possible to make a form field, in a template, compulsory, or non compulsory, for specific user? I have a field which I'd like to be compulsory for everyone but the administrator. My understanding is that it is not possible, since the null=False, blank=False in the model.py is valid for all the instances of the field. Am I wrong? -
Django How to annotate elastic search dsl query like we do in normal queries?
Django Query ObjectModel.objects.filter(param=param).annotate(param1=F('param')) ElasticSearch Dsl ObjectDocument.search().query(param=param).annotate(param1=F('param')) How to achieve this as well as apply database functions like concat, sum, max Any sort of help with an example would be appreciated -
Django: pre schedule publishing of homepage features
pretty new to python/django so please forgive my ignorance. I have a 'feature' model that inherits publish and unpublish fields. The feature could be a book, article, whatever and whatever object is 'published' for today shows as the main image/banner on the homepage. I'd like to figure out a way to pre schedule a rotation of features. so: Days 1-5 - feature A Days 6-10 - feature B Days 11-15 - feature A Days 16-20 - feature B Right now i can schedule the first two rotations but on day 11 I need to go back to my admin and edit the publish/unpublish first for the last two rotations. I'm thinking I could maybe move my publish/unpublish fields to an inline model so I can capture 1 or many sets, or maybe rather than capture a publish and unpublish date, I can capture a range of dates instead? like 9/1/2020-9/5/2020, 9/11/2020-9/10/2020 class PublishableObject(models.Model): publish = RadioBooleanField( default=True, help_text=_('Show this resource on the website?')) publish_on = models.DateTimeField( blank=True, null=True, default=timezone.now, help_text=_('The date to publish this resource.')) unpublish_on = models.DateTimeField( blank=True, null=True, help_text=_('The date to unpublish this resource.')) objects = models.Manager() #So default manager remains live = PublishableObjectManager() class PublishableObjectManager(MainLanguageManager): def filter_live(self, … -
Django: FormView, get_context_data invalidate form validation and discards inputs
I'd like my FormView to conduct validation (showing which fields contains an error) as well re-use already made input if form is invalid. At the moment, if form is invalid: Error is not shown on form / form field (red rectangle around, with error text below) Form is reloaded and made inputs are discarded (form re-loads as new). It seems that get_context_data invalidate default behaviour of class based FormView I have tried several ways but cannot figure it out. class ProductFormView(FormView): template_name = 'product/product_create.html' model = Product success_message = f'Product created successfully' success_url = '/product/list' def get_context_data(self, **kwargs): context = super(ProductFormView, self).get_context_data(**kwargs) context['form_1'] = CommonFieldsForm(instance=self.model()) context['form_2'] = PriceForm(instance=self.model()) return context def form_invalid(self, form): response = super().form_invalid(form) return response def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) -
Loading Multiple Plotly offline graphs into HTML DOM
Tools of note: Using Django 3.0, plotly offline, jQuery. I am not sure if my workflow needs changing or if there is a different DOM manipulation technique, but I am seeing slow load times while adding plots into a dashboard. The generated string elements from plots are quite large and could be a factor. (MB size if I interpret the console correctly. I am new to web design.) Basically what I think happens is the jQuery runs, and then once it returns the webpage 'freezes' while it tries to add in the DOM elements. Okay so here is the current workflow: Load a html page with bare essentials using a Django view. Nothing fancy and this works okay. Call jQuery to run another view. This view takes a while to run a calculation and do some data manipulations which is why I tried to use jQuery. The view generates between 5-10 plotly graph_objects. Insert the images into a carousel for viewing. Step 3 is really the step I think needs fixing if possible. If not, is there an alternative solution? Here is my jQuery which I hope can be improved - It is found within 'script' tags inside my .html … -
Python + Django + Pandas - pandas script rewrite the uploaded file
I am writing a web application which could be able to convert the uploaded (by user) .xlsx file using the PANDAS script. I would like the application to work like this: 1: "Excle_file" view - here the user uploads the .xlsx file def excle_upload(request): if request.method =='POST': # This is a place # where pandas logic should # be implemented? #how to insert file to below form as: # requesr.FILES ??? form = ExcleForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('excle_list') else: form = ExcleForm() 2.The pandas script converts the .xlsx file to the required form (question: logic + pandas script must also be in the "excle_file" view ???) The script starts like this: df = pd.read_excel(path) # request.FILES df.loc[:,"ODOMETER_FW"] = df.loc[:,"ODOMETER_FW"].fillna(0).astype('int') df.dropna(inplace = True) df.sort_values(by= ['VEHICLE_ID_FW','TRANSACTION_DATE_FW','TRANSACTION_TIME_FW'], ascending=[True,False,False],inplace=True) df['ODOMETER_FW'] = df['ODOMETER_FW'].apply(lambda x: 0 if x <1000 else x) df.set_index(['VEHICLE_ID_FW'], inplace=True) 3."Excle_list" view -should contain already processed (converted by pandas) files and allows user to download them def excle_list(request): files = Excel.objects.all() return render(request, 'odo_correction/excle_list.html', {'files':files}) Currently I have written functionalities from points 1 and 3 without pandas logic. The application works that way: I can upload and then download exactly the same file. (target is point 3, however – download converted … -
Aggregate data from one model to create field for another model
I'm working on a website for my fantasy football league. I have two models Team class Team(models.Model): team_logo = models.FileField(upload_to='team_logos', blank=True, null=True) team_name = models.CharField(max_length=255, blank=True, null=True) team_uniform = models.FileField(upload_to='team_uniforms', blank=True, null=True) team_uniform_alt = models.FileField(upload_to='team_uniforms', blank=True, null=True) team_abv = models.CharField(max_length=4, blank=True, null=True) owner_first_name = models.CharField(max_length=255, blank=True, null=True) owner_last_name = models.CharField(max_length=255, blank=True, null=True) Game class Game(models.Model): season = models.IntegerField(blank=True, null=True) week = models.IntegerField(blank=True, null=True) home_team = models.ForeignKey(Team, related_name="home_team", on_delete=models.CASCADE, blank=True, null=True) home_score = models.DecimalField(max_digits=7, decimal_places=2, blank=True, null=True) away_team = models.ForeignKey(Team, related_name="away_team", on_delete=models.CASCADE, blank=True, null=True) away_score = models.DecimalField(max_digits=7, decimal_places=2, blank=True, null=True) def result(self): if self.home_score < self.away_score: return self.away_team elif self.home_score > self.away_score: return self.home_team else: return "-" result = property(result) def home_margin(self): return self.home_score - self.away_score home_margin = property(home_margin) def away_margin(self): return self.away_score - self.home_score away_margin = property(away_margin) I am wanting to use the data in the game models to create season and career stats for every team. How would I achieve this? Would I need to create a "Season" and "Career" model? if so how do I aggregate the data and fill the field in the new models? I have currently have all of the game data being displayed on a team detailview. Would I need to make the stats … -
Django cookies with CORS
I try to send cross-domain POST request from "test.net" to my host "example.com" with browser. In response I set test cookie. response = Response({'ok': True}, status=status.HTTP_200_OK) response.set_cookie('test1', 'test-cookie', domain='example.com') return response However cookies are not set in browser. If I send request with client (Postman, Insomnia) - cookies are returned and set like this test1=test-cookie; Domain=example.com; Path=/ In browser I get no warnings, cookies are gone. Maybe any browser have some logs for this case? I tried this settings on django server: SESSION_COOKIE_SAMESITE = None CORS_ALLOW_CREDENTIALS = True SESSION_COOKIE_DOMAIN = 'example.com' -
Having a problem with the follower system, I am following myself in Django
Hey guys I am trying to send a follow request through the django notifications and the person at the other end will be either accepting or rejecting the request. But I have a problem that when the person at the other end accepts the request, this error is showing Something went wrong! and he is following himself. This is the code I have now. def send_follow_request(request, id): current_user = request.user user = Account.objects.get(id=id) notify.send(request.user, recipient=user, verb='has sent you a follow request', target=user) return redirect('posts:userprofile', user.username) def accept_follow_request(request, id): current_user = request.user user = Account.objects.get(id=id) contact, created = Contact.objects.get_or_create(user_from=request.user, user_to=user, follow_status='AC') if user != request.user: create_action(request.user, 'started following', user) notify.send(request.user, recipient=user, verb='started following you') return redirect('all_user_notifications') return HttpResponse('Something went wrong!') This is the notification view class AllNotificationsList(LoginRequiredMixin, NotificationViewList): def get_queryset(self, *args, **kwargs): if get_config()['SOFT_DELETE']: qset = self.request.user.notifications.active() else: qset = self.request.user.notifications.all() return qset Can anyone tell me where the problem is? Thanks! -
¿Why my CORS config in django is not working?
I have my REST API settings in my production.py file. This REST API is uploaded to Heroku and uses django-cors-headers with the following configuration: # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Third-Party apps 'rest_framework', 'rest_framework.authtoken', 'corsheaders', 'gunicorn', # Local apps 'core', 'users', 'checkers', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = ( 'myapi.herokuapp.com' ) The idea when putting myapi.herokuapp.com in CORS_ORIGIN_WHITELIST is to see if making the request from localhost is rejected (it would be the right thing to do). But this is accepted which gives me to understand that CORS is not working well. -
Implement a tenant like structure for shops
I need a little pointing in the right direction please. I have a shop who owns (multiple) locations and those locations have (multiple) products. models.py: class Shop(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField('name', max_length=120) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) shop = models.ForeignKey(Shop, on_delete=models.CASCADE) class Location(models.Model): name = models.CharField('name', max_length=120) shop = models.ForeignKey(Shop, on_delete=models.CASCADE) class Product(models.Model): price = models.DecimalField("price", decimal_places=2, max_digits=8) location = models.ForeignKey(Location, on_delete=models.CASCADE) name = models.CharField('name', max_length=120) So there is for example a user "me" and this user belongs to the Shop "Wallmart". "Wallmart" has locations like "NY Shop" and "London Shop". It is ok for me to create the locations in the admin panel and assign them to tenants (working). How would I implement a select box to define the location variable so I can catch it when saving a new product? -
Django rest framework passing ValidationError messages to response
i'm currently trying to pass the ValidationError message from Django to the body of my response. Is there any way to do that? Here is a create method that i'll customize in my viewset. def create(self, request, *args, **kwargs): try: serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) except Exception as error: return Response(data={"Message": str(error)}, status=status.HTTP_400_BAD_REQUEST) And here is the Message that is being returned when there is a ValidationError { "Message": "{'username': [ErrorDetail(string='A user with this username already exists.', code='unique')], 'email': [ErrorDetail(string='Insert a valid email.', code='invalid')]}" } But the result that im trying to achieve is this: { "Message": "A user with this username already exists. Insert a valid email." } Is there any way to extract the strings from the validation error message? -
Django timezone.now() giving wrong time
thanks for your time. i've got a model Profile thats linked on User. And a Hours models thats linked on Profile. By every time a user login a Hours object should be created with the loging_in field automatically set to timezone.now(). I've tried timezone.now(), datetime.now(), timezone.localtime(timezone.now()). Tried all of them on default of loging_in field and on login_view. every try creates the object as i want. But every time gives me the wrong time about 20 minutes earlier or later. So i'd like to know what am i doing wrong and whats the best way to set this (models or views). settings.py: LANGUAGE_CODE = 'pt-br' TIME_ZONE = 'America/Sao_Paulo' USE_I18N = True USE_L10N = False USE_TZ = True DATETIME_FORMAT = "d/m/Y H:s" models.py: class Hours(models.Model): profile = models.ForeignKey(Profile, on_delete=models.SET_NULL, related_name='hours', null=True) loging_in = models.DateTimeField(default=timezone.localtime(timezone.now())) loging_out = models.DateTimeField(null=True) done = models.BooleanField(default=False) delta = models.DurationField(default=datetime.timedelta(hours=0)) objects = HoursManager() views.py: def login_view(request): if not request.user.is_anonymous: logout_view(request) else: # raise ValidationError('DESLOGUE PRIMEIRO') next = request.GET.get('next') form = LoginForm(request.POST or None) # se estiver escrito certo# if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') # autenticando o usuario# user = authenticate(username=username, password=password) # se estiver tudo certo (autendicado) chamar a função login# login(request, user) p1, status … -
how to update user data in django
I am new to Django I want to add more fields to registration form like (first name, last name, and gender). so I add those fields but when I create update form only username and email appear in fields . here all code ******* views.py ****** from django.shortcuts import render,redirect from django.contrib.auth.forms import UserCreationForm from . forms import RegisterForm , UserUpdateForm from django.contrib.auth.decorators import login_required def register(request): if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): form.save() return redirect('home-page') else: form = RegisterForm() return render(request,'Users/register.html',{'form':form}) @login_required def Profile(request): if request.method == 'POST': u_form=UserUpdateForm(request.POST,instance=request.user) if u_form.is_valid: u_form.save() return redirect('Profile-page') else: u_form=UserUpdateForm(instance=request.user) context={'u_form':u_form} return render(request,'Users/profile.html',context) models.py from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) def __str__(self): return f'{self.user.username} Profile' signals.py* from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save,sender=User) def create_profile(sender,instance,created,**kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save,sender=User) def save_profile(sender,instance,**kwargs): instance.profile.save() ***** forms.py ****** from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class RegisterForm(UserCreationForm): """docstring for ClassName""" email = forms.EmailField() firstName = forms.CharField(max_length=30) LastName = forms.CharField(max_length=30) CHOICES=[('Male','Male'), ('Female','Female')] gender = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect) class Meta: model = User fields = ['username','firstName','LastName','gender','email','password1','password2'] class UserUpdateForm(forms.ModelForm): """docstring for UserUpdateForm""" email = forms.EmailField() … -
Self id in ExpressionWrapper (annotate)
I want to get aggregate of only those values that are created_by a specific user but the expression I wrote gets all of them for me. The issue is fairly simple, don't get too bothered by the code it's only there for reference. I'm Working on following query_set. query_set = ClanMember.objects.select_related('user').prefetch_related( 'user__interviews', 'user__interviews__interview', 'user__interviews__interview__user_task', 'user__interviews__interview__user_task__application__job' 'user__interviews__interview__user_task__job_application_notes' ).filter( role=HiringMemberChoices.Interviewer, is_active=True, user__interviews__interview__user_task__is_active=True, user__interviews__is_active=True, ).values( 'user__id', 'user__email').annotate( interviews=all_interviews_expression, recommendations=total_recommended_expression, accepted_candidates=hired_candidates_expression ).order_by('-interviews') Here lets focus on total_recommended_expression which is collected using the following expression total_recommended_expression = ExpressionWrapper( Count('user__interviews__interview__user_task__job_application_notes__id', distinct=True, filter=Q( user__interviews__interview__user_task__job_application_notes__overall_rating=NoteOverallRatingChoices.Recommended) & Q(user__interviews__interview__user_task__job_application_notes__is_active=True)), output_field=IntegerField() ) Now here is the problem, in job_application_notes there could be multiple entries by different users which is distinguished job_application_notes__created_by_id. Right now it's returning all the values in application_notes against a particular user_task_id, What I want is aggregate for all users specifically (for a user get only those entries whose created_by_id matches). Following is the SQL equivalent that works select * from workflow_jobapplicationnotes where is_active=True and overall_rating='Recommended' and created_by_id=91 .... The thing that I was to add to my Expression wrapper filter is created_by_id={user_id} where user_id will be variable coming from the query but I can't seem to figure out a way to do that. Any help or sense of … -
AttributeError: has no attribute 'STATIC'
So have been trying to start my server on python (Am new to python , django)and below is my code to run my server which can be seen herehttps://shrib.com/#Meerkat9GKd1xx and when i run the code i get the attribute error below: AttributeError: module 'student_management_system.settings' has no attribute 'STATIC' ``` How can i fix this issue -
DRF how to change standart error “No active account found with the given credentials?
Is it possible to change standart error message “No active account found with the given credentials? and if yes so how? Would be nice change the error message (e.g. “Entered email address or password incorrect. Please, try again”. -
Retrieve GraphQL Introspection Schema as http response
I can generate the Django Graphene introspection schema by using the Django management command as ./manage.py graphql_schema --schema tutorial.quickstart.schema --out schema.json How can I return the JSON schema as HTTP Response from a view, so that the client is able to view/fetch the same any time? -
Conditionally save data to different serializer upon certain condition
I am looking to save data to two serializers which are not not nested upon certain conditions. The condition is if data coming to serializer's endpoint has a certain field data, then the data should be saved to the second serializer while at the same time saving to the current serializer. Here is the serializer in question class BookingsCreateSerializer(ModelSerializer): items = BookingItemSerializer(many=True) class Meta: model = Booking fields = ( 'guest_name', 'company_name', 'mobile_Number', 'email', 'special_requests', ) Now if the data that is comming to this serializer contains a password field. Data should also be saved the user profile serializer. How can i go about this? Thank you. Here is the user serializer class UserProfileSerializer(serializers.ModelSerializer): """Serializes user profile object""" class Meta: model = models.UserProfile fields = ['name', 'email', 'password', 'parent', 'from_api', 'is_active', ] //more code here def create(self, validated_data): """Create and return a new user with encrypted password via API""" user = models.UserProfile.objects.create_user( email=validated_data['email'], name=validated_data['name'], from_api=validated_data['from_api'], password=validated_data['password'], is_active=validated_data['is_active'], ) user.set_password(validated_data['password']) user.save() return user -
React and Django routing problem in media file
When I am using re_path('.*',index,name='index') unable to route to my media locations and instead of re_path when I am using path('/',index,name='index') then my react app routing is not working. So what should I do? from django.contrib import admin from django.urls import path , include,re_path from .views import index from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('api/bookdetails/', include('backend.api.urls', 'api')), re_path('.*', index , name='index') ] urlpatterns += static(settings.MEDIA_URL,document_root= settings.MEDIA_ROOT) -
Render Menu with one active item
I am using Django and in my admin i have some items. When i use every item gets Highlighted. But i want only one item to be highlighted when i click that item. This is in my base.html in templates. <aside class="main-sidebar left fadeInleft qaod-sidebar"> <div class="slimScrollDiv"> <section class="sidebar"> <ul class="left-nav"> {% if request.user.is_superuser %} <li><a href="#"><i class="nav-icon fa fa-tachometer-alt"></i><span>Dashboard</span></a></li> <li><a href="#"><i class="nav-icon fa fa-users"></i><span>Groups</span></a></li> <li><a href="#"><i class="nav-icon fa fa-user"></i><span>Users</span></a></li> {% else %} <li><a href="/admin/"><i class="nav-icon fa fa-tachometer-alt"></i><span>Dashboard</span></a></li> <li><a href="/admin/test_suite_optimizer/duplicatetestcase/"><i class="nav-icon fa fa-copy"></i><span>Duplicate Test Case</span></a></li> <li><a href="/admin/test_suite_optimizer/project/"><i class="nav-icon fa fa-project-diagram"></i><span>Projects</span></a></li> <li><a href="/admin/test_suite_optimizer/duplicatetestcase/upload_csv/"><i class="nav-icon fa fa-file-csv"></i><span>Process CSV</span></a></li> {% endif %} </ul> </section> </div> </aside> -
django.db.utils.OperationalError: FATAL: no pg_hba.conf entry for host "::1", user "XXXXX", database "XXXX", SSL off
I am new to this after successfully created the Django app and Postgres install, I try to run migration using python manage.py runserver. But I am getting this error django.db.utils.OperationalError: FATAL: no pg_hba.conf entry for host "::1", user "XXXXX", database "XXXXX", SSL off. I am running this on namecheap cPanel terminal. Anyone with a hint?