Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it possible to make a real-time clock with Django?
I know that Django have a function that can get current time. However, it cannot continuously updates the time to the user interface (Real-time clock). The code for getting the current time. views.py from datetime import datetime from django.shortcuts import render def clock(request): now = datetime.now() context = { 'current_time': now.strftime('%Y-%m-%d %H:%M:%S') } return render(request, 'clock.html', context) clock.html {% extends "base.html" %} {% block content %} <h1>Current Time:</h1> <p>{{ current_time }}</p> {% endblock %} -
Does mezzanine allow custom navigation items to be displayed according to a custom permission?
I have a system that uses mezzanine custom navigation items to display some navigation items. However, I want the navigation items to only be displayed if a user have a specific set of permissions which are custom and not really Model based. Does mezzanine support this? Sample code ADMIN_MENU_ORDER = ( ('Customer service'), ( ('Customer X OverX', 'summary_e'), summary_e is a URL. How can I ensure Customer service is only displayed if a user has certain permission? -
Django - Changes to related field listed on History
I have two models class Project(models.Model): # ... history = HistoricalRecords() class ProjectMember(models.Model): project = models.ForeignKey(Project) user = models.ForeignKey(User) # ... Using django-simple-history, how can I list creation/changes of ProjectMembers under the Project history? The documentation mentions HistoricForeignKey, but it is not clear how to use it. I've tried this class Project(models.Model): # ... history = HistoricalRecords() class ProjectMember(models.Model): project = HistoricForeignKey(Project) user = models.ForeignKey(User) # ... history = HistoricalRecords() but it didn't produce the results I wanted. Is it even possible? -
How to set up test db settings in a DRF project?
I'm running unit tests in a drf project with a mongo db and djongo connector. When I run tests one by one they compile successfully but when I run all of them with python3 manage.py test test.path they all fail except the first test. The following line from the logs indicates that there is an issue with dropping the test database. FAILED SQL: DROP DATABASE "test_my_project_name" Here's the database configuration. DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'my_project_name', 'CLIENT': { 'host': os.environ[DB_HOST], } }, 'test': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'test_mytestdatabase', 'USER': 'mytestdatabaseuser', 'PASSWORD': 'mytestpassword', 'HOST': 'localhost', 'PORT': '5432', } } What do I need to do to make the test db be used during tests and not the main db. Also do I need to set up anything else for the testing? -
Options request throws AssertionError error in Django REST Framework
I have the following Viewset: class My_ViewSet(viewsets.ModelViewSet): serializer_class = My_Serializer queryset = My_Object.objects.all() def list(self, request): # The code here is irrelevant return Response() def retrieve(self, request, pk=None): # The code here is irrelevant my_object = get_object_or_404(My_Object, id=pk) return Response(my_object.id) urls.py sample: urlpatterns = [ path('api/my_object/', My_ViewSet.as_view({'get': 'list'})), path('api/my_object/<int:pk>/', My_ViewSet.as_view({'get': 'retrieve'})), ] When I try to make OPTIONS request on api/my_object/ I have the following error: AssertionError: Expected view My_ViewSet to be called with a URL keyword argument named "pk". Fix your URL conf, or set the .lookup_field attribute on the view correctly. -
TypeError at /follow/4 follow() got an unexpected keyword argument 'user_id'
I'm creating a follow/unfollow button where a user clicks on the button and follows the other user if they are not already following the user. I am getting a TypeError with the below code; MODESL.PY class User(AbstractUser): following = models.ManyToManyField( "self", blank=True, related_name="followers", symmetrical=False ) def __str__(self): return str(self.username) URL.PY path("profile/<int:user_id>", views.profile, name="profile"), path("follow/<int:user_id>", views.follow, name="follow"), PROFILE.HTML <div class="row"> <b> following : </b> <p class="text-muted"> {{ profile.following.count }} </p> &nbsp;&nbsp;&nbsp;&nbsp; <b> followers : </b> <p class="text-muted"> {{ profile.followers.count }} </p> </div> {% if user.is_authenticated %} {% if user in profile.following.all %} <a href="{% url 'follow' user.id %}" class="btn btn-primary">Unfollow</a> {% else %} <a href="{% url 'follow' user.id %}" class="btn btn-primary"> Follow </a> {% endif %} {% else %} <button class="btn btn-outline-primary">Message</button> <p class="text-muted"> please, login to follow </p> {% endif %} VIEWS.PY def profile(request, user_id): profile = User.objects.get(pk = user_id) context = { "profile": profile, } return render(request, "network/profile.html", context) def follow(request, user_id): authorObj = User.objects.get(pk=user_id) currentUserObj = User.objects.get(pk=request.user.pk) following = authorObj.following.all() if user_id != currentUserObj.pk: if currentUserObj in following: authorObj.following.remove(currentUserObj) else: authorObj.following.add(currentUserObj) return HttpResponseRedirect(reverse("index")) I suspect the error is coming from the views def follow(request, user_id): searching on the template for the argument 'user_id which I've checked and the … -
404: NOT FOUND Vercel
I depolyed a simple django app on vercel with github. The build was successful, but the site says 404: NOT FOUND I edited ALLOWED_HOSTS in my settings.py ALLOWED_HOSTS = ['vercel.app'] -
Non admin users can access a view that is supposed to be restricted to admin users in django rest framework and simplejwt
I have made a custom user model inside my django backend and I have created a view that register a new user, but I have set the view only for admin users. When I tried to register a new user using a non admin account, it has also worked!! so the view is correct but there is something wrong with the permissions! could someone please tell me what did I do wrong? this is the models.py that has the custom user model: from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.db import models class CustomUserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): if not email: raise ValueError('The Email field must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_admin', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self.create_user(email, password=password, **extra_fields) class User(AbstractBaseUser): email = models.EmailField(unique=True) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=True) is_superuser = models.BooleanField(default=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] objects = CustomUserManager() def __str__(self): return self.first_name def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): … -
How to create DateTImeFromToRangeFilter only with 1 field and DateRangePicker
Im looking for way to do something like that: I use package django-filter and i choose DateTimeFromToRangeFilter and it creates 2 input fields with different date pickers I wonder if there`s way to connect them into 1 field, use date range picker and make them work filters.py: import django_filters from django_filters import DateTimeFromToRangeFilter class MyFilter(django_filters.Filterset): work_date = DateTimeFromToRangeFilter() class Meta: Model = MyModel fields = ('__all__',) -
CommonMiddleware is not working in custom middlewares
CommonMiddleware not working in custom middlewares I have a custom middleware like below: class PageNotFoundMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) sura_pattern = r"/sura/[1-9]\d*-[1-9]\d*/$" print(f'\n\n{request.path_info}: {response.status_code}\n\n') # <-- if response.status_code == 404: if re.match(sura_pattern, request.path_info): return response return render(request, '404.html') elif response.status_code == 400: return render(request, '400.html') elif response.status_code == 500: return render(request, '500.html') elif response.status_code == 200 or response.status_code == 301: return response In the line I marked with arrow: "<--", the request.path_ifo, has no ending "/". example: If the inputted url is: /sura/10, then it shows me /sura/10, but it must append and ending "/" to it. this url is valid, here is the urls.py: urlpatterns = [ path("", home, name="home"), path('sura/<int:sura>/', sura_handler, name='sura_handler'), # <-- path which should get the url path('sura/<str:sura_aya>/', index, name='index'), path('page/<str:page>/', page_handler, name='page_handler'), path('juz/<str:juz>/', juz_handler, name='juz_handler'), path('api/', include('quran.api.urls')), path('sw/', sw, name="sw"), path('manifest/', manifest, name="manifest"), ] Note: Before regex executed, the response.status_code is 404. While if I correctly input the url, (like this: /sura/10/) then the response.status_code in not 404. can someone help me please find out why CommonMiddleware doesn't work in custom middlewares? Middlewares in django: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'quran.middleware.PageNotFoundMiddleware' … -
Setting the column fields for a laravel model
In another mvc framework like django,we can define the column fields by defining the attributes in the corresponding model clas. How to do that in laravel? class Model { name : string; address:string; } In the model class we can declare the column for the database and its data type ? How to do that in laravel? -
Django : Currently there is no database set to DATABASE_URL
I am working on a Django project for my client and I have to refactor the custom middleware to django authentication ( login ) and Django views. In the case of middleware, I put a passphrase which acts like a password and then it authorizes the users and everything works fine. now I changed the code from middleware to Django authentication to let the users login and then do the other logic. I was searching for the question on SO and I found this problem Django settings: DATABASE_URL is not working I tried to do the same but it is not fixing the issue. This is the code that tells me why my database url is not set: def message_check_db(request, **kwargs): try: DB_Found = False DB_Connected = False result = run_command() print("\n RESULT :", result) for (env, url) in os.environ.items(): if env.startswith('HEROKU_POSTGRESQL'): DB_Found = True print("\n FOUND DB :", DB_Found) formatted_Data = [] for formatted_String in str(result.stdout).split('=== '): start_DbName = formatted_String.find("HEROKU_POSTGRESQL_") end_DbName = formatted_String.find("\\nPlan") DbName = formatted_String[start_DbName:end_DbName] start_AddOn = formatted_String.find("Add-on:") end_AddOn = formatted_String.find("\\n\\n") AddOn = formatted_String[start_AddOn:end_AddOn].replace('Add-on: ', "") formatted_Data.append({ "name": DbName.replace(", DATABASE_URL", ""), "addon": AddOn }) color_DB = getDbName(env) current_DB = getDbName('DATABASE_URL') for data in formatted_Data: if env == data['name'] … -
django_celery_beat - No module named 'pymemcache'
I have a strange issue when i try to add a task from the django_celery_beat package on my production server. (Everything runs fine on my local workspace). I get a No module named pymemcache error but i've installed it already on my venv. On my production server i have a memcached server running and the configuration is the following: 'default': { 'BACKEND': 'django.core.cache.backends.memcached.PyMemcacheCache', 'LOCATION': '10.100.23.95:11211', }, How can i fix this issue ? Thank you very much for your time I've tried installing the packages again but i don't understand what i'm doing wrong. ERROR LOG: Environment: Request Method: GET Request URL: http://env-2969130.jcloud.ik-server.com/admin/django_celery_beat/periodictask/add/ Django Version: 4.1.6 Python Version: 3.11.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django_countries', 'phonenumber_field', 'crispy_forms', 'django_filters', 'django_select2', 'mathfilters', 'django_quill', 'corsheaders', 'captcha', 'user_visit', 'django_social_share', 'django_celery_beat', 'core.apps.CoreConfig', 'shopcore.apps.ShopcoreConfig', 'shopuser.apps.ShopuserConfig', 'customer.apps.CustomerConfig', 'product.apps.ProductConfig', 'catalog.apps.CatalogConfig', 'discount.apps.DiscountConfig', 'order.apps.OrderConfig', 'wishlist.apps.WishlistConfig', 'basket.apps.BasketConfig', 'authentification.apps.AuthentificationConfig', 'front.apps.FrontConfig', 'vinx.apps.VinxConfig', 'saferpay.apps.SaferpayConfig', 'promotion.apps.PromotionConfig', 'information.apps.InformationConfig', 'job.apps.JobConfig', 'newsletter.apps.NewsletterConfig', 'blog.apps.BlogConfig', 'dashboard.apps.DashboardConfig', 'stats.apps.StatsConfig'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'user_visit.middleware.UserVisitMiddleware'] Traceback (most recent call last): File "/opt/jelastic-python311/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/opt/jelastic-python311/lib/python3.11/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/opt/jelastic-python311/lib/python3.11/site-packages/django/contrib/admin/options.py", line 686, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/opt/jelastic-python311/lib/python3.11/site-packages/django/utils/decorators.py", line … -
How to make a Django form for a model that has a OneToOne connection with the base User model?
The details are in the code, it speaks for itself. I have this profile model with fields that aren't in User, and I need to make a form that fills up both the fields from User and Profile: class Profile(models.Model): user = models.OneToOneField( to=User, on_delete=models.CASCADE ) rating = models.IntegerField(default=0, blank=False) avatar = models.ImageField() def __str__(self): return self.user.string() def absolute_url(self): return f"/post/{self.pk}/" class Meta: db_table = 'profile' ordering = ['-user'] class SignUpForm(UserCreationForm): username = UsernameField( max_length=256, label=_('RegisterUsername'), widget=forms.TextInput( attrs= { 'class': "form-control" } ), ) email = forms.CharField( max_length=320, label=_('RegisterEmail'), widget=forms.EmailInput( attrs= { 'class': "form-control" } ), ) nickname = forms.CharField( max_length=256, label=_('RegisterUsername'), widget=forms.TextInput( attrs= { 'class': "form-control" } ), ) password1 = forms.CharField( max_length=256, label=_('RegisterPassword1'), widget=forms.PasswordInput( attrs= { 'class': "form-control" } ), ) password2 = forms.CharField( max_length=256, label=_('RegisterPassword2'), widget=forms.PasswordInput( attrs= { 'class': "form-control" } ), ) avatar = forms.ImageField( label=_('UploadAvatar'), widget=forms.FileInput( attrs= { 'class': "btn btn-outline" } ), ) class Meta: model = Profile fields = [ 'username', 'email' 'nickname' 'password1', 'password2', 'avatar', ] django.core.exceptions.FieldError: Unknown field(s) (emailnicknamepassword1) specified for Profile I expected it to work somehow... -
Update and create an entry in the same view in Django
I'm quite new in Django and I am developing a CRUD application for initiatives. The 'add' and 'delete' actions are working well. For the update action, instead of overwriting the initiative once the user confirmed, I would like to change the status of this initiative to 'DELETED' and add a new line for the modified initiative in my database. Here is what I have so far for creating a new initiative, which is working well: def init(request): if request.method == 'POST': form = InitiativeForm(request.POST) if form.is_valid() : try : form.save() return redirect('/show') except : pass else: form = InitiativeForm() return render(request, 'index.html', {'form': form}) Here is what I have for deleting an initiative. I don't want to delete the initiative but just want to switch the status to 'DELETED'. This also working well: def destroy(request, id): initiative = Initiative.objects.get(id=id) initiative.status_init = Status.objects.get(status = 'DELETED') initiative.save(force_update=True) return redirect('/show') But for the updating action, I would like to keep the previous record and switch the status to 'DELETED' (as I do for deleting an initiative) and I would like to save the new record as a new line (as I do for creating a new initiative). Here is the current code I … -
Issue with file write using Django and Celery
I have such a model for representing posts in my system. class Post(models.Model): caption = models.CharField(max_length=256) text = models.CharField(max_length=256, null=True, blank=True) date_posted = models.DateTimeField(null=True, blank=True) source = models.ForeignKey(Source, on_delete=models.CASCADE) source_url = models.URLField() image = models.ImageField(upload_to='post_images', null=True) I have a data collector who scrapes data and puts it in this model. The method for inserting scraped single record looks like this: @staticmethod def _load_post(post: CollectedPostData, source: Source) -> None: print('#' * 70) print(source) post_obj, created = Post.objects.get_or_create( caption=post.caption, text=post.text, source=source, source_url=post.source_url, date_posted=parse(post.date_posted) if post.date_posted else None, ) print(post_obj, created) print(post.image) if created: print('CREATED') image_content = requests.get(post.image, allow_redirects=True).content print(len(image_content)) post_obj.image.save(post.image, ContentFile(image_content), save=True) print('After SAVE') print('#' * 70) When I run the code with Celery, I see that all print statements are executed, there are no issues in logs, all Post objects are created with correct data, but 'post_images' folder in 'media' is not created and zero file created... The funny thing is that when I am running this code snipped manually all files are created... I am 'playing' with this for few days and still can't understand why it's not working. Could someone please help? p.s. I am using: Django==4.1.7 Pillow==9.4.0 redis==4.5.3 -
Pass a filtered field to views.py for further operation
I'm pretty new to Django working in a small project. I need to have the logged in user to be able to see the total of taxes. In the user model is every users info, including each of these taxes, I need to have them called in the views.py so I can use it for further operation with other variables. So far I've been able to Sum .filter() and .all() fields in the same column or field, but cant see to find a way to Sum or call different fields of same row. models.py class User(AbstractUser): username = models.CharField(unique=True, max_length=20, null=True) email = models.EmailField(null=True) tax1 = models.DecimalField(max_digits=7, decimal_places=2, default=0) tax2 = models.DecimalField(max_digits=7, decimal_places=2, default=0) tax3 = models.DecimalField(max_digits=7, decimal_places=2, default=0) views.py def Calc(request): m_tax1 = User.objects.filter(username=request.user) m_tax11 = m_tax1.aggregate(Sum('tax_1')) m_tax2 = User.objects.filter(username=request.user) m_tax22 = m_tax2.aggregate(Sum('tax_2')) m_tax3 = User.objects.filter(username=request.user) m_tax33 = m_tax2.aggregate(Sum('tax_3')) total_tax = m_tax11 + m_tax22 + m_tax33 context = { 'm_tax11' : m_tax11, 'm_tax22' : m_tax22, 'm_tax33' : m_tax33, 'total_tax' : total_tax} return render(request,'main/calc.html', context) template {{m_tax11}} + {{m_tax22}} + {{m_tax33}} = {{total_tax}} -
my cards are not same size. how to fix it?
{% extends 'shop/layouts/main.html' %} {% block title %} Ar Choose | Register {% endblock title %} {% block content %} <section class="py-5 text-center container" style="margin-top: 70px;"> <div class="row py-lg-5"> <div class="col-lg-6 col-md-8 mx-auto"> <h1 class="fw-light">AR Choose</h1> <p class="lead text-muted">Our Sales are Coming Soon....</p> <p> <a href="#" class="btn btn-primary my-2">Already User</a> <a href="#" class="btn btn-secondary my-2">New User</a> </p> </div> </div> </section> <section class="bg-light py-4 my-5"> <div class="container"> <div class="row"> <div class="col-12"> <h4 class="mb-3">Categories</h4> <hr style="border-color: brown;"> </div> {% for item in catagory %} <div class="col-md-4 col-lg-3"> <div class="card my-3 "> <img src="{{item.image.url}}" class="card-image-top" alt="Categories"> <a href="#"> <div class="card-body"> <h5 class="card-title text-primary">{{ item.name }}</h5> <p class="card-text">{{item.description}}</p> </div></a> </div> </div> {% endfor %} </div> </div> </section> how to change my code? only change in my code pls -
django: a model can be accessed from shell, but fail from web ui
I have models like class Customer(models.Model): id = models.UUIDField(primary_key=True, default=uuid4, editable=False) company = models.ForeignKey(Company, on_delete=models.CASCADE, null=True, editable=False) name = models.CharField(max_length=30) user = models.OneToOneField(User, related_name='customer_profile' , null=True, on_delete=models.SET_NULL, editable=False) created_by = models.ForeignKey(User, related_name='mycustomer' , null=True, on_delete=models.SET_NULL, editable=False) id_card = models.CharField(max_length=30, unique=True) phone = models.CharField(max_length=20, blank=True) email = models.EmailField(max_length=50,blank=True) address1 = models.CharField(max_length=50, blank=True) address2 = models.CharField(max_length=50, blank=True) address3 = models.CharField(max_length=50, blank=True) provinsi = models.ForeignKey(Provinsi, null=True, on_delete=models.SET_NULL) kota = models.ForeignKey(Kota, null=True, on_delete=models.SET_NULL) kecamatan = models.ForeignKey(Kecamatan, null=True, on_delete=models.SET_NULL) desa = models.ForeignKey(Desa, null=True, on_delete=models.SET_NULL) kodepos = models.IntegerField(blank=True, null=True) gmap = models.URLField(blank=True, max_length=100) def __str__(self) -> str: return self.name class ContractCode(models.Model): id = models.UUIDField(primary_key=True, default=uuid4, editable=False) code = models.CharField(unique=True, max_length=8) def __str__(self) -> str: return self.code class BaseContract(models.Model): id = models.UUIDField(primary_key=True, default=uuid4, editable=False) code = models.OneToOneField(ContractCode, on_delete=models.PROTECT, null=True) company = models.ForeignKey(Company, on_delete=models.CASCADE, null=True, editable=False) customer = models.ForeignKey(Customer, on_delete=models.PROTECT) # -- location address1 = models.CharField(max_length=50, blank=True) address2 = models.CharField(max_length=50, blank=True) address3 = models.CharField(max_length=50, blank=True) provinsi = models.ForeignKey(Provinsi, null=True, on_delete=models.SET_NULL, blank=True) kota = models.ForeignKey(Kota, null=True, on_delete=models.SET_NULL, blank=True) kecamatan = models.ForeignKey(Kecamatan, null=True, on_delete=models.SET_NULL, blank=True) desa = models.ForeignKey(Desa, null=True, on_delete=models.SET_NULL, blank=True) kodepos = models.IntegerField(blank=True, null=True) gmap = models.URLField(blank=True, max_length=100) # EOL location step = models.IntegerField(choices=ContractStep.choices, default=ContractStep.SURVEY_WAIT.value, editable=False) open_close = models.IntegerField(choices=JobStatus.choices, default=JobStatus.OPEN.value, verbose_name='status', editable=False) is_enable = models.BooleanField(default=False, editable=False) created_at = models.DateTimeField(auto_now_add=True) … -
How to avoid duplicates bcs of __str__ function Django
I have model with Foreign Key and i use name of that foreinKey in my template and i have 38 sql queries bcs of __str__ funciton in my model How can i show name of foreignKey without duplicates and similiar queries? models.py class SectionList(models.Model): GUID = models.UUIDField(default=uuid.uuid4, editable=True, unique=True) object = models.ForeignKey(ObjectList, related_name='object', on_delete=models.CASCADE, default=None, verbose_name='Объект') clean_sections = models.ForeignKey(CleanSections, on_delete=models.CASCADE, null=True) class Meta: verbose_name = 'Раздел' verbose_name_plural = 'Разделы' def __str__(self): return f'{self.clean_sections.name}' -
How to fix wrong number of constraints in Django with psql prompt?
I'm unable to migrate a model due to the following exception and I'm trying to fix the issue with psql. ValueError: Found wrong number (2) of constraints for accounting_inventory(trade_id) models.py class Inventory(TimestampedModel): class Type(models.TextChoices): SNAPSHOT = 0, "Snapshot" ASSET = 1, "Asset" CONTRACT = 2, "Contract" id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False) account = models.ForeignKey(Account, on_delete=models.CASCADE, null=True) trade = models.OneToOneField(Trade, on_delete=models.CASCADE, null=True) type = models.CharField(max_length=64, choices=Type.choices) datetime = models.DateTimeField() assets = models.JSONField(default=dict, null=True) contracts = models.JSONField(default=dict, null=True) class Meta: verbose_name_plural = "Inventory" unique_together = [('trade',), ] def __str__(self): return str(self.id)[-4:] Now, Django says there is no migration: root@1f3de954c6e0:/app# python manage.py makemigrations No changes detected But as soon as I make a change, for example to remove the unique_together it generates this migration file but can't migrate because of the exception above. migration root@1f3de954c6e0:/app# more accounting/migrations/0022_alter_inventory_unique_together.py # Generated by Django 4.0.6 on 2023-04-10 06:40 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('accounting', '0021_alter_inventory_unique_together_inventory_account_and_more'), ] operations = [ migrations.AlterUniqueTogether( name='inventory', unique_together=set(), ), ] So I connected with psql and found this when listing constraints: defaultdb=> SELECT con.* defaultdb-> FROM pg_catalog.pg_constraint con defaultdb-> INNER JOIN pg_catalog.pg_class rel defaultdb-> ON rel.oid = con.conrelid defaultdb-> INNER JOIN pg_catalog.pg_namespace nsp defaultdb-> ON nsp.oid = connamespace … -
check fields of a model to fill together in creation in django
I want to make conditions for my model in this way (for just creation): field A, B, C, and D fields together(not null) and Filed E, F, G, and H fields together. So we can have input= (somthingA,somthingB,somthingC,somthingD,None,None,None,None) OR input= (None,None,None,None,somthingE,somthingF,somthingG,somthingH) If I left one or more filed empty it returns an error: input=(somthingA,None,somthingC,somthingD,None,None,None,None) error: field B can not be empty in condition 1 -
I have a task model and I want to create activity flow of task.My question is that how to find that which field is changed when doing updation
I want to store the changed field of a model in to another model when doing updation using pre_save() method in Django, how it possible? i am tried but not get, can you give me a solution? -
django how can I sort by user field
How to make sure that when creating a task, when choosing a category, the user sees only the category created by himself, and not others' together with his own. There are 2 users. One has a category "user1 category" created, the second has a "user2 category" created. How to make user1 see only the category "user1 category" in the selection field when creating a task for him The screenshot is attached below. selection field Code: class Tasks(models.Model): title = models.CharField(max_length=75) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="creator", editable=False) class Category(models.Model): title = models.CharField(max_length=30, db_index=True, verbose_name="category_name") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="category_creator", editable=False) class TaskCreateView(CreateView): form_class = TaskForm template_name = 'main/add_task.html' def form_valid(self, form): form.instance.user = self.request.user return super(TaskCreateView, self).form_valid(form) def get_queryset(self): return Tasks.objects.filter(user=self.request.user) I tried to do it with this code, but i couldn't: class TaskForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['category'].queryset = Tasks.objects.filter(category__category__user=self.request.user) self.fields['category'].empty_label = "Not selected" class Meta: model = Tasks fields = ['title', 'category'] -
writing a custom logic in admin.py for prepopulated fields value in django
I have a model - Comment to which I have added a slug field. class Comment(Model): on_blogpost = models.ForeignKey(BlogPost, on_delete=models.CASCADE) commentor = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) content = models.TextField(max_length=300) posted_on = models.DateTimeField(editable=False, auto_now=True) edited_at = models.DateTimeField(editable=False, auto_now_add=True) slug = models.SlugField(max_length=100) In the corresponding CreateView.form_valid() I have added a logic to populated the slug field so that every time a user comments an appropriate slug is created: form.instance.slug = slugify(f"{form.instance.commentor.username}-{slugify(form.instance.content[:50])}-{utils.get_random_alphanumeric()}") My goal is to write a similar logic in admin.py for prepopulated fields. How to achieve that? I am already aware of the fact that prepopulated fields do not use foreign key fields, datefields, etc so I would not be able to include the commentor in custom logic. But I would want to add rest of fields into the logic of building up the slug value i.e content and utils.get_random_alphanumeric(). Thanks!