Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: extra argument using field from parent table
I'm trying to pull a value from a table in an app with no foreignkey association to another table in a separate app. While using .extra() is fairly straightforward, I'm wondering how one uses a field from the parent table in the WHERE clause of the select argument in .extra(). I would prefer to use Django's built in mechanisms rather than resorting to raw sql. The main area of focus is the queryset argument in association.views.py. I've tried simply setting the product_code equal to consequent but this does not return any values for price (product_code and consequent have common records), whereas using raw SQL returns the correct values. My assumption would be that consequent is coming through as a list rather than individual values. Consider one app as 'association' and the other app as 'pricing'. Here are the two models from each app and the views.py file from the 'brand' app: pricing.models.py class CurrentSchedule(models.Model): price_schedule_id = models.IntegerField(null=True, blank=True) price_schedule_name = models.CharField(max_length=200, null=True, blank=True) unit_charge_amount = models.FloatField(null=True, blank=True) product_code = models.CharField(max_length=50, null=True, blank=True) association.models.py class AssociationData(models.Model): antecedent = models.CharField(max_length=10, primary_key=True) consequent = models.CharField(max_length=10, null=True) confidence = models.FloatField(null=True) lift = models.FloatField(null=True) class Meta: ordering = ['antecedent','-confidence'] association.views.py def association_price_table(request): """ Generates the … -
Django send Messages by WhatsApp
Goodnight. I'm developing a system where users, in addition to all the bureaucratic part, can register their clients' whatsapp so that automatic billing messages, congratulations, etc. are sent. Where the user would read the QR code and the system would be in charge of sending messages over time, using the user's whatsapp, thus opening a user<-> clinet conversation. I've seen a system working like this, but researching I didn't find many ways, just Twilio and selenium. Any suggestions for simplifying this process? And if it's Selenium, how to keep sessions loaded with so many users, so that the qr code doesn't need to be read all the time? Thanks! I thought about using Selenium on heroku, with automation a few times a day, to execute pending messages. But I don't know if selenium with webdrive would work and the question of hundreds of open sections in webdriver. -
Not an executable object: 'SELECT * FROM LoanParcel'
I want to use the database by creating it as a dataframe, and I've used sqlalchemy for importing create_engine, but I'm stuck with the not an executable object: 'SELECT * FROM LoanParcel', where LoanParcel is the name of the database I want to create as a dataframe, how should I fix it? views.py from sqlalchemy import create_engine engine = create_engine("mysql+pymysql://mariadb:mariadb@localhost:9051/mariadb") def user_detail(req, id): conn = engine.connect() QLoanParcel = "SELECT * FROM LoanParcel" dfParcel = pd.read_sql(QLoanParcel, conn) conn.close() df = dfParcel.drop(["id", "date_add", "start_date"], axis = 1) return render(req,'pages/user_detail.html') -
Django add language code to url in html if condition
I have a navbar that shows active when it is in the current section. I have internationalised the web so now the url includes the language code. How can I add the language code in the if condition below? {% if '/{LANGUAGE_CODE}/accounts/dashboard/' == request.path %} active {% endif %} webpage url: http://127.0.0.1:8000/en/accounts/dashboard {% load i18n %} {% get_current_language as LANGUAGE_CODE %} <aside class="col-md-3"> <!-- SIDEBAR --> <ul class="list-group"> <a class="list-group-item {% if '/{LANGUAGE_CODE}/accounts/dashboard/' == request.path %} active {% endif %}" href="{% url 'dashboard' %}"> Dashboard </a> [continues...] I tried {{LANGUAGE_CODE}} and some pasting. Any ideas how to get the if condition working? -
How to set ordering of Apps and models in Django admin dashboard
i would like to set a specific order of the models list of an app in the django dashboard. my models look like this: i've tried several tutorial like this one and looked other people solution inside SO like this questions How to use custom AdminSite class? Set ordering of Apps and models in Django admin dashboard Reorder app and models in Django admin but none of these works, they either use a third party library or they don't specify where to put the pieces of code. This one seem to be the most promising but i tried to put the piece of code, class WebsiteAdminSite(admin.AdminSite): def get_app_list(self, request): """ Return a sorted list of all the installed apps that have been registered in this site. """ ordering = { "Menues": 1, "Entrees": 2, "First_dishes": 3, "Second_dishes": 4, "Side_dishes": 5, "Desserts": 6, "Wines": 7, "Opening_hours": 8, "Contacts": 9, "Gallery_images": 10, } app_dict = self._build_app_dict(request) # a.sort(key=lambda x: b.index(x[0])) # Sort the apps alphabetically. app_list = sorted(app_dict.values(), key=lambda x: x['name'].lower()) # Sort the models alphabetically within each app. for app in app_list: app['models'].sort(key=lambda x: ordering[x['name']]) return app_list inside the admin.py of my app but it doesn't work. i can't provide any … -
Django Custom Authentication Backend does not work
I've made a user model with USERNAME_FIELD defined as phone_number. So that is login, it requires phone_number and password. But I want users to be able to also login through their emails. So I created an authentication backend class: authentication.py: from django.contrib.auth import get_user_model class CustomAuthBackend: def authenticate(self, username=None, password=None): try: user = get_user_model().objects.get(email=username) if password: if user.check_password(password): return user return None except: return None def get_user(self, user_id): try: user = get_user_model().objects.get(pk=user_id) return user except: return None forms.py: class UserLoginForm(forms.Form): username = forms.CharField(label="Phone Number / Email") password = forms.CharField(widget=forms.PasswordInput(), label="Password") views.py: class UserLogin(View): form_class = UserLoginForm template_name = "accounts/login.html" def get(self, request): return render(request, self.template_name, {"form": self.form_class}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): cd = form.cleaned_data user = authenticate( request, username=cd["username"], password=cd["password"] ) if user: login(request, user) messages.success(request, "Logged in successfully.", "success") return redirect("home:home") else: messages.error(request, "Username and/or password is wrong.", "danger") return render(request, self.template_name, {"form": form}) messages.error(request, "Login failed", "danger") return render(request, self.template_name, {"form": form}) Users can login with their phone numbers properly. But it login always fails when I type an email in username field. -
Related Field got invalid lookup: icontains in admin.py
I know this problem have been posted before with its respective solution, but I do not know what is the problem in this specific case, Im trying to add a searching bar in the admin page of a specific class called "Dish" here is the context: Error in browser FieldError at /admin/menu/dish/ Related Field got invalid lookup: icontains Request Method: GET Request URL: http://www.lupita.restaurant/admin/menu/dish/?q=naranja Django Version: 4.0.6 Exception Type: FieldError Exception Value: Related Field got invalid lookup: icontains Exception Location: /usr/local/lib/python3.10/site-packages/django/db/models/sql/query.py, line 1262, in build_lookup Python Executable: /usr/local/bin/uwsgi Python Version: 3.10.5 Python Path: ['/home/juanfrax/lupita', '/var/www', '.', '', '/var/www', '/usr/local/lib/python310.zip', '/usr/local/lib/python3.10', '/usr/local/lib/python3.10/lib-dynload', '/home/juanfrax/.local/lib/python3.10/site-packages', '/usr/local/lib/python3.10/site-packages'] Server time: Fri, 10 Feb 2023 03:38:57 +0000 Traceback Switch to copy-and-paste view /usr/local/lib/python3.10/site-packages/django/core/handlers/exception.py, line 55, in inner response = get_response(request) … Local vars /usr/local/lib/python3.10/site-packages/django/core/handlers/base.py, line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … Local vars /usr/local/lib/python3.10/site-packages/django/contrib/admin/options.py, line 683, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) … Local vars /usr/local/lib/python3.10/site-packages/django/utils/decorators.py, line 133, in _wrapped_view response = view_func(request, *args, **kwargs) … Local vars /usr/local/lib/python3.10/site-packages/django/views/decorators/cache.py, line 62, in _wrapped_view_func response = view_func(request, *args, **kwargs) … Local vars **models.py: ** class Dish(models.Model): name = models.CharField(max_length=50) nombre = models.CharField(max_length=50) description = models.TextField(max_length=500) descripcion = models.TextField(max_length=500) category = models.ForeignKey('Category', null=True, on_delete=models.SET_NULL) categoria = … -
How to add multiple options to a feature in Django?
My last question for today. I created a filter to only show items with certain values. A list of social measures is displayed. There are two questions about having children and unemployment. We have or don't have children, and we are or aren't unemployed. The main problem is that the filter doesn't work correctly, due to the fact that I only add one option "no" to the entity. For example, we have a social measure "child allowance", and it's paid regardless of income. I created this measure with having children "yes" and unemployment "no". And if the user selects having children "yes" and unemployment "yes", then the page won't show this measure, although the person is entitled to it. Because only "no" was introduced into unemployment. How to enter "no" and "yes" at the same time when creating a measure? And for the site to show this measure regardless of the choice of unemployment. measure_list.html <div class="headtext"> <h3>Choose your life features</h3> </div> <form action="{% url 'filter' %}" method="get" name="filter"> <h3>Do you have children?</h3> <ul> {% for measure in view.get_children %} <li> <input type="checkbox" class="checked" name="children" value="{{ measure.children }}"> <span>{{ measure.children }}</span> </li> {% endfor %} </ul> <h3>Are you unemployed?</h3> <ul> … -
Pass session data to new session Django
Hello Iam working on Django website and I need to pass saved session data to new one after assigning a new session to the user. Example is when a player is doing an online quiz and his browser crashes, so that the data saved for the session will be assignment to a new one after re-login. I've been trying to look for possible workarounds, but I couldn't come up with an answer, as many sources state that django can't detect a new session after a crash unless the user logs out manually. -
I get this error when I try to render some templates in my django project, what's wrong?
I get this error when I try to render or display to a localhost the templates in my django project, and below is my error: TemplateSyntaxError at / Could not parse the remainder: '/style_home.css' from 'css/style_home.css' Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 4.1.3 Exception Type: TemplateSyntaxError Exception Value: Could not parse the remainder: '/style_home.css' from 'css/style_home.css' Exception Location: C:\Users\Admin\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\template\base.py, line 703, in init Raised during: myapp.views.home Python Executable: C:\Users\Admin\AppData\Local\Programs\Python\Python311\python.exe Python Version: 3.11.0 Python Path: ['D:\IT\Proiecte Python\Django Site\mysite', 'C:\Users\Admin\AppData\Local\Programs\Python\Python311\python311.zip', 'C:\Users\Admin\AppData\Local\Programs\Python\Python311\Lib', 'C:\Users\Admin\AppData\Local\Programs\Python\Python311\DLLs', 'C:\Users\Admin\AppData\Local\Programs\Python\Python311', 'C:\Users\Admin\AppData\Local\Programs\Python\Python311\Lib\site-packages', 'C:\Users\Admin\AppData\Local\Programs\Python\Python311\Lib\site-packages\win32', 'C:\Users\Admin\AppData\Local\Programs\Python\Python311\Lib\site-packages\win32\lib', 'C:\Users\Admin\AppData\Local\Programs\Python\Python311\Lib\site-packages\Pythonwin'] I expected to view my html files render in the localhost site, and that's what I did Here is my code in urls file: from django import views from django.contrib import admin from myapp import views from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home'), path('about_me/', views.about_me, name='about_me') ] and also I have in each html document on the first paragraph this django html line graph: {% load static %} because I had and some static files, and I created a static folder also with css and js: And in the settings I have also implemented this code: 'DIRS': [BASE_DIR, 'templates'], #that's in the TEMPLATES in settings and for static … -
Is there a more efficient way to process this data?
I have a bunch of data points in the format (x, y, z, a, b, c) where x is an integer, y is a date, z is an integer, and a, b, and c are different numerical values (integers and floats). My goal is to allow the user to provide two dates (so two y values), and then be presented with the values of (delta_a, delta_b, delta_c) for all existing (x, z) values; delta_a would be the increase/decrease in the value of a between the two dates, etc. For example, let's say there's just 3 possible values of x and 3 possible values of z. The user provides two dates, y1=date(2023,2,7) and y2=date(2023,2,15) This data is presented in a table, like this: Now in reality, there's about 30 different values of x and about 400 different values of z, so this table would actually have about 30 rows and about 400 columns (I have a horizontal scrollbar inside the table to look through the data). Also, the value of y can be any date (at least since I started importing this data, about a month ago). So every day, about 12,000 new data entries are added to the database. The … -
Django override User.groups ManyToMany to be a ForeignKey
I am developing a Django application that only uses Django Admin as the only way to create new user. I need to create roles or groups for the users and each user should have only one group. For each group I will add the necessary permissions. The problem is, that the Groups from Django are written on a ManyToMany relationship and I need to override it to a ForeignKey. How to achieve it? user.py: from django.db import models from django.contrib.auth.models import AbstractUser, Group from django.utils.translation import gettext_lazy as _ from api_auth.models.user_manager import UserManager class User(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) name = models.CharField(_("name"), max_length=150, blank=True) organisation = models.ForeignKey('api_orgs.Organisation', on_delete=models.PROTECT, verbose_name=("Organisation"), blank=True, null=True) welcome_email_sent = models.BooleanField(('welcome email'), default=False) is_staff = models.BooleanField( _("staff status"), default=True, help_text=_("Designates whether the user can log into this admin site."), ) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] -
KeyError at /x/x/ 'pk' django
I'm trying to get a DetailView's model's pk in a variable in the get_context_data but I keep getting the error KeyError at /x/x/ 'pk'. views.py class MangaView(DetailView): model = Manga template_name = 'mangas/manga.html' context_object_name = 'manga' slug_field = 'manga_slug' slug_url_kwarg = 'manga_slug' def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) manga = get_object_or_404(Manga, id=self.kwargs['pk']) # error line favorited = False latered = False ... return data urls.py urlpatterns = [ path('mangas/', MangasHomeView.as_view(), name='mangas-home'), path('manga/<slug:manga_slug>/', MangaView.as_view(), name='manga'), ... ] -
Real time application (React + Django)
Just want to get some suggestion on what would be best approach to create a real time application. What architecture and libraries should be used on both sides I have looked int to sockit.io for front end and channels for the django side, Do I have to use both of them or only one side front-end or back-end -
Django: in 2 joint querysets, the empty queryset.annotate() is replaced in the non empty queryset.annotate(). I want each of them to keep their values
I don't understand this. I have in views.py firstQuerySet=firstQuerySet.annotate(status=Value('active', output_field=CharField())) secondQuerySet=secondQuerySet.annotate(status=Value('waiting', output_field=CharField())) If I print the first one I get Queryset[] because while performing an object filter no user is active so it is empty. If I print the second one, is not empty, I get for example, <QuerySet [{'field1': 'name1', 'field2': 'name2', 'status': 'waiting'}]> Then I joint them into a single query set considering globalQuerySet = firstQuerySet | secondQuerySet If now I print global the status has changed to 'status': 'active'. I don't get why -
Multiple Authentication Models in Django
I am working on a project where I need to have 3 types of Users. Staff (for admin,superadmin like stuff) Dealers Customers i have created 3 models for each using AbstractBaseUser class . I also created separate model managers for each . models.py class Staff(allmodelfields): USERNAME_FIELD = 'email' # fields class Customer(allmodelfields): USERNAME_FIELD = 'email' # fields class Dealer(allmodelfields): USERNAME_FIELD = 'email' # fields after getting through this Django Multiple Auth Models i made a custom authentication backend authentication.py as follows: from .models import Staff,Customer,Dealer var_model = "" class authentication_models_backends(object): def authenticate(self, request, email=None, password=None): global var_model if "admin" in request.path: var_model = Staff elif "customer" in request.path: var_model = Customer elif "dealer" in request.path: var_model = Dealer else : return "no_model_found" # authenticate user based on request object try: validated_email = email.lower() if var_model.objects.filter(email=validated_email).exists(): user = var_model.objects.get(email = validated_email) if user.check_password(password): return user else: return "invalid password" else: return "email not found" except var_model.DoesNotExist: return None def get_user(self, user_id): # logic to get user try: return var_model.objects.get(pk=user_id) except var_model.DoesNotExist: return None in settings.py AUTH_USER_MODEL = 'account.Staff' AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.ModelBackend', 'account.authentication.authentication_models_backends',] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication',#(user not found error) )} SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'ROTATE_REFRESH_TOKENS': False, … -
pip install psycopg2 Fatal error in launcher: Unable to create process using
I'm creating a blog in and trying to migrate the database to PostgreSQL, when I type in the command pip install psycopg2 this error appears, does anyone know what it could be? Fatal error in launcher: Unable to create process using It's the first time I try to do this migration, I just installed PostgreSQL on my pc and now I'm trying to CON in my project by pip -
Django ORM create model object using another object
How can we create a model record or object using another object. get_object = my_model.objects.filter(id=1) I want to do something like below to create object in another database my_model.objects.using('DB2').create(my_model=get_object) -
Django CreateView doesn call the success url
My CreateView doesn't call the success url, i've also tried using get_success_url function but still gives the same result, it just returns the form sending the request. It actually creates the objects in the data base and prints out the entered value, but it never goes to the success url. This is what i've got MODELS.PY from django.db import models from ckeditor.fields import RichTextField from django_random_id_model import RandomIDModel DELIVERED_OPTIONS = ( ("false", "Not Delivered"), ("true", "Delivered"), ) # Create your models here. class Order(models.Model): name = models.CharField(max_length=200) email = models.CharField(max_length=200) address = models.CharField(max_length=200) phone = models.CharField(max_length=200) measurements = RichTextField(default='') delivered = models.CharField( max_length=200, choices=DELIVERED_OPTIONS, default="false") FORMS.PY from django import forms from ckeditor.widgets import CKEditorWidget from .models import Order class DeliveryForm(forms.ModelForm): class Meta: model = Order exclude = ["id"] fields = ['name', 'email', 'address', 'phone', 'measurements'] name = forms.CharField(label="Enter your full Name", min_length=5, widget=forms.TextInput( attrs={'placeholder': 'Full name please', 'class': 'form-control'})) email = forms.CharField(label="Enter your Email address", widget=forms.EmailInput( attrs={'placeholder': 'Enter a valid email address', 'class': 'form-control'})) address = forms.CharField(label="Enter Your delivery address", widget=forms.TextInput( attrs={'placeholder': 'Delivery address', 'class': 'form-control'})) phone = forms.CharField(label="Enter your phone number", widget=forms.NumberInput( attrs={'placeholder': 'A valid phone number', 'class': 'form-control'})) measurements = forms.CharField(widget=CKEditorWidget( attrs={'class': 'form-control', 'rows': '3'}), required=True) def send_email(self): … -
Obtaining a list of Wagtail posts to display in a Django template outside of Wagtail
I have a main Django website, which consists of a main page at / using standard django templates, and then a wagtail blog situated at /blog On my homepage, I would like someone to be able to show the most recent published articles from the wagtail blog. I'm having a lot of trouble doing this as I can't find any resources or guides. So far I added a model for my homepage (which didn't have one previously), just to obtain blogs: from myblog.models import BlogPage class HomePage(Page): def blogs(self): blogs = BlogPage.objects.all() blogs = blogs.order_by('-date') return blogs Then for my homepage template I have: {% for blog in page.blogs %} <div class="col-md-4"> <a class="blog-post-link" href="{% pageurl blog %}"> <h3>{{ blog.title }}</h3> </a> <div class="blog-intro"> {{ blog.body|richtext|truncatewords_html:50 }} <a class="read-more" href="{% pageurl blog %}">Read More &raquo;</a> </div> </div> {% endfor %} However nothing is displayed, nor are any errors given. How can I obtain and display a list of published Wagtail posts in an app outside of Wagtail? -
How to check if an identical element exists in another table in Django?
I have two models: CaseRequest and Case. The CaseRequest object has values name and datebirth. I need to check if the same values exists for name and datebirth in Case. For instance, The result should be like this: Case: Name DateBirth Don Honn 01.03.1959 Freak Hu 04.11.1993 Wend Don 06.03.1988 CaseRequest: Name DateBirth Status Tom Hawk 01.05.1999 accepted - no Don Honn 01.03.1959 accepted - yes Fold Len 03.07.1967 denied - no Freak Hu 04.11.1993 denied - yes Wend Don 13.12.1956 denied - no My code: Models.py class CaseRequest(models.Model): name = models.CharField(max_length=255) datebirth = models.DateField() status = models.CharField(max_length=255) def __str__(self): return self.name def get_absolute_url(self): return reverse('caserequest') class Case(models.Model): name = models.CharField(max_length=255) datebirth = models.DateField() def __str__(self): return self.name + ' | ' + str(self.datebirth) def get_absolute_url(self): return reverse('case_list') Views.py class CaseRequestView(ListView): model = CaseRequest template_name = 'caserequest.html' caserequest.html <div> {% for caserequest in object_list %} <div> <p>{{ caserequest.name }}, {{ caserequest.datebirth }}</p> <p>{{ caserequest.status }}</p> <!-- The result should be here: YES or NO --> </div> {% endfor %} </div> -
Django query for getting common Libraries between book list
I have 2 models linked with each other with Foreign key. A Book and a Library models. I have a list of books IDs. And I want to get the list of Libraries where I can find all those books I’m trying not loop through all the libraries as there the number of both libraries and books list isn’t small -
cart total in Django shows blank space
I'm trying to get cart total sum of products in the html template, while the the total sum of particular products works fine, the cart total price/quantity shows blank spaces. Models: from django.db import models import Accounts.models as accounts_models import Products.models as products_models class Order(models.Model): customer = models.ForeignKey(accounts_models.Customer, on_delete=models.SET_NULL, blank=True, null=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False) transaction_id = models.CharField(max_length=100, null=True) def __str__(self): return str(self.id) @property def get_cart_total(self): orderproducts = self.orderproduct_set.all() total = sum([product.get_total for product in orderproducts]) return total @property def get_cart_products(self): orderproducts = self.orderproduct_set.all() total = sum([product.quantity for product in orderproducts]) return total class OrderProduct(models.Model): product = models.ForeignKey(products_models.Products, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) @property def get_total(self): total = self.product.price * self.quantity return total views: def cart(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderproduct_set.all() else: items = [] context = {'items': items} return render(request, 'cart.html', context) html template: {% for item in items %} <tr> <td>{{ item.product.name }}</td> <td>{{ item.quantity }}</td> <td>${{ item.product.price }}</td> <td>${{ item.get_total }}</td> </tr> {% endfor %} <tr> <td colspan="3"><strong>Total:</strong></td> <td>${{ order.get_cart_total }}</td> </tr> How can I start showing the total numbers in the html template? -
Getting mistake while importing xlsx file into database django. Please correct my code. I cant deal with it. PLEASE
Line number: 1 - 'id' 1, 28799772, 306509594, "GOLDEN NILE AAA" MChJ, 1726294, Toshkent shahri, Chilonzor tumani, X.TURSUNQULOV KOʻCHASI, 38-UY, 974079981, makhmudjon.khakimjonov@mail.ru, 47190 Traceback (most recent call last): File "C:\Users\AbdulAziz\AppData\Local\Programs\Python\Python38\lib\site-packages\import_export\resources.py", line 708, in import_row instance, new = self.get_or_init_instance(instance_loader, row) File "C:\Users\AbdulAziz\AppData\Local\Programs\Python\Python38\lib\site-packages\import_export\resources.py", line 378, in get_or_init_instance instance = self.get_instance(instance_loader, row) File "C:\Users\AbdulAziz\AppData\Local\Programs\Python\Python38\lib\site-packages\import_export\resources.py", line 365, in get_instance import_id_fields = [ File "C:\Users\AbdulAziz\AppData\Local\Programs\Python\Python38\lib\site-packages\import_export\resources.py", line 366, in self.fields[f] for f in self.get_import_id_fields() KeyError: 'id' models.py class Company(models.Model): id = models.AutoField(primary_key=True) okpo = models.PositiveIntegerField(null=True,blank=True) inn = models.PositiveIntegerField(null=True,blank=False) name = models.CharField(max_length=25,blank=False,default='Tashkilot Nomi') soato = models.PositiveIntegerField(null=True,blank=False) address = models.CharField(max_length=50,blank=True,null=True,default='Tashkilot Adresi') street = models.CharField(max_length=50,blank=True,null=True,default='Tashkilot Street') phonenumber = models.CharField(max_length=13, blank=True, null=True,default='+998') email = models.EmailField(max_length=25,default='tashkilot@email.com') oked = models.PositiveIntegerField(null=True,blank=False) views.py def import_file(request): if request.method == 'POST' : dataset = Dataset() new_employee = request.FILES['myfile'] data_import = dataset.load(new_employee.read()) result = CompanyResources.import_data(dataset,dry_run=True) if not result.has_errors(): CompanyResources.import_data(dataset,dry_run=False) return render(request, 'home.html',{}) admin.py class CompanyResources(resources.ModelResource): class Meta: models = Company fields = [field.name for field in Company._meta.fields if field.name != 'id'] exclude = ['id',] import_id_fields = ['id',] class CompanyAdmin(ImportExportModelAdmin): resource_class = CompanyResources list_display = [field.name for field in Company._meta.fields] admin.site.register(Company,CompanyAdmin) -
A celery task called twice modifies one object
I'm experimenting with celery to understand how it works. I've written a simple worker, which modifies an array: from .celery import app import time arr = [] status = 'waiting' @app.task def push_back(val): global arr if status == 'busy': return 'try later' status = 'busy' arr.append(val) time.sleep(5) status = 'waiting' return arr And here is my client: from proj.tasks import push_back from sys import argv res = push_back.delay(int(argv[1])) data = res.get() print(data) I call the client twice, one immediately after the other with different arguments. E.g. my call is: python3 update_object.py 3 & python3 update_object.py 5 The responses are [3] and [5], respectively. I have another task for checking the state of the array, which returns [3], so only the first call has made any effect. Could somebody explain what exactly is going on during such a call? Why is the status not checked? Why does the second call modify the array? My ultimate goal is to implement Django API and an AI server being a celery worker. Besides predictions, I also want to load different models (modify the state) using remote calls from Django. I want to disable the task execution if it has been called by another user. …