Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting KeyError at /home in mostused['opentime'] in Django
I am trying to display the most used website using their active time and open time. But I am getting this KeyError in the most used object for the opentime key. When I print it, opentime key and its values are present. Here is my views.py code from typing import Set from django.http import HttpResponse from django.shortcuts import render from tabtracker.models import trackdetails from datetime import datetime def gettime(sec): sec=sec%(24*3600) hour=sec//3600 sec%= 3600 minutes=sec//60 sec%=60 return hour,minutes,sec def index(request): if request.user.is_authenticated and trackdetails.objects.filter(email=request.user.email).exists(): tabdetails=trackdetails.objects.get(email=request.user.email) opentabs=eval(tabdetails.opentabs) closedtabs=eval(tabdetails.closetabs) activetime=eval(tabdetails.activetime) todayminutes=0 todayhour=0 todaysec=0 yesterdayhour=0 yesterdayminutes=0 yesterdaysec=0 thisweekhour=0 thisweekminutes=0 lastweekhour=0 lastweekminutes=0 opent=[] yesterday=[] for i in opentabs: s = i['opentime'] f = "%Y-%m-%dT%H:%M:%S.%fZ" # diff=s-datetime.now() # yesterday.append(diff) out = datetime.strptime(s, f) ds={"opentime":out,"id":i['id'],"url":i['url'],"fullurl":i['fullurl']} opent.append(ds) senddata={} todaytime=0 yesterdaytime=0 thisweektime=0 lastweektime=0 for i in opent: if((datetime.now()-i['opentime']).days>1 and (datetime.now()-i['opentime']).days<2): for j in activetime: if(i['id'] in j.values()): print("yesterday found") yesterdaytime+=j['seconds']+j['minutes']*60+j['hours']*60*60 if((datetime.now()-i['opentime']).days<1): for j in activetime: if(j['id'] in i.values()): todaytime+=j['seconds']+j['minutes']*60+j['hours']*60*60 # print(todaytime) if((datetime.now()-i['opentime']).days<=7): for j in activetime: if(j['id'] in i.values()): thisweektime+=j['seconds']+j['minutes']*60+j['hours']*60*60 print(i['url'],i['opentime']) if((datetime.now()-i['opentime']).days>7 and (datetime.now()-i['opentime']).days<14): for j in activetime: if(i['id']==j['id']): lastweektime+=j['seconds']+j['minutes']*60+j['hours']*60*60 todayhour,todayminutes,todaysec=gettime(todaytime) yesterdayhour,yesterdayminutes,yesterdaysec=gettime(yesterdaytime) thisweekhour,thisweekminutes,thisweeksec=gettime(thisweektime) lastweekhour,lastweekminutes,lastweeksec=gettime(lastweektime) mostused=sorted(activetime, key=lambda d: d['minutes']) mostused=mostused[1:] mostused.reverse() for i in range(len(opent)): for j in range(len(mostused)): if(mostused[j]['id']==opent[i]['id']): mostused[j]['url']=opent[i]['url'] mostused[j]['opentime']=opent[i]['opentime'] mostused[j]['fullurl']=opent[i]['fullurl'] finalmostusedtoday=[] finalmostusedthisweek=[] for i in mostused: print(i) … -
How to query different field using the pk_url_kwargs field in TemplateView
I have two models using model 1 instance i am creating model 2 instance i want to query i have class(TemplateView) for creating model_2 instance which has pk_url_kwargs = model_1_pk, In my Model 1 i have a field called type, i need to filter that type using pk_url_kwargs how can my query be. class MyCreateView(TemplateView): pk_url_kwargs = 'model_1_pk' def get_context_data(): type = model1.objects.filter(type(pk_url_kwargs)) The view is for creating model_2 instance i need to filter field type using pk_url_kwargs which is id of object in model1 -
How can I retrieve the return value of a method of a class within the same class?
I was wondering if I could get any insight on this. So far, I have this class: class MaterialTaggingListView(ServerSideDatatableView): def get_queryset(self): vLatestUpdateDate = ScTaggingLargeTableIp.objects.values('update_date').order_by('-update_date')[:1] request = self.request if 'selectedcountries' not in request.session: vSelectedCountries = ['CN'] else: vSelectedCountries = request.session['selectedcountries'] vSelectedPlants =request.session['selectedplants'] vSelectedValClass = request.session['selectedvalclass'] vSelectedCoCode = request.session['selectedcocode'] columns = request.session['selectedtags'] return ScTaggingLargeTableIp.objects.filter(update_date = vLatestUpdateDate,plant_country__in=(vSelectedCountries), plant__in=(vSelectedPlants), valclass__in=(vSelectedValClass), company_code__in=(vSelectedCoCode)) def set_columns(self): request = self.request columns = request.session['selectedtags'] return columns columns = set_columns() With this code above, I got the error: missing 1 required positional argument: 'self' Can anyone tell me if what I'm trying to do is possible and how I could resolve the error. -
How to change plotly bar size in python
I am trying to plot a bar chart using python and plotly, but the size of the bar is high. I want to reduce the size of the bar. Can anyone help me? and I am sharing my code. data_plots = go.Bar(x=df1['MeterReading_DateTime'], y= df1['ACT_IMP_TOT'],marker = {'color' : '#060805'},width = 1) layout = {'title': '','xaxis': {'title': 'Date and time'},'yaxis': {'title': 'Total Import(KWH)'},'plot_bgcolor':'#8099b3' } fig = {'data': data_plots, 'layout': layout} plot_div = offline.plot(fig, output_type='div') return plot_div -
intergrate Chart.js with Django ( data not showing )
im new to django and chart js, and trying to develop some project but I was having some trouble when trying to visualize my data from myAPI into chart JS and it shows nothing, here is my code : var endpoint = '/chart/data/' var defaultData = [] var labels = []; $.ajax({ method: "GET", urls: endpoint, success: function(data){ labels = data.labels defaultData = data.default setChart() }, error: function(error_data){ console.log("error") console.log(error_data) } }) function setChart(){ var ctxSI = document.getElementById("SumberChart"); var SumberChart = new Chart(ctxSI, { type: 'bar', data: { labels: labels, datasets: [{ label: '# of Votes', data: defaultData, backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { scales: { y: { beginAtZero: true } } }, }); } views.py user = get_user_model() class ChartData(APIView): authentication_classes = [] permission_classes = [] def get(self, request, format=None): labels = ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'] defaultitem = [12, 19, 3, 5, 2, … -
Adding object.id to render to string to avoid django.urls.exceptions.NoReverseMatch error
I have a Django project that starts with a List view and when one of the objects are clicked it goes to a detailed view which has a button. When this button is clicked I am using Ajax to change a boolean from False to True value. So far I have reached to the point where when the button is clicked it changes the boolean in the backend using Ajax but the page still needs to be manually refreshed to show the effect of the boolean change. I am getting a No Reverse Match Error which can seem to solve it. In my project I have a Detail view as following class workout_details(DetailView): model = Workout template_name = 'my_gym/start_workout.html' context_object_name = 'workout' def change_status(request, id): context = {} if request.is_ajax() and request.method == 'POST': startsession = Workout.objects.get(id=id) if request.POST.get('active') == 'true': startsession.active = True startsession.save() context.update({'status': 'success'}) context.update({'active': str(startsession.active)}) html = render_to_string('my_gym/start_workout.html', context) return JsonResponse({'form': html}) Here is the template my_gym/start_workout.html : <!-- button --> <div id="startworkout"> {% include 'my_gym/button.html' %} </div> <!-- button --> Here is the my_gym/button.html: <form action="{% url 'my_gym:bla' object.id %}" method='post'> {% csrf_token %} {% if object.active %} <button disabled type="button">Start the workout</button> {% else … -
If Statement Problems with For Loop
I am new to Django, and is facing some problem I have categories for say computer programing, computer hardware, and website development. Under each category a candidate has to study 3 books. Book One, Book Two, and Book Three. To list all the categories, and their respective books in Django, I am using if statement, with for loop. I have tried, both for loop within the if statement, and vice versa, however failed. I want to show the website development (category) books (book one to book three) if the website development is satisfied, and if the computer programing is satisfied, the list should show the computer programing books. May you please help me how to get it done. Thanksenter image description here -
missing 1 required positional argument in django createsuperuser
i am trying to create an Account model that extends AbstractBaseUser and i am using a Accountmanger but it shows me the following error when i tried to create a superuser. AccountManager.create_superuser() missing 1 required positional argument: 'phone' and this is the Manager class class AccountManager(BaseUserManager): def create_user(self, email,phone,password, **extra_fields): if not email: raise ValueError('The given email must be set') if not phone: raise ValueError('User must have a phone number.') account = self.model( email=self.normalize_email(email) ) extra_fields.setdefault('is_superuser', False) account.phone=phone account.set_password(password) account.save(using=self._db) return account def create_superuser(self,email,phone,password,**extra_fields): extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') if not phone: raise ValueError('User must have a phone number.') account = self.create_user(email,phone,password=password) return account and here is the Model class class Account(AbstractBaseUser, PermissionsMixin): name = models.CharField(max_length = 20,verbose_name = "Name",) email = models.CharField(max_length = 50, unique = True, validators [validators.EmailValidator()],verbose_name = "Email") phone = models.CharField(max_length=15,unique=True,null=True) date_joined = models.DateTimeField(default=timezone.now) picture = models.ImageField(upload_to='account/', blank=True, null=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) admin = models.BooleanField(default=False) USERNAME_FIELD = 'email' # Custom user manager objects = AccountManager() def __str__(self): return self.name i have searched error like this but didn't work out ... help -
Why Ajax with Django is giving me double values for increase and decrease the values of the like_count?
So I was making a like button with Ajax, and when I like or remove the like I need the like_count to decrease and make this in real time, but what is happening is that when I click the like button it increase or decreases 2 values and I don't know why. Here's the code. Models: class Post(models.Model): favs = models.ManyToManyField(User, blank=True, related_name='favs') likes_count = models.IntegerField(default=0) Views: class AddLike(LoginRequiredMixin, View): def post(self, request, pk, *args, **kwargs): post = Post.objects.get(pk=pk) is_like = False for like in post.likes.all(): if like == request.user: is_like = True break if not is_like: post.likes.add(request.user) post.likes_count = post.likes_count +1 if is_like: post.likes.remove(request.user) post.likes_count = post.likes_count -1 post.save() next = request.POST.get('next', '/') return HttpResponseRedirect(next) HTML: <form method="POST" id="like-post"> {% csrf_token %} <input type="hidden" name="next" value="{{ request.path }}"> <input type="hidden" name="pk" value="{{ post.pk }}"> <input type="hidden" name="like-count" value="{{ post.likes_count }}"> <button style="background-color: transparent; border: none; box-shadow: none;" type="submit"> <span id="count{{ post.pk }}" >{{ post.likes_count }}</span> {% if request.user in post.likes.all %} <i id="no-like{{ post.pk }}" style="color:gray ;display: none;" class="fa-solid fa-champagne-glasses"></i> <i id="liked{{ post.pk }}" style="color:green ;" class="fa-solid fa-champagne-glasses"></i> {% else %} <i id="liked{{ post.pk }}" style="color:green ;display: none;" class="fa-solid fa-champagne-glasses"></i> <i id="no-like{{ post.pk }}" style="color:gray ; " class="fa-solid fa-champagne-glasses"></i> … -
After using pipx to install graphene-django getting No module named 'graphene_django'
I have instlled pipx and successfully run the following... PS C:\Users\oliver\base\forms\forms> pipx install graphene-django --include-deps ⚠️ Overwriting file C:\Users\oliver\.local\bin\django-admin.exe with C:\Users\oliver\.loc al\pipx\venvs\graphene-django\Scripts\django-admin.exe pipx\venvs\graphene-django\Scripts\sqlformat.exe installed package graphene-django 2.15.0, installed using Python 3.10.6 These apps are now globally available - django-admin.exe ⚠️ Note: 'C:\\Users\\oliver\\.local\\bin' is not on your PATH environment variable. These apps will not be globally accessible until your PATH is updated. Run `pipx ensurepath` to automatically add it, or manually modify your PATH in your shell's config file (i.e. ~/.bashrc). done! ✨ 🌟 ✨ my settings.py has... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'core', 'graphene_django', 'corsheaders', ] When I try python manage.py runserver I get... ModuleNotFoundError: No module named 'graphene_django' -
Django occassionally and temporarily cant connect to database. It is causing requests to it to temporarily timeout and fail
Setup: AWS RDS db (postgres), Dockerised django backend hosted on elastic beanstalk Some context: I have a django backend that accepts form post requests from a separate website, and django saves the form data to the database. The django app I'm creating is replacing existing software that is used for this purpose. I started testing the django app by having the website send the form data to BOTH the existing software and my django app. I noticed that occassionally my django app will not receive a form that the existing software receives. E.g django will finish the day with 25 forms but the existing software will finish with 26. I have request logging setup, but even the logs don't show any records of the 26th form. To debug what was going wrong, I set up a script command within the django app to send forms to my django app endpoint every minute. It eventually failed: Exception retrieving data fields SSL SYSCALL error: EOF detected Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.OperationalError: SSL SYSCALL error: EOF detected The above exception was the direct cause of the following exception: Traceback (most recent call last): … -
Include django static files in javascript dinamically
I have this situation. I have some bookcovers on my static files on Django. The jpg files names are the isbn of each book. I am building img tags on Javascript and would like to incluide these images to change dinamically. I got each book's isbn already in a variable called "isbn". I am assigning it in this way: var src = "{% static 'img/" + isbn + ".jpg' %}";, and then adding it to the img element. However, the src is been taking as follows: <img id="book-card1img" src="/static/img/%22%20%2B%20isbn%20%2B%20%22.jpg" class="card-img-top">. Is something I am doing wrong? -
django-filter | first filter "------"
I want to rename first filter (all), now its like "--------", question is: how to let it name filters.py: class DoctorsFilter(django_filters.FilterSet): category = ModelChoiceFilter(queryset=DoctorCategory.objects.all().order_by('category'), widget=forms.Select(attrs={"onchange":"submit();"}), label='') class Meta: model = Doctors fields = ['category'] -
Django Rest Framework says CSRF verification failed despite CSRF token is included in axios POST header
I have following react code to make call to django rest framework API: import Cookies from 'js-cookie'; import axios from "axios"; async downloadVideowiseCSV (fromDate, toDate) { var url = '/stat/getStats/'; const axiosInstance = axios.create(); try { const response = await axiosInstance.post(url, { data: { 'format': 'json' }, header: { 'X-CSRFToken': Cookies.get('csrftoken') } } ) //... } When this method gets called, the corresponding request fails with CSRF verification: However when I check the payload of the request, I could see that X-CSRFTOken is indeed populated: Then whats going wrong here? -
Collect & Store Data From API using requests in python to SQLite database
I am new to python and django. But I am trying to set up an app in my project which collects odds data from an API then parses out what I need from the json, and then saves it to a table in an SQLite database. So far I have the following, which gives me the data I would like to collect and store. The data will need to be called and updated if changed once or twice a day to ensure it's up to date. def BluebetNrlOdds(): """Fetch and extract JSON data from Bluebet Australia""" import requests import json # Bluebet Rugby League Odds API. link = 'https:/xxxxxxxxxx.com.au/json/reply/MasterCategoryRequest?EventTypeID=102&WithLevelledMarkets' \ '=true&WithLevelledMarkets=true ' # Request data from link as 'str' nrldata = requests.get(link).text # convert 'str' to Json nrldata = json.loads(nrldata) # NRL ODDS DATA for nrl_odds in nrldata['MasterCategories'][0]['Categories'][0]['MasterEvents']: competition = nrl_odds['CategoryName'] event_id = nrl_odds['MasterEventId'] event_title = nrl_odds['MasterEventName'] start_time = nrl_odds['MaxAdvertisedStartTime'] home_team = nrl_odds['Markets'][0]['OutcomeName'] home_team_win_odds = nrl_odds['Markets'][0]['Price'] home_team_win_handicap = nrl_odds['Markets'][2]['Points'] home_team_handicap_odds = nrl_odds['Markets'][2]['Price'] home_team_1_12 = nrl_odds['Markets'][4]['Price'] home_team_13 = nrl_odds['Markets'][6]['Price'] away_team = nrl_odds['Markets'][1]['OutcomeName'] away_team_win_odds = nrl_odds['Markets'][0]['Price'] away_team_win_handicap = nrl_odds['Markets'][3]['Points'] away_team_win_handicap_odds = nrl_odds['Markets'][3]['Price'] away_team_1_12 = nrl_odds['Markets'][5]['Price'] away_team_13 = nrl_odds['Markets'][7]['Price'] print(competition, event_id, event_title, start_time, home_team, home_team_win_odds, home_team_win_handicap, home_team_handicap_odds, home_team_1_12, home_team_13, away_team, away_team_win_odds, away_team_win_handicap, away_team_win_handicap_odds, … -
Best way to load JSON data into Snowflake Table using Django
After perusing through a few resources, I can't quite find a solution that addresses my problem. I'm building a Django API that users will ideally be able to post to save data locally, as well as insert into a Snowflake Table. I'm able to store that data into my local database fine, but not sure how to go about storing that data into a Snowflake Table. It's stored into my local database as JSON format, like so: [ { "id":1, "player": "Lilly", "power": "Punch" } ] Here is my views.py file class PlayersView(APIView): def post(self, request): player = PlayerSerializer(data=request.data) if player.is_valid(): player.save() snow = Snowflake() query = f""" create or replace TABLE {table_name} (ID NUMBER(38,0) NOT NULL autoincrement start 0 increment 1, PLAYER VARCHAR(16777216), POWER VARCHAR(16777216)); """ snow.query(query, return_data=True) return Response(player.data, status=status.HTTP_201_CREATED) else: return Response(player.errors, status=status.HTTP_400_BAD_REQUEST) def get(self, request): players = Players.objects.all() data = PlayerSerializer(players, many=True).data print(data) return Response(data) Happy to clarify if anyone has any further questions. Thanks in advance! -
How to add data from javascript in databases django
I'm new with Django Framework. I made a template in html using a script javascript. It looks like a chat. I want to put answers from user in my databases. Here is the link with my code: https://codepen.io/maria-lupu-the-sasster/pen/abGdgPQ And the end, after the "conversation" is over and appear the button "Let's go", I want all the details (that 'uid' and name) to be added in my databases. There are my model where I want to add the details: class Employee(models.Model): employee_id = models.BigAutoField(primary_key=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) u_id=models.CharField(max_length=20) badge_number=models.CharField(max_length=50) email_adress = models.CharField(max_length=300) role = models.CharField(max_length=40) def __str__(self): return self.last_name for first_name and last_name I was thinking of doing a split to the string provided by the user (that time when the bot from chat ask user for his name) email_adress will be composed with uid+@gmail.com I searched on google for many solutions, but I still don't know how to do it. I saw something with Ajax, but I don't know how to work with this. Please, can someone help me and explain me? -
Inline formset not saving
I'm having trouble with an inline formset that saves files. It used to work as expected, but it stopped doing so. I'm new to Django and Python, so I don't know much about debugging in this environment. It doesn't throw any error, the terminal only shows the POST, and the parent forms saves its changes. It's worth mentioning that, if I use a normal form to store those files, they get saved in the database and in the filesystem. So, the problem must be in the formset itself. Any help would be much appreciated. Thanks in advance. Here are my forms class ReporteForm(forms.ModelForm): class Meta: model = Reporte fields = ('fecha', 'tipo', 'nis', 'descripcion') def __init__(self, *args, **kwargs): pk = kwargs.pop('pk', None) super(ReporteForm, self).__init__(*args, **kwargs) self.fields['pk'].queryset = Reporte.objects.filter(pk=pk) class ArchivosForm(forms.ModelForm): class Meta: model = ArchivosReporte fields = ['archivo', 'reporte'] ArchivoInlineFormset = inlineformset_factory( Reporte, ArchivosReporte, form=ArchivosForm, extra=5, max_num=5, can_delete=False ) My View class ReporteCV(CreateView): model = Reporte context_object_name = 'contexto' fields = ['fecha', 'tipo', 'nis', 'descripcion'] template_name = "segcom/modal_form.html" def form_valid(self, form): if form.has_changed(): self.object = form.save(commit=True) reporte = self.object formset = ArchivoInlineFormset(request.POST,request.FILES) if formset.has_changed(): #### IT'S NOT BEING TRIGGERED archivos = formset.save(commit=False) for archivo in archivos: if actualizacion: archivo.actualizacion = … -
How can I access the instance of the object on a django form?
I have a Django related question for which I can't seem to find a proper answer: Given this form that gets it's field data from a queryset to another model: class EditTripForm(ModelForm): start_date = forms.DateField(label='Desde', widget=MyDateInput(attrs={'class': 'form-control'})) end_date = forms.DateField(label='Hasta', widget=MyDateInput(attrs={'class': 'form-control'})) operations = forms.ModelMultipleChoiceField( widget = forms.CheckboxSelectMultiple, queryset = OperationCard.objects.order_by('-date').all() ) class Meta: model = Trip fields = ['start_date', 'end_date', 'operations'] I would like to filter the queryset so that I can use the form's own start_date or end_date to make a query like this: class EditTripForm(ModelForm): start_date = forms.DateField(label='Desde', widget=MyDateInput(attrs={'class': 'form-control'})) end_date = forms.DateField(label='Hasta', widget=MyDateInput(attrs={'class': 'form-control'})) operations = forms.ModelMultipleChoiceField( widget = forms.CheckboxSelectMultiple, queryset = OperationCard.objects.order_by('-date').filter(date__gte=start_date) ) class Meta: model = Trip fields = ['start_date', 'end_date', 'operations'] Note the .filter(date_gte=start_date) part Is that even possible? How should I approach this? -
specify permissions per method django REST framework
i need to use different permission depending on the methods class API_methods(APIView): permission_classes = [HasAPIKey | IsAuthenticated] def get(self, request): def post(self, request): for get HasAPIKey and for post IsAuthenticated there is a solution without using custom permission? -
How Do I create a nested comment section?
hat is the best way to create a nested comment section? My current Views is setup is class AddCommentView(CreateView): model = Comment form_class = CommentForm template_name = 'add_comment.html' # fields = '__all__' def form_valid(self, form): form.instance.post_id = self.kwargs['pk'] return super().form_valid(form) success_url = reverse_lazy('home') This is my current models is.. class Comment(models.Model): post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE) name = models.CharField(max_length=250) body = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' % (self.post.title, self.name) Any help on this would be greatly appreciated! -
Django - Can't login into admin site with user create directly from admit site
So, i have created a Customer user model using AbstractUser Model.py class Department(models.Model): department_name = models.CharField(max_length=20) def __str__(self): return self.department_name class Role(models.Model): role_name = models.CharField(max_length=120) def __str__(self): return self.role_name class Task(models.Model): task_desp = models.TextField(max_length=100) in_progress = models.BooleanField() def __str__(self): return self.task_desp class Employee(AbstractUser): username = None email = models.EmailField(max_length=100,unique=True) phone_number = models.CharField(max_length=14) department = models.ForeignKey(Department,on_delete=models.CASCADE,null=True,blank=True) role = models.ForeignKey(Role,on_delete=models.CASCADE,null=True,blank=True) address = models.TextField(max_length=200) task_assigned = models.ForeignKey(Task,on_delete=models.CASCADE,null=True,blank=True) USERNAME_FIELD= 'email' REQUIRED_FIELDS = ['phone_number'] objects= UserManager() def __str__(self): return self.email manager.py from django.contrib.auth.base_user import BaseUserManager class UserManager(BaseUserManager): use_in_migrations = True def create_user(self,email,password=None,**extra_fields): if not email: raise ValueError("Please provide email") email = self.normalize_email(email) user = self.model(email=email,**extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self,email,password,**extra_fields): extra_fields.setdefault('is_staff',True) extra_fields.setdefault('is_superuser',True) extra_fields.setdefault('is_active',True) if extra_fields.get('is_staff') is not True: raise ValueError("super user must have staff user") return self.create_user(email,password,**extra_fields) Added the model in setting AUTH_USER_MODEL = 'emp.Employee' So,I have made 3 user via python manage.py createsuperuser and was able to login into admit site, but when I made a 4th user directly from admin site, gave it all staff and superuser permission I am not able to login I get this error Please enter the correct email and password for a staff account. Note that both fields may be case-sensitive. I create this Elon user ( … -
Why Django auto adds permissions to group?
Currently I'm making some groups for my backend and I noticed through the admin panel that the groups have some extra permissions I did not add. What is the cause of this behavior? models.py: produccion_group, created = Group.objects.get_or_create(name="Produccion y cuentas") produccion_group.permissions.add( Permission.objects.get(codename='add_brand'), Permission.objects.get(codename='change_brand'), Permission.objects.get(codename='view_brand'), Permission.objects.get(codename='add_expense'), Permission.objects.get(codename='change_expense'), Permission.objects.get(codename='view_expense'), ) produccion_group.save() Admin panel: -
Wrap Django template content in a React layout
I'm used to building Single Page Apps. But for the current project I have a complex application serving almost everything from django templates. It's out of scope to rebuild all the django based content into the SPA with API access. This project is only to replace the header and add a sidebar which slides out of the way when the "hamburger" icon is clicked, or when the media size gets small enough. It's a typical responsive, mobile first, application menu layout with the sidebar to the left of the content on large viewports. In development, the layout works as intended. But there's no server rendered content being put in the "main" content area. This is how I would construct the layout in HTML if I wasn't using react. It doesn't currently work this way because if I render the components individually, they don't share a context for responding to changing viewport and events. <body> <noscript>You need to enable JavaScript to run this app.</noscript> <div id="header"><!-- React --></div> <div> <div id="sidebar"><!-- React --></div> <div id="main">{{ Django Content Here }}</div> </div> <div id="footer">{{ Django Footer Here }}</div> </body> If I follow the standard convention, the layout works because the App.js pulls various … -
Class based views does not render HTML in template-Is context missing?
I started to work with class based views, but the codes that I've written initially does not render in the template when I use class based views. The data that is in note.title (see template) simply does not show up when I use class based views. When I change back to function based views and refresh the page, the HTML code in the template shows up without any problems. Could someone explain what causes this error? I've read something about context not been found by the template but I don't really understand what it means and how context resolves the issue. Thanks in advance! views.py from multiprocessing import context from django.shortcuts import render import notes from .models import Notes from django.http import Http404 from django.views.generic import ListView, DetailView, CreateView # Create your views here. class NotesCreateView(CreateView): models = Notes fields = ["title", "text"] succes_url = "/smart/notes" class NotesListView(ListView): model = Notes context_objects_name = "note" template_name = "notes/notes_list.html" class NotesDetailView(DetailView): model = Notes context_object_name = "note" # def list(request): # all_notes = Notes.objects.all() # context = {'notes': all_notes} # return render(request, 'notes/notes_list.html', context) # def detail(request, pk): # try: # note = Notes.objects.get(pk=pk) # except Notes.DoesNotExist: # raise Http404("This note doesn't …