Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Conditional form according to choice of dropdown list
I need a form to be displayed depending on the option chosen in the dropdown list, which will be selected by the administrator when creating the new candidate. However, the problem is that even if you select any option in the dropdown list, form 2 corresponding to the else of the conditional is displayed. help please. models.py: Here the model is defined as well as functions to be able to rename the files when saving them cc= ( ('1','Quebrada Blanca'), ('2','Lo Pinto'), ('3','Oficina Central'), ('4','Carbonato'), ('5','Toconao'), ('6','Centinela'), ('7','Spence'), ('8','La Negra'), def create_path(instance, filename, file_type): ext = filename.split('.')[-1] new_filename = "DSR_%s_%s_%s_0.%s" % (instance.rut, instance.nombre, file_type, ext) return os.path.join('uploads',new_filename) def imagen_upload_path(instance, filename): return create_path(instance, filename, 'imagen') def certificado_antecedentes_upload_path(instance, filename): return create_path(instance, filename, 'certificado_antecedentes') def hoja_de_vida_conductor_upload_path(instance, filename): return create_path(instance, filename, 'hoja_de_vida_conductor') def certificado_residencia_upload_path(instance, filename): return create_path(instance, filename, 'certificado_residencia') def certificado_afiliacion_afp_upload_path(instance, filename): return create_path(instance, filename, 'certificado_afiliacion_afp') def certificado_afiliacion_salud_upload_path(instance, filename): return create_path(instance, filename, 'certificado_afiliacion_salud') def fotocopia_cedula_identidad_upload_path(instance, filename): return create_path(instance, filename, 'fotocopia_cedula_identidad') def fotocopia_licencia_conducir_upload_path(instance, filename): return create_path(instance, filename, 'fotocopia_licencia_conducir') class Candidato(models.Model): nombre = models.CharField(max_length = 70, null=True, blank=True) rut = models.CharField(max_length = 10, primary_key=True) correo = models.EmailField(null=True, blank=True) centro_de_costo =models.CharField(null=True, blank=True, max_length =30, choices = cc) estado = models.IntegerField(null=True, blank=True) imagen = models.ImageField(upload_to=imagen_upload_path, null=True, blank=True) certificado_antecedentes … -
update the 'div' after ajax request
This is my first project in django. I'm new to Django, ajax, javascript. I have to send the data to jinja template after making ajax request. My index.html is {% if data %} <p>{{data.title}}</p> <p>{{data.price}}</p> {% endif %} My javascript is <script> $.ajax({ type: "POST", url: "/", // Replace with the actual URL of your view data: { input_value: "test", csrfmiddlewaretoken: "{{ csrf_token }}" }, success: function(response) { title = response // after request, response be like { "data" : {"title":"t1", "price":20} } }, error: function() { console.log("Error") } }); <script> I don't know this is possible. Some using element.innerHTML to update, but i need to send to jinja format. Thanks -
How to get a value from the context dictionary without looping through it
I have to list the products belonging to a particular category and also above the products I want to display the name of the category (only once). I can get the name of category when iterating over products but I want to display it only once on the top. My models are follwing: class category(models.Model): title = models.CharField(max_length=30) image = models.ImageField(null=True, blank=True) def __str__(self): return self.title class product(models.Model): name = models.CharField(max_length=50, null=True, blank=True) slug = models.SlugField(null=True, blank=True) description = models.TextField(max_length=500,null=True, blank=True ) category = models.ForeignKey(category, on_delete=models.CASCADE) cost = models.PositiveIntegerField() image = models.ImageField(null=True, blank=True) def save(self, *args, **kwargs): # new self.slug = slugify(self.name) return super().save(*args, **kwargs) def __str__(self): return self.name and the view is: class ProductsListView(ListView): model = product template_name = 'products/productList.html' context_object_name = 'products' def get_queryset(self, *args, **kwargs): return ( super() .get_queryset(*args, **kwargs) .filter(category_id=self.kwargs['cat_id']) ) template code: {% extends 'products/base.html' %} {% load static %} {% block content %} <h1>Product PAGE!!</h1> <!-- I want to display the category name here --> {% for product in products %} <img src="{{ product.image.url }}" alt="{{ product.name }}" width="10%"> <h2>{{product.name}} </h2> <h2>{{product.cost}} </h2> <h2>{{product.description}} </h2> {% endfor %} {% endblock %} I tried it using the key method "products[category] but it doesn't work. -
What is the Bettery way Django Tags with DRF
I'm developing a Blog project with Django. I have thoughts on 'tag'. What should be the best approach? What I want is a tag system like here(stackoverflow) class Post(models.Model): title = subtitle = category = FK author = FK content = tags = ManyToMany class Tag(models.Model): name = slug = -
How to organize containers if they use each other?
I use the dependency injection method in my Django web-application. I have a containers.py file with 3 instances of containers.DeclarativeContainer: BoardContainer, ColumnContainer and LabelContainer. Each of containers has repository layer, service layer and interactor layer. class BoardContainer(containers.DeclarativeContainer): repository = providers.Factory(BoardRepository, converter=ConvertorsContainer.from_queryset_to_dto) service = providers.Factory(BoardService, repository=repository) interactor = providers.Factory(BoardInteractor, service=service) class ColumnContainer(containers.DeclarativeContainer): repository = providers.Factory(ColumnRepository, converter=ConvertorsContainer.from_queryset_to_dto) service = providers.Factory(ColumnService, repository=repository) interactor = providers.Factory(ColumnInteractor, service=service, board_service=BoardContainer.service) class LabelContainer(containers.DeclarativeContainer): repository = providers.Factory(LabelRepository, converter=ConvertorsContainer.from_queryset_to_dto) service = providers.Factory(LabelService, repository=repository) interactor = providers.Factory(LabelInteractor, service=service, board_service=BoardContainer.service) But i need to use LabelContainer.service and ColumnContainer.service in BoardContainer.interactor. And it turns out that a two-way dependency is created. So far I have solved this problem in this definitely a bad way: class ColumnContainer(containers.DeclarativeContainer): repository = providers.Factory(ColumnRepository, converter=ConvertorsContainer.from_queryset_to_dto) service = providers.Factory(ColumnService, repository=repository) interactor = providers.Factory(ColumnInteractor, service=service) # without board_service class LabelContainer(containers.DeclarativeContainer): repository = providers.Factory(LabelRepository, converter=ConvertorsContainer.from_queryset_to_dto) service = providers.Factory(LabelService, repository=repository) interactor = providers.Factory(LabelInteractor, service=service) # without board_service class BoardContainer(containers.DeclarativeContainer): repository = providers.Factory(BoardRepository, converter=ConvertorsContainer.from_queryset_to_dto) service = providers.Factory(BoardService, repository=repository) interactor = providers.Factory(BoardInteractor, service=service, column_service=ColumnContainer.service, label_service=LabelContainer.service) class ColumnContainer(containers.DeclarativeContainer): repository = providers.Factory(ColumnRepository, converter=ConvertorsContainer.from_queryset_to_dto) service = providers.Factory(ColumnService, repository=repository) interactor = providers.Factory(ColumnInteractor, service=service, board_service=BoardContainer.service) class LabelContainer(containers.DeclarativeContainer): repository = providers.Factory(LabelRepository, converter=ConvertorsContainer.from_queryset_to_dto) service = providers.Factory(LabelService, repository=repository) interactor = providers.Factory(LabelInteractor, service=service, board_service=BoardContainer.service) How i should fix this problem? -
How to handle timezones in FCM
I'm in the process of developing an API backend using Django Rest Framework. Currently, I have a requirement to send notifications to mobile devices, which I've implemented using FCM (Firebase Cloud Messaging). However, I'm facing an issue: I need to send notifications at specific times according to different timezones, and I have access to the timezones of each user. I'm considering implementing a cron job to check if the designated time has arrived. Is this approach ideal for my requirements? -
How to call celery task in Django from Fastapi app
I have two apps (Django and FastApi) that use Celery to do some background task. Now, I need to communicate the two applications and I have thought about reusing the queues that celery uses (I don't really know if it is the best way to do it).The two apps are using the same broker and all are in Docker containers. I wolud like to execute a task that is in the django app when calling a route in the FastApi app. Django app celery.py app = Celery("app_1") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) settings.py ... CELERY_TASK_DEFAULT_QUEUE = "app_1" CELERY_TASK_CREATE_MISSING_QUEUES = False CELERY_TASK_QUEUES = ( Queue("default"), Queue("app_1"), ) def route_task(name, args, kwargs, options, task=None, **kw): if ":" in name: queue, _ = name.split(":") return {"queue": queue} return {"queue": "default"} CELERY_TASK_ROUTES = (route_task,) ... tasks.py @shared_task( name="app_1:test", bind=True, base=BaseTaskRetry ) def test() -> None: print('Result') FastApi app create_celery.py def create_celery(): celery_app = Celery("app_2") celery_app.config_from_object(settings, namespace="CELERY") celery_app.autodiscover_tasks(["Infraestructure.Celery.tasks"]) return celery_app celery_app = create_celery() config_celery.py (In this case I have tried without defining the django exchange and defining it, but I've got the same result) ... django_exchange = Exchange('app_1', type='direct') settings = { ... 'CELERY_TASK_DEFAULT_QUEUE' : "app_2", 'CELERY_TASK_CREATE_MISSING_QUEUES' : False, 'CELERY_TASK_QUEUES' : ( Queue("app_2"), Queue('app_1', exchange=django_exchange), ), … -
Django: Configuration for serving static files on IIS server
I have a django application deployed on an AWS IIS server. Static fils are served just fine via 'runserver', but not via the IIS server. I have done everything right but it doesn't work. i even tried adding a static folder virtual directory but it didnt work. this is my webconfig: <?xml version="1.0" encoding="utf-8"?> <configuration> <appSettings> <!-- Required settings --> <add key="WSGI_HANDLER" value="django.core.wsgi.get_wsgi_application()" /> <!-- Your django path --> <add key="PYTHONPATH" value="C:\myvenv2\NutMIS" /> <!-- Your djangoname.settings --> <add key="DJANGO_SETTINGS_MODULE" value="NutMIS.settings" /> </appSettings> <system.webServer> <handlers> <!-- Remove duplicate entries --> <remove name="NutMIS" /> <remove name="StaticFiles" /> <remove name="StaticFile" /> <!-- Add handler for StaticFiles --> <add name="StaticFile" path="*" verb="*" modules="StaticFileModule" resourceType="Unspecified" requireAccess="Read" /> <!-- Add your custom NutMIS handler --> <add name="NutMIS" path="*" verb="*" modules="FastCgiModule" scriptProcessor="C:\Users\Administrator\AppData\Local\Programs\Python\Python311\python.exe|C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\wfastcgi.py" resourceType="Unspecified" requireAccess="Script" /> </handlers> <staticContent> <mimeMap fileExtension=".*" mimeType="application/octet-stream" /> </staticContent> </system.webServer> </configuration> this is my settings: STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / "static" The static files feature is installed in my IIS. My 'static' folder is placed in the app folder and it works just fine via runserver but not via the public IP over IIS. Please i need help with this. i also tried adding this web.config to to my static file folder … -
Python Django Framework - How to make up ownername and password in Models as login authentication?
This is my class models. I wish to use the ownername and vehicle_password in class Vehicle for owner login. #this is my models.py. class AbstractOwnerInfo(models.Model): ownername = models.CharField(max_length=100) vehicle_password = models.CharField(max_length=100) class Meta: abstract = True #this is my class Vehicle. class Vehicle(models.Model): id = models.AutoField(primary_key=True) parkingnumber = models.CharField(max_length=20) ownercontact = models.CharField(max_length=100) ownername = models.CharField(max_length=100) vehicle_password = models.CharField(max_length=100) IC = models.CharField(max_length=14) regno = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE) vehiclecompany = models.CharField(max_length=50) pdate = models.DateField() intime = models.CharField(max_length=50, default='default_value') outtime = models.CharField(max_length=50) parkingcharge = models.CharField(max_length=50) remark = models.CharField(max_length=500) status = models.CharField(max_length=20) def __str__(self): return self.parkingnumber And then I defined the classess, I wish to use the ownername and vehicle_password in class Vehicles as login credentials. This is my defined member_login request and member_home request. def member_login(request): if request.method == 'POST': ownername = request.POST.get('ownername') password = request.POST.get('vehicle_password') if ownername and password: user = authenticate(username=ownername, password=password) if user is not None: login(request, user) messages.success(request, "Logged in successfully.") return redirect('member_home') else: messages.error(request, "Invalid login credentials. Please try again.") return render(request, 'member_login.html') def member_home(request): return render(request, 'member_home.html') And this is my member_login.html page. {% csrf_token %} <label for="ownername"><b>Ownername</b></label> <input type="text" name="ownername" class="form-control" required> <label for="vehicle_password"><b>Password</b></label> <input type="password" name="vehicle_password" class="form-control" required> <br> <input type="submit" value="Login" class="btn … -
AttributeError: 'NoneType' object has no attribute 'cursor'
I have a code that populates data to DB every time I run a script and this data gets displayed on a webpage. But I'm getting the error as : File "/xyz/dept/triangulation/work_dir/db.py", line 124, in populateSpecificRecord cur = conn.cursor() AttributeError: 'NoneType' object has no attribute 'cursor' def populateSpecificRecord(self, jobid, runid, run_label, table_name, input_dict): """Populate database where jobid and runid both exists""" if bool(input_dict) == True: inputStrList = [] logging.debug(f'Updating to db jobid {jobid}, runlabel {run_label}') for key in input_dict: elem = f"{key}='{input_dict[key]}'" inputStrList.append(elem) inputStr = ','.join(inputStrList) sql = f"UPDATE {table_name} SET {inputStr} WHERE jobid='{jobid}' AND runid={runid} AND pca_run_label='{run_label}'" conn = self.createConnection() cur = conn.cursor() cur.execute(sql) cur.close() conn.commit() conn.close() else: print("Inputed dictionary with no data, DB not updated") How to resolve this issue? I just need that it should populate each Record in the database. -
IntegrityError at /add_emp FOREIGN KEY constraint failed Django problem
while adding a user data in db through a form i create i got this error intergrityerror at \add_emp and it says foreign key constraint failed i tried delete dbsqlite3 files pycache files but that didnt work plzz tell where i am wrong its my first time getting this error. **This is Models.py code ** from django.db import models # Create your models here. class Department(models.Model): name = models.CharField(max_length=100,null=True) location = models.CharField(max_length=100) def __str__(self): return self.name class Role(models.Model): name = models.CharField(max_length=100, null=True) def __str__(self): return self.name class Employee(models.Model): first_name = models.CharField(max_length=100, null=False) last_name = models.CharField(max_length=100,null=True) dept = models.ForeignKey(Department, on_delete=models.CASCADE) salary = models.IntegerField(default=0,null=True) bonus = models.IntegerField(default=0,null=True) role = models.ForeignKey(Role, on_delete=models.CASCADE) phone = models.IntegerField(default=0,null=True) hire_date = models.DateField(null=True) def __str__(self): return "%s %s %s" %(self.first_name, self.last_name, self.phone) **Thats views.py code ** from django.shortcuts import render,HttpResponse from .models import* from datetime import datetime # Create your views here. def index (request): return render(request,"index.html") def all_emp (request): context={"emps":Employee.objects.all(),"roles":Role.objects.all(),"departments":Department.objects.all()} return render(request,"all_emp.html",context) def add_emp(request): if request.method == 'POST': first_name = request.POST['first_name'] last_name = request.POST['last_name'] salary = int(request.POST['salary']) bonus = int(request.POST['bonus']) phone = int(request.POST['phone']) dept = int(request.POST['dept']) role = int(request.POST['role']) new_emp = Employee(first_name= first_name, last_name=last_name, salary=salary, bonus=bonus, phone=phone, dept_id=dept,role_id=role,hire_date = datetime.now()) new_emp.save() return HttpResponse ("Employee added sucessfully") elif … -
Django register form validation for javascript
In django i followed form method is model form i not validate in backend only validate frontend using javascript but if click the submit button the data is not store to database how to fix I tried to submit the data in database but if I click data is validate but not store to database -
Forget Password using Email Django Send Email
I am working on the function of forgetting password then sending email to user to retrieve password using Django programming language. I have the following problem: When I run the server, it shows the link (1) and then I click send email, it shows the link (3) and I check the mail, it doesn't send an email forgot the password to the user even though the system says it has been sent successful email. Please help me. It took me 2 days to fix this function. I hope to be able to send forgotten password emails to users in Django. It took me a total of 2 days to work over and over again, but the result was that I couldn't do it. Very butt get help from everyone. I would like to thank all of you for helping me -
How to make Django Rest Framework Serializers to work different with GET and POST request
Actually, I have am creating the API for Bookmark manager, where I will be having CRUD operations on Bookmark, Collection and Tags Here I am using the BookmarkSerializer for serialization, class BookmarkSerializer(serializers.ModelSerializer): class Meta: model = Bookmark fields = "__all__" def create(self, validated_data): tags_data = validated_data.pop('tags', []) bookmark = Bookmark.objects.create(**validated_data) for tag_data in tags_data: bookmark.tags.add(tag_data) return bookmark and Bookmark model is like class Bookmark(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) url = models.URLField() thumbnail_url = models.URLField(blank=True, default="https://site.image.jpg") title = models.CharField(max_length=512, blank=True) description = models.TextField(blank=True) note = models.TextField(blank=True) tags = models.ManyToManyField("Tag", blank=True) is_favorite = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) collection = models.ForeignKey("Collection", on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.title My requirement is that, when GET request comes in I will return all information, and when POST request comes in I will create the new instance of Bookmark model. Here everything works well, but in the response the primary keys (id) of user, tags and collections are sent, which I don't want. I want it to be string representation. Like { "id": 1, "url": "https://www.flipkart.com/", "title": "Exiting website", "description": "", "note": "Shopping website", "is_favorite": false, "created_at": "2023-08-14T20:41:32.033584Z", "user": "john2000", "collection": "Shopping", "tags": [ "buy", "great_ui"] } but result's are, { "id": 1, "url": "https://www.flipkart.com/", "title": … -
ModelViewSet routes and methods
Following is my model view set for user model: class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() def get_serializer_class(self): if self.action == 'list': serializer_class = UserSerializer elif self.action == 'update': serializer_class = UserEditSerializer else: serializer_class = UserRegisterSerializer return serializer_class def get_permissions(self): if self.action == 'list': permission_classes = [IsAuthenticated] elif self.action == 'update': permission_classes = [IsAuthenticated, isOwner] else: permission_classes = [] return [permission() for permission in permission_classes] Basically what i want is .create, .update, and .list methods from the model viewset for user Registration, Edit profile and get user list functionalities respectively. This is my urls.py router = SimpleRouter() router.register(r'users', views.UserViewSet, basename='user') urlpatterns = [ # path('register/', views.RegisterUser.as_view(), name='api-register'), path('login/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), # path('', views.UsersList.as_view(), name='api-home'), # path('users/<pk>/edit/', views.EditProfile.as_view(), name='api-edit'), path('', include(router.urls)), ] Im not sure what is going on because when i send GET request with user edit url api/users/ i can view any users information. Is there a way to avoid this? i want to view all users using api/users only. Not specific ones. -
I want to link tawk.to live chat feature to email
I am building a freelance django website for my client where he want to get orders from the visitors who visit the site, he want to chat with the visitors and communicate with them and throw them the offer, so he want to keep the chat history with the linked email, how can i do that with tawk.to live chat. i only tried the tawk.to live chat widget, i enclosed that in a condition that if the user is logged in then to show up and now i want that when the user will again visit the site he should be able to see his chat history. -
Attach listener to Azure Active Directory Microsoft login for Django
I'm writing an app using Django that uses exclusively MS login to authenticate users. I've followed the same structure as the sample code set up at their Django tutorial. https://github.com/Azure-Samples/ms-identity-python-django-tutorial/tree/main/1-Authentication/sign-in, where it uses some middleware and Django adapters provided by a seemingly undocumented and unused library they've created at https://github.com/Azure-Samples/ms-identity-python-samples-common/. I'm able to grab ID token claims from a request, but what I want to do is attach a listener to login to manipulate or add an entry in a database (regarding user information). I can't figure out a way to hook something to login. For reference, I created and am using a basic AAD tenant, and MS automatically redirects users after authentication to localhost/auth/redirect with some GET parameters like "code", "state", and "session state". -
django admin broken in development mode
I am a newbie in django (not in programming though) and following the w3school tutorials. When running the django admin at 127.0.0.1:8000/admin/ and in development mode, I end up with a layout problem which seems to be related to how the django css files are accessed. I have a clean and new django install. I have googled the problem and all that I have found are posts solving the same problem in production mode (not in development mode) or posts dated more than 10 years. Does anyone understand what is going on and how to fix the problem? -
Can I create a symbolic link inside Azure file share for a file in Azure file share?
I need some understanding and possibility on, how to create a symbolic link for a file present in Azure File share, inside another directory in the same file share. Is it possible? If yes, then please provide an insight on how to do the same using the Azure Python SDK or Azure Portal. PS: I looked into the NTFSAttributes class of Azure Python File share SDK. Is it possible to do it that way? Any guidance on the above would be appreciated. Thank you! -
CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False. while debug is true
in the settings.py i use environs for my debug and in docker-compose.yml i set it to True my django is 4.2.4 and python 3.11.3 settings.py from pathlib import Path # from django.db.models import Q from environs import Env # # from accounts.models import CustomUser # Build paths inside the project like this: BASE_DIR / 'subdir'. env = Env() env.read_env() BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = env('DJANGO_SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = env.bool('DJANGO_DEBUG') ALLOWED_HOSTS = ['*'] docker-compose.yml version: '3.9' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: - db environment: - 'DJANGO_SECRET_KEY=...' - 'DJANGO_DEBUG=True' db: image: postgres:14 environment: - "POSTGRES_HOST_AUTH_METHOD=trust" but it says CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False i try asking chat gpt and its help and internet and in manage .py i import a file and in that i add django.setup and settings.configure after this i have this error -
Django model aggregate function returns different result in shell and in request endpoint
Django version: 4.2.4 Python version: 3.10.8 from django.shortcuts import render from django.db.models.aggregates import Max from .models.product import Product def product_page(request): agg = Product.objects.aaggregate(max__price=Max('price')) return render(request, 'product.html', {'max_price': agg['max__price']} I get following error when reading the result from agg : 'coroutine' object is not subscriptable But, when I run the same code in django shell I get the expected result in dict What am I missing here? -
How can I create a Django form out of a Model with an intermediary model? (I.E, a box with many products, as in, 10 products A, 5 products B)
First of all, the specifics of the project I'm working on are essentially the same as the example shown in this question, so I think it's easier to explain what I want to achieve using them. Background from the mentioned question: Think of a Box model that contains products, using an intermediary model, we can store not only multiple products but also different quantities of each product. Here is the code from the answer to the question mentioned above: class Box(models.Model): boxName = models.CharField(max_length=255, blank = False) product_set = models.ManyToManyField(ProductSet) def __str__(self): return self.boxName class ProductSet(models.Model): quantity = models.PositiveIntegerField() product = models.ForeignKey(Product, on_delete = models.PROTECT) class Product(models.Model): productName = models.CharField(max_length=200) productDescription = models.TextField(blank=True) productPrice = models.DecimalField(max_digits=9, decimal_places=0, default=0) class Meta: db_table = 'products' ordering = ['-productName'] def __str__(self): return self.productName This solution solves the model set up for what I want to achieve. In my specific case, the box model is a project model, and the products model is a materials model, essentially I want to store projects, which reference various materials required for said project, so each material will have different quantities. As a quick example: if there's a cake project, the materials can be 5 eggs and 1 … -
Django: update model via task
The code examples mentioned below are (over) simplified I have a users model with a field where all data related to each user from that model is recorded as xml. File -> users.py class Users(models.Model): firstname = models.CharField(max_length=200) dob = models.DateTimeField("date published") unconfirmed = models.BooleanField(blank=True, default=False) xml = models.TextField(blank=True, default="") I created a task in charge of updating that field for all users. At the end of the process, I trigger user.save() and it works fine. This task will be used on a regular basis to run a full update File -> update-users-xml.py Class Command(ParallelCommand): def handle(self, *args, **options): users = Users.objects.filter(unconfirmed__isnull=True) for user in users: # Get all fields user.xml = .... user.save() Now, what I'm trying to achieve is -> if an user is edited/created from the admin, the task is called and the xml column is updated. I edited the save function in the users model to trigger the task: def save(self, *args, **kwargs): async_task(call_command, "update-users-xml", self.id) And, as I anticipated, it wouldn't work because: Can't update because of lock key Maximum recursion depth exceeded Checking what options are available, using signal seems the way to go but I cannot make it work In the users model, … -
Why is 'Go Back' button not working in Django?
I am currently building an image description writing website. Tools/langs I use are html, css, django, and javascript. The problem is, when I click on the 'Go back' button on the html provided below, it doesn't redirect me to the previous mission-acting-writing page (account:write_page_url) but stays at the mission-acting-finish.html. 'Posting' and 'Image' are the models stored in models.py. 'Posting' stores every info user enters when writing one's post, and 'Image' stores individual image files extracted from the image zip file user has provided when writing the post. I've been struggling with this problem for the past 20 hours nonsleep. Please identify the problem in the code. Thank you so much in advance! Here is the code of my function 'end' in views.py: def end(request, posting_id, image_index): posting = get_object_or_404(Posting, id=posting_id) user_detail, created = UserDetail.objects.get_or_create(user=request.user) if request.method == 'POST': action = request.POST.get('action') if action == 'complete': total_reward = request.session.get('total_reward', 0) user_detail.point += total_reward user_detail.save() request.session['total_images'] = 0 request.session['total_reward'] = 0 request.session['image_index'] = 0 request.session['listlength'] = posting.remaining_count return redirect('account:explore') context = { 'total_images': request.session.get('total_images', 0), 'total_reward': request.session.get('total_reward', 0), 'posting_id': posting_id, 'image_index': image_index, } request.session.pop('image_ids', None) return render(request,'mission-acting-finish.html',context)` Here is a section of my mission-acting-finish.html: <main class="main-wrapper"> <header class="section_product-header"> <div class="w-layout-blockcontainer w-container"> <h1 … -
Showing 'str' object has no attribute 'text'
I am trying to build a quiz app, where a user can select an option and the option is saved against its question in a particular quiz. So i tried using the below approach. I created my models.py as below. class Quiz(models.Model): name=models.CharField(max_length=200) topic=models.CharField(max_length=100) number_of_questions=models.IntegerField() difficulty=models.CharField(max_length=100,choices=difficulty_choices) TimeLimit=models.IntegerField(blank=True) def get_questions(self): return self.questions_set.all()[:self.number_of_questions] class Questions(models.Model): text=models.CharField(max_length=200) quiz=models.ForeignKey(Quiz,on_delete=models.CASCADE) correct=models.CharField(max_length=25) def __str__(self): return str(self.text) def get_answers(self): return self.answers_set.all() class Answers(models.Model): text = models.CharField(max_length=200) question = models.ForeignKey(Questions, on_delete=models.CASCADE) def __str__(self): return f"Question: {self.question.text}, Answer: {self.text}" class UserAnswer(models.Model): quiz=models.ForeignKey(Quiz,on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) question = models.ForeignKey(Questions, on_delete=models.CASCADE) answer = models.ForeignKey(Answers, on_delete=models.CASCADE,null=True,blank=True) now the question and eahc of its respective answers is displayed in a form. the options are in the forms of radio select button. I have created that form below. class QuizForm(forms.ModelForm): class Meta: model = Quiz fields = ['text'] exclude = ["text"] # Add other fields as needed selected_answer = forms.ChoiceField( label="Select the correct answer", choices=[], # We'll update choices dynamically widget=forms.RadioSelect ) def __init__(self, *args, **kwargs): super(QuizForm, self).__init__(*args, **kwargs) quiz_instance = kwargs.get('instance') questions = quiz_instance.get_questions() for question in questions: answers = question.get_answers() answer_choices = [(answer.id, answer.text) for answer in answers] # Update the choices of the selected_answer field self.fields['selected_answer'].choices = answer_choices Now in …