Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Does not understanding what does the Operating system security website means?
For the FYP of Operating System subject , i create the django website buy domain from namecheap use Heroku for hosting and SSL . But my teacher is saying something different which i'm not getting what he want me to build read the email of my teacher kindly guide me what i have to build to show him the email : Unfortunately i do not see your project satisfying the requirements of the OS security project.i understand u worked hard building the web Application using django .However the project was not to build the web application alone ,it was to build install the OS the entire web application slack and then use SSL, in addition it was to build the certificate Authority from what i can see, You used the django web framework on a heroku service (with all the slack pre -installed ). -
FiedDoesNotExist with ManytoMany field
I have an issue while running migrations, I get this error : django.core.exceptions.FieldDoesNotExist: Profile has no field named 'following yet I have defined the field in my model, what could be the issue ? below is my model : class Profile(TimeStampedModel, models.Model): last_name = models.CharField(_('Last Name'), max_length=150, null=True, blank=True) gender = models.CharField(_('Gender'), null=True, max_length=30, choices=GENDER_CHOICES, blank=True) following = models.ManyToManyField(User, related_name='following', default=None, blank=True) What could be the issue ? -
How to show all objects by one on one page?
I am doing quiz app. I want questions to appear on one page but by one. For example, we have 5 questions. I see the first of them, answer this and only after that I can see the next one and the previous one disappears. How to do it? Plz I need help. It is really important. Thanks everyone! -
How to build sass files with django
I'm completly new with Django and python (and alone as tech in my company, not able to ask help to previous dev). I have to maintain an existing app written in django still developing new services fully written in node, which is my most important task (and my skills). I have a problem that i have fixed some bugs in UX, fixing CSS mostly. And I don't understand how to build sass. In manage.py, when i ask the list of commands the only things which is related to my problem is "collectstatic" which seems to not build but just collect static files (good naming so) in one folder. And obviously, it doesn't resolve my problem. Any suggestion ? I'm lost in this big new thing. Many love on every body who can help me. Do you know if there is an integrated tool ? Do i need to use an external compiler which is just not documented ? -
Filter doesn't work with prefetch_related_objects - Django
I'm trying to write a view that prefetch its request content so I can speed up the request execution (3.5s instead of 3min when chaining requests). The goal is to fetch some rows (Exchange_pair objects) depending on a root model value in the prefetch path (connection.exchange_id). connections__wallets__currency__base_pairs ^ | |_______________________________| depends on the current connection's exchange_id View: @api_view(['GET']) @permission_classes([permissions.IsAuthenticated]) def get_portfolio_view(request): portfolio_id = request.GET.get('id') # get portfolio + prefetch connections (and other things...) portfolio = Portfolio.objects.prefetch_related( 'connections__exchange', 'connections__wallets__currency__metadata__images' ).get(id=portfolio_id) for connection in portfolio.connections.all(): # build filter pairs_queryset = ExchangePair.objects.filter( exchange_id=connection.exchange_id, quote_id__in=["825", "2781", "3408", "4687"], last_price__isnull=False, ) # prefetch for related connection prefetch_related_objects( [connection], Prefetch('wallets__currency__base_pairs', queryset=pairs_queryset) ) data = PortfolioSerializer(portfolio).data return Response(data) Models: class Connection(models.Model): exchange = models.ForeignKey(Exchange, related_name='exchange', on_delete=models.CASCADE) portfolios = models.ManyToManyField(Portfolio, related_name='connections') # ... class ExchangePair(models.Model): id = models.IntegerField(primary_key=True) # CoinMarketCap id exchange = models.ForeignKey(Exchange, related_name='pairs', on_delete=models.CASCADE) # ... The code works in 90% of the cases. But in some cases: the queryset filter doesn't work and it retrieves ExchangePair objects with the wrong exchange_id. This makes no sense to me, I can't figure it out, seems like prefetch_related_objects() contains a bug. -
How to provide a source directory in the [tool.django-stubs] directive of a pyproject.tom file?
I'm using a src directory as root source directory in my django projects. I'm trying to perform pre-commit actions on those django projects, with mypy and django-stubs. Is is a way to say in pyproject.toml than the source root is in src/ ? For now, I've: [tool.django-stubs] django_version = "3.2" django_apps = ["account", "seniors", "seniors_app"] django_settings_module = "seniors.settings.dev" ignore_missing_settings = true ignore_missing_model_attributes = true pre-commit run --all ... ModuleNotFoundError: No module named 'seniors' When I put django_settings_module = "src.seniors.settings.dev", I've some errors later on importing the other modules ( account...) Have you any ideas ? For sure I don't want to change my project layout ! Thanks ! -
Bootstrap 5 site header works on desktop but not on mobile
I am following the great Django series by Corey Schafer (https://www.youtube.com/playlist?list=PL-osiE80TeTtoQCKZ03TU5fNfx2UY6U4p). Given that Bootstrap 5 has emerged since it's creation, i'm attempting to utilize it for my modified creation. The problem I am finding is that the header below is functioning properly desktop site (note: I've only activated the register.html link so far as I progress through the course), but the "hamburger" that should be created is inactive and unclickable on the mobile site. Here is the relevant file creating the header: base.html {% load static %} <!DOCTYPE html> <html> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'The6ixDjango/main.css' %}"> {% if title %} <title>{{ title }}</title> {% else %} <title>The6ixClan</title> {% endif %} </head> <body> <header class="site-header"> <nav class="navbar navbar-expand-md navbar-dark bg-steel fixed-top"> <div class="container"> <a class="navbar-brand mr-4" href="{% url 'The6ixDjango-home' %}">The6ixClan</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggle" aria-controls="navbarToggle" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarToggle"> <div class="navbar-nav mr-auto"> <a class="nav-item nav-link" href="{% url 'The6ixDjango-home' %}">Home</a> <a class="nav-item nav-link" href="{% url 'The6ixDjango-about' %}">About</a> </div> <!-- Navbar Right Side --> <div class="navbar-nav"> <a class="nav-item nav-link" href="#">Login</a> <a class="nav-item nav-link" href="{% … -
File not in request.FILES but in request.POST I'm using htmx to make post request
I have snippet of inputs that I render to the html page when a condition is met, everythings works appropriately except for the input with type file, I want to upload the files when a change has occured but the file object is not in request.FILES, it's in request.POST now I don't mind it being request.POST but the files is displayed as 'multiple': ['[object File]'] My partial template <div class="my-2"> <div id="uploaded"></div> <p class="lead">{{question.prompt}}</p> <input name="multiple" type="file" accept="image/*, .pdf" id="image_{{question.id}}" {% if question.required %}required{% endif %} {% if question.disabled %}disabled{% endif %} class="form-control" placeholder="{{question.placeholder}}" hx-post="{% url 'survey:file_multiple' %}" hx-trigger="change"> <input type="hidden" name="filemultipleId" value="{% if question.form_input_type == 'file-multiple' %}{{question.id}}{% endif %}"> </div> I am not rendering the form with django form as it will be difficult and near impossible to achieve the dynamicity I am looking for request.POST QueryDict <QueryDict: {'csrfmiddlewaretoken': ['TiLZFEWw88cqItD8MABv6lZKYDrNaVxGF4ZMDOV3sK43540z6uOcrx5uQO6iYldA', 'date': [''], 'dateId': ['20', '5'], 'multiple': ['[object File]'], 'filemultipleId': ['18'], 'fileId': ['17']}> Traceback Internal Server Error: /file-multiple/ Traceback (most recent call last): File "/home/tomms/.local/share/virtualenvs/web-app-QB9eq0sY/lib/python3.9/site-packages/django/utils/datastructures.py", line 83, in __getitem__ list_ = super().__getitem__(key) KeyError: 'multiple' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/tomms/.local/share/virtualenvs/web-app-QB9eq0sY/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/tomms/.local/share/virtualenvs/web-app-QB9eq0sY/lib/python3.9/site-packages/django/core/handlers/base.py", line … -
Deploy Django app with Nginx, Gunicorn, uvicorn, PostgreSQL
My app works on development mode (I run from a container with specified variable RTE=dev docker-compose up) I need to deploy the app to my domain and I have all settings in place for it (Nginx, Gunicorn, uvicorn, PostgreSQL). When I docker-compose up in Production mode I do not get any errors and I can't seem to find out where the issue is. settings.py class RuntimeEnvironment(Enum): """docstring: environment variables""" dev = 1 test = 2 prod = 3 RTE = RuntimeEnvironment[os.environ['RTE']] (...) if RTE is RuntimeEnvironment.dev: SECRET_KEY = 'django-insecure-l)lj4%c6(3v5r!0b9eac&0%%_500%ct4x1nbf5j5qsarmtn0#d' else: SECRET_KEY = os.environ['DJANGO_SECRET_KEY'] (...) if RTE is RuntimeEnvironment.dev: DEBUG = True ALLOWED_HOSTS = [] else: DEBUG = False ALLOWED_HOSTS = ['pbstyle.dk', 'https://pbstyle.dk/'] nginx.conf upstream app_upstream { server app:8080; } server { listen 80; listen 443; server_name pbstyle.dk; location /static/ { alias /static/; } location /media/ { alias /media/; } location / { proxy_set_header Host $host; proxy_pass http://app_upstream; } } docker-compose version: "3.8" services: db: image: postgres:13-alpine volumes: - db_data:/var/lib/postgresql/data - ./dbscripts/:/dbscripts/ env_file: - db_${RTE}.env app: build: . ports: - 8000:8000 - 8080:8080 env_file: - db_${RTE}.env volumes: - .:/app/ - static:/static/ - media:/media/ depends_on: - db nginx: build: nginx/ ports: - 443:443 - 80:80 volumes: - ./ngin/${RTE}/conf.d/:/etc/nginx/conf.d/ - ./certs/:/etc/letsencrypt/ - static:/static/ … -
Django is not recongizing a users password when login is attempted
When trying to create a simple web page with login and sign up i ran into the issue of django not recognzing the created user. In views.py i created a simple message that displays "Incorrect password or email" if user does not exist. I created a user and made sure that the password was correct when i inputed it into the login form however it still gave me the message of "Incorrect password or email". Instead of redirecting to home like a created user should it errored and i could not figure out why it is not accepting the password/email in the form. views.py from django.shortcuts import redirect, render from django.contrib.auth import authenticate, login, logout from django.contrib import messages from django.contrib.auth.models import User def home(request): return render(request, 'home.html') def signup(request): if request.method == "POST": email = request.POST['email'] password = request.POST['password'] myuser = User.objects.create_user(email, password) myuser.email = email myuser.password = password myuser.save() messages.success(request, "Your account has been successfully created ") return redirect('signin') return render(request, 'signup.html') def signin(request): if request.method == "POST": email = request.POST['email'] password = request.POST['password'] user = authenticate(request, email = email, password = password) if user is not None: login(request, user) email = user.email messages.success(request, "Successfully Logged In") return … -
Page not found, my template is there but I see an Page Not Found error
I saw different Q&A about this error, but I couldn´t find one similar to my case. I´m trying to create "read templates" from two classes, but I can´t. I already created the views and the models, but the templates don´t work. views: def readCoberturas(request): cobert = Coberturas.objects.all() dicCoberturas = {"Coberturas": cobert} return render(request, "AppURC/readCoberturas.html", dicCoberturas) Model (Coberturas): class Coberturas(models.Model): tipo = models.CharField(max_length=20) numeroPoliza = models.IntegerField() fechaContratacion = models.DateField() fechaVigencia = models.DateTimeField() detalle = models.CharField(max_length=40) def __str__(self): return f"Tipo de Cobertura: {self.tipo} | Poliza n°: {self.numeroPoliza} | Fecha alta: {self.fechaContratacion} | Vigencia hasta: {self.fechaVigencia} | Detalle: {self.detalle}" Url: path('readCoberturas/',views.readCoberturas, name='ReadCoberturas'), Template: {% load static %} {% block contenido %} {% for C in Coberturas %} <li>{{ c }}</li> {% endfor %} {% endblock %} I hope I have made this sufficiently clear. Thanks to all! -
Django - See exact value of foreign key import export
I have some models and some foreign keys assigned to them. What I want is to get the Foreign keys exact content rather than the ID of the foreign key. What I can do ? my models from django.db import models class MonkAttributes(models.Model): id = models.AutoField(primary_key=True) head = models.CharField(max_length=55) cloth = models.CharField(max_length=55) mouth = models.CharField(max_length=55) skin = models.CharField(max_length=55) eyewear = models.CharField(max_length=55) background = models.CharField(max_length=55) class MonkFiles(models.Model): id = models.AutoField(primary_key=True) uri = models.CharField(max_length=255) type = models.CharField(max_length=25) class MonkCreators(models.Model): id = models.AutoField(primary_key=True) address = models.CharField(max_length=255) share = models.IntegerField() class MonkProperties(models.Model): id = models.AutoField(primary_key=True) files = models.ForeignKey(MonkFiles, on_delete=models.CASCADE) category = models.CharField(max_length=55) creators = models.ForeignKey(MonkCreators, on_delete=models.CASCADE) class MonkDetailsModel(models.Model): id = models.AutoField(primary_key=True) dna = models.CharField(max_length=25) name = models.CharField(max_length=50) symbol = models.CharField(max_length=10) description = models.CharField(max_length=255) seller_fee_basis_points = models.IntegerField() image = models.CharField(max_length=255) external_url = models.URLField() attributes = models.ForeignKey(MonkAttributes, on_delete=models.CASCADE) properties = models.ForeignKey(MonkProperties, on_delete=models.CASCADE) def __str__(self): return self.name or '' exported json file is like this: I want to get the exact content of attributes and properties [ { "id": 1, "dna": "010001001110", "name": "Decentralized Monks Test Item", "symbol": "SYM", "description": "This image shows the true nature of Monks.", "seller_fee_basis_points": 100, "image": "https://ipfs.io/ipfs/QmNjsxLtyK5ZpmoyZFaPKFTXeDAmGQDq2vSSCfNXA279SB", "external_url": "http://0xmonks.com", "attributes": 1, "properties": 1 } ] -
Production web app - Django with Djongo or Flask with Mongo?
I am working on a new web app that will store data about transactions of multiple companies. As companies from various industries sell various products they need different columns (attributes) to describe each product. For example, food products require Best before date column, but books don't require it and instead they need Author and Genre columns. My way of thinking is that it is hard and inefficient to store this kind of data in relational, SQL database. Instead, I think that NoSQL such as MongoDB will be perfect for this case. Please correct me if I'm wrong. My question is: for such web app, which from the below options should I use? Django app with Djongo, which is an unofficial connector between Django and MongoDB Flask with MongoEngine Flask with PyMongo Other NoSQL technology. Maybe NoSQL is a bad choice in my case and should be avoided? My concerns are: Not sure if Djongo should be used in production, as support for it can be dropped any time (I expect this web app to last a few years) and I don't know if Djongo is reliable Not sure if Flask isn't too 'poor' and 'simple' for an app that is … -
Annotate QuerySet with the maximum of a date field and a manually created date
I have the following model: class Item(models.Model): last_used = models.DateTimeField() created_at = models.DateTimeField() I'm trying now to look at the average "lifetime" of items per month. Lifetime is how many days items are used, on average. I can calculate the overall average with the following: from django.db.models import IntegerField, F, Avg from django.db.models.functions import Cast, ExtractDay, TruncDate items = Item.objects.annotate(days_used=Cast(ExtractDay(TruncDate(F('last_used')) - TruncDate(F('created_at'))), IntegerField())+1) avg = items.aggregate(Avg('days_used'))['days_used__avg'] Now when I want to calculate this per month, I would like to annotate the query with a new field that is the maximum of created_at or the beginning of the month in question. This is needed so that the maximum lifetime value for all months is the number of days in that month. There's a function, Greatest that I think could be used for this, but I'm not sure how. Assuming we're interested in December, 2021, this is what I have at the moment: target_month = 12 items = items.annotate(created_max=Greatest(TruncDate(F('created_at')), TruncDate(F(timezone.datetime(2021, target_month, 1))) But using timezone.datetime is causing an error: AttributeError: 'datetime.datetime' object has no attribute 'split' NOTE: I'm aware that last_used may cause the value to go over the number of days but that's another issue we're tackling. -
How to get around the django Error : raw query must include primary key
Is there a way to run a query on Django without using the Primary key of the table? in the following code, I have a query that, at least I think, must be used only with SELECT DISTINCT p.type without adding the primary key of the table - in this case, the PK is NAME. Every time I run the code I get the same Error - raw query must include primary key is there a way to get around that? Code: def Query_result(request): AttackThreshold_res = request.POST.get('AttackThreshold') PokemonCount_res = request.POST.get('PokemonCount') sql_threshold_res = Pokemons.objects.raw(""" SELECT DISTINCT p.type FROM pokemons p INTERSECT SELECT DISTINCT p1.type FROM pokemons p1 WHERE p1.attack > %s INTERSECT SELECT DISTINCT p2.type FROM pokemons p2 GROUP BY ( p2.type ) HAVING Count(p2.type) > %s """, [AttackThreshold_res, PokemonCount_res]) return render(request, 'queries.html', {'sql_threshold': sql_threshold_res}) -
Django Stripe Invalid signature Azure Deployment
I'm trying to deploy a Django(3.2.9) app with payments using Stripe(2.61.0). Works well using the Stripe CLI locally. But soon as I deploy on Azure and try to a test mode webhook to test if it's working properly I keep receiving the result of been Invalid. I've made tests about if it's different webhook secret when deploy in anyway but the result is that the one on Stripe Dashboard. I wanna know if there's any possibility I'm oblivious to this issue? -
Django model related to self
How to create object to object relation suchwise that when i add this relation to parent and relaton to child added automatically? class Object(models.Model): name = models.CharField(max_length=150) description = models.TextField(blank=True) is_published = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) relation = models.ForeignKey('self', related_name="related", on_delete=models.DO_NOTHING, blank=True, null=True) def __str__(self): return self.name When I appoint some relation in django-admin for example to 'Spider Man' object related to 'Peter Pen' object I don't have relation 'Peter Pen' -> 'Spider Man' when I open 'Peter Pen' object -
Django models: How do I check that a decorartor property exists
I have a Profile model with a decorator property @property def primary_phone(self): When I query for the primary phone for a given id like this it works x = Profile.objects.get(id=3) x.primary_phone outputs Out[3]: '+256771000022' However filtering for the same like this Profile.objects.filter(primary_phone="+256771000022").exists() outputs FieldError: Cannot resolve keyword 'primary_phone' into field. Choices are: _created_at, _modified_at, apierror, business,...) -
django how to create object and add many to many best way or best practice
how can I make this code much more effective or faster def handle(self, *args, **kwargs): shops = MyShop.objects.all() for shop in shops: month_invoice = shop.shop_order.annotate(year=TruncYear('created'), month=TruncMonth('created')).values( 'year', 'month', 'shop_id' ).annotate(total=Sum(ExpressionWrapper( (F('item_comission') / 100.00) * (F('price') * F('quantity')), output_field=DecimalField())), ).order_by('month') for kv in month_invoice: a = ShopInvoice.objects.create(shop_id=kv['shop_id'], year=kv['year'], month=kv['month'], total=kv['total']) test = shop.shop_order.filter(created__month=kv['month'].month, created__year=kv['year'].year) for t in test: a.items.add(t.id) -
I am getting "token_blacklist.0008_migrate_to_bigautofield...Not implemented alter command for SQL ALTER TABLE "token_blacklist_blacklistedtoken"
Anyone please tell me what type of error is it? on django rest_framework I am getting this error after running "python manage.py migrate" I am using simple_jwt library for authentication and the migrations stop here Applying token_blacklist.0008_migrate_to_bigautofield...Not implemented alter command for SQL ALTER TABLE "token_blacklist_blacklistedtoken" ALTER COLUMN "id" TYPE long (env) D:\inductionplan\django-api\backend>python manage.py migrate Operations to perform: Apply all migrations: admin, api, auth, authtoken, contenttypes, sessions, token_blacklist Running migrations: Applying token_blacklist.0008_migrate_to_bigautofield...Not implemented alter command for SQL ALTER TABLE "token_blacklist_blacklistedtoken" ALTER COLUMN "id" TYPE long Traceback (most recent call last): File "D:\inductionplan\django-api\env\lib\site-packages\djongo\cursor.py", line 51, in execute self.result = Query( File "D:\inductionplan\django-api\env\lib\site-packages\djongo\sql2mongo\query.py", line 784, in __init__ self._query = self.parse() File "D:\inductionplan\django-api\env\lib\site-packages\djongo\sql2mongo\query.py", line 876, in parse raise e File "D:\inductionplan\django-api\env\lib\site-packages\djongo\sql2mongo\query.py", line 857, in parse return handler(self, statement) File "D:\inductionplan\django-api\env\lib\site-packages\djongo\sql2mongo\query.py", line 889, in _alter query = AlterQuery(self.db, self.connection_properties, sm, self._params) File "D:\inductionplan\django-api\env\lib\site-packages\djongo\sql2mongo\query.py", line 425, in __init__ super().__init__(*args) File "D:\inductionplan\django-api\env\lib\site-packages\djongo\sql2mongo\query.py", line 84, in __init__ super().__init__(*args) File "D:\inductionplan\django-api\env\lib\site-packages\djongo\sql2mongo\query.py", line 62, in __init__ self.parse() File "D:\inductionplan\django-api\env\lib\site-packages\djongo\sql2mongo\query.py", line 441, in parse self._alter(statement) File "D:\inductionplan\django-api\env\lib\site-packages\djongo\sql2mongo\query.py", line 500, in _alter raise SQLDecodeError(f'Unknown token: {tok}') djongo.exceptions.SQLDecodeError: Keyword: Unknown token: TYPE Sub SQL: None FAILED SQL: ('ALTER TABLE "token_blacklist_blacklistedtoken" ALTER COLUMN "id" TYPE long',) Params: ([],) Version: 1.3.6 The above exception was … -
how do i render text put into a django textfield with a its original format?
im building a site with django and i would like to output some text that I put into a text field from my model but when i do so in the html it loses all the form that i give it (spacing and new lines, etc.) does anyone have a solution?. so instead of coming out as: enter image description here it comes out as just a line without the proper spacing enter image description here -
How to get a user with 'django-microsoft-authentication' code?
I'm using the library django-microsoft-authentication. The application for microsoft was created, all the codes were received by me. I did everything according to the documentation. MICROSOFT = { "app_id": "<my app id>", "app_secret": "my app secret id", "redirect": "http://localhost:8000", "scopes": ["user.read"], "authority": "https://login.microsoftonline.com/common", "valid_email_domains": ["<list_of_valid_domains>"], "logout_uri": "http://localhost:8000/admin/logout" } Add 'microsoft_authentication' to INSTALLED_APPS LOGIN_URL = "/microsoft_authentication/login" LOGIN_REDIRECT_URL = "/admin" and urls.py from django.urls import path, include urlpatterns = [ ..... path('microsoft_authentication/', include('microsoft_authentication.urls')) ] And everything goes well, and without errors. I authenticate and get returned to the home page. But there is no new user in the admin area. Or I need to do create a new user manually? Or is callback not working? In my address bar I get some this: http://localhost:8000/?code=0.Awfwjhey79kyt4fe..........feky5hmj (random code). I understand that this is some kind of user token grant. According to the documentation, I checked the decorator @microsoft_login_required(), and it working when I was logged in, and it did not work when I was NOT logged in. So everything is going well. But I only get the code=..... above. But I don't see the user anywhere. How do I get a user? How do I create and save a user? Please, any help will … -
Django-taggit: how to save after adding tags in save()
def save(self, *args, **kwargs): super(Flow, self).save(*args, **kwargs) if self.pk: self.tags.add(str(date.today().year)) self.save() This doesn't work in my model Flow. How can I save the newly added tag into tags of my flow instance successfully? Thanks. -
making a new table in django for database by user from frontend
I am writing a web application by Django and Reactjs. It should be able that the user creates a new project in application with a specific name and, the project should have its table in the database. I need a tool to create a model and migrate it automatically in the database. -
ValueError: invalid literal for int() with base 10: in Django 3.0
I have updated my project from Django 1.8 to Django 3.0 Here when i am trying display items using autocomplete i am getting this error Here is my views.py def autocomplete_items(request, flag=None): client = request.user.client q = request.GET.get('term') category = request.GET.get('category', '') job_items = JobItems.objects.filter(client_id=client) if category: job_items = job_items.filter(category_id=category) if flag: job_items = job_items.filter(stock='Variety Master') else: if client.horticulture: job_items = job_items.exclude(stock='Variety Master') products = job_items.filter(Q(item_name__icontains=q)|Q(soil_type__icontains=q)|Q(height__icontains=q)|Q(pot_size__icontains=q)|Q(form__contains=q)|Q(unit_price__contains=q)|Q(supplier_one__supplier_name__icontains=q)|Q(part_number__icontains=q)|Q(batch_number__icontains=q),is_deleted=False, is_one_of_item=False) res = [] for c in products: #make dict with the metadatas that jquery-ui.autocomple needs (the documentation is your friend) dict = {'id':c.id, 'label':c.__str__()+ ' ('+ str(c.part_number)+')' if c.part_number else c.__str__() , 'label2':c.__str__()+ ' ('+ str(c.batch_number)+')' if c.part_number else c.__str__(), 'value':c.__str__(), 'partnumber': c.part_number} res.append(dict) return HttpResponse(json.dumps(res[:15])) Here is my models.py class JobItems(models.Model): description = models.TextField(blank=True) item_name = models.CharField(max_length=512) part_number = models.CharField(max_length=32, null=True, blank=True, verbose_name='Stock number') batch_number = models.CharField(max_length=200, blank=True, null=True) client = models.ForeignKey("core.Client", related_name="job_items",on_delete=models.CASCADE) is_deleted = models.BooleanField(default=False, help_text="Deleted tasks will not display in the UI.") is_checked = models.BooleanField(default=False, help_text="Save item into item details") created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) quantity = models.DecimalField( max_digits=10, decimal_places=2, default=0.00, verbose_name='Quantity In Stock') unit_price = models.DecimalField(null=True, max_digits=10, decimal_places=2, default=0.00, verbose_name='Retail price') def __str__(self): return self.item_name class Meta: ordering = ("quantity", ) here is my error traceback Traceback (most …