Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django How to get the value from many to many relationship
I have a product update form where I want to update the sizes of a product, with a many-to-many column relation. I am able to get the saved values but I can't get item ID or size. {{item.id}} shows empty value. {% for item in form.size.value %} <span> <input type="checkbox" name="size" id="{{ item.id }}" value="{{ item.id }}"> <label for="{{ item.id }}">{{ item }}</label> </span> {% endfor %} SIZE MODEL class Size(models.Model): identifier = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) size = models.CharField(max_length=200, unique=True, null=False, blank=False) active = models.BooleanField(default=True) date_created = models.TimeField(verbose_name='Date Created', auto_now_add=True) date_updated = models.DateTimeField(verbose_name='Last Updated', auto_now=True) PRODUCT MODEL class Product(models.Model): identifier = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) name = models.CharField(max_length=200, null=False, blank=False) slug = models.SlugField(max_length=30, unique=True) showcased = models.BooleanField(default=False) recommended = models.BooleanField(default=False) active = models.BooleanField(default=True) price = models.DecimalField(max_digits = 5, decimal_places = 2, null=True, blank=True) pagetitle = models.CharField(max_length=200, null=True, blank=True) shortDescription = models.CharField(max_length=200, null=True, blank=True) longDescription = HTMLField(null=True, blank=True) specifications = models.TextField(null=True, blank=True) features = models.TextField(null=True, blank=True) care = models.TextField(null=True, blank=True) category = models.ForeignKey(Category, on_delete=models.PROTECT) subCategory = models.ForeignKey(SubCategory, null=True, blank=True, on_delete=models.PROTECT) image = models.ManyToManyField(Image, blank=True) size = models.ManyToManyField(Size, blank=True) tag = models.ManyToManyField(Tag, blank=True) date_created = models.TimeField(verbose_name='Date Created', auto_now_add=True) date_updated = models.DateTimeField(verbose_name='Last Updated', auto_now=True) I have tried different ways but not had success in … -
Django setlang view does not exist - what could be the problem?
I want to create a button to choose between two languages, but when I'm clicking on it I am encountering error saying that view does not exist, what could be the problem? Error: DatabaseError at /en/i18n/setlang/ ORA-00942: table or view does not exist Template: {% get_current_language as LANG %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <form action="{% url '/i18n/' %}" method="post" id="form_{{ language.code }}" style="display:inline!important;"> {% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}" /> <input name="language" type="hidden" value="{{ language.code }}" /> </form> <button class="lang-button" type="submit" form="form_{{ language.code }}" value="Submit">[{{ language.code }}]</button> {% endfor %} URLS: urlpatterns = [ # url(r'', include('label_uwm.urls')), ] urlpatterns += i18n_patterns( url(r'', include('label_uwm.urls')), url(r'i18n/', include('django.conf.urls.i18n')), ) SETTINGS: LANGUAGE_CODE = 'pl' LANGUAGES = ( ('pl', _('Polish')), ('en', _('English')), ) TEMPLATE_CONTEXT_PROCESSORS = ( 'django.core.context_processors.i18n', ) MIDDLEWARE = ( 'django.middleware.locale.LocaleMiddleware', [...]) -
No module named 'imagekit' in django rest framework
i'm running into a very weird error in django rest framework. I tried all the solutions proposed in stackoverflow but nothing. the error: Traceback (most recent call last): File "C:\Users\User\Desktop\IVAN.ru\IVAN_backend\backend\manage.py", line 22, in <module> main() File "C:\Users\User\Desktop\IVAN.ru\IVAN_backend\backend\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\User\Desktop\IVAN.ru\IVAN_backend\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\User\Desktop\IVAN.ru\IVAN_backend\lib\site-packages\django\core\management\__init__.py", line 395, in execute django.setup() File "C:\Users\User\Desktop\IVAN.ru\IVAN_backend\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\User\Desktop\IVAN.ru\IVAN_backend\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\User\Desktop\IVAN.ru\IVAN_backend\lib\site-packages\django\apps\config.py", line 224, in create import_module(entry) File "C:\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'imagekit' please notice that i added 'imagekit' to installed apps , I uninstalled and reinstalled everything. but nothing worked for me. I installed django-imagekit and uninstalled Imagekit. i tried to replace 'imagekit' with 'Imagekit' . -
Django FormField: How to set `max_length` and other properties in a baseclass
I'd like to set label and max_length inside IBANField to generalize it and use it somewhere else. validate_iban is a validator function. Here is what I have now. It's ok, but not what I want. class IBANField(CharField): default_validators = [validate_iban] class SepaForm(forms.Form): iban = IBANField(max_length=34, label=_('IBAN')) -
Migration from bootstrap, django to react
I have a whole website build with frontend using bootstrap and backend with django and now i want to migrate the project to react as frontend by reusing as much as code possible. As i am new to react i am having a hard time to migrate the project. can anyone share some resources are sugestions. I am attaching my index.html for your reference. {% extends 'lab/navbar.html' %} {% load static %} {% block content%} <style> #newhr { border: 0; height: 1px; background-image: linear-gradient(to right, rgba(0, 0, 0, 0), rgba(0, 0, 0, 0.75), rgba(0, 0, 0, 0)); } #button { background-color: #1c87c9; border: none; color: white; padding: 20px 34px; text-align: center; text-decoration: none; display: inline-block; font-size: 20px; margin: 4px 2px; cursor: pointer; } </style> </head> <body> <!-- START carousel--> <div class="container"> <div class="carousel slide" id="main-carousel" data-ride="carousel"> <ol class="carousel-indicators"> <li data-target="#main-carousel" data-slide-to="0" class="active"></li> <li data-target="#main-carousel" data-slide-to="1"></li> <li data-target="#main-carousel" data-slide-to="2"></li> <!--<li data-target="#main-carousel" data-slide-to="3"></li>--> </ol><!-- /.carousel-indicators --> <div class="carousel-inner"> <div class="carousel-item active"> <img class="d-block img-fluid" src="{% static 'lab\images\carousel_photos\Figure_Transl-Bioinfo_home.jpg' %}" alt=""> <div class="carousel-caption d-none d-md-block"> <h3 style="color: white;">Biomaterial</h3> <p>We develop innovative biomaterials that can be used to <br> treat injuries or replace damaged tissues.</p> </div> </div> <div class="carousel-item"> <img class="d-block img-fluid" src="{% static 'lab\images\carousel_photos\dna.jpg' … -
Django-Q does not kill old threads and CPU raises 100%
I'm deploying Django-Q on a production server using a systemd service like below: [Unit] Description=Django-q management service After=network.target [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/api $e/ubuntu/.virtualenvs/env/bin/python manage.py qcluster Restart=always [Install] WantedBy=multi-user.target Every time qcluster starts a thread (about 8.5% CPU), the old ones does not die and CPU raises 100%. PD: The problem is also happening if I run qcluster directly on the terminal. -
What data format is this in google gantt chart? How can I return a format like this in Django?
I'm trying to integrate the google Gantt chart into my Django project, there's a model for tasks, the model has 2 date fields already, one is a start date and another is the due date. I tried to understand the data format the google chart requires, it was like ['Research', 'Find sources', new Date(2015, 0, 1), new Date(2015, 0, 5), null, 100, null], I'm confused, how could a month be 0, and the format seems like a list, how can I output a format like this in Django, I tried to google it, it seems like not many people using google chart and even less in the Gantt chart, I think it's a JSON format, but I have very limited knowledge of how to deal with JSON, does anyone have any idea about how to return the data format to HTML? Cheers chart.html ''' <script type="text/javascript"> google.charts.load('current', {'packages':['gantt']}); google.charts.setOnLoadCallback(drawChart); function daysToMilliseconds(days) { return days * 24 * 60 * 60 * 1000; } function drawChart() { var data = new google.visualization.DataTable(); data.addColumn('string', 'Task ID'); data.addColumn('string', 'Task Name'); data.addColumn('date', 'Start Date'); data.addColumn('date', 'End Date'); data.addColumn('number', 'Duration'); data.addColumn('number', 'Percent Complete'); data.addColumn('string', 'Dependencies'); data.addRows([ ['Research', 'Find sources', new Date(2015, 0, 1), new Date(2015, … -
How to pass an object to a model field in Django?
I am trying to pass an object I get from a model form to a field in a model. Three models are involved here. Patient , Donation and Donor Here are the models: class Donor(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) donor_dob = models.DateField(auto_now=False, auto_now_add=False, default=None) id_card = models.CharField(max_length=7) phone_number = models.CharField(max_length=7) blood_group = models.CharField(max_length=20, choices=BLOOD_GROUPS, default='O_Positive') availability = models.BooleanField(default=True) donor_donation = models.ForeignKey( 'Donation', blank=True, null=True, on_delete=models.DO_NOTHING) class Patient(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=30) patient_dob = models.DateField(auto_now=False, auto_now_add=False, default=None) id_card = models.CharField(max_length=7) phone_number = models.CharField(max_length=7) blood_group = models.CharField(max_length=20, choices=BLOOD_GROUPS, default='O+') class Donation(models.Model): donation_donor = models.ForeignKey( Donor, on_delete=models.CASCADE, related_name='donations') patient = models.ForeignKey(Patient, on_delete=models.CASCADE) donation_date = models.DateTimeField(auto_now=True) amount = models.DecimalField(max_digits=5, decimal_places=2) I am using DonationForm to enter a new donation record. here is the form: class DonationForm(forms.ModelForm): donation_donor = forms.ModelChoiceField( queryset=Donor.objects.filter(availability=True)) class Meta: model = Donation fields = ['donation_donor', 'patient', 'amount'] and finally here is the view for entering a new donation object/record def new_donation(request): if request.method == 'POST': form = DonationForm(request.POST or None) # print(request.POST) print(request.POST['donation_donor']) if form.is_valid(): donor = Donor.objects.get(id=request.POST['donation_donor']) donor.availability = False print('Donor: ', donor) donation = form.save() form.save() donor.donation_donor = donation donor.save() donor = setattr(donor, 'donation_donor', donation) print(donor) return render(request, 'new_donation.html', {'form': form}) form = DonationForm() return … -
Django psycopg2.errors.InvalidSchemaName: no schema has been selected to create in
I am trying to configure PostgreSQL in my Django project with a custom schema. My settings are: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ['DB_DATABASE'], 'USER': os.environ['DB_USERNAME'], 'PASSWORD': os.environ['DB_PASSWORD'], 'HOST': os.environ.get('DB_HOST', 'localhost'), 'PORT': os.environ.get('DB_PORT', '5432'), 'OPTIONS': { 'options': '-c search_path=my_custom_schema', }, } } I want django system tables to be created in the schema my_custom_schema as well. When I do first migration I get the error. $ python manage.py migrate ... psycopg2.errors.InvalidSchemaName: no schema has been selected to create in LINE 1: CREATE TABLE "django_migrations" ("id" bigserial NOT NULL PR... ... How do I resolve it? Python version: 3.9.7 Django version: 3.2.8 Psycopg2 version: psycopg2-binary==2.9.1 PostgreSQL version: 12.8 -
Can I use requests library in Celery task?
I have a Django app where I have push notifications for users. The users are identified based on JWT token, no usernames or passwords are used. I have a Model to save an event to the database and I also have a route to send a notification tot he user. I use Celery to check the events from the database every n minute and now I should build the logic to send the event to the user based on for example the timestamp value of the event. I've created a task to tasks.py to check the events: @shared_task def get_events(): from .models import User, Notification users = User.objects.all() for user in users: events = Notification.objects.filter(id=user.id) if len(events) > 0: for event in events: api_call(user.id) This is only a skeleton as I'm trying to find a correct way to do this. My main problem at the moment is that I can get all the users and all the events but I don't know how to use requests library to do a request to the endpoint I have for sending notifications. Or, maybe the bigger question is: am I doing this right at all? Is there some better way to check the … -
save data of a select after being filtered with ajax
hello I have a problem with a select that filters the other. I did all the filtering correctly from the frontend point of view but in the backend I can not save the data, indeed data since it is a formset. the error that comes out of me is this: select a valid choise. That choice is not one of the available choices. I think the problem is in the fact of the form as it does not find 'group_single' that I pass through post in my views. my models class Gruppi(models.Model): nome_gruppo = models.CharField(max_length=100) class Esercizi(models.Model): nome_esercizio = models.CharField(max_length=100) gruppo = models.ForeignKey( Gruppi, on_delete = models.CASCADE, related_name = 'gruppo' ) class Schede(models.Model): nome_scheda = models.CharField(max_length=100) data_inizio = models.DateField() data_fine = models.DateField() utente = models.ForeignKey( User, on_delete = models.CASCADE, related_name = 'utente' ) class DatiGruppi(models.Model): giorni_settimana_scelta = [ ("LUNEDI","Lunedì"), ("MARTEDI","Martedì"), ("MERCOLEDI","Mercoledì"), ("GIOVEDI","Giovedì"), ("VENERDI","Venerdì"), ("SABATO","Sabato"), ("DOMENICA","Domenica") ] giorni_settimana = MultiSelectField( choices = giorni_settimana_scelta, default = '-' ) dati_gruppo = models.ForeignKey( Gruppi, on_delete = models.CASCADE, related_name = 'dati_gruppo' ) gruppi_scheda = models.ForeignKey( Schede, on_delete = models.CASCADE, related_name = 'gruppi_scheda' ) class DatiEsercizi(models.Model): serie = models.IntegerField() ripetizione = models.IntegerField() peso = models.DecimalField( max_digits = 4, decimal_places = 1, blank = True, null = … -
How can I add tailwind css to an existing django app
I already have a Django project with many apps and one of them is demo_app. I have some views and templates added to the demo app but I want to start using tailwind in the demo_app templates. I have seen that to add tailwind I need to create the theme app using tailwind but I want to add it to the already existing demo_app. How can I do that? -
how to retrieve new data from database when db received new entry without refreshing or any other action in Django
I have a web & mobile application synced with the same DB. but now I want to fetch the latest data to my web app without refreshing or any other action like button click from browser. data will be saved from the mobile app. and displayed there, but in the web app when I refresh the page then I am getting the latest entries. how may I be able to fetch the latest entries from my web app without refreshing the page? what approach is best. data entered from mobile using API, the web app is in Django 3.2 and for API's I am using Django rest framework -
how to pass two models in django view in the following code?
i have two models : class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() bargainprice = models.FloatField(default=0) discount_price = models.FloatField(blank=True, null=True) category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) label = models.CharField(choices=LABEL_CHOICES, max_length=1) slug = models.SlugField() description = models.TextField() image = models.ImageField() and the second one : class BargainModel(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) itemId = models.IntegerField() bprice = models.FloatField() can anyone explain whats going on in the following view : class ItemDetailView(DetailView): model = Item template_name = "product.html" i know they passing one model in the view and here is how they accessed in template: <span class="mr-1"> <del>₹ {{ object.price }}</del> </span> <span>₹ {{ object.discount_price }}</span> and how can I pass two models in this view? -
DJANGO: Get a parent queryset from a child queryset
Say I have the following for my models.py: from django.db import models class Department(models.model): name = models.CharField(max_length=255) class User(models.model): name = models.CharField(max_length=255) department = models.ForeignKey( Department, related_name="department_users", on_delete=models.CASCADE ) ... So I am doing a lot of complex filtering on my User queryset to get to a subset of Users who are considered "active" but now I need to generate a list of Departments who have at least one "active" user. I know that I can use a reverse lookup like: Department.objects.filter(department_users__name__contains=...) etc and do the filtering all over again but I wanted to know if there was a way to get that information directly from the "active" User queryset. I tried using .values() but that gives me a queryset of dictionaries and I really wanted a queryset of django Models so I can do further filtering for the Department queryset. Do you guys know if there is a way to do that? -
Unable to download depencencies in virtual environment
Hope you're doing well, I was trying to work on this django project from github but i could not download all the packages in a virtual environment, it says (venv) C:\Users\me\Downloads\movie_recommender-master>pip install -r requirements.txt Unable to create process using 'C:\Users\me\AppData\Local\Programs\Python\Python310\python.exe "C:\Users\me\Downloads\movie_recommender-master\venv\Scripts\pip.exe" install -r requirements.txt' . I have read through tons of questions in stack over flow but nothing seems to work, I would be very grateful if you could help me here. My command prompt says this -
How to display loop items properly in Django
I have a list like this : {'serial1': 'BPCE-RNHC-25G8', 'subject1': 'EMP004', 'serial2': '7QF2-6HI9-XKZZ', 'subject2': 'EMP005', 'serial3': '8FIW-9JRB-NY4J', 'subject3': 'EMP003', 'serial4': 'SG8P-YQKG-ZV3C', 'subject4': 'EMP002', 'serial5': 'PBF7-WZ HT-WPZR', 'subject5': 'EMP001'} When I send this list over my html template using for loop , the serial and subject value is separated and divide into 2 column which represent: My desire output is the serial and subject appear on the same column for the same record. For example: My code: <div class="row"> <div class="col-md-5 grid-margin stretch-card"> <div class="card"> <div class="card-body"> <h4 class="card-title">Assigned Minis</h4> <div class="list-wrapper pt-2"> <ul class="d-flex flex-column-reverse todo-list todo-list-custom"> {% for key, value in assignedMini.items %} <li> <div class="form-check form-check-flat"> <label class="form-check-label"> {{ value }} </label> </div> </li> {% endfor %} </ul> </div> </div> </div> </div> -
Load images and show them in a grid contraint from max height
I have several image loaded from database linked by articles. Theses images have different width and height (portrait/landscape). 1 article can have 1 or more images. If 1 article have only one image, it show picture to take all size of (width max = 180mm) If more article I want to show them in a grid with contraint max for height. The goald is to load each article and show it on a single page (MediaPrint) to print only one article by page ... For each picture associated to one article I want to show in the same page and only on this page. In my template actually I made this ... It use jquery to show picture if portrait or landscape picture. If more than one picture, I fix width in style html properties directly without JQUERY. TEMPLATES <div class="col mb-5 text-center"> {% if value|length == 1 %} <img class="img-responsive_jquery" src="/media/photos/{{ image }}.jpeg" /> {% endif %} {% if value|length > 1 and value|length < 5 %} <img class="img-responsive" src="/media/photos/{{ image }}.jpeg" style="width:70mm !important" /> {% endif %} {% if value|length > 5 and value|length < 10 %} <img class="img-responsive" src="/media/photos/{{ image }}.jpeg" style="width:40mm !important" /> {% endif %} … -
username and email interchanged for social user
I am using google oauth2 for social authentication, I get the user's username and email and save it on my models, but the username and email fields are being swapped. What is causing such a problem? models.py class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=255, db_index=True) email = models.EmailField(max_length=255, unique=True, db_index=True) is_verified = models.BooleanField(default=False) # is_authenticated = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) auth_provider = models.CharField(max_length=225, blank=False, null=False, default=AUTH_PROVIDERS.get('email')) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = UserManager() def __str__(self): return self.email def tokens(self): refresh = RefreshToken.for_user(self) return { 'refresh': str(refresh), 'access': str(refresh.access_token) } register.py def register_social_user(provider, user_id, email, name): filtered_user_by_email = User.objects.filter(email=email) if filtered_user_by_email.exists(): if provider == filtered_user_by_email[0].auth_provider: registered_user = authenticate( email=email, password=os.environ.get('SOCIAL_SECRET')) return { 'username': registered_user.username, 'email': registered_user.email, 'tokens': registered_user.tokens()} else: raise AuthenticationFailed( detail='Please continue your login using ' + filtered_user_by_email[0].auth_provider) else: user = { 'username': generate_username(name), 'email': email, 'password': os.environ.get('SOCIAL_SECRET')} user = User.objects.create_user(**user) user.is_verified = True user.auth_provider = provider user.save() print('user',user) new_user = authenticate( email=email, password=os.environ.get('SOCIAL_SECRET')) print ('new:',new_user) return { 'id':user.id, 'email': user.email, 'username': user.username, 'tokens': user.tokens() } Here is the link to the full code: https://github.com/abinashkarki/rest_framework_authentication -
django restframework try using djoser to create multiple model get unexpected keyword argument
Im new to django rest-framework and Djoser and learning, trying to create a user with profile using UserCreateSerializer in Djoser. I followed bunch of tutorials to create a Serializer with two models and when trying to create a user in browser api end with: get unexpected keyword argument in the template, i know what the error means but i dont know how should i implement it or what did i do wrong. here is my model: from django.db import models # Create your models here. from django.contrib.auth.models import AbstractUser from django.utils.translation import ugettext_lazy as _ class User(AbstractUser): account_Option = ( ('P', 'is_something'), ('L', 'is_somethingelse'), ) ac_type = models.CharField(_("Status"), max_length=1, choices=account_Option, default='P', help_text=_('account Option')) class MyClass(models.Model): user = models.OneToOneField(User, on_delete=models.PROTECT, editable=False) my_field = models.CharField(help_text=_('Enter your...'), max_length=10, unique=True, null=True, blank=True, ) and serializers: from djoser.serializers import UserSerializer as BaseUserSerializer, UserCreateSerializer as BaseUserCreateSerializer from rest_framework import serializers from django.conf import settings from core.models import MyClass User = settings.AUTH_USER_MODEL class MyClassSerializer(serializers.ModelSerializer): class Meta: model = MyClass fields = ['my_field'] class UserCreateSerializer(BaseUserCreateSerializer): profile = MyClassSerializer() class Meta(BaseUserCreateSerializer.Meta): fields = ['id', 'username', 'password', 'email', 'first_name', 'last_name', 'profile'] def create(self, validated_data): profile_data = validated_data.pop('profile') # User_model = self.User.objects.create(**validated_data) User_model = User.objects.create(**validated_data) new_profile = self.profile.objects.create( user=User_model, **profile_data) return … -
Django - delete M2M field but keep join table
is it possible to remove an M2M field from a model and keep the joining table? context: I am trying to add through model to existing M2M field like described in this post But doing it simply like this will result in a production app crash when accessing the old table during deployment - short window between migration and code update, when old code will try to access a new database for a few moments - without the old table in it. -
How to update a value in database after n seconds of query made? Django
I have a model in which I created a field "bargain price " as shown in Models.py: class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() bargainprice = models.FloatField(default=0) somewhere in my template I take input from user and update the bargain price using ajax as shown below: $.ajax({ url: "/bargain/" + id + "/", data: { csrfmiddlewaretoken: window.CSRF_TOKEN, 'input': parseFloat(input) }, type: 'POST' }).done(function (response) { alert(response); }); and I successfully update the price by the view: def Bargain(request, uid): if request.method == 'POST': item = Item.objects.get(id=uid) item.bargainprice = request.POST['input'] item.save() message = 'update successful' return HttpResponse(message) else: return HttpResponse("this is not working..") **Now what I want. I want to reset this Bargain_price updated value to default after n seconds ** Can anyone suggest to me the method to do it? Thanks in advance. -
Concat or join query values
need to join objects values from query. For example: objects = Book.objects.all() and Book objects have id as a field So need to make a query with all ids of objects array, but not as a array of ids. Need to have something like this <QuerySet '1, 2, 3, 4'> -
Strange behave of VS code terminal while CMD works well
I have tried to install django-crispy-forms in VS Code terminal but it shows install django-crispy-forms': The system cannot find the file specified. After that, I tried installing the package in the CMD terminal and it worked well and was installed. Now it if run the project from VS Code terminal then shows no module found. Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\MH Habib\AppData\Local\Programs\Python\Python39\lib\threading.py", line 973, in _bootstrap_inner self.run() File "C:\Users\MH Habib\AppData\Local\Programs\Python\Python39\lib\threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "H:\Django web\NewProject\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "H:\Django web\NewProject\env\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "H:\Django web\NewProject\env\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "H:\Django web\NewProject\env\lib\site-packages\django\core\management\__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "H:\Django web\NewProject\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "H:\Django web\NewProject\env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "H:\Django web\NewProject\env\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "H:\Django web\NewProject\env\lib\site-packages\django\apps\config.py", line 224, in create import_module(entry) File "C:\Users\MH Habib\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'crispy_forms' Restart VS code several times but show the error every time. On the … -
How to get the error of no such table exist in Django API
I have the following codes @api_view(['DELETE']) def selected_device_delete(request,pk=None): if pk != None: #Open connection to database cursor = connection.cursor() #Removing related tables table1 = 'dev_interface_' + str(pk) table2 = 'dev_route_list_' + str(pk) table3 = 'dev_neighbour_list_' + str(pk) dropquery1 = f"DROP TABLE {table1}" dropquery2 = f"DROP TABLE {table2}" dropquery3 = f"DROP TABLE {table3}" cursor.execute(dropquery1) cursor.execute(dropquery2) cursor.execute(dropquery3) #Close connection to database cursor.close() device = Device.objects.filter(pk=pk) operation = device.delete() data = {} if operation: data["Success"] = "Successfully deleted" return Response(data) If user types an unknown pk which for example is 200 and the table does not exist, how do i get this error? I want to use this error and return a response like such table does not exist