Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How does django's `python manage.py shell` keep the command prompt open?
When you run python manage.py shell, (or shell_plus if you have the extension), the script will import some stuff for you and then open a regular python shell for you to try commands out, as opposed to running the script and immediately closing. I know that you can use the -i switch when calling a script to keep the command prompt open, for example python -i foo.py will run the contents of foo.py yet keep the shell open instead of immediately closing. I would guess that when you call django's manage.py shell it somehow uses the same feature to get the command prompt to stay open and not immediately close out. How does it work? Can I add something to any script file to make it behave the same way (without using the -i switch) ? -
Trying to implement Auth0 Authentication with React front-end and Django backend
For my project I am using React for my frontend and Django for my backend and connected using django rest framework. I am trying to set this up so that when a user is created in auth0 it updates my users table in django. Would greatly appreciate some general assistance or resources on accomplishing this. Thanks -
Django TemplateDoesNotExist at '/' with outside app
Lately i've been trying to connect my django application that serves as an API to a react app that will work as the frontend (the react app was made with vite by the way). The issue that i'm having is that, no matter what i change in the index.html (frontend), urls.py or settings.py (backend) i always get the same error: TemplateDoesNotExist at /. This would be my folder hierarchy, considering the react folder and django folder are at the same level (don't mind the name of the folders inside de hierarchy, i need to change them). React (front end): This is the index.html code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <link rel="icon" type="image/svg+xml" href="https://va.exeiot.com/static/assets/media/logos/favicon.png" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <!--Fuenes Material UI--> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" /> <!--Fuentes EXEIOT--> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Poppins:300,400,500,600,700"> <title>Video Analitica</title> <!--Linea de refereencia para que el navegador pueda encontrar index.algo.js--> <base href="/dist/"> <!--Fin referencia--> </head> <body> <div id="root"></div> <script type="module" src="/src/main.jsx"></script> </body> </html> Django (backed, API): In the Django directory the folder "backend" contains the settings of the django project and the folder "frontend" contains the api, views and models. This are the contents of: settings.py import os from pathlib import Path import environ … -
Why am I unable to add data to django Model's objects
So this is a bit weird. I make a post request from the website I'm working on, I get the data on the backend but I can't access the model's field with the received data. My Models.py: class Records(models.Model): user = models.ForeignKey(Teacher, null=True, on_delete= models.SET_NULL) Year = models.CharField(max_length=100, null=True) January = models.CharField(max_length=100, null=True) Feburary = models.CharField(max_length=100, null=True) March = models.CharField(max_length=100, null=True) April = models.CharField(max_length=100, null=True) May = models.CharField(max_length=100, null=True) June = models.CharField(max_length=100, null=True) July = models.CharField(max_length=100, null=True) August = models.CharField(max_length=100, null=True) September = models.CharField(max_length=100, null=True) October = models.CharField(max_length=100, null=True) November = models.CharField(max_length=100, null=True) December = models.CharField(max_length=100, null=True) My Views.py: @api_view(['POST']) def Attendance(request): data = request.data['list'] print (data) user = Teacher.objects.get(name=data[0].split('-')[0]) record = Records.objects.get(user=user, Year=data[0].split('-')[1]) month = data[1] print(month) # output is January return JsonResponse({'success':True}) So now when I try to print the January field of the records model, I do it like print(record.January) The issue I'm facing is that I can't do record.month even tho month represents January I want to add the data I got from the post request to the Model Field, normally what I do is: record = Records.objects.get(user=user) record.January = "50" record.save() but as mentioned before record.month isn't working, rather I get this error: AttributeError: 'Records' … -
How To Write QuerySet in Django TemplateView
class CatalogueView(TemplateView): """ Browse all products in the catalogue """ context_object_name = "products" template_name = 'oscar/catalogue/browse.html' model = Product def get(self, request, *args, **kwargs): try: self.search_handler = self.get_search_handler( self.request.GET, request.get_full_path(), []) response = super().get(request, *args, **kwargs) except InvalidPage: # Redirect to page one. messages.error(request, _('The given page number was invalid.')) return redirect('catalogue:index') return response def get_search_handler(self, *args, **kwargs): return get_product_search_handler_class()(*args, **kwargs) def get_context_data(self, **kwargs): context = super(CatalogueView, self).get_context_data(**kwargs) ctx = {} ctx['summary'] = _("All products") ctx['pro_list'] = Product.objects.all() ctx['pro_list'] = Product.objects.all().filter().order_by('upc') search_context = self.search_handler.get_search_context_data( self.context_object_name) ctx.update(search_context) return ctx Don't mind the messy Code indentation format. Django Oscar uses the class based TemplateViews and I want to write more queresets for my products model but everything seems not working. get_context_data will not work. I need a way to add more Queresets to the TemplateView in the catalogue view. How can this be resolved? I need to filter more queresets for the Product -
Run Linux shell or command in Python Django and present in dasboard
Good, I intend to run a command on Linux server using python django and show it on a screen on the web. Ex: ps auxf | grep java Present on screen in Python Django ` -
Using dj-rest-auth to authenticate multiple user types
I'm building a rest API using dj-rest-auth. I have multiple user types that inherit from a custom user model. I have integrated dj-rest-auth that works using the base user model. However, I need to use dj-rest-auth on the user types. How would I go about this? Also, I would like a user to be able to belong to multiple user types. -
OpenGraph show full image size in preview
I want to show a thumbnail when sending a link. I tried it with using open graph and now it looks like that: but I want it to look like this: how can I change the size of the image in the preview. This is my code right now: <meta property="og:image" content="/media/{{ image }}"> {{ image }} is just my templatetag for the image but that works like expected so there is no need to change something there. If it's necessary I'm also able to change the service from opengraph to some other if changing the size is not possible there. -
Upgrade to Django 4.0 has caused tests to fail even when the feature being tested works
A bit of an odd one. I've upgraded from Django 3.2 to 4.0. A lot of my tests fail and they all fail where I'm testing the result of a form submission. However the forms themselves work fine when I test them using my browser. And all the tests fail in exactly the same way with the message AssertionError: The form 'form' in context 166 does not contain the field 'date' (obviously the field, form name and number are different in each test). I've looked though the Django documents to see if the way forms should be tested has changed but I don't see any mention of anything that could have caused this. Sample test: def test_expenses_new_and_edit_ye(self): """ Submits expense before and after ye date, then again with edit """ self.client.force_login(User.objects.get_or_create(username='testuser')[0]) # Redate the most recent YE to 10 days ago ye = JournalEntry.objects.filter(type='YE').order_by('-id')[0] ye.date = (datetime.today() - relativedelta(days=10)) ye.save() # Try to submit into previous financial year date = (datetime.today() - relativedelta(days=10)).strftime('%Y-%m-%d') response = self.client.post(reverse('journal:expenses_new'), {'date':date, 'account': 20, 'expense': 7, 'project': 1, 'store': 'Test store 223', 'amount': 10}) self.assertFormError(response, 'form', 'date', 'Date must be within current financial year') Sample output: ====================================================================== FAIL: test_expenses_new_and_edit_ye (journal.tests.test_main.ExpensesChecks) Submits expense before and after … -
Django Alternative To Inner Join When Annotating
I'm having some trouble generating an annotation for the following models: class ResultCode(GenericSteamDataModel): id = models.IntegerField(db_column='PID') result_code = models.IntegerField(db_column='resultcode', primary_key=True) campaign = models.OneToOneField(SteamCampaign, db_column='campagnePID', on_delete=models.CASCADE) sale = models.BooleanField(db_column='ishit') factor = models.DecimalField(db_column='factor', max_digits=5, decimal_places=2) class Meta: managed = False constraints = [ models.UniqueConstraint(fields=['result_code', 'campaign'], name='result_code per campaign unique') ] class CallStatistics(GenericShardedDataModel, GenericSteamDataModel): objects = CallStatisticsManager() project = models.OneToOneField(SteamProject, primary_key=True, db_column='projectpid', on_delete=models.CASCADE) result_code = models.ForeignKey(ResultCode, db_column='resultcode', on_delete=models.CASCADE) class Meta: managed = False The goal is to find the sum of factors based on the result_code field in the ResultCode and CallStatistics model, when sale=True. Note that: Result codes are not unique by themselves (described in model). A Project has a relation to a Campaign The following annotation generates the result that is desired (possible solution): result = CallStatistics.objects.all().values('project').annotate( sales_factored=models.Sum( models.Case( models.When( models.Q(sale=True) & models.Q(project__campaign=models.F('result_code__campaign')), then=models.F('result_code__factor') ) ) ) ) The problem is that the generated query performs a Inner Join on result_code between the 2 models. Trying to add another field in the same annotation (that should not be joined with Resultcode), for example: sales=models.Sum(Cast('sale', models.IntegerField())), results in a wrong summation. The Questions is if there is an alternative to the automatic Inner Join that Django generates. So that it is possible … -
Field 'id' expected a number but got <QueryDict: {'csrfmiddlewaretoken':
I'm having this error and I can't solve the problem VIEW.PY def projects_add(request, client_id): if request.method == 'POST': form = ProjectForm(request.POST or None) if form.is_valid(): instance = form.save(commit=False) client = Clients.objects.get(pk=client_id) instance.client = client instance.created_date = datetime.date.today() instance.status = 'Análise' instance.save() messages.success(request,'Projeto adicionado') else: messages.error(request,'Ocorreu um erro!') return HttpResponseRedirect(reverse('projects')) else: form = ProjectForm(client_id) all_projects = Project.objects.all() return render(request,'projects.html',{'form':form, 'all_projects':all_projects}) FORMS.PY class ProjectForm(ModelForm): class Meta: model = Project fields = ['owner','farm','warranty','modal','culture','value','final_date'] def __init__(self, client_id, *args,**kwargs): super(ProjectForm, self).__init__(*args,**kwargs) self.fields['value'].required = False self.fields['final_date'].required = False self.fields['farm'].queryset = Farm.objects.filter(client=client_id) self.fields['warranty'].queryset = Farm.objects.filter(client=client_id) for field_name, field in self.fields.items(): field.widget.attrs['class'] = 'form-control' MODELS.PY class Project(models.Model): modal_types = [('CUSTEIO AGRÍCOLA','Custeio Agrícola'),('CUSTEIO PECUÁRIO','Custeio Pecuário'),('INVESTIMENTO AGRÍCOLA','Investimento Agrícola'),('INVESTIMENTO PECUÁRIO','Investimento Pecuário'),('FGPP','FGPP')] farm = models.ManyToManyField(Farm, related_name='project_farm',verbose_name='Propriedade beneficiada') client = models.ForeignKey(Clients, on_delete=models.CASCADE, related_name='project_client',default=None,null=True, verbose_name='Cliente') owner = models.ForeignKey(Owner, on_delete=models.CASCADE, related_name='project_bidder',default=None,null=True, verbose_name='Proponente') warranty = models.ManyToManyField(Farm, related_name='project_warranty',default=None, verbose_name='Propriedade de garantia') modal = models.CharField(max_length=100,default=None,choices=modal_types, null=True, verbose_name='Tipo') culture = models.CharField(max_length=50,null=True, verbose_name='Cultura') status = models.CharField(max_length=50,null=True, verbose_name='Status') created_date = models.DateField(null=True, verbose_name='Data de criação') value = models.FloatField(max_length=10,null=True, verbose_name='Valor financiado') final_date = models.DateField(default=None,null=True, verbose_name='Fim do contrato') I think the problem occurs because of the way I use to define queryset, but I've tried everything and it doesn't work. -
Model form create within listview in Django using CBV
Hi i m learning django by creating weather app. I dont know this is the correct way of doing this.I need a form within listview for adding city to user and I'm using CBV .but form is not present in website.what can I do? views.py from urllib import request from django.shortcuts import render import requests from datetime import datetime from .models import City from pytz import timezone from django.views.generic import ListView from .forms import CityForm from django.views.generic.edit import FormMixin, FormView class Cities(FormMixin,ListView): model=City template_name='home.html' form_class=CityForm success_url='/' def get_context_data(self, *, object_list=None, **kwargs): context =super(Cities, self).get_context_data(**kwargs) weather_data=[] for city in City.objects.all(): url=f'https://api.openweathermap.org/data/2.5/weather?q={city}' data=requests.get(url).json() if data["cod"] != "404": now_asia =datetime.fromtimestamp(data['timezone']).strftime('%a,%b %d %Y') payload={ 'city':data['name'], 'weather':data['weather'][0]['main'], 'icon':data['weather'][0]['icon'], 'fahrenheit':data['main']['temp'], 'celsius':int(data['main']['temp']-273), 'pressure':data['main']['pressure'], 'humidity':data['main']['humidity'], 'description':data['weather'][0]['description'], 'date' :now_asia, } weather_data.append(payload) else: weather_data={'invalid_city':f'{city} City not found.\n Enter valid city'} print(context) context={'weather_data':weather_data} return context forms.py from django.forms import ModelForm from .models import City class CityForm(ModelForm): class Meta: model=City fields=['name'] home.html {% csrf_token %} {{form}} <button class="btn" type="submit" >Add city</button> -
Django three model which should be connected and depends of other
I can't wrap my head how to store / define the right model / relationship. I have following data: CATEGORY is their own model because i like to view / request in some situation only the category. But to this category I want set VALUE which I can only define onetime depending ON YYYY-MM. What make me difficult to achieve / understand how i get the relationship between VALUE <-> YYYY-MM but still maintain the connection / dependency to only one CATEGORY "Rent". -
Django model datefield with YYYY-MM instead YYYY-MM-DD
I would like to have a model YYYY_MM which stores 2022-01 2022-02 etc I thought the best method would be to use the DateField but it looks like that YYYY-MM-DD is enforced? -
Django models unknown column in field list(1054, "unknown column in 'field list'")
In Django I have problem in creating a model object through admin interface. When I attempt to create a model object, I get this error django.db.utils.OperationalError: (1054, "Unknown column 'restaurant_restaurant.addressStreet' in 'field list'") I know that the problem is related to the mySQl data base, but I have no idea of how to resolve this. My models.py from django.db import models # Create your models here. class Restaurant(models.Model): name = models.CharField(max_length = 255) addressStreet = models.CharField(max_length=255, help_text='Street name of the restaurant', blank = True) addressStreetNumber = models.CharField(max_length=50, help_text = 'street number', blank = True) addressPostCode = models.CharField(max_length=50, help_text = '4 digits post code', blank = True) addressCity = models.CharField(max_length=100, help_text = 'City name', blank = True) phone = models.CharField(max_length=100, help_text = 'Phone', blank = True) email = models.EmailField(max_length = 255, blank = True) cvr = models.CharField(max_length = 50, help_text = 'CVR number', blank = True) openingDaysRange1 = models.CharField(max_length=255, help_text='For example Monday - Friday', blank = True) openingHoursRange1 = models.CharField(max_length=255, help_text = 'For example 14:00 - 20:00', blank = True) openingDaysRange2 = models.CharField(max_length=255, help_text='For example Saturday - Sunday', blank = True) openingHoursRange2 = models.CharField(max_length=255, help_text = 'For example 12:00 - 22:00', blank = True) class Meta: ordering = ['-name'] def __str__(self): … -
how i can give a good struture to my defaultdict
I have a defaultdict on my views.py: output: defaultdict(<class 'list'>, {'List of tubes': ['2324', '98', '7654', 'List of auto:': [147, 10048, 1009, 10050, 10, 1647, 10648, 649, 1005]}) how i can give a better structure to my defaultdict ? -
Django not loading CSS and JS files into browser
I am working on my first Django application. I built a template HTML file but cannot get the CSS and JS files to load when viewing on my localhost. I have consulted the Django official documentation but cannot manage to identify the issue. I have cleared the my browser's cache but it did not make a difference. Settings.py {% load static %} (included at the top of the script) STATIC_ROOT= os.path.join(BASE_DIR, 'static') STATIC_URL = 'static/' STATICFILES_DIR = [ os.path.join(BASE_DIR, 'myproject/static') ] templates/base.html - CSS <link href="http://fonts.googleapis.com/css?family=Roboto:300,400,700" rel="stylesheet" type="text/css" /> <link href="{% static '\fonts\font-awesome.css' %}" rel="stylesheet" type="text/css" /> <link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap.css' %}" type="text/css" /> <link rel="stylesheet" href="{% static 'css/bootstrap-select.min.css' %}" type="text/css" /> <link rel="stylesheet" href="{% static 'css/jquery.slider.min.css' %}" type="text/css" /> <link rel="stylesheet" href="{% static 'css/owl.carousel.css' %}" /> <link rel="stylesheet" href="{% static 'css/style.css' %}" /> templates/base.html - JS <script type="text/javascript" src="{% static 'js/jquery-2.1.0.min.js' %}" ></script> <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false" ></script> <script type="text/javascript" src="{% static 'js/jquery-migrate-1.2.1.min.js' %}" ></script> <script type="text/javascript" src="{% static 'bootstrap/js/bootstrap.min.js' %}" ></script> <script type="text/javascript" src="{% static 'js/smoothscroll.js' %}" ></script> <script type="text/javascript" src="{% static 'js/markerwithlabel_packed.js' %}" ></script> <script type="text/javascript" src="{% static 'js/infobox.js' %}"></script> <script type="text/javascript" src="{% static 'js/owl.carousel.min.js' %}" ></script> <script type="text/javascript" src="{% static 'js/bootstrap-select.min.js' %}" ></script> <script type="text/javascript" src="{% … -
Form Select value not being passed on submit [react
I am having troubles setting a form select within a react component: when i submit the form all fields are filled out but the first select value (product) is not passed, while the second (transaction_type) is passed. My API is returning that that value cannot be null. django.db.utils.IntegrityError: null value in column "product_id" of relation "product_transaction" violates not-null constraint DETAIL: Failing row contains (33, 2022-02-22 18:30:22.458768+00, OUT, 2, aaa, null, null). Please, what am i missing for it to grab that value and pass it on the submit? function AddTransaction() { const [product, setTransactionProduct] = useState('1'); const [transaction_type, setTransactionType] = useState('OUT'); ... const [Products, setProducts] = useState([]) useEffect(() => { const fetchProducts = async () => { ... } fetchProducts() }, []) const getProducts = () => { let list = []; Products.map(item => { return list.push( <option key={item.id} value={item.id} > {item.title} </option> ) }) return list } const navigate = useNavigate(); const addToForm = async () => { let formfield = new FormData() formfield.append('product', product) formfield.append('transaction_type', transaction_type) ... await axios({ method: 'post', url: 'http://127.0.0.1:8000/api/transaction_create', headers: { 'content-type': 'multipart/form-data', 'Authorization': '(*&^%$#@!)(*&^%$#*&^%@#$%^&*', }, data: formfield, }).then((response) => { navigate(-1) }, (error) => { }); } return ( <div className='container'> <h5>Agregar transacci&oacute;n</h5> … -
How can i make a model active/inactive without delete it, Django?
I want to deploy a way to active/inactive a model without delete it, like in User model that has a is_active field that we can deactivate a user, so I want to do same with models. Any Solutions for that? -
Django Alternative To Inner Join When Annotating
I'm having some trouble generating an annotation for the following models: class ResultCode(GenericSteamDataModel): id = models.IntegerField(db_column='PID') result_code = models.IntegerField(db_column='resultcode', primary_key=True) campaign = models.OneToOneField(SteamCampaign, db_column='campagnePID', on_delete=models.CASCADE) sale = models.BooleanField(db_column='ishit') factor = models.DecimalField(db_column='factor', max_digits=5, decimal_places=2) class Meta(): managed = False constraints = [ models.UniqueConstraint(fields=['result_code', 'campaign'], name='result_code per campaign unique') ] class CallStatistics(GenericShardedDataModel, GenericSteamDataModel): objects = CallStatisticsManager() project = models.OneToOneField(SteamProject, primary_key=True, db_column='projectpid', on_delete=models.CASCADE) result_code = models.ForeignKey(ResultCode, db_column='resultcode', on_delete=models.CASCADE) class Meta(): managed = False The goal is to find the sum of factors from CallStatistics based on the factor in the ResultCode model, when sale=True. Example: The result should be 2+1+1=4 Note that: multiple projects in CallStatistics are omitted, result codes are not unique by themselves (described in model). A Project has a relation to a Campaign The problem is that the generated query performs a Inner Join on result_code between the 2 models. Trying to add another field in the same annotation (that should not be joined with Resultcode), for example: sales=models.Sum(Cast('sale', models.IntegerField())), results in a wrong summation. The Questions is if there is an alternative to the automatic Inner Join that Django generates. So that it is possible to retrieve the following fields (and others similar) in 1 annotation: ... sales=models.Sum(Cast('sale', models.IntegerField())), … -
Django change_list editable fields header rows and items rows
I need to have multiple editable rows Header and Items of products and variants of products in Django Admin change_list.html / change_list_results.html like the image below: Example result this is my model: class VariantProduct(models.Model): product = models.ForeignKey(Product, verbose_name=_('Prodotto'), related_name='variants', on_delete=models.CASCADE) sku = models.CharField(_('SKU'), max_length=40, blank=True, null=True, help_text='SKU', unique=True) ean_13 = models.BigIntegerField('EAN 13', validators=[MaxValueValidator(9999999999999, "Ammessi massimo 13 numeri.")], blank=True, null=True, help_text='Codice numerico EAN 13') ean_128 = models.CharField('EAN-128', max_length=128, blank=True, null=True, help_text='Codice alfanumerico 128') qr_code = models.CharField("Codice QR", blank=True, null=True, max_length=255, help_text="digitare il codice per la generazione del QR Code") barcode = models.ImageField('Barcode', upload_to='barcode/', blank=True, null=True) quantity = models.IntegerField('Quantità', blank=True, null=True) class Meta: verbose_name = _('prodotto') verbose_name_plural = _("prodotti") ordering = ['name'] class VariantProduct(models.Model): product = models.ForeignKey(Product, verbose_name=_('Prodotto'), related_name='variants', on_delete=models.CASCADE) sku = models.CharField(_('SKU'), max_length=40, blank=True, null=True, help_text='SKU', unique=True) ean_13 = models.BigIntegerField('EAN 13', validators=[MaxValueValidator(9999999999999, "Ammessi massimo 13 numeri.")], blank=True, null=True, help_text='Codice numerico EAN 13') ean_128 = models.CharField('EAN-128', max_length=128, blank=True, null=True, help_text='Codice alfanumerico 128') qr_code = models.CharField("Codice QR", blank=True, null=True, max_length=255, help_text="digitare il codice per la generazione del QR Code") barcode = models.ImageField('Barcode', upload_to='barcode/', blank=True, null=True) quantity = models.IntegerField('Quantità', blank=True, null=True) qta_stock_add = models.PositiveSmallIntegerField('Q.ta +', help_text='Diminuisci N. Prodotti', blank=True, null=True, ) qta_stock_sub = models.PositiveSmallIntegerField('Q.ta -', help_text='Diminuisci N. Prodotti', blank=True, null=True, ) minimal_quantity = models.IntegerField('Scorta … -
Django Queryset how to create such a query?
There are two tables Products and Price history It is necessary to display the latest price by date from the price history table. It will work on Sqlite, but I can't figure out how to do it through Queryset SELECT name,max(date),price,price_discount FROM polls_products INNER JOIN polls_history_price on polls_history_price.product_id = polls_products.id GROUP BY polls_products.id class Products(models.Model): id = models.IntegerField(primary_key=True, blank=True) name = models.CharField(max_length=250) date_create = models.DateTimeField('Event Date') class HistoryPrice(models.Model): product = models.ForeignKey(Products, null=True, on_delete=models.PROTECT, related_name='price_list') date = models.DateTimeField('Event Date') price = models.FloatField(blank=True,) price_discount = models.FloatField(blank=False) -
Django: user.has_perm always returns false
I have a custom user: from django.contrib.auth.models import AbstractUser # Create your models here. class TaborUser(AbstractUser): email = models.EmailField('E-mail', unique=True) Its backend: from django.contrib.auth.backends import BaseBackend from django.contrib.auth import get_user_model from django.db.models import Q UserModel = get_user_model() class EmailBackend(BaseBackend): def get_user(self, user_id): user = UserModel.objects.filter(pk=user_id) breakpoint() if user: return user[0] else: return None def authenticate(self, request, username=None, password=None, **kwargs): user = UserModel.objects.filter(email=username) if not user: user = UserModel.objects.filter(username=username) # Both username and e-mail are unique. As long as we don't have # a very rogue admin, we should be alright. if user: user = user[0] else: return None if user.check_password(password): return user else: return None The model does not seem to pass this check: class AdminView(PermissionRequiredMixin, FormView): form_class = UploadFileForm template_name = "admin.html" login_url = "/login/" permission_required = ("taborapp.view_photomodel", "taborapp.add_photomodel", "taborapp.delete_photomodel", ) When user is added as follows: from taborapp.models import TaborUser from django.contrib.auth.models import Permission from django.contrib.contenttypes.models import ContentType user = TaborUser.objects.create_user("test") user.email = "test@example.me" user.set_password("LOLaPublicPassword123") permissions = [] photo_type = ContentType.objects.get(app_label="taborapp", model="photomodel") for codename in "view_photomodel", "add_photomodel", "delete_photomodel": perm = Permission.objects.filter(content_type=photo_type, codename=codename) permissions.append(perm[0]) user.user_permissions.add(*permissions) user.save() Am I doing anything wrong? I went over docs and similar issues on stack overflow a few times and I just cannot figure … -
Middleware to verify/update JWT access and refresh tokens
I have an app with JWT authentication written in React/ Django / Django-allauth. I have an endpoint to verify/ refresh my access token and it works fine. My question is regards to where to put the refresh logic so it is automatically processed before each request? Is there middleware I can use or is there a way to override fetch? Essentially, I want the app to verify the token, refresh it if necessary, and redirect unauthenticated user to login for every request dependent on JWT authorization. I also don't want to rewrite this logic over and over. I'm thinking of overriding fetch async function handle_token() { const {valid, status} = await API.process_token() return { status, valid, } } // initialize the fetch object to minimize code repeat at every request // https://stackoverflow.com/questions/44820568/set-default-header-for-every-fetch-request function updateOptions(options) { const update = { ...options } update.headers = Object.assign({ 'Content-Type': 'application/json', 'Accept': 'application/json' }, update.headers ? update.headers : {}) if(update.jwt) { const token = localStorage.getItem('access') ? localStorage.getItem('access') : '' update.headers = Object.assign(update.headers, {'Authorization': `Bearer ${token}`}) /******************************************************************************* * Perhaps put token logic here but unser how to to handle it ********************************************************************************/ const {valid, status} = handle_token() } return update; } function fetcher(url, options) { return fetch(url, … -
django display only foreign key object of the concerned user on dropdownlist
I have a drop drop down list as in below image.It should only show the logged user campaigns (here the last free item. But it's showing the others users campaign. Any help is apprecieated. Here are : Here is my view: def insertion_orders(request, pk): if request.user.is_authenticated: user = User.objects.get(id=pk) insertion_orders = user.insertionorder_set.all().order_by('-created_date') filter = InsertionOrdersFilter(request.GET, queryset=insertion_orders) insertion_orders_filter = filter.qs print(insertion_orders_filter) context = { 'user': user, 'insertion_orders': insertion_orders_filter, 'filter': filter } return render(request, 'insertion_orders.html', context) else: return HttpResponse('You re not logged in ! Please log in first') My model: class InsertionOrder(models.Model): kpi_choices = ( ('CPA', 'CPA'), ('CPC', 'CPC'), ('CPD', 'CPD'), ('CPL', 'CPL'), ('CPM', 'CPM'), ('CPV', 'CPV'), ('CTR', 'CTR'), ('Vsibility', 'Visibility'), ('VTR', 'VTR'), ('LTR', 'LTR'), ) user = models.ForeignKey(User, on_delete=models.CASCADE) campaign_naming_tool = models.ForeignKey(CampaignNamingTool, on_delete=models.CASCADE) budget = models.DecimalField(max_digits=20, decimal_places=2) kpi = models.CharField(max_length=10, choices=kpi_choices) goal_value = models.DecimalField(max_digits=20, decimal_places=2) start_date = models.DateField() end_date = models.DateField() created_date = models.DateTimeField(auto_now_add=True, blank=True, null=True) def __str__(self): return "%s" % self.campaign_naming_tool # return "{} - [{}]".format(self.insertion_order, self.user) class Meta: db_table = 'InsertionOrder'