Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
|PYTHON/DJANGO| Wait before resuming a task (Without sleep)
I am trying to do a simple task : Waiting. Here is an example : # Inform the user about the closing new_message = Message.objects.create(content='Game closing in 10 seconds...', game=self) new_message.save() time.sleep(10) # After waiting, delete the game self.delete() However, my host only allows me 1 worker process , hence, if I decide to use sleep, every other requests will be freezed and my app will become unresponsive to the users. Is there a way to work around this problem ? Also, I can't use threads in case of Thanks and sorry for the poor english -
How to call double nested reverse foreign key relation in django?
I'm working on forum project. Currently, I need to fetch somehow the latest posts for each category. My models structure is following (pseudo code): class Category(models.Model): ... class Topic(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) ... class Post(models.Model): topic = models.ForeignKey(Topic, on_delete=models.CASCADE) ... I need to fetch latest Post objects within Category model's functions, so I can call it latter on in my template. With single reverse foreign key call I would do something like: category: Category = self.topic_set.all() but I need to get one level deeper for Post. Is there any smarter way to do it instead of list comprehension like [topic.post_set.first() for topic in self.topic_set.all()] ?? -
How to resolve Positional Arguments error in Python
Am getting an error with below code. How can i get this error resolved def verify_payment (request: HttpRequest, ref: str, amount )-> HttpResponse: payment = get_object_or_404(Payment, ref=ref) amount = get_object_or_404(Payment, amount=amount) verified = payment.verify_payment() if verified : with transaction.atomic(): account = Account.objects.select_for_update().get(user=request.user) account.balance += amount asof = account.modified account.save(update_fields=[ 'balance', 'modified', ]) else: messages.error(request, "verification failed") return redirect('initiate-payment') Error response = wrapped_callback(request, *callback_args, **callback_kwargs) TypeError: verify_payment() missing 1 required positional argument: 'amount' How do i resolve this error. amount is a field in Payment model -
Connect two Django models
Hi! I'm trying to make a auctions website for a project and I can't get to connect 2 models I have in my models.py page, a model for the auction listings (Alisting) and a model for the bids that are made(Bid). -The Alisting model has 4 fields: "title" CharField for the title of the auction, "sta_bid" for a starting bid, "las_bid" ForeignKey to Bid model, and user ForeignKey to User. -The Bid model has 3 fields: "user" ForeignKey to User for the user that makes the bid, "listing" a ForeignKey to Alisting, and "new_bid" IntegerField for the latest bid. class User(AbstractUser): pass class Alisting(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=32) sta_bid = models.IntegerField() las_bid = models.ForeignKey(Bid, on_delete=models.CASCADE) class Bid(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) listing = models.ForeignKey(Alisting, on_delete=models.CASCADE) new_bid = models.IntegerField() How could I connect these 2 models so that when I create a listing I can create new bids to this listing from the other model. Because later in the project I'll have to allow users to modify bids from other user's listings. Thank you in advance! -
Saving data to Django database with Views
I need help with one thing in my django project. I have class games_renderer in my views.py which is connected to the path in URLs. I need this class to take three values and then store them in the SQL database in Django in the created UserGameScore model. I tried to do this using model.object.score but the application reports an error. I think the problem is that the application does not know which line to assign the value to, but I do not know where I can determine this value, using the value player_id. The Game_id value is used to specify in which column the value is to be written.Can anybody help me, it is urgent! views.py def games_renderer(request, game_id, player_id, score): if game_id == 1: UserGameScore.objects.create(game1_score = score) elif game_id ==2: UserGameScore.objects.create(game2_score = score) elif game_id ==3: UserGameScore.objects.create(game3_score = score) else: return render(request, 'result.html',{'game_id' : game_id, 'player_id' : player_id, "score" : score} ) models.py class UserGameScore(models.Model): user_rec = models.ForeignKey(User, on_delete=models.CASCADE) game1_score = models.IntegerField(null=True, blank=True) game2_score = models.IntegerField(null=True, blank=True) game3_score = models.IntegerField(null=True, blank=True) -
I'm trying to override a django formtools wizard form widget, but it is just using the standard widget
I have the following form class ProviderSignUp1(forms.ModelForm): class Meta: model = models.Provider fields = [ 'childcare_type_informal', 'childcare_type_accredited', ] wigdets = { 'childcare_type_informal': PatchRadioSelect( attrs={ 'class':'form-control' } ), 'childcare_type_accredited': PatchRadioSelect( attrs={ 'class':'form-control' } ) } def clean(self): cleaned_data = self.cleaned_data if cleaned_data['childcare_type_informal'] == True and cleaned_data['childcare_type_accredited'] == True: raise ValidationError("You must select only one type of childcare") if cleaned_data['childcare_type_informal'] == False and cleaned_data['childcare_type_accredited'] == False: raise ValidationError("You must select at least one type of childcare") return super().clean() The widget is defined as from django.forms.widgets import RadioSelect class PatchRadioSelect(RadioSelect): template_name = 'userprofiles/form_widgets/radio.html' option_template_name = 'userprofiles/form_widgets/radio_option.html' And my wizard is: PROVIDER_SIGNUP_TEMPLATES = { 'page0': 'userprofiles/provider_signup_wizard/page0.html', 'page1': 'userprofiles/provider_signup_wizard/page1.html', 'page2': 'userprofiles/provider_signup_wizard/page2.html', 'page3': 'userprofiles/provider_signup_wizard/page3.html', 'page4': 'userprofiles/provider_signup_wizard/page4.html', 'page5': 'userprofiles/provider_signup_wizard/page5.html', 'page6': 'userprofiles/provider_signup_wizard/page6.html', 'page7': 'userprofiles/provider_signup_wizard/page7.html', 'page8a': 'userprofiles/provider_signup_wizard/page8.html', 'page8b': 'userprofiles/provider_signup_wizard/page8.html', 'page9': 'userprofiles/provider_signup_wizard/page9.html', 'page10': 'userprofiles/provider_signup_wizard/page10.html', } PROVIDER_SIGNUP_FORMS = [ ("page0", forms.ProviderSignUp0), ("page1", forms.ProviderSignUp1), ("page2", forms.ProviderSignUp2), ("page3", forms.ProviderSignUp3), ("page4", forms.ProviderSignUp4), ("page5", forms.ProviderSignUp5), ("page6", forms.ProviderSignUp6), ("page7", forms.ProviderSignUp7), ("page8a", forms.ProviderSignUp8a), ("page8b", forms.ProviderSignUp8b), ("page9", forms.ProviderSignUp9), ("page10", forms.ProviderSignUp10), ] def accredited_only_condition(wizard): cleaned_data = wizard.get_cleaned_data_for_step('page1') or {} return cleaned_data.get('childcare_type_accredited', True) def informal_only_condition(wizard): cleaned_data = wizard.get_cleaned_data_for_step('page1') or {} return cleaned_data.get('childcare_type_informal', True) class ProviderSignUpWizard(SessionWizardView): form_list = PROVIDER_SIGNUP_FORMS condition_dict = { 'page2': accredited_only_condition, 'page8a': accredited_only_condition, 'page8b': informal_only_condition, 'page9': informal_only_condition, } def get_form_instance(self, step): if step == 'page4': return self.instance_dict.get(step, self.request.user) … -
Unique together in models
I have a model called Company. In a second model which is Branch, I use Company as a foreign key. class Branch(models.Model): tenant = models.ForeignKey(Company, on_delete=models.CASCADE) Now in some other model, I want to set a property(name) unique together with the Company but I use the branch as a foreign key. class ABC(models.Model): name = models.CharField() branch = models.ForeignKey(Branch, on_delete=models.CASCADE) class Meta: unique_together = ( ('branch.Company', 'code'), ) can I do something like the above? It gives me an error that the field is nonexistent. Or can I use both company and branch in my model as foreign key? class ABC(models.Model): name = models.CharField() branch = models.ForeignKey(Branch, on_delete=models.CASCADE) company = models.ForeignKey(Company, on_delete=models.CASCADE) class Meta: unique_together = ( ('company', 'code'), ) I want to attach ABC object with a branch but if once added it should be unique to that company. (other branches of that company can not have the same name). Read about the circular error and was thinking of the same here. Unique together will bE depreciated in the future but I'm not thinking about this right now. Any advise ? -
Django ORM prefetch field from manual join table on many-to-many relationship
I'm facing an n-plus-1 query explosion after changing a Django model and I think it is because I am having to re-query for fields from a manual join table As a stripped-down example class Dashboard(models.Model): team: models.ForeignKey = models.ForeignKey("Team", on_delete=models.CASCADE) items = models.ManyToManyField("Item", related_name="dashboards", through="DashboardItem") class Item(models.Model): deleted: models.BooleanField = models.BooleanField(default=False) class DashboardItem(models.Model): class Meta: unique_together = ( "dashboard", "item", ) dashboard = models.ForeignKey(Dashboard, on_delete=models.CASCADE) item = models.ForeignKey("Item", on_delete=models.CASCADE) combo_hash: models.CharField = models.CharField(max_length=400, null=True, blank=True) If I'm querying for a dashboard and know I need to see its items with only 2 queries I can do this dashboards = Dashboard.objects.filter(items__deleted==False).select_related("team").prefetch_related('items') but later in the code, despite having the opportunity to prefetch on dashboard or item. I find I'm needing to do DashboardItem.objects.filter(item=item,dashboard=dashboard).first().combo_hash How do I prefetch values on the manual through table when I load the dashboard or item? -
Docker and django No module named 'corsheaders'
Im trying to dockerize an existing django project. I have corsheaders installed and its included in my installed apps as follows: INSTALLED_APPS = [ 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] and in the middleware MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] after that i build my docker using docker-compose --build and then run it docker-compose up but always the same error ModuleNotFoundError: No module named 'corsheaders' i have tried to delete corsheaders from my installed aps but then i get ModuleNotFoundError: No module named 'restframework' ps: if i run the server through py manage.py runserver it works perfectly. -
Sum gives wrong results in Django [closed]
Why would such single sum still return wrong results? total = Mark.objects.filter(marks_class=card_class, year=year, term=term).values('child','exam_set').annotate( mtotal=Sum('marks'), ptotal=Sum('value'), avg=Round(Avg('marks', output_field=IntegerField()), 0)).order_by('-mtotal') -
Tastypie: How can I create an "abstract" ModelResource class with a Meta class
Using django-tastypie I'd like to create a child class of ModelResource to define some common things, which all my other API resource classes would inherit from. e.g.: class MyModelResource(ModelResource): class Meta: authentication = SessionAuthentication() authorization = APIAuthorization() always_return_data = True # Some other common methods here class UserResource(MyModelResource): class Meta(MyModelResource.Meta): queryset = User.objects.all() However, if I do this, I get the following error: django.core.exceptions.ImproperlyConfigured: ModelResource (MyModelResource) requires Meta.object_class or Meta.queryset So I must set object_class or queryset in MyModelResource.Meta, even though it's a kind of 'Abstract' class. I can set abstract = True in MyModelResource.Meta, and this works, so long as I remember to set abstract = False in every one of its child classes. Is there a better way to do this? -
Rendering local web pages as an iFrame in Django
I have a view that uploads a zip file, checks if it contains an index.html file, and unzips it in a specific folder in the static directory. I want to be able to view this by going to a page where there is an iFrame pointing to this directory, and the user will be able to navigate inside this html page. But I can't seem to get it to work. Here is the function that uploads the zip file, and the view that uses it: views.py: @user_passes_test(lambda u: u.is_staff or u.is_superuser) def createCategory(request): if request.method == "POST": name = request.POST.get("name_kw") lang = request.POST.get("lang_kw") moduleid = request.POST.get("module_kw") zip = request.FILES.get("zip_kw") category = Category() category.name = name category.lang = lang category.module = Module.objects.get(id=moduleid) category.zip = zip category.created_by = request.user try: if zip.name.endswith(".zip"): rtn = publish_doc(category.name, zip) if rtn == "No index file found": messages.error( request, "Pas de fichier index.html détecté. Assuez-vous qu'un fichier index.html est présent dans votre fichier ZIP", ) return redirect("categoryList") else: category.root = rtn category.save() messages.success(request, "Catégorie créée avec succès") print("categorie et zip créées") return redirect("categoryList") else: messages.error( request, "Seuls les fichiers .ZIP sont acceptés", ) return redirect("categoryList") except IntegrityError: print("erreuuuuuuuur") messages.error( request, "Une erreur s'est produite. Veuillez réessayer … -
Using templatetag "get_comment_list" from view, in Django comments?
I have a template expression {% get_comment_list for data.post as comment_list %}, it uses get_comment_list from Django-comments. It gets a list of comment objects for a specified object (in this case the Post object through data.post) However, I'm currently working on client side Ajax API to retrieve the comments and its related user data. So I cannot use the template html way to get/render the data, but in a view, Python script. I found that the tag get_comment_list is defined as follows: # django_comments/templatetags/comments.py @register.tag def get_comment_list(parser, token): return CommentListNode.handle_token(parser, token) I know how to import custom template tag to a view so Python can use it, like: @register.simple_tag def addFoo(value=""): return value + "Foo." The above type of tag is simply passing a string value, but the get_comment_list(parser, token) tag requires two parser thing and object thing object, it's not a plain string type. Now, I have no idea how I can construct that parser and token or pass a model to get_comment_list to get the comment objects. Is it possible to use this type of template tag in a view? Thanks. -
Connection to the postgres refused in Github Actions
I have a Django app with Postgres default database, running in docker. I also use Github actions as a CI. When I run the tests locally using the command docker-compose run --rm app sh -c "python manage.py wait_for_db && pytest -s -v" everything works fine. However, I get the following error when I use the same command in GitHub actions: E django.db.utils.OperationalError: connection to server at "postgres" (172.18.0.2), port 5432 failed: Connection refused E Is the server running on that host and accepting TCP/IP connections? /usr/local/lib/python3.10/site-packages/psycopg2/__init__.py:122: OperationalError Here is my github workflow code: # This workflow will install Python dependencies, run tests and lint with a single version of Python # For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions name: Python application on: push: branches: [ main ] pull_request: branches: [ main ] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Set up Python 3.10 uses: actions/setup-python@v2 with: python-version: "3.10" - name: Install docker-compose run: | pip install docker-compose - name: Test with pytest run: | docker-compose run --rm app sh -c "python manage.py wait_for_db && pytest -s -v" My docker-compose code: version: "3" services: postgres: image: postgres:14-alpine environment: - POSTGRES_DB=app - POSTGRES_USER=postgres - POSTGRES_PASSWORD=123 ports: - "5432:5432" app: build: context: … -
Django REST Framework update record mixin
I'm using Django 3.2 and the last version of djangorestframework. I need to be able to update the values of JobStatus record already crated before. As example I have { "id": 1, "status_timestamp": "2022-04-07T10:51:42Z", "status_activity": "Sync DDT", "status_status": "running", "launcher": 1 } and I need to obtain this (in the DB) via API { "id": 1, "status_timestamp": "2022-04-07T11:51:42Z", "status_activity": "Sync DDT", "status_status": "completed", "launcher": 1 } Can someone help me out? PS I need to mantain the Token authentication method MODELS class JobStatus(models.Model): status_timestamp = models.DateTimeField() status_activity = models.CharField(max_length=200) status_status = models.CharField(max_length=200) launcher = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.RESTRICT) class Meta: verbose_name = "Status" verbose_name_plural = "Status list" def __str__(self): return str(self.status_timestamp) + " " + self.status_activity URLS from django.urls import path, include from apps.api_c import views from rest_framework.routers import DefaultRouter from rest_framework.urlpatterns import format_suffix_patterns router = DefaultRouter() router.register('alert', views.AlertViewSet) router.register('jstatus', views.UpdateStatus) urlpatterns = [ ... path("", include(router.urls)), ] VIEWS class UpdateStatus(viewsets.GenericViewSet, mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin): """update status""" authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) serializer_class = StatusSerializer #queryset = JobStatus.objects.all() #TEST1 def put(self, request, *args, **kwargs): return self.update(request, *args, **kwargs) #TEST2 def perform_update(self, serializer): serializer_class.update() -
Class-Based View of 'User' model auto-authenticates user
I've made a class-based view (DetailView) of app user's profile and for some reason anyone who visits the view is automatically considered authenticated even without entering any credentials. This happens without adding any extra logic in neither view nor template, just basic DetailView. The code is below: views.py from django.views.generic import DetailView from django.contrib.auth.models import User class ProfileDetail(DetailView): model = User template_name = 'index.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context urls.py from django.urls import path from .views import ProfileDetail urlpatterns = [ path('<int:pk>/', ProfileDetail.as_view()) ] template (index.html) {{ user.is_authenticated }} {# returns True #} {{ user }} {# returns the user with the corresponding id #} The question is why does Django do it and is there any way to circumvent it except of using function-based view? I've looked through the docs, but couldn't find an answer. -
Negative value will rise validation error
I want to implement custom validation for negative value , can any one help me for this. So in the object we do not allow user to add negative value. -
I am trying to get the weather details from an API on django however I am facing an error and I can't get past it
def index(request): if request.method == 'POST': start_city = request.POST['city'] city= str(urlparse(start_city)) start_url = 'https://api.openweathermap.org/data/2.5/weather?city='+city+'&appid=<APPID>' url = start_url.replace(' ','') res = urllib.request.urlopen(url).read() json_data = json.loads(res) context = { 'city': city, 'country': json_data['sys']['country'], 'windspeed':json_data['wind']['speed'], 'temperature':json_data['main']['temp'], } else: city='' return render(request,'index.html', {'city':city}) ERROR HTTPError at / HTTP Error 400: Bad Request Request Method: POST Request URL: http://127.0.0.1:8000/ Django Version: 4.0.3 Exception Type: HTTPError Exception Value: HTTP Error 400: Bad Request -
Why LoginRequiredMixin don't stop my dispatch flow, when user is not authenticated
I have no clue why in this View, dispatch does not end after super(): class CreateBookView(LoginRequiredMixin, CreateView): template_name = 'library/create_book.html' form_class = BookForm def dispatch(self, request, *args, **kwargs): result = super().dispatch(request, *args, **kwargs) if self.request.user.is_authenticated and not self.request.user.contactform.is_completed: return redirect(reverse_lazy('edit_contacts') + f"?next={self.request.path}#edit") return result def form_valid(self, form): form.instance.owner = self.request.user form.instance.category = self._set_category(form) return super().form_valid(form) def get_success_url(self): pk = self.request.user.pk default_redirect = reverse_lazy('show_books_dashboard', kwargs={'pk': pk}) next_page = self.request.GET.get('next') return next_page if next_page else default_redirect @staticmethod def _set_category(form): category = form.cleaned_data.get('category') category_name = form.cleaned_data.get('category_name') if category or not category_name: return category new_category, created = Category.objects.get_or_create(name=category_name) return new_category But in this it works as I expected and end it: class DetailsNotificationView(LoginRequiredMixin, AuthorizationRequiredMixin, DetailView): model = Notification context_object_name = 'notification' template_name = 'common/notifications/notifications_details.html' authorizing_fields = ['recipient'] def dispatch(self, request, *args, **kwargs): result = super().dispatch(request, *args, **kwargs) notification = self.get_object() notification.is_read = True notification.save() if notification.offer: return redirect('show_offer_details', pk=notification.offer.pk) return result I expect LoginRequiredMixin to handle error immediately after super() when the user is not authenticated and stop dispatch flow. I cannot figure out why it does not work as expected in CreateBookView. Any ideas ? -
mod_wsgi not using venv
Hello I am trying to setup a Django project using Apache with mod_wsgi. I have set wsgi like this WSGIDaemonProcess Breath python-home=/var/www/vhosts/Breath/env/ WSGIProcessGroup Breath WSGIScriptAlias / /var/www/vhosts/Breath/BreathAlessio/wsgi.py process-group=Breath So I'd like to launch the wsgi.py with the version in the venv, but by checking the version I see it runs it with the default python installation. What am I doing wrong? I have tried to set all the permission to 777 and to change the owner of the project but nothing changed Thanks in advance. -
Pip: Fatal error in launcher: Unable to create process using
I developed a complete Django project on my system. When I try to run on another system, after activating my virtual environment "data". It shows me the path of my system (where it's developed). (data) PS D:\Hafiz\Data_Collection> pip Fatal error in launcher: Unable to create process using '"D:\Masters_FIT\4th\Webdatabese\Project\Data_Collection\Data\Scripts\python.exe" "D:\Hafiz\Data_Collection\data\Scripts\pip.exe" ': The system cannot find the file specified. On other systems python, pip, and Django are installed with their latest versions and paths are also added. I tried a new project there and it's working properly. -
How set username to ForeignKey
I want to set value, but i don't know how do it. Error: RelatedObjectDoesNotExist at /comments/ commentsTabl has no avtor. Request Method: GET Request URL: http://localhost:8000/comments/ Django Version: 4.0.2 Exception Type: RelatedObjectDoesNotExist Exception Value: commentsTabl has no avtor. Exception Location: D:\python39\lib\site-packages\django\db\models\fields\related_descriptors.py, line 197, in get Python Executable: D:\python39\python.exe Python Version: 3.9.6 Python Path: ['D:\Django\ForumXT\first', 'D:\python39\python39.zip', 'D:\python39\DLLs', 'D:\python39\lib', 'D:\python39', 'D:\python39\lib\site-packages'] Server time: Thu, 07 Apr 2022 12:20:35 +0000 models.py class commentsTabl(models.Model): Text = models.TextField(verbose_name='Text') date = models.DateTimeField(default=timezone.now, verbose_name='date') avtor = models.ForeignKey(User, verbose_name='avtor', on_delete=models.CASCADE, to_field="username") def __str__(self): return f'Comment {self.avtor} at {self.date}' class Meta: verbose_name = "Comment" verbose_name_plural = "Comments" views.py def comments(request): data = { 'com': reversed(commentsTabl.objects.all()) } if request.method =="POST": form = commentsTabl(request.POST) if form.is_valid(): form.save() else: form = commentsTabl() return render(request, 'home/comments.html', data, {'form':form}) -
Django csrf token + react
I'm using django for my API and react for my frontend app. My problem is I do not know how to get csrf token which is needed to submit the login form (I do not need registrition form, just few users). This is the code for handling the /accounts/login : from django.contrib.auth import authenticate, login from django.http import JsonResponse from json import loads def login_user(request): body_unicode = request.body.decode('utf-8') body = loads(body_unicode) username = body['username'] pwd = body['pwd'] user = authenticate(request, username=username, password=pwd) try: if user.is_authenticated: login(request, user) email = User.objects.get(username=username).email return JsonResponse({"username":username, \ "pwd":pwd, \ "email":email }, \ status=200)` except Exception as expt: return JsonResponse({"error": str(expt)}, status=401) And in my react app I'm trying to make a request for logging /accounts/login using the X-CSRFToken header and the csrf token goten by the getCookie() function (found here), but it is always null and the response always rejected with 403 status code. Could you please show me how I can handle that situation please ? (I do not want to use csrf_exempt which pose security issues). -
I can't filter the product vendor for orders
I want special users (vendors) to see their own orders in their django admin. When ever I tried that it filters out the user that ordered the products. Here are the codes. I connected the vendors in my product model. I can't figure out how to connect vendors with their respective orders. class Order(models.Model): STATUS = ( ('New', 'New'), ('Accepted', 'Accepted'), ('Preparing', 'Preparing'), ('OnShipping', 'OnShipping'), ('Completed', 'Completed'), ('Canceled', 'Canceled'), ) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) code = models.CharField(max_length=5, editable=False) first_name = models.CharField(max_length=10) last_name = models.CharField(max_length=10) phone = models.CharField(blank=True, max_length=20) address = models.CharField(blank=True, max_length=150) city = models.CharField(blank=True, max_length=20) country = models.CharField(blank=True, max_length=20) total = models.FloatField() status=models.CharField(max_length=10,choices=STATUS,default='New') ip = models.CharField(blank=True, max_length=20) adminnote = models.CharField(blank=True, max_length=100) create_at=models.DateTimeField(auto_now_add=True) update_at=models.DateTimeField(auto_now=True) class OrderProduct(models.Model): STATUS = ( ('New', 'New'), ('Accepted', 'Accepted'), ('Canceled', 'Canceled'), ) order = models.ForeignKey(Order, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) variant = models.ForeignKey(Variants, on_delete=models.SET_NULL,blank=True, null=True) # relation with variant quantity = models.IntegerField() price = models.FloatField() amount = models.FloatField() status = models.CharField(max_length=10, choices=STATUS, default='New') create_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.product.title class OrderAdmin(admin.ModelAdmin): list_display = ['first_name', 'last_name','phone','city','total','status','create_at'] list_filter = ['status'] readonly_fields = ('user','address','city','country','phone','first_name','ip', 'last_name','phone','city','total') can_delete = False inlines = [OrderProductline] class OrderProductAdmin(admin.ModelAdmin): list_display = ['user', 'product','price','quantity','amount'] list_filter = ['product'] … -
typeError: unsupported operand type(s) for -: 'long' and 'datetime.date'
For this piece of code (the model had other things too, but I deleted them so I can get a minimal example): class Invoice(models.Model): """ Represents one invoice line in the imported data. """ payment_date = models.DateField( blank=True, null=True, help_text="Format: YYYY-MM-DD") date = models.DateField(db_index=True, blank=True, null=True, help_text="Format: YYYY-MM-DD") date_diff = models.IntegerField(default=0) class Meta: app_label = 'analysis' ordering = ('claim_order',) def clean(self): self.date_diff = ( self.payment_date - self.date).days if (self.payment_date and self.date) else 0 I get typeError: unsupported operand type(s) for -: 'long' and 'datetime.date' and I can't see why, because both of the fields are DateFields. Can anybody help me understand why this happens? Thanks.