Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to refresh the JWT token in nuxt.js?
I want to use JWT authentication in my nuxtjs app but it's not refreshing the token. For testing purposes, I set the access token expire time 5 seconds and refresh token for 30 minutes. Access token expire after 5 seconds but the token is not refreshing after 5 second its logged-out I'm using the Django rest framework and in nuxt I'm using nuxt auth v5 settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), } SIMPLE_JWT = { 'AUTH_HEADER_TYPES': ('JWT',), 'ACCESS_TOKEN_LIFETIME': timedelta(seconds=5), 'REFRESH_TOKEN_LIFETIME': timedelta(minutes=30), } nuxt.config.js auth: { localStorage: false, strategies: { local: { scheme: 'refresh', token: { property: 'access', type: 'JWT', required: true }, refreshToken: { property: 'refresh', }, user: { property: false, autoFetch: true }, endpoints: { login: { url: '/jwt/create/', method: 'post',}, refresh: { url: '/jwt/refresh/', method: 'post',}, user: {url: '/users/me/', method: 'get' }, logout: false }, } } } } I'm little new in JWT and nuxt. Correct me if I'm wrong. My main goal is just to refresh the token automatically when access toke is expired. -
Slack API how to get conversations.list for different workspaces that installed the app?
Using this app as an example, how could I call conversations_list method while differentiating the conversations list I want for different workspaces? Do I have to construct a different WebClient with some specific token? If so, how do I store OAuth tokens generated for each workspace (as in I don't think the code example linked above handles storing OAuth tokens)? Thanks so much in advance! -
How to capture dynamic URL part to return a list in Django
I need to code an API which will be used by dropdowns in a react form. There are multiple dropdowns and exposed API url also follow similar pattern. For example - /api/trend/foo?bar=0 /api/trend/foo?bar=1 /api/trend/baz?bar=0 /api/trend/baz?bar=0 /api/trend/fish?foss=1 /api/trend/baz?foss=2 So it boils down to /api/trend/{table}?{filter}={val} which will return a list {col}, which further boils down to SELECT col FROM table WHERE filter=val I don't want to write multiple functions for same pattern. I am looking for something like this # in views.py def dropdown_api(request, table, filter): # fire the SQL statement # get the result in a df/list # serialize the result # return the response to consume by react # in urls.py path('api/trend/{table}?{filter}={val}', views.dropdown_api) #something like this to capture the dynamic url content -
how to add images int database in django with out showing the path of images in choosen button
class ProductForms(forms.ModelForm): images1 = forms.ImageField(widget=forms.FileInput,) class Meta: model = Product fields = 'all' -
Error after user creation using Django allauth
After setting up Django-allauth using Microsoft sql as the backend database i get the following error after registering a new user. However user is created and can log in as long as account_email_verification is set to optional django.db.utils.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]An expression of non-boolean type specified in a context where a condition is expected, near ')'. (4145) (SQLExecDirectW); [42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Statement(s) could not be prepared. (8180)") also get the same error when trying to verify email address through emailed link any help is appreciated thanks -
TypeError at /show_cart/ can only concatenate str (not "int") to str
I am building an e-commerce site and i'm working on a quantity & price section. What I want to do is, when the user increses the quantity of the product the price should also change depending upon the quantity. This is views.py def show_cart(request): if request.user.is_authenticated: user = request.user cart = Cart.objects.filter(user=user) amount = 0 shipping_amount = 70 total_amount = 0 cart_product = [p for p in Cart.objects.all() if p.user == user] if cart_product: for p in cart_product: temp_amount = (p.quantity * p.product.discounted_price) amount = temp_amount + amount total_amount = amount + shipping_amount return render(request, 'app/addtocart.html', {'carts':cart, 'amount':amount, 'total_amount':total_amount}) this is models.py: Here is have added comma sepeated integers. coz i wanted the products price to look like this: 14,999 insted of 14999 this. class Product(models.Model): title = models.CharField(max_length = 100) selling_price = models.CharField(validators=[validate_comma_separated_integer_list],max_length=200, blank=True, null=True,default='') discounted_price = models.CharField(validators=[validate_comma_separated_integer_list],max_length=200, blank=True, null=True,default='') I know i am getting this error coz coma seperated interger is considered as a String & quantity is an integer field. So, i want to know that how can i solve this problem, when the user increases the quantity of the product the price should also change depending upon the quantity. -
Why do I get CommandError: App 'appname' does not have migrations in heroku?
So I'm trying to deploy my Django project with heroku. I have successfully deployed the project, but then ran into this issue while trying to migrate. Below is my settings.py ... import dj_database_url DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'my_project_db', 'USER': 'ryan', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '', } } db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) I have run python manage.py makemigrations appname and python manage.py migrate appname in local. Then I ran heroku run python manage.py makemigrations appname, which worked without any error. Below is what I got. Migrations for 'appname': appname/migrations/0001_initial.py - Create model Book - Create model Category - Create model Content Seeing it worked fine, I ran heroku run python manage.py migrate appname. But then I got this issue : CommandError: App 'appname' does not have migrations. What do you think is the problem? Thanks in advance. FYI, when I try to access the model in the admin page, I see an error page saying the relation does not exist. -
How to serialize creation with Django Rest Framework models with many-to-many field and foreign-key, when models data inside some field in request?
I am trying to serialize this JSON { "api_key": "<something key>", "contract_id": 3808, "params": { "contract_id": 3808, "title": "Глюкоза", "doctor_description": "Запрашивает у пациента уровень глюкозы в крови.", "patient_description": "Пожалуйста, измерьте уровень сахара в крови до еды с помощью глюкометра и укажите его в поле ниже.", "thanks_text": null, "fields": [ { "category": "glukose", "description": "ммоль/л", "max": null, "min": null, "text": "Глюкоза", "type": "float", "uid": "24c2258b-d338-4184-a114-5cae3721bb16" }, { "category": "information", "text": "Комментарий", "type": "textarea", "uid": "93722301-d652-4903-8404-e56da4d31ad7" } ] } } Inside params there is instance of model MeasurementTask (models.py): class MeasurementTask(models.Model): title = models.CharField(max_length=255) doctor_description = models.TextField() patient_description = models.TextField() thanks_text = models.TextField(null=True) contract_id = models.ForeignKey(Contract, on_delete=models.CASCADE) fields = models.ManyToManyField(MeasurementTaskGeneric) is_sent = models.BooleanField(default=False) is_done = models.BooleanField(default=False) It related by ManyToManyField with MeasurementTaskGeneric: class MeasurementTaskGeneric(models.Model): uid = models.CharField(max_length=255, unique=True) category = models.CharField(max_length=255) description = models.CharField(max_length=255, null=True) max_value = models.FloatField(null=True) min_value = models.FloatField(null=True) text = models.CharField(max_length=255) value_type = models.CharField(max_length=255) And with foreign key with Contract: class Contract(models.Model): contract_id = models.IntegerField(unique=True, primary_key=True) speaker_active = models.BooleanField(default=False) def __str__(self): return "Contract id - {}".format(self.contract_id) With request I need to create instance of MeasurementTask and create (or get if it already exists) instance of MeasurementTaskGeneric, get instance of Contract by Contract.contract_id and add it ti foreignKey to MeasurementTask.contract_id … -
Mongo db gets truncated frequently
Django version 3.0.5 mongo version 4.4.6 settings.py DATABASES = { 'default': { 'ENGINE': 'djongo', 'ENFORCE_SCHEMA': True, 'NAME': 'cpv', 'HOST': 'xx.xx.xx.xxx', 'PORT': 27017, 'USER': 'username', 'PASSWORD': 'password', 'MONGO_AUTH_SOURCE': "admin" } } When I enable authorization in mongod.conf security: authorization: "enabled" And try to migrate I am getting below error pymongo.errors.OperationFailure: command listCollections requires authentication, full error: {'ok': 0.0, 'errmsg': 'command listCollections requires authentication', 'code': 13, 'codeName': 'Unauthorized'} -
Django imagefield don't shows on template
i've a model with an imageField and when i upload file works and in database adds file path to img field but when i try call it in my template seem is always empity item.img instead other fields works well, to show it i use a listview model def content_file_name(instance, filename): ext = filename.split('.')[-1] # filename = "%s_%s.%s" % (instance, instance.questid.id, ext) return f"uploads/items/{instance.id}.{ext}" class Item(models.Model): type = models.IntegerField(choices=TYPE, blank=False, default=NO_CAT) name = models.CharField(max_length=250 ) description = models.CharField(max_length=250, blank=True ) img = models.ImageField(upload_to=content_file_name, blank=True) tags = models.ManyToManyField(Tag, through='Item_Tags') author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING) active = models.BooleanField(default=False) created = models.DateTimeField(default=timezone.now) updated = models.DateTimeField(auto_now=True) def __str__(self): #metodo righiesto return self.name my template <div class="card-columns"> {% for item in page_obj %} <div class="card"> {% if item.img %} <img class="card-img-top" src="{{item.image.url}}" alt="Card image cap"> {% else %} NO image {% endif %} <div class="card-body"> <h5 class="card-title">{{item.name}}</h5> <p class="card-text">{{item.description}}</p> <p class="card-text"><small class="text-muted"></small></p> </div> </div> {% endfor %} </div> -
count hours of a week depending on a given date django
I have a model that has 2 fields: a date as a Datefield and hours as a Decimalfield, and a form in which the user input a date. I want to count the hours in the week based on the input date. -
How do I display subcategories in the Django admin based on the selected category?
i am new at django, and i am doing online store, and i want to create items by using admin panel. When i choose main category for item and tried to choose sub i see nothing. I tried ChainedForeignKey my model from django.db import models from smart_selects.db_fields import ChainedForeignKey class Collection(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(max_length=255, unique=True) def __str__(self): return self.name class Category(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(max_length=255, unique=True) collection = models.ForeignKey(Collection, on_delete=models.CASCADE) def __str__(self): return self.name class Item(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(max_length=255, unique=True) collection = models.ForeignKey(Collection, on_delete=models.CASCADE) category = ChainedForeignKey(Category, chained_field='category', chained_model_field='collection') description = models.TextField(blank=True) size = models.CharField(max_length=255) price = models.PositiveIntegerField() image = models.ImageField(upload_to='photos/%Y/%m/%d/') def __str__(self): return self.name -
how to subtract from DateTimeField to DateField in Django
.annotate(gap=ExpressionWrapper(F('create_date') - F('register_date'), output_field=DurationField() As the title suggests, is it impossible to operate on two fields DateField and DateTimeField in Django? When I google and calculate when the db models type is different, I said that expressionwrapper can be used. When I wrote the code and ran it, 'gap': datetime.timedelta(0) is output. For reference, create_date is the date created when data is added and is in datetime format. register_date is a date format of yyyy-mm-dd format entered by selecting a date from the calendar. Is there any way to count both fields? -
General delete view in django gives error after slugify urls
I am getting error on delete view Generic detail view ItemDeleteView must be called with either an object pk or a slug in the URLconf. URL: path('item/<slug:item_slug>/remove', ItemDeleteView.as_view(), name='item_delete'), VIEW: class ItemDeleteView(DeleteView): model = Item template_name = 'waqart/item_delete.html' success_url = reverse_lazy TEMPLATE: <a class='text-blue-500 text-xs' href="{% url 'item_delete' item.slug%}">Delete this Post</a> -
Schedule a job to run after 30 seconds using Django-rq
I'm trying to implement the django-rq since I have some scraping that sometimes fails and has to be scheduled to run again after, say, 30 seconds. As far as I understand, I push a job the queue by django_rq.enqueue(scrape_func, foo, bar=baz) is there a way to push it to the queue and give it A timestamp to run (like Airflow) e.g 0 01 * * * or a time-delay before run (e.g 30 sec) -
Database contents not showing up after render
So, I try to display a list of items from database, but after calling return render(...) it behaves as if there were no objects in the database. I am new to django and after a second day of trial and error I have no idea what to do with it Affected view: class DropDownList(ListView): context_object_name = 'drop_down' template_name="browse.html" model=ServiceList asd = '' def post(self, request): name = request.POST.get('selected') obj = ServiceList.objects.get(sourceFile=name) print(obj) print(request.POST) #some prints for debugging context = {'asd': obj} return render(request, self.template_name, context) Models: class ServiceList(models.Model): version = models.IntegerField() location = models.CharField(max_length=500) services = models.ManyToManyField(Service) drms = models.ManyToManyField(Drm) sourceFile = models.CharField(max_length=500) class Service(models.Model): uid = models.CharField(max_length=255, unique=True) locations = models.ManyToManyField(Location) names = models.ManyToManyField(Name) category = models.CharField(max_length=500) drm = models.CharField(max_length=500) description = models.CharField(max_length=500) html fragment: <p> <br/> <form action="/browse/" id="tableform" method="POST">{% csrf_token %} <select class="form-select" aria-label="Default select example" form="tableform" name="selected"> <option selected>-----------------</option> <option >One</option> <option >Two</option> <option >Three</option> {% for obj in drop_down %} <option name={{obj.sourceFile}}>{{obj.sourceFile}}</option> {% endfor %} </select> </form> <button id="add-list" type="submit" class="btn btn-success pull-left" class="button1" form="tableform">+</button> </p> <table class="table table-bordered table-dark"> <tr> <th>UID</th> <th>Category</th> </tr> {% for obj in drop_down %} adasdasd {% if obj.sourceFile == asd %} <br/>fghfghfgh {% for service in obj.services.all %} <tr> … -
Django bulk_create ignoring foreign key integrity errors
I am using django with an sqlite database and I need to load entries from a json file. Since there are a lot of entries (190 mil) I have to use the bulk_create. Unfortunately we have only an incomplete database, so sometimes values should be inserted into a Many To Many relation for which there is no matching foreign key. In this case I get the following error: django.db.utils.IntegrityError: The row in table 'projects_paper_citing_literature' with primary key '1' has an invalid foreign key: projects_paper_citing_literature.to_paper_id contains a value '90241d37be4b06dd9b2f4ee4cf8de9089d7ea9ce' that does not have a corresponding value in projects_paper.paper_id. I found out that some other errors can be solved with ignore_conflicts=True. However, this does not apply to these errors: see my code below. Unfortunately, due to the high number of entries, it is also impossible/way to slow to check with filter() before each insertion if the two entries really exist. My code to read the database in is: def load_citations(paper_json_entries: List[Dict[str, any]]): paper_cites_paper_relationship = Paper.citing_literature.through citations: List[paper_cites_paper_relationship] = [] for paper_json in paper_json_entries: base_paper_id: int = paper_json['id'] for citation_id in paper_json['outCitations']: new_citation: paper_cites_paper_relationship = paper_cites_paper_relationship( from_paper_id=base_paper_id, to_paper_id=citation_id) citations.append(new_citation) paper_cites_paper_relationship.objects.bulk_create(citations, ignore_conflicts=True) -
Do I use the same database for Django-RQ as for my Django-project?
I'm trying to implement django-rq in my Django-project. In my settings.py I need to include some back-end informations (taken from the guide) RQ_QUEUES = { 'default': { 'HOST': 'localhost', 'PORT': 6379, 'DB': 0, 'PASSWORD': 'some-password', 'DEFAULT_TIMEOUT': 360, }, 'with-sentinel': { 'SENTINELS': [('localhost', 26736), ('localhost', 26737)], 'MASTER_NAME': 'redismaster', 'DB': 0, 'PASSWORD': 'secret', 'SOCKET_TIMEOUT': None, 'CONNECTION_KWARGS': { 'socket_connect_timeout': 0.3 }, }, 'high': { 'URL': os.getenv('REDISTOGO_URL', 'redis://localhost:6379/0'), # If you're on Heroku 'DEFAULT_TIMEOUT': 500, }, 'low': { 'HOST': 'localhost', 'PORT': 6379, 'DB': 0, } } I'm completly new to Redis and job-queing, so I wonder, if I just should use the same credentials as for DATABASES i.e using the same database as for my models, or is it best-practice to have a different database for the queing? If that has any impact, my database for Django is a PostgreSQL at Google SQL-server. -
This site can’t be reached - django setup
I'm starting working with django and try to setup new project and after the command "py manage.py runserver" Everything working and I get this address http://127.0.0.1:8000/ and when I try to enter this address I get that message " This site can’t be reached127.0.0.1 refused to connect". What I need to fix ? Thanks -
Which model shall be used by using() in django when there are two models with same name and different apps in the same db?
I have defined a model MyUser in two apps(let's say A and B) in different projects in django with the same DB(CAP_db). The second project uses more than one DB. So, when querying the model MyUser in one of its apps, I am using the statement : ambassador = MyUser.objects.using('CAP_db').get(code=code). By default, Django is creating the two tables a_myuser and b_myuser for the model from the two different apps. Is there any way to direct the query from one particular table( from the different project i.e. a_myuser)? Note: The model doesn't contain any foreign key nor is used as a foreign key in any other model. Also, the views.py for the query doesn't import any models from any app. -
Cannot render the details saved in database to another app in same project
This is my HTML File in where I am trying to render the details of the AffProduct Model which has been saved and created in another app inside the project named: affiliation. I am using from affiliation.models import AffProduct to import the details of the product in which the details have been saved. But the details is not rendering and also showing no error. <!-- Start of Online Shopping Part--> <h1>I-Frame</h1> <iframe height="75%" id="encoder_iframe" src="{% url 'blink_network' %}" width="50%"> </iframe> <div class="a-section a-spacing-none"> <div class="a-row"> {% for rows in resulted %} <div class="a-column a-span12"> <div class="a-section a-spacing-medium"> <a class="a-color-base a-link-normal" href=””></a> <div class="a-row"> <a class="a-color-base a-link-normal" href=""> <div class="a-column a-span4 a-text-center"> <img alt="X" src="{{rows.img1.url}}"> </div> </a> <div class="a-column a-span8 a-span-last"><a class="a-color-base a-link-normal" href=””> <div class="a-section a-spacing-none"> <span class="a-size-base-plus a-color-base a-text-bold" dir="auto">{{rows.product_title}}</span> </div> <div class="a-section a-spacing-none apb-browse-searchresults-mobileproduct-byline"> <span class="a-size-small a-color-secondary a-text-normal" dir="auto">ID: {{rows.uid}}</span> </div> <div class="a-section a-spacing-none a-spacing-top-micro"> <i class="a-icon a-icon-star-small a-star-small-4"></i> <span class="a-size-small a-color-secondary" dir="auto">14,464</span> </div> </a> <div class="a-section a-spacing-none a-spacing-top-micro"> <a class="a-color-base a-link-normal" href=""> <span class="a-price" data-a-color="base" data-a-size="l"><span class="a-offscreen">₹{{rows.sale_price}}</span><span aria-hidden="true"><span class="a-price-symbol">₹</span><span class="a-price-whole">{{rows.sale_price}}<span class="a-price-decimal">.</span></span></span></span> <span class="a-price a-text-price" data-a-color="secondary" data-a-size="b" data-a-strike="true"><span class="a-offscreen">{{ rows.discount }}</span><span aria-hidden="true">{{ rows.discount }}</span></span> <b>FREE Delivery.</b> </a> <a href=" ">Details</a> </div> <div class="a-section a-spacing-none a-spacing-top-micro"> Delivery By: <b>July … -
Django/Postgres integration issues
whenever i try to integrate the postgres database into my django application to deploy on heroku. It continues to display this error despite the correct integration made on the settings.py. how do i fix this? File "/home/tochikaze/Projects/b-aid/env/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: cannot cast type timestamp with time zone to interval LINE 1: ...LUMN "last_login" TYPE interval USING "last_login"::interval -
Django - Giving "a bytes-like object is required, not 'dict'" error while trying to create manual jwt token function
I need to create custom JWT token creator. When I want to test it with dump data it gives this error. All I need is return a json web token. I am new to Django and Python. I partially understand the problem but can't relate. I'm struggling with data types while working on them. I tried to convert token variable into different data type but didn't work. https://dpaste.com/B9K9KWP27 Here is my codes def base64url_decode(input: Union[str, bytes]) -> bytes: if isinstance(input, str): input = input.encode("ascii") rem = len(input) % 4 if rem > 0: input += b"=" * (4 - rem) return base64.urlsafe_b64decode(input) def base64url_encode(input: bytes) -> bytes: return base64.urlsafe_b64encode(input).replace(b"=", b"") def jwt_creator(expiration, userid, userrole): header = { "alg": "HS256", "typ": "JWT" } payload = {'expired': expiration, 'userid': userid, 'userrole': userrole } secret_key = secrets.token_hex(32) userauth =User_Tokensec(iduser_tokensec=userid, key=secret_key, personal_id=Personal.objects.get(id=userid)) userauth.save() total_params = base64url_encode(header) + '.' + base64url_encode(payload) signature = hmac.new(secret_key, total_params, hashlib.sha256).hexdigest() token = total_params + '.' + base64url_encode(signature) context3 = {'jwt': token, 'title': 'jwtt'} return context3 def jwt_decoder(jwt): input = jwt.split(".") payload = base64url_decode(input[1]) secret_key = User_Tokensec(personal_id=payload['userid']) header = { "alg": "HS256", "typ": "JWT" } total_params = base64url_encode(header) + '.' + base64url_encode(payload) signature = hmac.new(secret_key, total_params, hashlib.sha256).hexdigest() token = total_params … -
I have this error in my project, how can i rectify this error? How can i add jinja template extention in my visual studio 2019?
{% extends 'base.html' %} 2 3 {% block content %} 4 5 Hello {{name}}!!!!! 6 7 8 {% csrf-token %} 9 10 Enter 1st number= 11 Enter 2nd number= 12 13 14 15 {% endblock %} -
i want to handle multiple manytomanyField in django but i got different types of error
I want to handle multiple manytomanyField in Django but I got different types of error. I use json response for save the data .but i got different errors like invalid literal for int() with base 10 , and other function savecontract(){ allowance = $('#allowance').val(); var data = new FormData(); data.append("allowance", allowance) var r = false; $.ajax({ type: 'POST', contentType: "application/json; charset=utf-8", contentType: false, processData: false, url: '/Employee/savecontract/', data: data, async: false, success: function (response) { if(response.status == "success"){ $('#cid').val(response.id) r=true; } else{ swal("Error","Something Went Wrong!","error") } }, error: function () { swal("Error","Something Went Wrong!","error") } }); return r; } }); {% for d in allowance %} <input value="{{d.id}}" type="checkbox" class=" " name="{{allowance.enName}}" id="allowance" style=" zoom: 1.5;"> {{d.enName}}<br> {% endfor %} models.py class allowances(models.Model): enName = models.CharField(max_length=200, blank=True, null=True) company = models.ForeignKey(Company, on_delete=models.CASCADE) class CreateContracts(models.Model): allowance = models.ManyToManyField(allowances) views.py def savecontract(request): uid = request.session["userid"] e = Employees.objects.get(user=uid) allowance = [x.enName for x in allowances.objects.filter(company=e.company)] allowance_id=[] for x in allowance: allowance_id.append(int(request.POST.get(x))) if request.POST.get(x) else print("Error") for x in allowance_id: contract.allowance.add(allowances.objects.get(id=x)) contract.save() res = {"status": "success"} return JsonResponse(res)