Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
append data in list in django template
I want to create a list and append data within for loop in django template. How can i do this I try this but not working @register.simple_tag def appendDataInList(list_data, add_data): print(list_data, add_data) if list_data is not None: return list_data.append(add_data) return list_data In my view i have set a list like this return render(request, self.template_name, {'list_data' : [] } ) And in template {% for value in data %} {% appendDataInList list_data value.order_id as list_data %} {% endfor %} When i want to print this list out of loop {{ list_data }} #it give me only one result in list why? -
Django Form request.POST.get() returns none value
Here is my Django if request.method == 'GET': term = request.POST.get('term') grade = request.POST.get('grade') year = request.POST.get('year') Here is my HTML code <form method="GET"> <label><b>Term</b></label> <input type="text" name='term' id='term' placeholder="Ex:Term3"> <label><b>Grade</b></label> <input type="text" name='grade' id='grade' placeholder="Ex:Grade 11A"> <label><b>Year</b></label> <input type="number" name='year' id="year" placeholder="Ex:2021"> <button type="submit" class="btn btn-primary"><a href="{% url 'prediction'%} ">Search</a></button> </form> but term year and grade always show empty Any one cam help me -
Django UpdateView AttributeError 'UserPostUpdateView' object has no attribute 'publish'
I get the error when I try to save the form after editing. If I override get_context_date(currently commented out), I get the error when loading the form. I've looked at the documentation and previous questions with this problem. Those who ran into this had overridden post() which I have not. So I have no idea why this is happening and how to solve it. Would appreciate any help. Traceback Environment: Request Method: POST Request URL: http://127.0.0.1:8000/create/my_collideas/2021/7/28/title-2-by-user2/edit/ Django Version: 3.2.4 Python Version: 3.8.2 Installed Applications: ['home', 'search', 'userauth', 'blog', 'menus', 'contact', 'create', 'wagtail.contrib.forms', 'wagtail.contrib.modeladmin', 'wagtail.contrib.redirects', 'wagtail.contrib.table_block', 'wagtail.embeds', 'wagtail.sites', 'wagtail.users', 'wagtail.snippets', 'wagtail.documents', 'wagtail.images', 'wagtail.search', 'wagtail.admin', 'wagtail.core', 'modelcluster', 'taggit', 'allauth', 'allauth.account', 'allauth.socialaccount', 'ckeditor', 'widget_tweaks', 'dbbackup', 'django_extensions', 'captcha', 'wagtailcaptcha', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'debug_toolbar'] Installed Middleware: ['debug_toolbar.middleware.DebugToolbarMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', 'wagtail.contrib.redirects.middleware.RedirectMiddleware'] Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.8/site-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/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/contrib/auth/mixins.py", line 71, in dispatch return super().dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/views/generic/base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/views/generic/edit.py", line 194, in post return super().post(request, *args, **kwargs) File … -
How to allow sqlite3 databate take duplicate values in different rows providing the primary keys are different?
I'm trying to import a .csv file into my Django db.sqlite3 and I followed exactly as the the instructions from a Youtube video. However, there are a couple of rows in my .csv file that have the same latitude and longtitude values and sqlite3 fails to import some rows as the latitute and longtitude already appear in the table. sqlite> .import venues.csv myapi_venue venues.csv:17: INSERT failed: UNIQUE constraint failed: myapi_venue.name venues.csv:44: INSERT failed: UNIQUE constraint failed: myapi_venue.name venues.csv:49: INSERT failed: UNIQUE constraint failed: myapi_venue.name venues.csv:60: INSERT failed: UNIQUE constraint failed: myapi_venue.name venues.csv:66: INSERT failed: UNIQUE constraint failed: myapi_venue.name venues.csv:73: INSERT failed: UNIQUE constraint failed: myapi_venue.name venues.csv:80: INSERT failed: UNIQUE constraint failed: myapi_venue.name I tried to force the model to have unique as False, but it doesn't help. class venue(models.Model): name = models.CharField(_("name"), primary_key=True, max_length=300) address = models.CharField(_("address"), max_length=300, unique=False) categories = models.CharField(_("category"), null=True, max_length=300, unique=False) latitude = models.FloatField(_("latitude"), max_length=150, unique=False) longitude = models.FloatField(_("longitude"), max_length=150, unique=False) When I try migrate the changes, it shows this: $ python manage.py makemigrations No changes detected How do I import all the rows into the database? -
Cannot resolve keyword '_cart_id' into field. Choices are: cart_id, cartitem, date_added, id
views.py def allProdCat(request, c_slug=None): c_page = None products_list = None if c_slug != None: c_page = get_object_or_404(Category, slug=c_slug) products_list = Product.objects.all().filter(category=c_page, available=True) else: products_list = Product.objects.all().filter(available=True) paginator = Paginator(products_list, 6) try: page = int(request.GET.get('page', '1')) except: page = 1 try: products = paginator.page(page) except (EmptyPage, InvalidPage): products = paginator.page(paginator.num_pages) return render(request, "category.html", {'category': c_page, 'products': products}) category.html {% extends 'base.html' %} {% load static %} {% block metadescription %} {% if category %} {{category.description|truncatewords:155 }} {% else %} Welcome to ABC store where you can buy different items... {% endif %} {% endblock %} {% block title %} {% if category %} {{category.name }} - ABC Store {% else %} See our New Collections -ABC Store {% endif %} {% endblock %} {% block content %} {% if category %} {% endif %} {% if category %} {{category.name}} {{category.description}} {% else%} Our products Collections What is Lorem Ipsum Lorem Ipsum is simply dummy text of the printing and typesetting industry Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book it has? {% endif %} {% for products in … -
Sum values from child models using nested Subquery and annotaions in Django Viewset
I'm trying to calculate the total price of a Recipe. To optimize DB queries I'm trying to use Django's ORM capabilities to perform the fewest requests. My models.py is like this: class BaseRecipe(models.Model): title = models.CharField(_('Base recipe title'), max_length=255, user = models.ForeignKey(User, null=True, on_delete=models.CASCADE, related_name='user_base_recipes') class Meta: ordering = ['title'] def __str__(self): return self.title class IngredientBaseRecipe(models.Model): base_recipe = models.ForeignKey(BaseRecipe, on_delete=models.CASCADE, related_name='ingredients') name = models.CharField(_('Name'), max_length=255) products = models.ManyToManyField(Product) quantity = models.FloatField(_('Quantity'), default=0.0) class Meta: ordering = ['-id'] def __str__(self): return self.name class Product(models.Model): name = models.CharField(_('Name'), max_length=255, help_text=_('Product name')) price = models.FloatField(_('Sale price'), default=0) class Meta: ordering = ['name', ] indexes = [models.Index(fields=['name',]), ] Then in my Viewset I'm trying to get the BaseRecipes queryset with an annotated field that shows the sum of the ingredients prices. I get to the point to obtain the ingredients price, but I'm stucked trying to sum them in the BaseRecipe query set: min_price = ( Product.objects.filter(name=OuterRef('name')) .annotate(min_price=Min('price')) .values('min_price') ) ingredients_price = ( IngredientBaseRecipe.objects .filter(base_recipe=OuterRef('id')) .annotate(price=Subquery(min_price)) .order_by() .annotate(total=Sum(F('price') * F('quantity'))) .values('total') ) queryset = BaseRecipe.objects.filter(user=self.request.user) \ .annotate(cost=Sum(ingredients_price)) return queryset Thanks a lot for your help! -
How does Django map the urls when there is ambiguity
I have the url patterns in my project urls.py url(r'^', include('app.urls')), url(r'^api/app/', include('app.url.router_urls')), and in the app.urls i have something like url(r'^api/app/user$', views.user_validator), and in the app.url.router_urls i have something like url('^v1/', include('app.url.app_v1.urls')) I have a question around these. so when the request is BASE_URL/api/app/{user} which url will be mapped to this? and how about BASE_URL/api/app/v1/ which url will be mapped. this will map first with ^ right and will use the app.urls for both? thanks -
Warnings in command prompt about notepad after installation Of python package
Why its showing this warning "(process:14700): GLib-GIO-WARNING **: 12:08:05.830: Unexpectedly, UWP app HaukeGtze.NotepadEditor_1.811.1.0_x64__6bk20wvc8rfx2' (AUMId HaukeGtze.NotepadEditor_6bk20wvc8rfx2!notepad') supports 182 extensions but has no verbs" I just installed weasyprint in python and GTK for 64 bit from there on its showing this error? Can anyone help me out of this? Thanks in advance.. -
While testing my Websocket Consumer a model object is not created (Django Channels)
I'm new in Django Channels and I'm trying to build a simple chat app. But when I'm trying to test my async Websocket Consumer I run into the following exception: chat.models.RoomModel.DoesNotExist: RoomModel matching query does not exist. It seems like the test room is not created. test.py file is the following: class ChatTest(TestCase): @sync_to_async def set_data(self): room = RoomModel.objects.create_room('Room1', 'room_password_123') room_slug = room.slug user = User.objects.create_user(username='User1', password='user_password_123') print(RoomModel.objects.all()) # querySet here contains the created room return room_slug, user async def test_my_consumer(self): room_slug, user = await self.set_data() application = URLRouter([ re_path(r'ws/chat/(?P<room_name>\w+)/$', ChatConsumer.as_asgi()), ]) communicator = WebsocketCommunicator(application, f'/ws/chat/{room_slug}/') communicator.scope['user'] = user connected, subprotocol = await communicator.connect() self.assertTrue(connected) await communicator.send_json_to({'message': 'hello'}) response = await communicator.receive_json_from() self.assertEqual('hello', response) await communicator.disconnect() My consumer.py file is the following: class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = f'chat_{self.room_name}' await self.channel_layer.group_add(self.room_group_name, self.channel_name) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard(self.room_group_name, self.channel_name) async def receive(self, text_data): self.message = json.loads(text_data).get('message') data = {'type': 'chat_message'} data.update(await self.create_message()) await self.channel_layer.group_send(self.room_group_name, data) async def chat_message(self, event): await self.send(text_data=json.dumps({ 'message': event['message'], 'user': event['user'], 'timestamp': event['timestamp'] })) @database_sync_to_async def create_message(self): print(RoomModel.objects.all()) # qyerySet turns out to be empty here room = RoomModel.objects.get(slug=self.room_name) msg = room.messagemodel_set.create(text=self.message, user_name=self.scope['user']) return { 'message': msg.text, 'user': self.scope['user'].username, 'timestamp': … -
Update data with image in Django through Axios
I am trying to update the data with a field image. I followed this link https://stackoverflow.com/a/28036805/15320798 to successfully upload an image. But when I try to update the data without changing the image field, it throws the error Upload a valid image. The file you uploaded was either not an image or a corrupted image. The scenario is that I have to change other fields and keep the image field the same. Example Request Payload: { "name":"John" "age":18, "image:""http://localhost:8000/media/9154fb95-0f1.jpg" } and this is how I send the data from vue axios .put(url, data) .then((response) => { console.log("success") }) serializers.py class UserSerializer(serializers.ModelSerializer): image = Base64ImageField(max_length=None,use_url=True,) # this is from the link above class Meta: model = User fields = ( "name", "age", "image" ) Is there any way I can execute this? -
{ "detail": "CSRF Failed: CSRF token missing or incorrect." }
hello guys . I try to register a new Product in my app using DRF and Postman. when I send a request I get this error. the problem is just about my csrf_token. I'll be thankfull if you help me..... this is my view class ProductViewSet(viewsets.ModelViewSet): authentication_classes = (SessionAuthentication,TokenAuthentication) permission_classes = [IsAdminUser] queryset = ProductInfo.objects.all().order_by('-id') serializer_class = ProductSerializer filter_backends = (filters.SearchFilter,) search_fields = ['title','code','owner__username'] I don't have any problem for GET request. -
What's the reason of my drop down class doesn't iterate?
this is base html codes. I sent categories, products in views.py to base.html. they are defined in models.py as Category, Product as OnetoOne Relationship. <div class="btn-group"> {% for category in categories %} <button type="button" class="btn" id="BASE_SECOND_ADAPTERS"> <a href="{{category.get_absolute_url}}" class="btn" id="C_TITLE">{{category.title}}</a> </button> <button type="button"> <span class="sr-only">Toggle Dropdown</span> <div> {% for product in category.product_set.all %} <div class="button"> <a href="{{product.get_absolute_url}}">{{product.name}}</a> </div> {% endfor %} </div> </button> {% endfor %} </div> this is the problem. first, the href in products iteration doesn't work. When i delete the data-toggle="dropdown" it works. 1Cat - 1-2Pro, 1-1Pro 2Cat - 2Pro 3Cat - 3Pro But Iteration ended before 2Category. If i delete the drop down class, It work. How can i solve it? -
connection error between two devices: ImportError: libmariadb.so.3: cannot open shared object file: No such file or directory
I have two devices that I use as MySql server and Django server. My system, which works on my development device, becomes inoperable when it switches to other devices. Settings on 192.168.3.60: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'bildirdi_hurmalar', 'USER': 'gungelir_tirmalar', 'PASSWORD': 'EhuEhu_1793', 'HOST': '192.168.3.65', 'PORT': '3306', } } Apache2 and wsgi on mainside. Error when I run Migrate or runserver: (env) pi@raspberrypi:~/bilidrdi.com $ python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/home/pi/bilidrdi.com/env/lib/python3.7/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: libmariadb.so.3: cannot open shared object file: No such file or directory During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3.7/threading.py", line 917, in _bootstrap_inner self.run() File "/usr/lib/python3.7/threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "/home/pi/bilidrdi.com/env/lib/python3.7/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/pi/bilidrdi.com/env/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/home/pi/bilidrdi.com/env/lib/python3.7/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/home/pi/bilidrdi.com/env/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "/home/pi/bilidrdi.com/env/lib/python3.7/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/pi/bilidrdi.com/env/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/pi/bilidrdi.com/env/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/pi/bilidrdi.com/env/lib/python3.7/site-packages/django/apps/config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.7/importlib/__init__.py", line 127, … -
Django don't login after change password use Abstractuser
i custom user use abstractuser class User(AbstractUser): create_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) name=models.CharField(max_length=50) phone=models.CharField(max_length=15) position=models.CharField(max_length=30) but when i change password user in adminpage i can't login with login function class LoginClass(View): def get(self,request): if not request.user.is_authenticated: return render(request, 'new_template/signin.html') else: return redirect('user:view_camera') def post(self,request): username1 = request.POST.get('username1') password1= request.POST.get('password1') my_user = authenticate(username=username1,password=password1) if my_user is None: return redirect('/') login(request, my_user) next_url = request.GET.get('next') if next_url is None: return redirect('user:view_camera') else: return redirect(next_url) -
Django data getting issue
Django giving different data to browser and swagger(or postman) it's in swagger(in postman too): But in browser getting wrong data: please any ideas -
How to render .astro files in django
I tried to create a Django web app since the web pages had heavy js files so it took a long time to load the page. To tackle this problem I tried to implement Astro to create a static webpage. But the problem here is that Django renders .astro files also as HTML.Like shown in this image How do I tell Django to render .astro as an Astro file -
Dynamically iterate over variables if it contains a url using Jinja
I have a collection of uploaded photos in Django admin photos URLs are stored in a Django app namely Listing, inside model.py class Listing(models.Model): photo_1 = models.ImageField(upload_to='photos/%Y/%m/%d/',blank=True) photo_2 = models.ImageField(upload_to='photos/%Y/%m/%d/',blank=True) photo_3 = models.ImageField(upload_to='photos/%Y/%m/%d/',blank=True) photo_4 = models.ImageField(upload_to='photos/%Y/%m/%d/',blank=True) photo_5 = models.ImageField(upload_to='photos/%Y/%m/%d/',blank=True) photo_6 = models.ImageField(upload_to='photos/%Y/%m/%d/',blank=True) my code for views.py looks like def listing(request, listing_id): listing = get_object_or_404(Listing, pk=listing_id) context = { 'listing': listing } return render(request, 'listings/listing.html', context) now, inside my listing.html file I can check if a photo URL is available and then apply the design to show the photo as following {% if listing.photo_1 %} <div class="col-md-2"> <a href="{{ listing.photo_1.url }}" data-lightbox="home-images"> <img src="{{ listing.photo_1.url }}" alt="" class="img-fluid"> </a> </div> {% endif %} I can do it for all six photos but I want to do it dynamically like {% for i in range (1,7) %} {% if listing.photo_{{i}} %} <div class="col-md-2"> <a href="{{ listing.photo_{{i}}.url }}" data-lightbox="home-images"> <img src="{{ listing.photo_{{i}}.url }}" alt="" class="img-fluid"> </a> </div> {% endif %} {% endfor %} is there any way to do it? I tried to pass photos URLs inside the context dictionary as a list like def listing(request, listing_id): listing = get_object_or_404(Listing, pk=listing_id) context = { 'listing': listing 'photos': [listing.photo_1,listing.photo_2,listing.photo_3,listing.photo_4,listing.photo_5,listing.photo_6] } return render(request, 'listings/listing.html', context) … -
How do I use Django's CheckConstraint to restrict a variable at the database level?
I'm trying to write an application that receives incoming tickets for a small IT department. Currently these tickets come in through a webhook so I want to restrict what comes in at the database level. I want to restrict the status variable of the ticket to the choices described in the ticketStatus model but the database is still accepting values outside these choices. I've experimented with using CheckConstraint but can't quite get it to work. My code is as follows: class ticketStatus(models.TextChoices): Active = "Active" Acknowledged = "Acknowledged" Resolved = "Resolved" Unresolved = "Unresolved" class Ticket(models.Model): dateTimeRecieved = models.DateTimeField(default=timezone.now) deviceId = models.ForeignKey(Device, related_name="Device", on_delete=models.DO_NOTHING) issue = models.CharField(max_length=100) status = models.CharField(max_length=20, default="Active") def __str__(self): return f"Device {self.deviceId}: {self.issue}" class Meta: constraints = [ models.CheckConstraint( models.Q(status__in=ticketStatus.values) ), ] At the moment, I'm getting this error when I attempt the migration: TypeError: __init__() takes 1 positional argument but 2 were given I believe this is associated with models.Q(status__in=ticketStatus.values) I'm currently using Django version 3.2.4 -
Return pk of form after submission
I need to return the PK of a form after it is submitted so I can use it in a second form. Everything I find online about returning the PK is for a http redirect not storing it in a variable and working with it in the view view def createPostView(request): currentUser = request.user postForm = PostForm() if request.method == 'POST': postForm = PostForm(request.POST, request.FILES) if postForm.is_valid(): PostFormID = postForm.save(commit=False) PostFormID.author = request.user PostFormID.save() return #need to get pk from this form for f in request.FILES.getlist('images'): test = PostImagesForm(request.POST, request.FILES) if test.is_valid(): instance = test.save(commit=False) instance.post = #need to use pk here instance.images = f instance.save() return HttpResponseRedirect("/") return render(request, 'blog/post_form.html', {'postForm': postForm, 'PostImagesForm':PostImagesForm}) -
Cant display values in Django templates
I'm new to Django, I am trying to display a single book in a template(show.html) like <h1 class="text-center text-4xl py-5">{{book.title}}</h1> <img src="{{ book.thumbnailUrl }}" alt="" class="w-56"> <p>{{book.shortDescription}}</p> <p>{{book.longDescription}}</p> The view rendering the template is (trying to render a single book from JSON file by id) def show(request, id): with open('bookstore/books.json') as file: book_dict = json.load(file)['books'] book = [book for book in book_dict if book['id'] == id] context = {'book': book} return render(request, 'books/show.html', context) When debugging by printing {{ book }} in show.html it results in a list with a dictionary of a book [{'id': 1, 'title': 'Unlocking Android', 'isbn': '1933988673', 'pageCount': 416, 'publishedDate': {'$date': '2009-04-01T00:00:00.000-0700'},...}] Hence I think that's the problem when I try to access the title using dict syntax like({{ book. title}} ) But I can't seem to find a workaround. -
Django saves time data in UTC despite using localtime
In my settings file, I have : LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Kolkata' USE_I18N = True USE_L10N = True USE_TZ = True in my views: import datetime def some_function: print(datetime.datetime.now()) << prints my local time However, when using the same datetime.datetime.now() to store the current localtime into a DateTimeField, it gets converted in UTC. I understand that its a good things that it all gets converted into UTC when being stored into Database. Objective being, it will be easier for us to convert UTC to any localtime when we are using these stored values and rendering to the user. This last step, of converting UTC time to localtime, which I assume that django should do by default, is where I'm stuck at. the datetime values are still being rendered as UTC instead of my localtime despite using USE_TZ = True in my settings. -
How can I let my users send email from my django app?
I have a django app and users can create a profile and upload their contacts. Is there a way for me to allow them to send email using their email account but through the app? The use case would be that a user would like to send 50 emails to its contacts that are sent through his own email thought. As i write this, I feel this is not possible - lol -
How to query a Django queryset through a foreign key on another model?
I have the following models in my project: class Case(models.Model): ... class File(models.Model): class StatusType(models.TextChoices): ACTIVE = "ACTIVE", _("ACTIVE") DELETED = "DELETED", _("DELETED") case = models.ForeignKey(Case, on_delete=models.CASCADE, null=True) user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) status = models.CharField( max_length=255, choices=StatusType.choices, default=StatusType.ACTIVE, ) Basically, in one of my views, I want to a get a list of all the cases where the following conditions are met through the File model: user = request.user status = "ACTIVE" How can I do this in a simple way? I can query for all the files first and then loop through them and add the cases to a list. Is that the best way to go about this problem? Thanks in advance for any help. -
AttributeError: 'User_Profile' object has no attribute '__name__'
Hello I hope everyone is having a good day, my goal is to get my forms.py to send the email form content to a different model into my Django database, from the default User model in Django to my custom-made User_Profile model. I believe if I can fix the error above that, my goal will be accomplished. In my forms.py file, I am importing a class from the model.py then using the function again in the forms.py, which is what is causing the error. I did my research on __ name__ with classes, and from what I understood, it has to do with using the same class two different times and it doesn't know which one to run or something. If someone could explain __name __ with classes better and help me fix the error, I would much much appreciate that. Here is my models.py class User_Profile(models.Model): user = models.OneToOneField(User, null = True, blank = True, on_delete = models.CASCADE) name = models.CharField(max_length = 200, null = True) phone = models.CharField(max_length = 200, null = True) email = models.CharField(max_length = 200, null = True) profile_image = models.ImageField(null = True, blank = True) data_created = models.DateTimeField(auto_now_add = True, null = True) def … -
How can i update the field of a model from another model field in django?
I have two models. DepartmentGoal with a field 'scores' and Task also with a field 'scores' and a foreign departmentgoal. What I want is; If I allocate scores to DepartmentGoal, scores allocated to Task should subtract from scores of DepartmentGoal which means Any number of instances of scores of Task when summed up should be equal to score of a single instance of DepartmentGoal. I just need a clue on how to implement this. This are the models class DepartmentGoal(models.Model): name = models.TextField(max_length=150, null=True) score = models.IntegerField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True, null=True) updated_at = models.DateTimeField(auto_now=True, null=True) def __str__(self): return self.name class Task(models.Model): name = models.CharField(max_length=300, null=True) departmentgoal = models.ForeignKey(DepartmentGoal, on_delete=models.CASCADE, related_name='departgoal', null=True, blank=True) score = models.IntegerField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True, null=True) updated_at = models.DateTimeField(auto_now=True, null=True) def __str__(self): return self.name Here the the forms class DepartmentGoalForm(ModelForm): class Meta: model = DepartmentGoal fields = ( ('name'), ('score'), ) class TaskForm(ModelForm): class Meta: model = Task fields = [ 'departmentgoal', 'name', 'score', ]