Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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! -
Unable to migrate data in Django
My Django structure follows this article: https://studygyaan.com/django/best-practice-to-structure-django-project-directories-and-files#:~:text=The%20way%20I%20like%20to,content%20in%20the%20media%20folder. where I put my app sync_wits_meta in apps folder and add app_1 in INSTALLED_APPS INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'apps.sync_wits_meta', # <--- here ] then when I run python manage.py makemigrations, it shows the error: Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/apps/config.py", line 210, in create app_module = import_module(app_name) File "/usr/local/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'sync_wits_meta' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 420, in execute django.setup() File "/usr/local/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python3.8/site-packages/django/apps/config.py", line 212, in create raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Cannot import 'sync_wits_meta'. Check that 'apps.sync_wits_meta.apps.SyncWitsMetaConfig.name' is correct. The command '/bin/sh -c python manage.py makemigrations apps/sync_wits_meta' returned a non-zero code: 1 How can I do migration if I put app in the apps folder? I am using … -
How to create a App Specific User roles and access in Django?
I want to create a user management system in Django where I will have multiple apps and for a single user, I want to assign different roles for the various apps as in the image below. Expert advice would be appreciated. The Image shows the different roles assigned to a user for different apps -
Django Admin Crash When Default Storage Changed
I'm trying to change the default storage of a model in django so that it stores files in an amazon S3 bucket the bucket has the next permissions: { "Version": "2012-10-17", "Id": "Policy1680906499830", "Statement": [ { "Sid": "Stmt1680906498320", "Effect": "Allow", "Principal": "*", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::tuenlaceinmobiliariodevelopmentbucket/*" } ] } I need to be able to load images from django admin, but the page loads only in html, the admin tried to load static files from the bucket and I don't know how to make it work correctly, I can still navigate to the create images form, however when I fill out the file form and press the button save, the manager throws an ERR_EMPTY_RESPONS error. Even so, the image is stored in the Amazon S3 bucket, but django admin stops working. This is my configuration #model class Image(Item,models.Model): image = models.ImageField( upload_to='images/' ) #admin @admin.register(Image) class ImageAdmin(admin.ModelAdmin): list_display = ( 'nombre', 'descripcion', 'image' ) search_fields = ( 'nombre', 'descripcion', 'image' ) #compose_file DEFAULT_FILE_STORAGE = "storages.backends.s3boto3.S3Boto3Storage" STATICFILES_STORAGE = "storages.backends.s3boto3.S3Boto3Storage" COLLECTFAST_STRATEGY = "collectfast.strategies.boto3.Boto3Strategy" -
django on_delete = DO_NOTHING
I am developing an app where I need some of the data to be protected even when some models are deleted. I've been reading on the on_delete options, and seems to be a lot of warnings against using on_delete=DO_NOTHING. In my case, I need the results to be maintained even when a yacht or event gets deleted. The basic structure is this; # models.py class Yacht(models.Model): yacht_name=models.CharField(max_length=100) class Event(models.Model): event_name=models.CharField(max_length=100) yachts = models.ManyToManyField(Yacht, through="Result") class Result(models.Model): yacht = models.ForeignKey(Yacht, on_delete=DO_NOTHING) event = models.ForeignKey(Event, on_delete=DO_NOTHING) ranking = models.IntegerField(max_lenght=4) For record keeping, I need the results to remain even if a yacht or event is deleted. What is the best approach here? Some thoughts; Create additional Result field (_yacht = models.CharField()) and use a post_save signal to provide a string. Create a separate table to keep records of the events. Table gets created/updated at post_save Thanks in advance, J -
Django deployment missing/admin view css/media/static files
I developed an e-commerce project, and I tried to publish it in my domain. When I publish my website, I see that media/static files and admin view css is missign in my website. (Of course, everything works fine in development mode localhost server.) I bought the web server and domain from Antagonist.nl by knowing it supports Python; however, they do not give me any technical support to deploy my Django project, and I see that documentation is missing. When I do deploy my project in antagonist.nl webserver provider, I see it works with errors. Altough I see many similar posts are available in stackoverflow, I couldn't find the answers for my case yet. Moreover, I see need of manual work from Django documentation in this https://docs.djangoproject.com/en/4.2/howto/static-files/deployment/. However, they are all for apache and nginx web servers. I would like to get help from the community for my webserver. Part of my settings.py file: from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent DEBUG = False INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'store', # Django app 'cart', # Django app 'account', # Django app 'payment', # Django app 'mathfilters', … -
GenericForeignKey in Django Admin Panel
I'm having issues with displaying GenericForeignKey fields in the Django Admin Panel. Additionally, I'm wondering if there's a way to vary the options for the object ID field based on the content type, while ensuring that the selected ID is saved correctly. Can anyone offer guidance or suggestions on how to accomplish this? Thanks in advance for your help.enter image description here I need help to improve the wording of the following issue. I've tried creating forms with JavaScript and modifying the admin, but the closest I got was using JavaScript to change the options and display them correctly. However, I had trouble with self.cleaned_data not saving the new choices when they varied, and form.is_valid() always returned false due to validation issues and lost data. from django.contrib import admin from django.contrib.contenttypes.models import ContentType from django.contrib.admin.widgets import ForeignKeyRawIdWidget from django.core.exceptions import ValidationError from django.forms.widgets import ClearableFileInput from django.forms import ModelForm, ModelChoiceField from django import forms from .models import PlaylistContent, Playlist, Image, Video from django import forms class PlaylistContentForm(ModelForm): object_select = forms.ChoiceField( choices=[], widget=forms.Select() ) class Meta: model = PlaylistContent fields = '__all__' class Media: js = ('admin/playlist_content/playlist_content.js',) def update_object_select_choices(self, choices): print(choices) self.fields['object_select'].choices = choices def __init__(self, *args, **kwargs): global EDIT_DATA_FORM super().__init__(*args, … -
CSS files not showing up in Django
Setting up a new Django project and can't seem to get the CSS sheets to load. I added a directory in the base directory of my project named 'static'. Inside of that I have a directory named 'css' and inside of that I have a file named 'styles.css' At the moment I just want to prove everything is connected and functioning properly so the styles.css has only one line. In styles.css: h1 { color: orange; } In Settings.py: STATIC_URL = "static/"` STATICFILES_DIRS = [os.path.join(BASE_DIR, "static"),] In base.html: {% load static %} <link rel="stylesheet" href="{% static 'css/styles.css' %} The template is showing fine in the browser. It's simply a h1 tag that reads: 'hi' The text color is black and it should be orange according to CSS. -
How to check if a user is subscribed to a product in Django template
I am working on a Django project whereby I want to check if a user is subscribed to a product or not. I have created in my models.py several model instances and I am stuck on how to check if the user is subscribed inside the template. Here is my template where I loop through the fetched data: <ul> {% for content in content %} {% if content.model.is_premium and user.is_subscribed %} <li>Premium</li> {% else %} <li>Not premium</li> {% endif %} {% endfor %} </ul> Here is my views.py : @login_required(login_url='/user/login') def homepage(request): content = ModelContent.objects.all() categorys = Category.objects.all() models = MyModels.objects.all() suggestions = MyModels.objects.all()[:3] # profiles = Profile.objects.filter(user__is_creator=True) context = {"categorys": categorys, "models": models, "content":content, "suggestions":suggestions} return render(request, 'users/home.html', context) And here is the models.py: User = get_user_model() class MyModels(models.Model): owner = models.ForeignKey(Profile, on_delete=models.CASCADE, null=False, blank=False) name = models.CharField(max_length=500, null=False, blank=False) username = models.CharField(max_length=500, null=False, blank=False, unique=True) title = models.CharField(max_length=500, null=False, blank=False) description = models.TextField(max_length=500, null=False, blank=False) image = models.ImageField(upload_to='img', blank=True, null=True) placeholder = models.ImageField(upload_to='img', blank=True, null=True) sex = models.CharField(max_length=50, choices=SEX_CHOICES, default=NONE) category = models.ForeignKey(Category, on_delete=models.CASCADE, null=False, blank=False) content_id = models.UUIDField(default=uuid.uuid4, primary_key=True, unique=True, editable=False) created = models.DateField(auto_now_add=True) is_popular = models.BooleanField(default=False) is_premium = models.BooleanField(default=False) # posted_content = models.ManyToManyField('ModelContent', related_name='model_content') def __str__(self): …