Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot change istance in a queryset/dropdownlist, with no errors
I am currently developing an app to manage apartments. One requirement is to be able to handle payment from tenants by utilizing his room/security deposit. For this case, the involve models will be as follows (minimum setup): ''' class Billing(models.Model): bill_batch = models.ForeignKey(BillBatch, on_delete=models.PROTECT) reservation = models.ForeignKey( 'tenants.Reservation', on_delete=models.PROTECT) rental = models.DecimalField(max_digits=9, decimal_places=2, default=0) electricity = models.DecimalField(max_digits=9, decimal_places=2, default=0) water = models.DecimalField(max_digits=9, decimal_places=2, default=0) class SecurityDeposit(models.Model): payments = models.ForeignKey(Payment, on_delete=models.PROTECT) reservations = models.ForeignKey( 'tenants.Reservation', on_delete=models.PROTECT) deposit_date = models.DateField(default=date.today, verbose_name='Date deposited') deposited_amount = models.DecimalField(max_digits=9, decimal_places=2, default=0, verbose_name='Amount deposited') class ConsumeDeposit(models.Model): billings = models.ForeignKey( 'billings.Billing', on_delete=models.PROTECT) security_deposits = models.ForeignKey( SecurityDeposit, on_delete=models.PROTECT) pay_date = models.DateField() allocated_amount = models.DecimalField( max_digits=9, decimal_places=2, default=0) ''' In my code, ''' class ConsumeDepositEditMixin(object): def dispatch(self, request, *args, **kwargs): self.consume_deposit = get_object_or_404( SecurityDeposit, id=self.kwargs['deposit_id']) # the qs must contain only billings exclusive to the reservation # by which the deposit is allocated for; that is, deposit can't be consumed # by other room reservations of the same tenant self.billing_qs = Billing.objects.filter( reservation=self.consume_deposit.reservations) # TODO: need fix, can't change billing item return super().dispatch(request, *args, **kwargs) def get_form(self, form_class=None): form = super().get_form(form_class=None) form.fields['security_deposits'].widget = forms.HiddenInput() form.fields['billings'].queryset = self.billing_qs return form ''' In the tests I made, I have 2 billings available, … -
Django - PUT endpoint authenticator error "wrapped_view() missing 1 required positional argument: 'request'"
So I'm trying to create a PUT endpoint for editing post data. In the endpoint the post id is given in the URL then the new post dated is inserted into the entity. The issue I'm running into is that request isn't coming through on the authenticator (I'm using Cognito to authenticate, not super important for the error). So even though you can see I'm clearly passing in data, the request isn't coming through on the wrapped_view in the cognito_authenticator function. Why is this happening? The error I'm getting is: "wrapped_view() missing 1 required positional argument: 'request'" Test.py def test_edit(self): response = self.client.put(reverse('edit_post_by_id', kwargs={'post_id': str(self.post.uuid)}), data={'body': 'updated text #update'}, content_type='application/json', **{'HTTP_AUTHORIZATION': f'bearer {self.cognito.access_token}'}) self.assertEqual(response.status_code, status.HTTP_200_OK) View.py @api_view(['PUT']) @method_decorator(cognito_authenticator) def edit_post(request, post_id): try: post = Post.objects.get(pk=post_id) except Post.DoesNotExist: return JsonResponse(dict(error=f'Post id: {post_id} does not exists'), status=status.HTTP_400_BAD_REQUEST) authenticator def cognito_authenticator(view_func=None): if view_func is None: return partial(cognito_authenticator) @wraps(view_func) def wrapped_view(request, *args, **kwargs): # Check the cognito token from the request. auth = request.headers.get("Authorization", None) if not auth: return Response(dict(error='Authorization header expected'), status=status.HTTP_401_UNAUTHORIZED) parts = auth.split() if parts[0].lower() != "bearer": return Response(dict(error='Authorization header must start with bearer'), status=status.HTTP_401_UNAUTHORIZED) elif len(parts) == 1: return Response(dict(error='Token not found'), status=status.HTTP_401_UNAUTHORIZED) elif len(parts) > 2: return Response(dict(error='Authorization header … -
Field 'card_exp_month' expected a number but got (4,) - Django and stripe API when adding to model
I'm writing a second ecommerce site. The first one seems to work perfectly well when downloading data from the stripe API. It extracts the card details and saves the information to the model perfectly. The second site, I keep getting the following error and I can't see why. Any help to track this down would be great! Field 'card_exp_month' expected a number but got (4,). This is the code which is being run to save the data I'm getting: def process_card(order, charge): print("I HAVE THE DATA AS: ", charge) print("I have the brand as: ", charge.payment_method_details.card.brand) print("I have the expiry year as: ", charge.payment_method_details.card.exp_year) print("I have the expiry month as: ", charge.payment_method_details.card.exp_month) print("I have the last 4 as: ", charge.payment_method_details.card.last4) payment = order.payment payment.stripe_payment_intent = order.stripe_payment_intent payment.total_paid = Money(charge.amount / 100, charge.currency) payment.card_brand = str(charge.payment_method_details.card.brand), payment.card_exp_year = int(charge.payment_method_details.card.exp_year), payment.card_exp_month = int(charge.payment_method_details.card.exp_month), payment.card_last4 = str(charge.payment_method_details.card.last4), payment.receipt_url = charge.receipt_url payment.save() order.stripe_payment_intent = None order.order_flow = "PAID" order.save() When I view the console I get the following output which seems to show the correct values followed by the error message! I have the brand as: visa I have the expiry year as: 2024 I have the expiry month as: 4 I have the … -
how to return queryset as a list on seperate lines, without the brackets
I have my model for my lessons: class Lessons(models.Model): student = models.ForeignKey(Students, on_delete=models.SET_NULL, null=True) headed_by = models.ForeignKey(Tutors, on_delete=models.SET_NULL, null=True) day = models.CharField(max_length=4, choices=DAY_CHOICES, null=True) start_time = models.TimeField(null=True, blank=True) type = models.CharField(max_length=7, choices=TYPE_CHOICES, null=True) price_band = models.CharField(max_length=7, choices=PAYMENT_TYPE_CHOICES, blank=True, null=True) created = models.DateTimeField(auto_now_add=True ) def __str__(self): return str(self.student) + " at " + str(self.start_time)+ " on " + str(self.day) class Meta: ordering=['student',"headed_by",'day','start_time'] I have my Query set: tn_mon = Lessons.objects.all().filter(headed_by__name="Tutor Name").filter(day__icontains="Mon") which returns <QuerySet [<Lessons:Studentname1 at Time on Day>, <Lessons:Studentname2 at Time on Day> how can i return the output without the queryset, ,<> [] so that it returns as set out like below? Studentname1 at Time on Day, Studentname2 at Time on Day -
My urls is not updating correctly adding some extra path itself
I want to update the lead lead of the url If you look on the url section it says update_lead/1 which is perfectly right but when i hit update lead i am getting extra update lead in the url section due to which django cant reach its function i am very confuse about it please help here are my codes from update_lead.html {% extends 'base.html' %} {% block exhead %} {% endblock exhead %} {% block body %} <div class="container"> <h2>Update Lead</h2> <form action="update_lead_handle" method="POST"> {% csrf_token %} <div class="form-row"> <div class="form-group col-md-6"> <label for="inputEmail4">Name</label> <input type="text" class="form-control" id="inputEmail4" required name="name" value="{{lead.name}}"> </div> <div class="form-group col-md-6"> <label for="inputPassword4">Subject</label> <input type="text" class="form-control" id="inputPassword4" name="subject" required value="{{lead.subject}}"> </div> </div> <div class="form-row"> <div class="form-group col-md-6"> <label for="inputAddress">Email</label> <input type="email" class="form-control" id="inputAddress" name="email" placeholder="abc@email.com" value="{{lead.email}}"> </div> <div class="form-group col-md-6"> <label for="inputAddress2">Contact Number</label> <input type="number" class="form-control" id="inputAddress2" name="number"value = "{{lead.mobile_no}}" placeholder="99XX80XXXX"> </div> </div> <div class="form-row"> <div class="form-group col-md-4"> <label for="inputState">Source</label> <select id="inputState" class="form-control" name="source" > <option selected value="{{lead.source}}">{{lead.source}}</option> {% for x in source %} <option value="{{x.name}}">{{x.name}}</option> {% endfor %} </select> </div> <div class="form-group col-md-4"> <label for="inputState">Assign To</label> <select id="inputState" class="form-control" name="assign"> <option selected value="{{lead.assign_to}}">{{lead.assign_to}}</option> {% for x in agent %} <option value="{{x.name}}">{{x.name}}</option> {% endfor %} … -
Django unit-testing for ProfileEditForm with disabled (read-only) fields
I want to write unit tests for my ProfileEditForm form that has some fields with disabled=True. So, these fields are read-only and cannot be changed. I want to test this logic. As far as I know, I don't have to give disabled fields to the form. The form itself validates these fields. models.py class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=63, blank=False) last_name = models.CharField(max_length=63, blank=False) about_me = models.CharField(max_length=511, blank=True) forms.py class ProfileEditForm(forms.ModelForm): class Meta: model = Profile fields = [ "username", "email", "first_name", "last_name", "about_me", ] username = forms.CharField(label="Username", disabled=True) email = forms.EmailField(label="Email", disabled=True) first_name = forms.CharField(label="First Name", max_length=63, required=False) last_name = forms.CharField(label="Last Name", max_length=63, required=False) about_me = forms.CharField(label="About Me", max_length=511, required=False) tests.py class ProfileEditFormTests(TestCase): def setUp(self) -> None: self.user = get_user_model().objects.create_user(username="testuser", email="test@test.com", password="password123") self.profile = Profile.objects.create(user=self.user) def test_email_field_is_not_editable(self): form_data = { "username": self.profile.user.username, "email": self.profile.user.email, "first_name": "first", "last_name": "last", "about_me": "", } form = ProfileEditForm(data=form_data) self.assertTrue(form.is_valid()) I get: AssertionError: False is not true When I print out the form errors with print(form.errors): <ul class="errorlist"><li>username<ul class="errorlist"><li>This field is required.</li></ul></li><li>email<ul class="errorlist"><li>This field is required.</li></ul></li></ul> Even if I provide all fields, the form is still invalid. form_data = { "username": self.profile.user.username, "email": self.profile.user.email, "first_name": "first", "last_name": "last", "about_me": "", } … -
Reverse for 'edit-item' with keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['dashboard/edit\\-item/(?P<slug>[^/]+)/$']
Can you please help me to find out the problem. Previously, the functions for editing and deleting the item are work. But, currently it shows me errors and I cannot find out the reason why this error happened suddenly. Can you guys please help me. I will be very appreciated. html {% for object in furniture %} <tr class="clickable-tr" href="{{ object.get_absolute_url }}"> <td>{{ object.furnitureId }}</td> <td>{{ object.furnitureName }}</td> <td>{{ object.categoryId.categoryName }}</td> <td class="text-center">{{ object.stock }}</td> <td class="text-center"> <a href="{{ object.slug }}"> <i class='material-icons' style="color: brown;">delete</i> </a> </td> </tr> {% endfor %} models.py def get_absolute_url(self): return reverse("administration:edit-item", kwargs={ 'slug': self.slug }) def delete_item_url(self): return reverse("administration:delete-item", kwargs={ 'slug': self.slug }) urls.py app_name = 'administration' urlpatterns = [ path('products/',views.prodManagement,name='dashboard'), path('add-item/',views.addProduct,name='add-item'), path('edit-item/<slug>/',views.editProduct, name='edit-item'), path('delete-item/<slug>/',views.deleteItem, name='delete-item'), ] views.py def prodManagement(request): context = { 'furniture':Furniture.objects.all(), 'category':Category.objects.all() } return render(request, 'admin/prod_management.html', context) def editProduct(request, fid): item = get_object_or_404(Furniture, slug=fid) category = Category.objects.all() context = { 'object':item, 'category':category } return render(request, 'admin/item.html', context) def deleteItem(request, slug): print('here') item = get_object_or_404(Furniture, slug=slug) item.delete() messages.success(request, 'Item is deleted.') return redirect('administration:dashboard') -
cant solve the problem > TypeError: create_superuser() missing 1 required positional argument: 'image'
hello there im new to django and im trying to create my own custom user and this TypeError made me go crazy while i was trying to run py manage.py createsuperuseri dont know how to fix it please review my problem and help me <3 if im missing any other things to mentions please tell me so i will edit my case TypeError: create_superuser() missing 1 required positional argument: 'image' from django.db import models import os from django.contrib.auth.models import User from django.contrib.auth.models import AbstractUser, AbstractBaseUser, PermissionsMixin, BaseUserManager class customMemberManager(BaseUserManager): def create_user(self, email, mobileNumber, name, familyName, password, nationalCode, image, **other_fields): if not email: raise ValueError('YOU MUST ENTER VALID EMAIL') email = self.normalize_email(email) user = self.model(email=email, mobileNumber=mobileNumber, name=name, image=image, familyName=familyName, password=password, nationalCode=nationalCode, **other_fields) user.set_password(password) user.image = image user.save() return user def create_superuser(self, email, mobileNumber, name, familyName, image, password, nationalCode, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError('superuser must be is_staff set to True') if other_fields.get('is_superuser') is not True: raise ValueError('superuser must be is_superuser set to True') return self.create_user(email, mobileNumber, name, familyName, password, nationalCode, image, **other_fields) class Members(AbstractBaseUser, PermissionsMixin): class Meta: verbose_name_plural = 'Members' name = models.CharField(max_length=50) familyName = models.CharField(max_length=50) email = models.EmailField(max_length=50) nationalCode = models.IntegerField(null=True) mobileNumber … -
CSRF token missing or incorrect - Django
I'm trying to build a Django webapp to test the functionalities of a Forex Converter I installed with pip. I created an application with django-startapp Converter and routed the url /convert to the view convert_view(). This is my views.py file: from django.shortcuts import render from forex_python.converter import CurrencyRates # Create your views here. def convert_view(request): if request.method == "POST": c = CurrencyRates() print(c.convert('EUR', 'RON', request.POST.get('eur'))) context = {} return render(request, "convert.html", context) Also, because my view returns a template convert.html, I created a form there. This is my convert.html: {% csrf_token %} <form action="." method="POST"> <input type="text" name="eur" placeholder="EUR"> <input type="submit"> </form> As you can see, just a simple page that has a form inside it, redirects to the same page and uses POST to send the data. It also uses the {% csrf_token %} tag, so there shouldn't be any problems. When I navigate to /convert everything works fine. I type in the amount of money I like to convert from EUR to RON, but when I send the POST request, I get redirected to an error page, telling me: CSRF token missing or incorrect. I read another article on stack overflow about not using request as a parameter … -
Django: Query database from Channels consumers.py (WebSocket is closed before the connection is established)
I had live chat functionality working, but now I am trying to add a query to the database within the connect method. I am following the Channels documentation, and tried the solution in this other StackOverflow question but nothing is working. Below is my code. The error I'm seeing in the Javascript console is WebSocket connection to 'ws://localhost:8000/ws/chat/334/' failed: WebSocket is closed before the connection is established. I do have redis-server running on localhost and that was working before, so that's not a problem. async def connect(self): print('connect (got here!)') self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name print('self.room_name: ' + str(self.room_name)) valid_connection = await database_sync_to_async(self.verify_chat_room_key)() print('valid_connection: ' + str(self.valid_connection)) # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def verify_chat_room_key(self): trans = database_sync_to_async(Transaction.objects.get)(id=self.room_name) print('trans.status: ' + str(trans.status)) return True -
How to modify docker settings for multiple database for a django project?
My development file is as follows: version: '3' services: db: image: mdillon/postgis container_name: sl_database ports: - "5432:5432" volumes: - db_vesatogo_starling_v1:/var/lib/postgresql/data env_file: - ./config/dev.env networks: - db_network pgadmin: image: dpage/pgadmin4:4.28 container_name: sl_admin links: - db depends_on: - db environment: PGADMIN_DEFAULT_EMAIL: admin PGADMIN_DEFAULT_PASSWORD: password ports: - "80:80" networks: - db_network redis: image: redis:latest container_name: sl_redis ports: - "6379:6379" restart: always networks: - redis_network networks: db_network: driver: bridge redis_network: driver: bridge volumes: db_vesatogo_starling_v1: static: Now, I have introduced a replica databases in my settings. What changes should I make in my development file to implement multiple databases? I tried adding database on another server which in this case is 5433 as I am running my main db on 5432 but it is showing me following error: "could not connect to server: Connection refused Is the server running on host "db-replica" (172.25.0.3) and accepting TCP/IP connections on port 5433?" Please help me out! -
How to get the model instance calling the mixin?
I am putting the form_valid() method into a mixin like this.. ''' class PaymentAtomicMixin(object): @transaction.atomic def form_valid(self, form): try: with transaction.atomic(): self.instance = form.save(commit=False) .... .... form.instance.user = self.request.user return super().form_valid(form) ''' 3 models are sub-classing/utilizing this mixin, and I will have to perform different actions depending on what model is executing the form_save() method. How will I know which model and the model instance is utilizing the mixin? (Django 3.2.7, Python 3.9.5) -
Need to deploy django app in Apache windows server 2016, Without C++ Build Tools
I have a Django app, I need to deploy this in Apache windows server 2016. But we were not able to deploy because of licensing issue. To deploy in windows we need Microsoft c++ build tools, but we can't install them because it's bundled with Visual Studio MSDN licensing. We are getting Microsoft c++ dependency errors while trying to install "wsgi" package, could you please tell me any alternate solution to install wsgi and deploy it in apache without using Microsoft c++ build tools. Thank You!! -
when i trying to add a data to database with Django i got error calls NOT NULL constraint failed: pages_login.password
The strange thing is I cant send data and add it to data base when I make user_data.save() comment and open the page then delete the # but when I go our from the page and try to join it again I got the error " NOT NULL constraint failed: pages_login.password " models.py folder from django.db import models class Login(models.Model): username = models.CharField(max_length=40) password = models.CharField(max_length=20) views.py folder from django.shortcuts import render from .models import Login def index(request): index_context = { 'name': 'yahia', 'age': '20', } return render(request, 'pages/index.html', index_context) def about(request): usernamee = request.POST.get('username') password = request.POST.get('password') user_data = Login(username=usernamee, password=password) user_data.save() return render(request, 'pages/about.html') here the user_data.save() when i comment it like this #user_data.save() the code word and the page opens and i can send the data when i remove the # but when i restart the page i get the error admin.py page from django.contrib import admin from .models import Login # Register your models here. admin.site.register(Login) the full error IntegrityError at /about/ NOT NULL constraint failed: pages_login.password Request Method: GET Request URL: http://127.0.0.1:8000/about/ Django Version: 3.2.7 Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: pages_login.password Exception Location: C:\Users\a\OneDrive - Higher Technological Institute\Desktop\test\lib\site-packages\django\db\backends\sqlite3\base.py, line 423, in … -
How to precisely set breakpoint when debugging remotely using PDB
I want to set breakpoint in like() function in below source code, ## views.py @csrf_protect @login_required def like(request, comment_id, next=None): However, in PDB prompt, when I use command break views.like to set break, the breakpoint goes to Breakpoint 1 at /usr/local/lib/python3.7/site-packages/django/utils/decorators.py:119, then after so many subsequent continue and next commands expecting to step into like() function soon, i failed and got lost. is there a way to set breakpoint and skip all those decorators ? or any convenient ways for me to view source file (views.py) remotely under PDB command prompt to identify which line to set breakpoint ? -
Two many values to unpack (expected two)
I'm making a python project for returning recipes with certain genres or ingredients. I'm getting a two many values to unpack error thrown when I am trying to create the genre in my database. def createbgenre(request): BreakfastGenre.objects.create(genre=request.POST['genre'],user=User.objects.get(request.POST['user'])) return redirect ('/breakfast') this breakfastgenre object creation is throwing the error. -
Is there a way to import a file in forms.py or views.py?
In my Django project I created a subdirectly country/translations where country is the name of the app, translations is the folder. I created __init__.py inside it, so Python will recognize it as a module and inside it I created a file, countries_fr.py. Inside countries_fr.py I have this custom translation function: def t_countries(c): country_dict = { "Albania" : "Albanie", "Algeria" : "Algérie", "Antigua and Barbuda" : "Antigua-et-Barbuda", "Argentina" : "Argentine", "Armenia" : "Arménie", # etc. } if c in country_dict: return country_dict[c] return c I don't use gettext in this case because the country list come form a json file and gettext doesn't translate data coming from databases or files. I want to use it in Forms.py this way def get_country(): filepath = 'myproj/static/data/countries_states_cities.json' all_data = readJson(filepath) all_countries = [('----', _("--- Select a Country ---"))] for x in all_data: y = (x['name'], t_countries(x['name'])) all_countries.append(y) return all_countries The problem is I can't import the infamous function I tried all this from .translations/countries_fr import t_countries from .translations.countries_fr import t_countries from translations.countries_fr import t_countries from translations import t_countries from translations import countries_fr from .translations import countries_fr from translations import t_countries from countries.translations import countries_fr from countries.translations.countries_fr import t_countries import countries.translations and more I have … -
Django channel occasionally gets error "cannot call this from an async context - use a thread or sync_to_async"
My project recently added django channel for websocket and layer: Django=3.2.6 Channel=3.0.4 channels-redis="3.3.0" gevent=21.8.0 gunicorn=20.1.0 Gunicorn and daphne run WSGI and ASGI separately, Nginx proxy the traffic to WSGI or ASGI. In my production environment, it has less 0.1% chances to get cannot call this from an async context - use a thread or sync_to_async. These errors are not from ASGI(daphne) but from normal WSGI(Gunicorn) requests, they didn't occur in same piece of code but the root cause is a database query. For example, this is in a database query: Traceback (most recent call last): File "/usr/local/lib/python3.8/dist-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.8/dist-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.8/dist-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/usr/local/lib/python3.8/dist-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.8/dist-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/usr/local/lib/python3.8/dist-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/usr/local/lib/python3.8/dist-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/usr/local/lib/python3.8/dist-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/opt/www/myproj/myproj/services/member_service.py", line 275, in _wrapped_view return view_func(api_view, request, *args, **kwargs) File "/opt/www/myproj/myproj/api/restful/form.py", line 108, in get published_form = PublishedForm.objects.get_latest_published_for_form(form_identifier, try_master_form=False) File "/opt/www/myproj/myproj/webform/models.py", line 44, in get_latest_published_for_form return self.filter(form_case__identifier=form_identifier, form_case__form_state=FORM_STATE_PUBLISHED).latest('version') File … -
How to insert a new row for each data in django?
I have a multiselct data (using select2) - by which user can select multiple datas and do a post ! This is how i receive the post request: <QueryDict: {'csrfmiddlewaretoken': ['XNcF2x.......'], 'document_type': ['equivalent', 'level', 'passport']}> So now, i need to insert new rows for each of "document_type", in other words if document_type has three datas then i need to make 3 new rows ! How to do that ? I have read few things bulk_create or is there any efficient way to achieve this ? -
How to protect Nginx autoindex within the scope of a Django project?
So I have a Django application that's not publicly accessible. I also utilize an autoindex through nginx which users can access. Problem is so can everyone else on the internet. How can I protect this autoindex location so that only logged in users can view it? -
Django Error - ValueError: Field 'id' expected a number but got 'company'
I'm currently writing an application in django called account, now everything was working fine (as it usually happens), but I had to add more information in my models.py file, and all of the sudden, I got problems running the migrations, certainly as django enthusiast the usual approach is to delete all the migrations in the migration folder, delete the Database and finally run the usual set of commands. Unfurtunetely this time, that trick is not solving my problem, and I'm getting the following error: ValueError: Field 'id' expected a number but got 'company'. That error appears when I type python manage.py migrate, the run migration runs without problems, and a migration 0001 file and a database is created, but I still get the error when running the migrate command. models.py from django.db import models from django.conf import settings from django_countries.fields import CountryField from phone_field import PhoneField from djmoney.models.fields import MoneyField class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) email = models.EmailField(blank=True,null=True) role = models.TextField(blank=True) location = models.TextField(blank=True) photo = models.ImageField(upload_to='users/%Y/%m/%d', blank=True) def __str__(self): return self.user class Company(models.Model): company = models.CharField(blank=True, max_length=30) def __str__(self): return self.company class Client(models.Model): firstname = models.CharField(blank=True, max_length=30) lastname = models.CharField(blank=True, max_length=15) company = models.ForeignKey(Company, on_delete=models.CASCADE, default="company") position = … -
Django: How can I changes values via views.py
I am trying to make a "upload" page so that I can upload a file and process to postgres DB using pd.to_sql(). All the data has been succefuly recorded into DB, but cannot change the values of "is_recorded" and "has_issue". Here is the files I am working on so far. In upload/models.py from django.db import models class Upload(models.Model): file_name = models.FileField(upload_to='uploads', max_length=255) uploaded = models.DateTimeField(auto_now_add=True) # When uploaded successfully is_recorded = models.BooleanField(default=False) # When it has a problem to fix has_issue = models.BooleanField(default=False) def __str__(self): return f'{self.file_name}: {self.id}' In views.py import os from django.shortcuts import render from core.db_implements import upload_csv_to_DB from upload.forms import UploadForm from upload.models import Upload def upload_view(request): error_message = None success_message = None form = UploadForm(request.POST or None, request.FILES or None) if form.is_valid(): form.save() form = UploadForm() try: obj = Upload.objects.get(is_recorded=False) recorded, issue, success_message, error_message = ***upload_csv_to_DB***(obj) obj.is_recorded = recorded obj.has_issue = issue obj.save() success_message = success_message error_message = error_message except: error_message = 'Something went wrong.' context={ 'form': form, 'success_message': success_message, 'error_message': error_message, } return render(request, 'upload/upload.html', context) In forms.py from django import forms from django.db.models import fields from django.forms.fields import FileField from django.forms.models import ModelFormMetaclass from .models import Upload class UploadForm(forms.ModelForm): # file_name = forms.FileField(max_length=255, label=False) … -
Remove record from database when session is expired
My cart is working based on sessions and Cart model. When an item is added to the cart the session is created and product added to the Cart model. Delete product from cart is handled by this function: def remove_cart(request, slug): cart_id = request.session['cart_id'] cart = Cart.objects.get(id=cart_id) try: product = Product.objects.get(slug=slug) cart.products.remove(product) cart.total -= product.price cart.save() except Product.DoesNotExist: pass except: pass if cart.products.count() < 1: cart.delete() return HttpResponseRedirect(reverse("cart")) When the user deletes every item from the cart, the record is deleted from the database so it doesn't store empty records. The problem is when the user leaves items in the cart and the session expires (for example: user logged out). The record stays in the database and will never be used again, so it just takes up space. What would I have to do, to delete the Cart model, when the session is expired? The Cart id corresponds to the session name. -
How to create new python classes with different names dynamically in a cycle? [duplicate]
I'm making a kind of online shop. I have a base abstract class and child classes for all products. ***models.py*** class Item(models.Model): class Meta: abstract = True class FirstItem(Item): pass class SecondItem(Item): pass I register all classes in admin.py ***admin.py*** class FirstItemAdmin(admin.ModelAdmin): inlines = [] def foo(): pass class SecondItemAdmin(admin.ModelAdmin): inlines = [] def foo(): pass admin.site.register(FirstItemAdmin) ... How can I dynamically create new classes with different names like class ThirdItemAdmin(), class FourthItemAdmin(), class FifthItemAdmin()... in a cycle so that these classes could be registered in further code ? admin.site.register(ThirdItemAdmin) admin.site.register(FourthItemAdmin) ... I tried like that def classMaker(*args, **kwargs): for class in args: new_class_name = cls.__name__ + 'Admin' type(new_class_name, (admin.ModelAdmin,), {}) classMaker(FirstItem, SecondItem, ThirdItem, FourthItem, FifthItem) and all classes are created, but they are invisible in further code. Is there a way to make it dinamycally or I'll have to make classes for all items manually ? -
how to get object numbers in django models
I am a new user in Django and I am trying to print the total number of objects in a model but this code below prints the query set with its title. Here's my function def showthis(request): count= Item.objects.count() print (count) I need to get the total number of objects in Model Item