Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Calculation after POST action with Django
I am trying to create an API for efficiency calculation using Django Rest Framework. After sending and saving the consumption and production values to the database, I want to perform calculations on the data and find the efficiency and save it to database. How should I structure the project? How can I trigger the calculation function? Could you share an example that can help with this? -
Import Django Model Serializer and Use it in Model's Save Method
Peace, I am getting ImportError: cannot import name 'Tenant' from 'tenant_profile.models' I am assuming it's due to circular import. # models.py from .serializers import TenantSerializer class Tenant(models.Model): # model fields def save(self, *args, **kwargs): _ = super().save(*args, **kwargs) data = TenantSerializer(self).data # do something return _ # serializers.py from .models import Tenant class TenantSerializer(serializers.ModelSerializer): class Meta: model = Tenant fields = '__all__' A Pythonic way to fix would be much appreciated. -
I have a file called test.local. How can I redirect dns to my web project written with dijango running on raspberry pi using this file?
How should I use the test.local file I have? How can I do domain forwarding in my application? -
Django many to many field save after commit
Branch Model which to separate to data branch wise class Branch(models.Model): # Branch Master status_type = ( ("a",'Active'), ("d",'Deactive'), ) code = models.CharField(max_length=100, null=True, blank=True, default=None) name = models.CharField(max_length=100, unique=True) suffix = models.CharField(max_length=8, unique=True) Remark = models.CharField(max_length=200, null=True, blank=True) created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) create_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) status = models.CharField(max_length=1, choices = status_type, default = 'a') def __str__(self): return self.name Vendor Model which is I am use to separate branch wise vendors class Vendor(models.Model): status_type = ( ("a",'Active'), ("d",'Deactive'), ) code = models.CharField(max_length=100, null=True, blank=True, default=None) branch = models.ManyToManyField(Branch) company = models.CharField(max_length=200) name = models.CharField(max_length=200) phone = models.CharField(max_length=11, unique = True) email = models.EmailField(max_length=254, unique = True) gst = models.CharField(max_length=15, unique = True) pan_no = models.CharField(max_length=10, unique = True) add_1 = models.CharField(max_length=50, null=True, blank = True) add_2 = models.CharField(max_length=50, null=True, blank = True) add_3 = models.CharField(max_length=50, null=True, blank = True) city = models.CharField(max_length=50, default=None) state = models.CharField(max_length=50, default=None) Remark = models.CharField(max_length=200, null=True, blank=True) created_by = models.ForeignKey(User, on_delete=models.CASCADE) create_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) status = models.CharField(max_length=1, choices = status_type, default = 'a') **this is forms.py file ** class VendorForm(ModelForm): class Meta: model = Vendor fields = '__all__' labels = { 'add_1':'Address', 'add_2':'Address', 'add_3':'Address', } exclude = ['created_by', … -
Celery, Django, Eventlet, django-celery-beat "raise NotImplementedError("unsupported platform")"
Celery, Eventlet, django-celery-beat for a project, but when give the bellow command celery -A app worker -P eventlet -c 100 -l info --logfile=celery.log I get the following error (sample_app) neerajgoyal@Neerajs-MacBook-Pro app % celery -A app worker -P eventlet -c 100 -l info --logfile=celery.log Traceback (most recent call last): File "/Users/neerajgoyal/miniconda3/envs/sample_app/bin/celery", line 10, in <module> sys.exit(main()) File "/Users/neerajgoyal/miniconda3/envs/sample_app/lib/python3.10/site-packages/celery/__main__.py", line 13, in main maybe_patch_concurrency() File "/Users/neerajgoyal/miniconda3/envs/sample_app/lib/python3.10/site-packages/celery/__init__.py", line 140, in maybe_patch_concurrency patcher() File "/Users/neerajgoyal/miniconda3/envs/sample_app/lib/python3.10/site-packages/celery/__init__.py", line 101, in _patch_eventlet import eventlet.debug File "/Users/neerajgoyal/miniconda3/envs/sample_app/lib/python3.10/site-packages/eventlet/__init__.py", line 17, in <module> from eventlet import convenience File "/Users/neerajgoyal/miniconda3/envs/sample_app/lib/python3.10/site-packages/eventlet/convenience.py", line 7, in <module> from eventlet.green import socket File "/Users/neerajgoyal/miniconda3/envs/sample_app/lib/python3.10/site-packages/eventlet/green/socket.py", line 21, in <module> from eventlet.support import greendns File "/Users/neerajgoyal/miniconda3/envs/sample_app/lib/python3.10/site-packages/eventlet/support/greendns.py", line 79, in <module> setattr(dns, pkg, import_patched('dns.' + pkg)) File "/Users/neerajgoyal/miniconda3/envs/sample_app/lib/python3.10/site-packages/eventlet/support/greendns.py", line 61, in import_patched return patcher.import_patched(module_name, **modules) File "/Users/neerajgoyal/miniconda3/envs/sample_app/lib/python3.10/site-packages/eventlet/patcher.py", line 132, in import_patched return inject( File "/Users/neerajgoyal/miniconda3/envs/sample_app/lib/python3.10/site-packages/eventlet/patcher.py", line 109, in inject module = __import__(module_name, {}, {}, module_name.split('.')[:-1]) File "/Users/neerajgoyal/miniconda3/envs/sample_app/lib/python3.10/site-packages/dns/asyncquery.py", line 38, in <module> from dns.query import ( File "/Users/neerajgoyal/miniconda3/envs/sample_app/lib/python3.10/site-packages/dns/query.py", line 63, in <module> import httpcore File "/Users/neerajgoyal/miniconda3/envs/sample_app/lib/python3.10/site-packages/httpcore/__init__.py", line 1, in <module> from ._api import request, stream File "/Users/neerajgoyal/miniconda3/envs/sample_app/lib/python3.10/site-packages/httpcore/_api.py", line 5, in <module> from ._sync.connection_pool import ConnectionPool File "/Users/neerajgoyal/miniconda3/envs/sample_app/lib/python3.10/site-packages/httpcore/_sync/__init__.py", line 1, in <module> from .connection import HTTPConnection File "/Users/neerajgoyal/miniconda3/envs/sample_app/lib/python3.10/site-packages/httpcore/_sync/connection.py", line 12, … -
Django filter on many to many with having count
After a lot of try, I am not able to translate this kind of sql queries into django filtering. Basically, it is retrieving all users with at least x selected tags (and other filters). In the case of two tags, users need to have both tags, I don't want to retrieve users with at least one of the tag. Here are my definitions: class User(models.Model): name = models.CharField(max_length=64) tags = models.ManyToManyField(Tag) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Tag(models.Model): name = models.CharField(max_length=128) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) SQL query will look like: SELECT user.id FROM user INNER JOIN "user_tags" ON ("user"."id" = "user_tags"."user_id") AND "user_tags"."tag_id" in (8, 163) group by "user"."id", user_tags.user_id having count(*) = 2 ORDER BY user.id DESC LIMIT 100; As you can see, the having count(*) part is done on the created m2m table user_tags, and the filtering of tags also "user_tags"."tag_id" in (8, 163) Is it achievable in a django way? All my attempts use user and tab tables, never the created table. Thanks, -
Celery retrieve exception type or info from previous retries
My purpose is to set different max_retries for each exception type Example code @app.task(bind=True, serializer='json') def create_user(self, client): try: data = client.get('users/') except requests.ConnectionError as e: raise self.retry(exc=e, max_retries=10) from e except requests.ReadTimeout as e: raise self.retry(exc=e, max_retries=5) from e The goal is to stop retrying task only if 5 ReadTimeout errors occured or 10 ConnectionError occured. The current code unifies the retries: if 6 ConnectionErrors occured, and then ReadTimeout is raised the celery does not retry the task. Is there a way to set retries for each error type -
How to add calculated field to Django model
I am building a database system and am trying to add calculated field to model as well as the template. I want to field to automatically generate the result of to the values entered on two fields. I am building a database system and am trying to add calculated field to model as well as the template. I want to field to automatically generate the result of to the values entered on two fields. This is my model.py: class VinanPet(models.Model): transaction_Date = models.DateTimeField(auto_now_add=True, auto_now=False, blank=True, null=True) entry_Date = models.DateTimeField(null=True) branch = models.CharField(max_length=300, null=True) product = models.CharField(max_length=300, null=True) tank_Opening = models.DecimalField(max_digits=13, decimal_places=3, null=True) tank_Closing = models.DecimalField(max_digits=13, decimal_places=3, null=True) tank_Difference = models.DecimalField(max_digits=13, decimal_places=3, null=True) pump_Opening = models.FloatField(null=True) pump_Closing = models.FloatField(null=True) pump_Difference = models.DecimalField(max_digits=13, decimal_places=3, null=True) price = models.DecimalField(max_digits=13, decimal_places=3, null=True) amount = models.DecimalField(max_digits=13, decimal_places=3, null=True) expenses = models.DecimalField(max_digits=13, decimal_places=3, null=True) bank = models.DecimalField(max_digits=13, decimal_places=3, null=True) teller_id = models.IntegerField(null=True) teller = models.ImageField(upload_to="teller", null=True) And this is my forms.py from django import forms import calculation from django.forms.widgets import NumberInput from .models import VinanPet class ManagerForm(forms.ModelForm): class Meta: model = VinanPet fields = "__all__" widget = { 'entry_Date': forms.DateInput(attrs={'type': 'date'}), 'tank_Difference': forms.DecimalField(disabled=True,widget=calculation.FormulaInput('tank_Opening-tank_Closing')) } The calculated field only work on form not on database. -
How to list the field names from a Django serializer
I have a model serializer and I was wondering how to get a list of the names of the fields of this serializer. Similarly, I know how to get a list of the fields form a model and from a form. Example model: class Account(models.Model): account_holder = models.CharField(blank=False, max_length=50) age = models.IntegerField(blank=False) salary = models.DecimalField(blank=False, max_digits=10, decimal_places=2) Then the list of fields can be derived from: obj_fields = Account._meta.get_fields() # as objects [field.name for field in Account._meta.get_fields()] # as list of strings # output: ['id', 'account_holder', 'age', 'salary'] From the form: class AccountForm(forms.ModelForm): class Meta: fields = '__all__' model = Account The list of the form fields (one of the possible methods without derailing into a different topic): fields = AccountForm.base_fields # as dictionary of objects [field for field in AccountForm.base_fields.keys()] # as list of strings # output: ['account_holder', 'age', 'salary'] And I have a serializer: class AccountSerializer(serializers.ModelSerializer): class Meta: model = Account fields = ( 'id', 'account_holder', 'age', 'salary', 'age_score', 'salary_score', ) which has a few more fields than the model. But for example using the following, it throws an error: >>> AccountSerializer.get_field_names() Traceback (most recent call last): File "<console>", line 1, in <module> TypeError: ModelSerializer.get_field_names() missing 3 required … -
Building a WhatsApp Chat Bot with Django & MySQL for Collecting User Information [closed]
I am working on a project to build a WhatsApp chat bot using Django as the backend framework. The primary goal of the bot is to interact with users on WhatsApp and collect their information, such as name and email. However, the information criteria can vary, including long paragraphs or options like "Yes" or "No." My requirements are as follows: WhatsApp Integration: I need to integrate the chat bot with WhatsApp so that users can interact with it directly through the messaging app. User Information Collection: The chat bot should be able to prompt users for their information, and the responses could be simple data like name and email or more complex like paragraphs and options. Django Backend: I plan to use Django as the backend framework for processing and storing the collected user information in a MySQL database. MySQL Database: The user information should be stored in a MySQL database for further analysis and usage. I'm not sure how to connect these different components effectively. If you have prior experience building similar chat bots or integrating WhatsApp with Django, I would greatly appreciate your guidance on the best practices and tools to achieve this. Additionally, I'm open to using … -
I want to customize my password field in django admin panel to implement hide/unhide functionality
I want to customize my password field in django admin panel to implement hide/unhide functionality. #app/models.py from django.db import models class CustomInput(models.Model): name = models.CharField(max_length=100) password = models.CharField(max_length=128) I want to add a "eye" sign in password field and implement hide/unhide functionality inside my admin panel. Please refer image for admin panel reference -
Make a regular expression in the search in VS code
I'd like to change the imghtml tag to django html with {%static Can you make a regular expression in the ctrl + f function so I can change it at once? ex) <img src="../img/logo.png" => <img src=" {%static 'img/logo.png' %}" r'<img\s+src="(.*?)"' But I can't find a way to change the code while preserving the middle values -
Stop the currently running task by celery worker in Django
I have a Django application and React as my frontend framework and I am using celery for running lengthy tasks which do take a lot of time and everything is working fine. Also I am providing real time status of the each task running on the celery via celery signals and all . Also I have created a database table which stores the status of all the tasks that are running , like when the task is created , i create a row with the parameters and they are unique so that task with same parameters won't run if its already running or is in the queue , so the user interface is good . But there are few tasks which need to stop and also the user have the authority and permission to stop the tasks that are running as i am updating every user for the tasks. Now if the task is in the queue i can use revoke to stop the from being executed . from celery.task.control import revoke revoke(task_id, terminate=True) But the thing is that , i have tasks which are very lengthy , so the user may want to stop the task and focus on … -
Internal Server Error for a football match prediction app
I am developing a football match prediction app in python/django. views.py has 3 major functions: def (matrix) generates random numbers using "secrets" module of python. The numbers are validated with an algorithm which returns either "valid" or "invalid". If valid, the next function is called, otherwise, new set of random numbers are generated. def (sincerity) checks whether the match is actually scheduled. An algorithm returns either "sincere" or "Oops! We detected an error ..." If sincere, the next function is called, otherwise, user gets a response in frontend "Oops! We detected an error ..." def determine_winner(home_team, away_team) uses 5 algorithms tagged formula 1, formula 2, ... formula 5. A summary of the 5 formulae returns "home team will win", "away team will win", "it will be a draw" or "sorry, we cannot determine match winner". These steps make up the function, def process_form (request). When I submit request, instead of getting the desired response, I get "Internal Server Error: /process_form/". Note that app is yet to be deployed to a live server. Internal Server Error: /process_form/ Traceback (most recent call last): File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, … -
make manytomany field hyperlink
thanks for your time i need to change categories in api my category and books models are manytomany my serializer: class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('id', 'name') class BookSerializer(serializers.ModelSerializer): price_after_discount = serializers.SerializerMethodField() def get_price_after_discount(self, instance): discounts = instance.get_discount(user=self.context['request'].user) def formatNumber(num): if num % 1 == 0: return int(num) else: return "{:.1f}".format(num) return formatNumber(float(instance.price)*((discounts)/ 100 )) class Meta: model = Book fields = ('id','isbn','title','content','price','authors','categories','price_after_discount') result : { "id": 1, "isbn": "978-1-4061-9242-1", "title": "Energy carry different lot. Back room practice with.", "content": "Suddenly various answer author.", "price": "7346.00", "authors": [ 1, 2 ], "categories": [ 2 ] }, but i need: "categories": [ "http://127.0.0.1:8000/category/2/" ], thanks for reading. -
How to upload a file in a nested directory to Storage accounts File Share service using Python SDK?
I am trying to upload a file to the path, using ShareDirectoryClient Class of Azure Python SDK.I have attached below the code and errors that I am getting. path = "users/vaibhav11/projects/assets/fbx" directories = path.lower().strip("/").split("/") for directory in directories: try: directory_client = directory_client.get_subdirectory_client(directory) if not directory_client.exists(): directory_client.create_directory() except Exception as e: print(e.args) with directory_client.get_file_client(file_name=upload_file.name) as file_client: file_client.upload_file(data = file_content, length=len(file_content)) print("Uploaded") The "directory_client" is an object of ShareDirectoryClient, which is used in the above code snippet to create directories. The problem faced is, with every directory that is being created I get the below Exception. ('The specifed resource name contains invalid characters.\nRequestId:fc43b173-e01a-000c-1ae8-bd388a000000\nTime:2023-07-24T04:37:52.5072468Z\nErrorCode:InvalidResourceName',) ClientAuthenticationError Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature. ErrorCode:AuthenticationFailed authenticationerrordetail:The MAC signature found in the HTTP request 'E0eObuCq+OdHAtf4qG80kb3wprxR4vwIsDpjinnVvUM=' is not the same as any computed signature. Server used following string to sign: 'PUT.......' And sometimes I even get ClientAuthenticationError. I'm not really sure, what is creating the problem in both the cases. Any solutions and suggestions are open. Thanks! -
Struggling with AWS S3 storage
My concern is about media images on AWS S3 from a Django based website. I'm able to view images from and save them to S3 when I'm on localhost, everything works well. However when the app is deployed and the website is running live on the internet, actual link: I'm only able to view the images that are on S3, but NOT able to save images to S3 bucket, though the AWS S3 bucket has full public access. I get the following error while trying to save images to S3: 2)Error Error message ClientError at / An error occurred (400) when calling the HeadObject operation: Bad Request It highlights this line of my code: form_instance.save() My code: (views.py) def make_and_see(request): if request.method == 'POST': form_instance = ProductForm(request.POST, request.FILES) if form_instance.is_valid(): form_instance.save() messages.success(request, 'Picture is saved') return redirect('home') else: messages.error(request, form_instance.errors) return redirect('home') else: context = {'data': Product.objects.all().order_by('?').first(), 'my_form': ProductForm(), 'time': timezone.now} return render(request, 'app1/home.html', context) (settings.py) STORAGES = {"default": {"BACKEND": "storages.backends.s3boto3.S3Boto3Storage"}, "staticfiles": {"BACKEND": "storages.backends.s3boto3.S3StaticStorage"}} AWS_ACCESS_KEY_ID = os.environ["MY_AWS_ACCESS_KEY_ID"] AWS_SECRET_ACCESS_KEY = os.environ["MY_AWS_SECRET_ACCESS_KEY"] AWS_STORAGE_BUCKET_NAME = '****' AWS_S3_REGION_NAME = 'ap-south-1' AWS_QUERYSTRING_AUTH = False AWS_DEFAULT_ACL = None AWS_S3_FILE_OVERWRITE = False AWS_S3_CUSTOM_DOMAIN = f"{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com" My webite is hosted on Vercel via Github, the Postgresql db hosted … -
Celery tasks succeeding in Django but not showing on Flower or Celery Logs
I have a Django project using cookiecutter's template, I have been trying to get celery working with it. I have done the setup according to the celery docs and when I run a task, on Django's output it shows as succeeded but if I check the terminal running celery, celery logs don't even show if it received the tasks, I am running it using celery -A proj_name worker -l DEBUG. I also tried it with INFO but same thing. The tasks also dont show up on the Flower dashboard and I am using django-celery-results with both redis/postgres backends and both don't get the results populated. I am not really sure what's going on but as far as I can tell celery is not receiving the tasks at all despite what Django's logs show. Also, when I try to print the task's state using AsyncResult it always shows PENDING despite django again saying it succeeded. Here's my celery.py import os from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "proj_name.config.settings.local") app = Celery("proj_name") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) and my celery related configs if USE_TZ: CELERY_TIMEZONE = TIME_ZONE CELERY_BROKER_URL = env("CELERY_BROKER_URL", default="redis://localhost:6379/0") # CELERY_RESULT_BACKEND = f"db+postgresql://{env('POSTGRES_DB_USER')}:{env('POSTGRES_DB_PWD')}@localhost/{env('POSTGRES_DB_NAME')}" CELERY_RESULT_BACKEND = CELERY_BROKER_URL CELERY_CACHE_BACKEND = 'django-cache' … -
How do I iterate through a QuerySet of a QuerySet?
I'm trying to iterate through a Review QuerySet associated to an Album QuerySet in order to gather the total amount of ratings within the Review QuerySet. (9 + 8 + 7 + 9 = 33, for instance.) Here are my models: class Album(models.Model): creator = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) artist = models.CharField(max_length=255) title = models.CharField(max_length=255) # image = rating = models.IntegerField( choices=[(i, i) for i in range(1, 11)], validators=[MaxValueValidator(10), MinValueValidator(1)], default=10, ) ... class Review(models.Model): reviewer = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) album = models.ForeignKey(Album, on_delete=models.CASCADE) rating = models.IntegerField( choices=[(i, i) for i in range(1, 11)], validators=[MaxValueValidator(10), MinValueValidator(1)], default=10, ) ... Here are my attempts at for loops to try and get these totals: # Attempts working off of: `all_albums = Album.objects.all()` # Attempt 1 >>> for album in all_albums: ... review_ratings_amount = album.review_set.rating.all() ... print(review_ratings_amount) # Attempt #2 >>> for album in all_albums: ... review_ratings = album.review_set.filter("rating") ... print(review_ratings) # Attempt #3 >>> for album in all_albums: ... review_ratings = album.review_set.get(rating) ... print(review_ratings) # Attempt #4 >>> for album in album_ratings: ... review_ratings = album.review_set.get("rating") ... for rating in review_ratings: ... print(rating) # Attempt 5 (this was an attempt to see if ANYTHING would return, and I actually got some QuerySets in … -
Trigger htmx with radio button selection
I am using django and htmx to update a field on a form below is the code for displaying the radio buttons and my attempt at trigging. But it does not trigger. What am I doing wrong? {% extends 'core/base.html' %} {% block title %}Booking{% endblock %} {% block content %} <div class="container"> <div class="form-group"> <div class="row row-cols-1 row-cols-sm-2 row-cols-md-3 row-cols-lg-4"> <div class="col text-center p-1"> <form method="POST" action="."> {% csrf_token %} <legend>{{s_form.species.name.title}}</legend> <div hx-get="{% url 'book_services' %}" hx-trigger="change from:find .btn-check" hx-target="#book-services"> {% for choice in s_form.species.field.choices %} <input type="radio" class="btn-check" name="{{s_form.species.name}}" id="id_{{s_form.species.name}}_{{choice.0}}" autocomplete="off"> <label class="btn btn-outline-primary btn-lg m-1 col" for="id_{{s_form.species.name }}_{{choice.0}}"> {{choice.1}}</label> {% endfor %} </div> </form> </div> <div class="col text-center p-1 border"> <h5 class="text-lg">Service</h5> <div id="book-services" data-hx-trigger="load,bookSerivesChanged from:body" data-hx-get="{% url 'book_services' %}" data-hx-target="this"></div> </div> </div> <div class="row row-cols-1 row-cols-sm-2 row-cols-md-3 row-cols-lg-4"> <div class="col border">Date</div> <div class="col border">Time</div> </div> </div> </div> {% endblock %} I have attempted moving the trigger from a to the form and not luck. -
Retrieve last message for each conversation
I have a chat-like system on my website. I would like to make a list of conversation displaying the last message sent or received with each user I discussed with. Same as you can see on whatsapp or messenger or SMS applications. My Message model looks like this for now: class Message(models.Model): sender = models.ForeignKey('accounts.User', on_delete=models.CASCADE, related_name='messages_sent') receiver = models.ForeignKey('accounts.User', on_delete=models.CASCADE, related_name='messages_received') content = models.TextField() date = models.DateTimeField(auto_now_add=True) seen = models.BooleanField(default=False) I tried few things, the closest I achieved was this: latest_messages = Message.objects.filter(Q(sender=request.user) | Q(receiver=request.user)).order_by('sender', 'receiver', '-date').distinct('sender', 'receiver') The problem is, it returns the last message sent AND the last message received for each user, when I want the last of these 2. Thanks for your help -
admin.StackedInline in the Django Template
I am using Django. I made a Menu class in models.py class Menu(models.Model): nome = models.CharField(max_length=255) data = models.DateTimeField(auto_now=False, auto_now_add=True) class Meta: verbose_name_plural = 'Menu' # Python 2 def __unicode__(self): return self.nome # Python 3 def __str__(self): return self.nome and a Submenu class: class Submenu(models.Model): nome = models.CharField(max_length=255) data = models.DateTimeField(auto_now=False, auto_now_add=True) menu = models.ForeignKey(Menu, on_delete=models.CASCADE) class Meta: verbose_name_plural = 'Submenu' # Python 2 def __unicode__(self): return self.nome # Python 3 def __str__(self): return self.nome Then in admin.py I added: class SubmenuAdmin(admin.StackedInline): model = Submenu extra = 0 class MenuAdmin(admin.ModelAdmin): list_display = ['__str__'] inlines = [SubmenuAdmin,] class Meta: model = Menu admin.site.register(Menu, MenuAdmin) Now my goal is to be able to print the various menus in the template with a FOR loop, and under each respective menu the various submenus, as in this photo: -
Django makemigration does not detect my models
I have the following structure : DjangoProjectRoot API Peak peak_model.py Waterfall waterfall_model.py models.py ... As you can sea I organized the code to have separate module for each models, containing the model itself as well as the associated serializer and view. When I delete my database schema, all the migrations "makemigrations", the others tables are created, except the waterfall one. api/migrations/0001_initial.py - Create model Book - Create model Department - Create model Natural - Create model Publisher - Create model Region - Create model Cave - Create model Glacier - Create model Lake - Create model Peak - Create model Saddle - Create model Shelter - Create model Municipality - Create model Guide - Add field region to department - Create model Collection - Create model Author Any idea why ? I just refactored my code, before everything was in the model field. I'm also a bit surpised by " - Add field region to department ". My database is empty and I cleaned the migrations. Maybe I should add something in the init.py file ? Seems like django needs to detect my new structure ? waterfall_model.py : from django.db import models from api.natural.natural_model import Natural class Waterfall(Natural): height = … -
ERROR [nginx production-stage 3/4] COPY backend/static /usr/src/app/static/
trying to docker-compose build and get the response: failed to solve: failed to compute cache key: failed to calculate checksum of ref 5adae266-6345-4011-aeaf-cbed2c4d0e45::leen62wz7bu0oi2emahxawc9r: "/backend/static": not found Any idea how to solve the error? -
Profile Page cannot updating
I have a simple profile page and the information filled here comes in the form. The problem is that if I change a value it redirects to pages. I don't get an error but that update is not written to the database views.py def update_user(request): if request.method == 'POST': form = ProfileUpdateForm(request.POST) if form.is_valid(): profile_data = form.cleaned_data profile = get_object_or_404(UserProfile, user=request.user) profile.first_name = profile_data['first_name'] profile.last_name = profile_data['last_name'] profile.save() messages.success(request, "Update is successful") return redirect('/pages/') else: form = ProfileUpdateForm() return render(request, 'profile.html', {'form': form}) template.html <form class="form" method="POST" action='{% url "update" %}'> {% csrf_token %} <div class="row"> <div class="col"> <label>First Name</label> <input class="form-control" type="text" name="first_name" placeholder="{{ user.first_name }}"" value="{{ user.first_name }}"> </div> </div> </div> <div class="col"> <div class="form-group"> <label>Last Name</label> <input class="form-control" type="text" name="last_name" placeholder="{{ user.last_name }}"" value="{{ user.last_name }}"> </div> </div> </div> <div class="row"> <div class="col d-flex justify-content-end"> <button class="btn btn-primary" type="submit" value="profile">Save Changes</button> </div> </div> </form> forms.py class ProfileUpdateForm(forms.ModelForm): class Meta: model = UserProfile fields = ['first_name', 'last_name', 'plz', 'street', 'street_no', 'city'] widgets = { 'first_name': forms.TextInput(attrs={"class": "form-control"}), 'last_name': forms.TextInput(attrs={"class": "form-control"}), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) any help?