Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Return results of Django Query as Dictionary
Suppose I have a Django model that looks like this: class User(models.Model): customer_id = models.TextField() date_time_period_start = models.DateField() date_time_period_end = models.DateField() total_sales = models.IntegerField() The underlying table looks like this: customer_id | date_time_period_start | date_time_period_end | total_sales 1 | 2023-04-01 | 2023-04-01 | 10 1 | 2023-04-02 | 2023-04-02 | 20 1 | 2023-04-03 | 2023-04-03 | 30 I would like to query using Django and return a python dictionary where the key is the value of date_time_period_start and the values is a dictionary where the keys are the columns and the values are the column values. In this example, I would like to return { '2023-04-01': {'date_time_period_start': '2023-04-01', 'date_time_period_end': '2023-04-01', 'customer_id': 1, 'total_sales': 10}, '2023-04-02': {'date_time_period_start': '2023-04-02', 'date_time_period_end': '2023-04-02', 'customer_id': 1, 'total_sales': 20}, '2023-04-03': {'date_time_period_start': '2023-04-03', 'date_time_period_end': '2023-04-03', 'customer_id': 1, 'total_sales': 30}, } I can achieve this by doing the following records = list( self.model.objects .values( "customer_id", "date_time_period_start", "date_time_period_end", "total_sales", ) ) records_dict = {} for record in records: records_dict[record["date_time_period_start"]] = { "date_time_period_start": record["date_time_period_start"], "date_time_period_end": record["date_time_period_end"], "customer_id": record["customer_id"], "total_sales": record["total_sales"], } Is there a more efficient way of doing this rather than looping through the list of records? I was trying to use values() and annotate() so something like … -
If statement in Django and Json
I have a script like this for adding the data of the table from a JSON. <script> const tableData = $('#table-data').DataTable({ dom: 'Bfrtip', "serverSide": true, "processing": true, "ajax": { "url": '{{ data_url }}' }, "columns": [ { {% comment %} "data": "pertanyaan__bidder_id__name" {% endcomment %} "data": "pertanyaan__bidder_id__name" }, {"data": "waktu_pengambilan" }, {"data": "id", "render": function(data, type, full, meta){ const statusUrl = "{{ status_url }}".replace('1', data) const actions = [] const dokumen = data actions.push(`<a href="${statusUrl}" class="btn btn-sm btn-dark" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-custom-class="tooltip-dark" title="Download" target="_blank" style="pointer-events: none;">Lihat<span class="btn-icon-end"><i class="fa fa-eye"></i></span></a>`) return actions.join('&nbsp;') } }, {"data": "keterangan"}, ] }) $('.dt-button').addClass('btn btn-primary') $('.dt-button').removeClass('dt-button') </script> the JSON gets from class PertanyaanData. This result will pass to a class called PertanyaanView class PertanyaanData(View): def get(self, request): limit = int(request.GET.get("length", 10)) offset = int(request.GET.get("start", 0)) rows = ListDokselPertanyaan.objects.all()[offset:limit].values( 'id','pertanyaan__bidder_id__name', 'waktu_pengambilan', 'pertanyaan__pertanyaan', 'keterangan', 'pertanyaan') count = rows.count() data = { 'draw': request.GET.get("draw", 1), 'recordsTotal': count, 'recordsFiltered': count, 'data': list(rows), } return JsonResponse(data) class PertanyaanView(View): def get(self, request): context = { 'title': 'Pertanyaan Dokumen Seleksi', 'data_url': reverse_lazy(conf.APP_BASE_NAME + conf.PERTANYAAN_DATA_URL_NAME), 'status_url': reverse_lazy(conf.APP_BASE_NAME + conf.PERTANYAAN_SELECT_URL_NAME, kwargs={'pk': 1}) } return render(request, 'app/pertanyaan/index.html', context) I am a beginner in Django and I don't know how to make an if statement here. For example, … -
Django database Migration Traceback (most recent call last):
i am beginner at Django python. after create the table and run the migration command i got the error was i attached below.what i tried so far i attached below. models.py from django.db import models # Create your models here. class Students(models.Model): StudentId = models.AutoField(primary_key=True) StudentName = models.CharField(max_length=500) Course = models.CharField(max_length=500) Fee =models.CharField(max_length=500) Full Error after run the migranation command : python manage.py makemigrations StudentApp Traceback (most recent call last): File "E:\django\stud_crud\manage.py", line 22, in <module> main() File "E:\django\stud_crud\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Hp\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "C:\Users\Hp\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\__init__.py", line 416, in execute django.setup() File "C:\Users\Hp\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Hp\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) ^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Hp\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\apps\config.py", line 178, in create mod = import_module(mod_path) ^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Hp\AppData\Local\Programs\Python\Python311\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1128, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1142, in _find_and_load_unlocked ModuleNotFoundError: No module named 'StudentApp' -
Heroku credit card
Why i can not add my credi or debit card to heroku every time it shows error please try again later My cards from egypt if any one face this problem please hellp My cards from egypt if any one face this problem please hellp. -
django channels how to send json to all users of group
i have a problem with the group_send function. If I try to run it it doesn't give me any errors but it doesn't even run. I'm using the function with django channels with redis server. It should send me the json but nothing is received from the group_send while with the self.send it arrives. Can someone help me? class Accettazioni(WebsocketConsumer): def connect(self): self.room = 'test' async_to_sync(self.channel_layer.group_add)(self.room, self.channel_name) self.accept() def receive(self, text_data=None, bytes_data=None): user = self.scope["user"] id_user = user.id id_postazione = self.scope['session']['ID'] print(user, id_user, id_postazione) text_data_json = json.loads(text_data) print(text_data_json) if 'prossimo_cliente' in text_data_json: prossima_prenotazione = richiesta_prossimo_cli() prenotazione_in_PresaInCarico(id_user, id_postazione, prossima_prenotazione) if prossima_prenotazione is not None: json_pronto = impacchetta_json(prossima_prenotazione) self.send(json.dumps({'prossima_prenotazione': json_pronto})) async_to_sync(self.channel_layer.group_send)(self.room, {'prossima_prenotazione': json_pronto}) else: self.send(json.dumps({'prossimo_cliente': 'KO'})) i tried without the async_to_sync function too but it still doesn't work. I expect the json to be sent to all users who are connected to this consumer.how can i solve? -
what is the best path to choose as a beginner (i like to go for backend)? [closed]
i have a suggestion to start with (node js) but iam thinking about python and his framework and i have another suggestion to go for php iam not sure what to start with and also iam studying html5 now so what to go next i expecting for suggestion to be a good back end -
How to correctly use djngo slippers in templates
I started using Django slippers recently and I am very confused with some things. I am trying to render a template but I keep having this error. I don't know where this error is from: {% extends 'base.html' %} {% load slippers %} {% block content %} {% #card title='video game' name='name1' %} <span>Hii</span> {% /card %} {% endblock %} This is my template. I have this error: File "C:\Users\DELL\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\functional.py", line 241, in wrapper if any( ^^^^ RecursionError: maximum recursion depth exceeded I don't understand why I m having this issue and Django Slippers is fairly new so there is no help online. Can anyone help? -
A column naming conflict between joining tables, including an EAV and a straight table
We have an internal fork of EAV-Django and have upgraded it to Python 3, so our internal fork is similar to the new repository of django-eav2. In the application, we need to join the transaction table with 1) the eav table's email records and 2) the customer table. We use Django annotate() function to automatically generate the sample SQL code below, and please refer to the join clauses as: ... left outer join `eav_value` eav_email on ... left outer join `app_customer` on ... The problem is a naming conflict: we get a column named email from the eav_value table, and the customer table also contains a column named email. Therefore, when intending to sort by the EAV's email attribute, the clause order by email asc triggers an error saying "Column 'email' in order clause is ambiguous". Question: We could rename the EAV's email to eav_email but the change will trigger other changes on the frontend, because the frontend component relies on the column name email or customer.email. So, we wonder if there is any way to give a parent annotation to EAV attribute, e.g. in SQL query, we do instead of eav_email.value_text as email, we can do eav_email.value_text as eav.email,. … -
Forbidden error 403 with React and Django
I'm trying implement a login form where I'm passing the username and password to backend but I'm getting a 403 forbidden request error. Here is my frontend code where I'm sending username and password along with header named 'Access-Control-Allow-Origin. const login = (username, password) => { return axios .post( API_URL + "signin/", { username: "test@test.com", password: "password", }, { headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*", }, } ) .then((response) => { if (response.data.accessToken) { localStorage.setItem("user", JSON.stringify(response.data)); } return response. Data; }); }; This is my settings.py file in backend: ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ ...... 'rest_framework_simplejwt.token_blacklist', 'rest_framework_simplejwt', 'rest_framework', 'corsheaders', ] MIDDLEWARE = [ .......... 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = False CORS_ALLOW_HEADERS = ['*'] And this is the views.py file: @api_view(['POST']) def signin(request): username = request.data.get('username') password = request.data.get('password') print(username," ",password) return JsonResponse(username) I'm trying to debug this error from the past few hours but haven't found a solution yet. On trying to debug, sometimes I also get the CORS error when I make a few changes to the settings.py file. I tried searching for answers on stack overflow but those solutions didn't work for me. I know it should be a minor issue but am not … -
Errno 13: Permission denied: 'celerybeat-schedule' with Celery running on AWS ECS and SQS
I have a separate Celery Beat and Work service running in ECS. The worker appears to be connecting to SQS fine. The Beat on the other hand is giving me trouble. I used these instructions as a template for what I am doing. https://dev.to/daiquiri_team/deploying-django-application-on-aws-with-terraform-setting-up-celery-and-sqs-38ik I deviated a little bit because I already had an existing Terraform/Django project running within AWS. The Django project is also on ECS. I am having difficulty knowing what to be looking for because the error is rather vague. Why would the schedule create a Permissions denied? Is the Beat trying to write to SQS? I currently have 4 queues. I am executing the command below from the container definition: celery -A backend beat I also am running the following in my container definition because I read that ECS is always run as root. {"name": "C_FORCE_ROOT", "value": "true"} -
Deploying my nlkt chatbot to web using django
I just developed a chatbot for a client using nltk frame work, the bot works well but am having it difficult deploying it on django,tried using html form get method as my user input but it not working nor my bot response is not displaying...can someone please put me through the steps to follow.....thanks in advance I did run my code on the views on my django project if I call the url for the front page, my bot runs in my system but nothing works at the front end -
Validate data on all associated models before saving any Django models
I have two models in a Django project. One of them has a foreignkey to the other and within the admin is displayed as an inline model so that we can work with both models together. class Model1(models.Model): name = CharField(max_length=150) class Model2(models.Model): parent = ForeignKey(Model1, on_delete=CASCADE) name = CharField(max_length=15) My current goal is to be able to save Model1 in the admin and before any data is saved at all check all associated Model2 instances to make sure their 'name' field is not a certain value. This would mean that if I changed the name of Model1 and created 2 Model2 instances I would check both Model2 instances for their name incoming name value, make sure it checks out, if both do not DO NOT save ANYTHING, if they both check out, save everything. So far I have not found anything that will allow me to see the incoming values prior to saving Model1. Instead, I can only check each incoming Model2 right before it is saved. -
I'm working on Django project Asynchronous with Uvicorn async view
python==3.11.3 asgiref==3.6.0 Django==4.1.8 I'm working on Django project Asynchronous with Uvicorn async view. all the building books is fine but when I call the post build it create the book but show's this problem but after refreshing the page again it showin TypeError at /builds/ sync_to_async can only be applied to sync functions. ` import re from subprocess import check_output from asgiref.sync import sync_to_async from django.contrib.auth import get_user_model from django.contrib.auth.mixins import LoginRequiredMixin from django.db.utils import IntegrityError from django.shortcuts import get_object_or_404, render, redirect from django.views.generic import View from crayon.books.models import Book from crayon.builds.models import Build from crayon.core.mixin import AsyncViewMixin class AsyncViewMixin: async def __call__(self): return super().__call__(self) def build_book(book_id: int, user_id: int) -> str: global document, build # step 1: Get the book book = Book.objects.get(id=book_id, creator_id=user_id) # step 2: compile the book's contents build = Build.objects.create(builder_id=user_id, book_id=book_id) build.status = Build.STATUS.IN_PROGRESS build.save() document_list = [] for chapter in book.chapter_set.all(): document_list.append(f"# {chapter.title}") # If a "reges" finds an markdown H1 if re.search(r"\n\#\s", chapter.body) or re.match("\#\s", chapter.body): chapter.body = add_pound_to_headers(chapter.body) document_list.append(chapter.body) document = "\n\n".join(document_list) # step 3: render as something using pandoc # Pandoc -o book.html input.md with open("input.md", "w") as f: f.write(document) commands = ["pandoc", "-o", "book.html", "input.md"] output = check_output(commands) return output … -
Django adding related field with multiple databases
I have a Django project with two databases, each has a game model and a language model that are connected with Many2Many relationships. When saving each object with: game.save(using=db) I’m able to save to the desired database, but when I attempt to add the related field: game.add(language) It doesn’t work for the second database. Any idea why? *from research I think it might be a problem in my routers.py but I took it from the Django documentation.. -
django-tailwind: doesnt start upon running 'python manage.py tailwind start'
i followed the docs and it says that after the command 'python manage.py tailwind start' the development server should start. however im getting this and its stuck on the 'rebuilding phase' and doesnt continue Node.js: v18.10.0 django: 4.2 django-tailwind: 4.5 > my_theme@3.5.0 start > npm run dev > my_theme@3.5.0 dev > cross-env NODE_ENV=development tailwindcss --postcss -i ./src/styles.css -o ../static/css/dist/styles.css -w Rebuilding... Done in 1143ms. anyone encountered a similar problem? -
PyReportJasper connection error with a report with null values
i'm trying to create a Django Rest app and im trying to create reports, since pip doesn't support Crystal Reports or viceversa i'm trying to use Jasper Studio, the problem here is this: def generar_reporte(self, request): REPORTS_DIR = os.path.join(os.path.abspath(os.path.dirname(__file__)), '') input_file = os.path.join(REPORTS_DIR, 'CuentasXCobrarSL.jrxml') output_file = os.path.join(REPORTS_DIR, 'CuentasXCobrarSL') conn = { 'driver': 'com.microsoft.sqlserver.jdbc.SQLServerDriver', 'username': 'sa', 'password': 'sa123*', 'host': 'IBM2', 'database': 'Futuro', 'port': '1433' } try: pyreportjasper = PyReportJasper() pyreportjasper.config( input_file, output_file, output_formats=["pdf"], parameters={ 'FI': "19/04/23 00:00:00", 'FF': "20/04/23 00:00:00", 'Directorio': 0, 'TipoCtaId': 0, }, ) pyreportjasper.process_report() with open(output_file + '.pdf', 'rb') as f: data = f.read() response = HttpResponse(data, content_type='application/pdf') response['Content-Disposition'] = 'filename=CuentasXCobrarSL.pdf' return response except Exception as e: print(f"Error: {e}") return Response("Error generando el reporte.", status=status.HTTP_500_INTERNAL_SERVER_ERROR) here are the parameters that this report needs, FI and FF are dates, Directorio, TipoCtaId and MonedaType are integers This is a test report, when it finally works i'll use request params but for now, i'm using static params, but... when i call this function without the connection to the database, it returns me a pdf with all values in null, but when i put the connection it returns me a NullPointerException, i think the problem is in the connection, i dont know … -
Pipenv shell won't open an environment in current directory
When I create a new directory and change to it, I try to start a new pipenv environment and it opens to my root directory. I was messing with my path, adding geckodriver, and that seemed to have thrown it off. Here's my terminal: christopherchough@Christophers-MacBook-Pro ~ % cd ~/Desktop christopherchough@Christophers-MacBook-Pro Desktop % mkdir superlists && cd superlists christopherchough@Christophers-MacBook-Pro superlists % pipenv install django Installing django... Resolving django... Installing... Adding django to Pipfile's [packages] ... ✔ Installation Succeeded Installing dependencies from Pipfile.lock (c91b9a)... To activate this project's virtualenv, run pipenv shell. Alternatively, run a command inside the virtualenv with pipenv run. christopherchough@Christophers-MacBook-Pro superlists % pipenv shell Launching subshell in virtual environment... . /Users/christopherchough/.local/share/virtualenvs/christopherchough-PpcwrOBl/bin/activate christopherchough@Christophers-MacBook-Pro ~ % . /Users/christopherchough/.local/share/virtualenvs/christopherchough-PpcwrOBl/bin/activate (christopherchough) christopherchough@Christophers-MacBook-Pro ~ % I was expecting it to show: (superlists) christopherchough@Christophers-MacBook-Pro superlists ~ % -
Styling showing different on 2 separate apps with exact same style sheet
I am having an issue currently and I have no idea how to debug it so I'm hoping some one else may have encountered this or may point me in a direction to look. I have 2 django apps.... both identical HTML and Styling... But on one of them it is right and one is wrong... Please see screen shots and any ideas are welcome. EDIT when i remove the block in image below the styling goes to normal. -
Deploying a Django app with azure Web Service
I want to deploy a Django 3.2.18 app to the Azure cloud. I use the Azure DevOps pipeline to pull changes from the GitHub master branch and deploy them to the Azure web service. Here below is my Yaml file. # Python to Linux Web App on Azure # Build your Python project and deploy it to Azure as a Linux Web App. # Change python version to one thats appropriate for your application. # https://docs.microsoft.com/azure/devops/pipelines/languages/python trigger: - master variables: # Azure Resource Manager connection created during pipeline creation azureServiceConnectionId: '8b946b7b-8609-45ea-992d-ab1dadcbfcd0' # Web app name webAppName: 'ELaden' # Agent VM image name vmImageName: 'ubuntu-latest' # Environment name environmentName: 'ELaden' # Project root folder. Point to the folder containing manage.py file. projectRoot: $(System.DefaultWorkingDirectory) # Python version: 3.7 pythonVersion: '3.7' stages: - stage: Build displayName: Build stage jobs: - job: BuildJob pool: vmImage: $(vmImageName) steps: - task: UsePythonVersion@0 inputs: versionSpec: '$(pythonVersion)' displayName: 'Use Python $(pythonVersion)' - script: | python -m venv antenv source antenv/bin/activate python -m pip install --upgrade pip pip install setup pip install -r requirements.txt workingDirectory: $(projectRoot) displayName: "Install requirements" - task: ArchiveFiles@2 displayName: 'Archive files' inputs: rootFolderOrFile: '$(projectRoot)' includeRootFolder: false archiveType: zip archiveFile: $(Build.ArtifactStagingDirectory)/$(Build.BuildId).zip replaceExistingArchive: true - upload: $(Build.ArtifactStagingDirectory)/$(Build.BuildId).zip … -
Render image into django template
I am struggling to render an image into django template when I have paginator on. Here are my models: class BlogPost(models.Model): title = models.CharField(max_length=100, default="",) published = models.BooleanField(default=False) slug = models.SlugField() class BlogPostImage(models.Model): post = models.ForeignKey(BlogPost, on_delete=models.CASCADE, related_name='images') image = models.ImageField(upload_to="blogposts/", validators=[validate_file_size]) HTML: {% for post in page.object_list %} {% if post.published %} <picture> {% for post_image in post.images.all %} <img class="blog--box__image" src="{{post_image.image.url}}" alt=""> {% endfor %} </picture> {% endif %} {% endfor %} -
Filter by reverse lookup count of related field in django query
In my Django project, I have models for User, Player, and Game. A User can be a Player in any number of Games. There is a user statistics view (in this case, we are talking about finished games), that can be filtered and ordered by many different attributes. Example: each Game is played on a specific map. In the view, the map can be filtered; then, for each user, only the games are considered that were played on the filtered map. I want to do the same thing for number of players in the game; consider only the games played with e.g. 2 players in the statistics. There is no attribute players in the model Game; it's a reverse foreign key from model Player. To build the statistics per User: I start with User.objects.all() Create a player_filter containing the set parameters, e.g. player_filter = Q(player__game__map='O') Then apply annotations (e.g. users.annotate(high_score=Max('player__score', filter=player_filter)) Then display these values somehow in the view. However, to filter player from games with X number of players, I would need to do something like player_filter = Q(COUNT(player__game__player_set)=2) (not a working syntax of course). How can I do this? I kind of need to annotate the related player__game … -
Why the django signal receiver is not being executed?
I have the following code: signals.py: from django.dispatch import Signal, receiver new_device_signal = Signal() src/controller.py: from django.dispatch import receiver from domotic.signals import new_device_signal class Controller(MQTTClient): @receiver(new_device_signal) def handle_new_device_signal(self, sender, name, is_sensor, **kwargs): print('Añadiendo nuevo dispositivo: ' + name) if is_sensor == True: self.sensors.append(name) else: self.switches.append(name) def __init__(self, host, port): super().__init__(host, port, CONTROLLER_ID) self.rules = [] self.switches = [] self.sensors = [] #Lee todos los devices que hay registrados en la base de datos for device in Device.objects.all(): if device.is_sensor == True: self.sensors.append(device.name) else: self.switches.append(device.name) #Lee y procesa todas las normas que hay en la base de datos for rule in RuleText.objects.all(): self.rules.append(loadRule(rule.name)) new_device_signal.connect(self.handle_new_device_signal) views.py: from domotic.models import Device, RuleText from domotic.signals import new_device_signal class DeviceCreateView(CreateView): model = Device template_name = 'app/device/new.html' fields = ['uid', 'name', 'is_sensor'] success_url = reverse_lazy('app:devices') def form_valid(self, form): response = super().form_valid(form) new_device_signal.send(sender=self.__class__, name=self.object.name, is_sensor=self.object.is_sensor) return response apps.py: from django.apps import AppConfig class DomoticConfig(AppConfig): name = 'domotic' def ready(self): import domotic.signals settings.py: INSTALLED_APPS = [ "domotic.apps.DomoticConfig", 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', init.py: default_app_config = 'domotic.apps.DomoticConfig' I don't understand why even though the send in views.py is being executed the handler is not I tried to follow every post regarding this matter but i could not solve … -
Why clean_data works with or without self?
Why clean_data works with or without self ? Because I tested my project and whether I put a self or not, it doesn't change anything at all thks with def clean(self): cleaned_data = super().clean() quantity = self.cleaned_data.get("quantity") if quantity > self.instance.ticket.stock: raise forms.ValidationError(f"Il ne reste que {self.instance.ticket.stock} tickets en stock") return cleaned_data without def clean(self): cleaned_data = super().clean() quantity = cleaned_data.get("quantity") if quantity > self.instance.ticket.stock: raise forms.ValidationError(f"Il ne reste que {self.instance.ticket.stock} tickets en stock") return cleaned_data **Complete code : ** class OrderForm(forms.ModelForm): # je modifie le widget utilisé # modifier la qté dans le panier : quantity = forms.IntegerField(max_value=100, min_value=1) # supprimer un article du panier : delete = forms.BooleanField(initial=False, required=False, label='supprimer') class Meta: model = Order fields = ["quantity", 'delete'] def clean(self): cleaned_data = super().clean() quantity = self.cleaned_data.get("quantity") if quantity > self.instance.ticket.stock: raise forms.ValidationError(f"Il ne reste que {self.instance.ticket.stock} tickets en stock") return cleaned_data # relier le delete avec save def save(self, *args, **kwargs): # récupérer les données de mon formulaire : # avec cleaned_data qui est un dictionnaire, données de mon formulaire après qu'il ait été validé if self.cleaned_data['delete']: # if self.cleaned_data['delete'] is True: return self.instance.delete() return super().save(*args, **kwargs) I just know and understand why self is optionnal. thks -
Not able to send the comment to db and getting "IntegrityError at /add-comment NOT NULL constraint failed: core_comment.post_id"
models.py This was the model I created : class Post(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) user = models.CharField(max_length=100) image = models.ImageField(upload_to='post_images') caption = models.TextField() created_at = models.DateTimeField(default=datetime.now) no_of_likes = models.IntegerField(default=0) def __str__(self): return self.user class Comment(models.Model): post = models.ForeignKey( Post, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=80) body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' % (self.post.user, self.name) views.py I am not able to create object at the backend. would be helpful if anyone knew how to call post and add it to the views. @login_required(login_url='signin') def add_comment(request): if request.method == 'POST': # import pdb # pdb.set_trace() user = request.user.username comment = request.POST['comment'] new_comment = Comment.objects.create(name=user, body=comment) new_comment.save() return redirect('/') else: return redirect('/') index.html : along with forms <!-- Comment section --> <form action="add-comment" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div> <!-- Comment section typing box --> <div class="bg-gray-100 bg-gray-100 rounded-full rounded-md relative "> <!-- <a href="/add-comment?post_id={{post.id}}"> --> <input type="text" placeholder="post a comment" class="bg-transparent max-h-10 shadow-none" name="comment" id="comment"> <div class="absolute bottom-0 flex h-full items-center right-0 right-3 text-xl space-x-2"> <button class="button bg-blue-700" type="submit">submit</button> </div> </div> </form> I am not able to bring the comment to the backend as I am new to django. comment section looks like this tracebackcall -
How to do type checking while using Django?
There are linters that support type checking, however they become a mess in a Django project. Is there any way to have type checking for where I define type hints, but not do it for all the Django bits and pieces? I'm using Conda and VS Code.