Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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' -
Import wants to override unchanged fields
If i export to xlsx and reimport, Django-Import-Export reports overwritten fields but there are no changes. I already tried to debug this myself with the skip_row() method but i think im generally doing sommething wrong resources.py class FormatClassResource(resources.ModelResource): number = fields.Field(column_name="Nummer", attribute="number") barcode = fields.Field(column_name="Barcode", attribute="barcode") name = fields.Field(column_name="Name", attribute="name") price = fields.Field(column_name="Preis", attribute="price") class Meta: model = FormatClass use_bulk = True use_transactions = True skip_unchanged = True import_id_fields = ["number", "barcode", "name", "price"] exclude = ["id"] Import result -
How do I optimize memory and cpu usage using python
enter image description hereHow do I optimize memory and cpu consuming by these applications in python, could you provide me any article it's related I couldn't find out in Google it's related...thank you. -
How to schedule the custom management command in Django?
I need to schedule the custom management django command. I am using windows. I tried django-crontab but that's not working. Can someone please help me with this? In my_app here is the file "check_links" : check_links.py class Command(BaseCommand): help = 'Check broken links' def handle(self, *args, **options): print("function executed") -
Django Add related_name error on AbstractUser Custom model
Django shows this error when migrating SystemCheckError: System check identified some issues: ERRORS: accounts.CustomUser.groups: (fields.E304) Reverse accessor for 'accounts.CustomUser.groups' clashes with reverse accessor for 'auth.User.groups'. HINT: Add or change a related_name argument to the definition for 'accounts.CustomUser.groups' or 'auth.User.groups'. accounts.CustomUser.user_permissions: (fields.E304) Reverse accessor for 'accounts.CustomUser.user_permissions' clashes with reverse accessor for 'auth.User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'accounts.CustomUser.user_permissions' or 'auth.User.user_permissions'. auth.User.groups: (fields.E304) Reverse accessor for 'auth.User.groups' clashes with reverse accessor for 'accounts.CustomUser.groups'. HINT: Add or change a related_name argument to the definition for 'auth.User.groups' or 'accounts.CustomUser.groups'. auth.User.user_permissions: (fields.E304) Reverse accessor for 'auth.User.user_permissions' clashes with reverse accessor for 'accounts.CustomUser.user_permissions'. HINT: Add or change a related_name argument to the definition for 'auth.User.user_permissions' or 'accounts.CustomUser.user_permissions'. It is suggesting to add related_name but I have not user any ForeignKey Field in my model, My model is inheriting from the AbstractUser models.py from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class CustomUser(AbstractUser): USER_TYPE_CHOICES = ( (1, 'CUSTOMER'), (2, 'AGENT'), (3, 'SUPERVISOR'), ) user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES) -
Django - How to add multiple permissions on group?
I have a list of permissions list = ['view', 'add', 'edit'] The permissions inside the list are already saved on my table. I first clear the group's previous permission so I can insert a new one group = Group.objects.get(name='Group1') group.permissions.clear() Is there a way to add the list of permission to Group1 programmatically? -
How to present only one data with foreign key in Django?
what happens is that I am using a foreign key in a form and it is presented as a select, the thing is that all the information appears and I only want to present the name of the client, however the name, the model of the car and much more information appears to me, how can I present only one data? carros-form-add.html <div class="row mb-3"> <div class="col-md-4"> <div class="mb-3"> <label>Cliente</label> {{ form.cliente }} </div> </div> </div> carros/models.py cliente= models.ForeignKey(Clientes, on_delete=models.SET_NULL, null=True) carros/models.py class Clientes(models.Model): tipo = models.CharField(max_length=200) TITLE = ( ('Mrs.', 'Mrs.'), ('Miss', 'Miss'), ('Mr.', 'Mr.'), ) corp=models.CharField(max_length=200) title= models.CharField(max_length=200, null=True, choices=TITLE,default='Mr.') name= models.CharField(max_length=200) -
In Django and DRF, why would an api route request.user return an AnonymousUser instance, while django.contrib.auth.get_user(request) return the user?
Let's take a very simple route: class Highscore(APIView): def get(request): user = request.user highscore = user.highscore return Response({"highschore":highscore}) For some unknown reason, there are cases in which request.user despite having the user authenticated and logged in (!) return an Anonymous User instance rather than the user itself. However, this can be bypassed by using get_user util function from django.contrib.auth. from django.contrib.auth import get_user class Highscore(APIView): def get(request): user = get_user(request) highscore = user.highscore return Response({"highschore":highscore}) What could be the cause of that? Important note: The user is for sure logged in. So much so that when opening the admin website in a different tab, it recognizes the correct user just from the session. If it is and admin it presents the admin content and if not if give the "you are logged in as ... but this view is reserved for admin users". -
Django-allauth links redirect
I'm using django allauth for my account management in a django project but the links tot the login, logout and register not redirecting to the appropriate pages for login, logout and register. -
I can't figure out django user registration forms
Good day! I have a problem with registering users on the site, I tried many methods viewed on the Internet, but I made something similar, but it doesn't work. I understand that this may not be a working method, or I have designed it incorrectly. Could you give me advice on how to register or fix errors in my code? Thank you in advance! Forms.py from django.forms import ModelForm, \ TextInput, \ Textarea, \ NumberInput, \ FileInput, \ PasswordInput, \ EmailInput from django.contrib.auth.models import User from .models import Recipe class FoodForm(ModelForm): class Meta: model = Recipe fields = ["recipe_title", "recipe", "recipe_time", "recipe_ingridients", "image"] widgets = { "recipe_title" : TextInput( attrs={ "class" : "title_form", "placeholder" : "Введите название рецепта" } ), "recipe": Textarea( attrs={ "class": "form_of_all", "placeholder": "Введите ваш рецепт" } ), "recipe_time" : NumberInput( attrs={ "class" : "ingr", "placeholder" : "Введите время" } ), "recipe_ingridients": NumberInput( attrs={ "class": "ingr", "placeholder": "Введите кол-во ингридиентов" } ), "image" : FileInput( attrs={ 'type' : "file", 'name' : "input__file", 'id' : "input__file" } ) } class RegisterationUserForm(ModelForm): class Meta: model = User fields = ["first_name", "last_name", "email", "password"] widgets = { "first_name" : TextInput( attrs= { "placeholder" : "Введите имя", "type" : "text", "class" … -
What would happen if I uninstall python, would my python project still work?
Let's say I created a django project with the help of virtualenv and I named my virtualenv venv, If I uninstall python from my system can I still use my project with the help of that venv? -
Full text search in MySQL in Django application
I have written Django app and I am using MySQL in it. I'd like to implement full text search but from what I see full text search is supported only for PostgreSQL. I checked many articles and answers but most of them are outdated. Is there currently any way to handle full text search in MySQL for multiple models. I am currently using Q lookups but it need to use something similar to trigram similarity or levenstein distance. -
Why does my environment variable are equal to None on github actions?
I am trying to build a CI with GitHub actions for my django app. I defined my environment variables on github in settings -> secrets -> actions. This is my ci.yaml file : # name of our workflow name: Django CI/CD Workflow # triggers for our workflow on: push jobs: health-check-job: # health check job for testing and code formatting check runs-on: ubuntu-latest # os for running the job services: postgres: # we need a postgres docker image to be booted a side car service to run the tests that needs a db image: postgres env: # the environment variable must match with app/settings.py if block of DATBASES variable otherwise test will fail due to connectivity issue. POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: github-actions ports: - 5432:5432 # exposing 5432 port for application to use # needed because the postgres container does not provide a healthcheck options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 steps: - name: Checkout code # checking our the code at current commit that triggers the workflow uses: actions/checkout@v2 - name: Cache dependency # caching dependency will make our build faster. uses: actions/cache@v2 # for more info checkout pip section documentation at https://github.com/actions/cache with: path: ~/.cache/pip … -
How to get rid of this "Upload Image Currently" in django ImageField?
I wanna show my image like this for my client, I just wanna get rid of the below "Upload Image Currently" tag. So how can I remove this? Upload Image Currently -
Python/Django - not able to run stand alone script / classes
I have a problem with running parts of script in Django as I can't get it to run the classes. The class I would like to import is this: class Location(models.Model): City = models.CharField(max_length=200) Province = models.CharField(max_length=200) Country = models.CharField(max_length=10) I have found some things when I tried to find a solution and at this point I have this: import os os.environ['DJANGO_SETTINGS_MODULE'] = 'portal.portal.settings' import django django.setup() from portal.core.models import * When I run this, it gives an error for django.setup(): Traceback (most recent call last): File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\code.py", line 90, in runcode exec(code, self.locals) File "<input>", line 1, in <module> File "C:\Users\User\Documents\Portal\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\User\Documents\Portal\venv\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\User\Documents\Portal\venv\lib\site-packages\django\apps\config.py", line 211, in create mod = import_module(mod_path) File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 992, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'core' 'core' is the package module where all the functions are located … -
Adding a date selector for a JavaScript chart in HTML
My chart data is based on a list of dictionaries. It's a Django project, so my data is defined in views.py: I count the number of records with Mike, Jane and Jack. mylist= [{'Date': '2021-10-02', 'ID': 11773, 'Receiver': Mike}, {'Date': '2021-10-02', 'ID': 15673, 'Receiver': Jane}, {'Date': '2021-10-03', 'ID': 11773, 'Receiver': Mike}, ... {'Date': '2021-12-25', 'ID': 34653, 'Receiver': Jack}] mike=len(tuple(d for d in mylist if d['Receiver'] == 'Mike')) jane=len(tuple(d for d in mylist if d['Receiver'] == 'Jane')) jack=len(tuple(d for d in mylist if d['Receiver'] == 'Jack')) count = [mike, jane, jack] I have already drawn a pie chart based on my total counted data in my chart.HTML file : <!-- pie Chart --> <div class="col-xl-4 col-lg-4"> <div class="card shadow mb-4"> <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between"> <h6 class="m-0 font-weight-bold">Team Chart</h6> </div> <!-- Card Body --> <div class="card-body"> <div class="chart-area"> <canvas id="myPieChart"></canvas> <script> var ctx = document.getElementById("myPieChart"); var myPieChart = new Chart(ctx, { type: 'doughnut', data: { labels: ["Mike", "Jane", "Jack"], datasets: [{ data: {{count}} , backgroundColor: ['#4e73df', '#1cc88a', '#36b9cc'], hoverBackgroundColor: ['#2e59d9', '#17a673', '#2c9faf'], hoverBorderColor: "rgba(234, 236, 244, 1)", }], }, }); </script> </div> </div> </div> </div> Instead of getting the total count, I want to draw the chart based on … -
Pytest client change content type
I have a working test that checks the functionality of the POST request coming to the django url endpoint @pytest.mark.django_db def test_me(logged_client): .... data = { 'creativeId': 12, 'descriptionTextId': 345, 'headlineText1Id': 432, 'headlineText2Id': 478, 'campaigns': ['HS_GP_UNKNONW_CAMPAIGN_Purchase07_WW_2_20.07.09'], 'creativeCategory': 'video', } response = logged_client.post( reverse('google_panel:run_google_soft_launch'), data=json.dumps(data), content_type='application/json', ).json() assert ... Now the list of values coming in the post request has changed. One more parameter creativeRotationType was added. accordingly a new value is added to the data data = { .... 'creativeRotationType': 'asset' } But now there is an error ValueError: Content-Type header is "text/html; charset=utf-8", not "application/json" How is it that adding a new field changes the type from application/json to text/html; charset=utf-8 ?