Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding IntegerField along with multiselectField?
I've been using MultiSelectField to select multiple list items, but after selecting I want to add their quantity too? Like a solution to add IntegerField alongside with the multiselectfield?? -
Django App: Timezone issues when running my Heroku app?
I'm creating a scheduling app on Django. As per most recommendations on the topic, the appointments (in my Appointments model) are stored in UTC. So my settings.py are set to TIME_ZONE = 'UTC'.The app was working perfectly on my local environment, but when I deployed to Heroku I started having issues. To give you an example (in production): >>> heroku run bash >>> python manage.py shell >>> from datetime import datetime >>> datetime.now() datetime.datetime(2020, 3, 10, 17, 10, 10, 453536) Yet, on local, I get: datetime.datetime(2020, 3, 10, 13, 10, 10, 196794) I tried to solve the issue (ie, 4-hour difference) by changing the TZ config value of the app to my local time, like so: heroku config:add TZ='America/Toronto' No luck. Anyone understands why this is happening? Any suggestions on how to solve this? -
How to validate empty label of M2M field in ModelForm?
I have a ModelForm overridden to have an extra option "None for now". When submitting the form it returns the form (invalid form) with the validation error: "" is not a valid value. ModelForm: class MCQuestionForm(forms.ModelForm): quiz = forms.ModelMultipleChoiceField( queryset=None, required=False, widget=forms.CheckboxSelectMultiple, help_text='Which tests this question applies to.') class Meta: model = MCQuestion exclude = () def __init__(self, *args, **kwargs): self.user = (kwargs.pop('user', None)) super(MCQuestionForm, self).__init__(*args, **kwargs) super_role = self.user.role subs_id = self.user.subordinates.values_list('role', flat=True) sub_roles = EmployeeType.objects.filter(pk__in=subs_id) cats = Category.objects.filter(groups=super_role) | Category.objects.filter(groups__in=sub_roles) self.fields['quiz'].queryset = Quiz.objects.filter(category__in=cats) self.fields['quiz'].choices = [('', 'None for now')] + \ [(quiz.pk, quiz.title) for quiz in self.fields['quiz'].queryset] How do I allow the empty label through the form validation? -
Django ModelChoiceField get choice of coneceted user
I created a forms.Modelchoicefield that contains items on my database. but it show all users data, I only want to show data of the connected user! THanks for helping models.py class List(models.Model): item = models.CharField(max_length=100) content = models.TextField() site = models.CharField(max_length=11, choices=THE_SITE) content_list = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.item forms.py class ListDataForm(forms.Form): message = forms.CharField(widget=forms.Textarea) listdata = forms.ModelChoiceField(queryset=List.objects.all()) Instead of forms.ModelChoiceField(queryset=List.objects.all()) I writed forms.ModelChoiceField(queryset=List.objects.filter(author=request.user)) but it doesn't work -
Count in django using foreign key
I have two models, User and JobGroup, User Model has a foreign key from Job Group. class User(AbstractUser): jobgroup = models.ForeignKey(JobGroup, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return self.username class JobGroup(models.Model): group_name = models.CharField(max_length=50, unique=True, blank=True, null=True) def __str__(self): return self.group_name I want to count the number of times a job group is assigned to a user E.G user1 - Jobgroup A, user2 - Jobgroup B, user3-Jobgroup A, user4-Jobgroup C The output I am looking for Jobgroup A-2 Jobgroup B-1 Jobgroup C-1 I tried this jobcount=User.objects.all().values('jobgoup__group_name').annotate(total=Count('jobgroup__group_name')) but it did't work.. It returns None -
What do "Stars" mean about a django package in djangopackages.org grids?
In djangopackages.org grids, it shows many aspects of different django packages. One of them is "Stars". Can't find any explanation on what that "Stars" mean or indicate. If it's a rating system, where does it come from & who makes that decision? Anyone has any idea? -
===== docker migrate release ===== [FATAL tini (8)] exec /app/migrate.sh failed: Permission denied
Successfully tagged app-registry-local.aldryn.net/agrowdevapi-test-37ae123fee35488aa7afaf88779408b0.2403de75863d452293464511e6f01f0d:rel-57c445067a40479da6af0e140792c18a finished docker build ===== docker migrate release ===== [FATAL tini (6)] exec /app/migrate.sh failed: Permission denied -
How to override ModelMultipleChoiceField to pass empty_label
I have a Model and ModelForm: class Question(models.Model): quiz = models.ManyToManyField( Quiz, blank=True) class MCQuestionForm(forms.ModelForm): quiz = forms.ModelMultipleChoiceField( queryset=None, required=False, empty_label="Something", widget=forms.CheckboxSelectMultiple, help_text='Which tests this question applies to.') class Meta: model = MCQuestion exclude = () def __init__(self, *args, **kwargs): self.user = (kwargs.pop('user', None)) super(MCQuestionForm, self).__init__(*args, **kwargs) super_role = self.user.role subs_id = self.user.subordinates.values_list('role', flat=True) sub_roles = EmployeeType.objects.filter(pk__in=subs_id) cats = Category.objects.filter(groups=super_role) | Category.objects.filter(groups__in=sub_roles) self.fields['quiz'].queryset = Quiz.objects.filter(category__in=cats) ..where I need to add an empty_label to the ModelMultipleChoiceField. When I pass empty_label="Something" it give the error: TypeError: init() got multiple values for keyword argument 'empty_label' This is in the Django module: class ModelMultipleChoiceField(ModelChoiceField): """A MultipleChoiceField whose choices are a model QuerySet.""" def __init__(self, queryset, **kwargs): super().__init__(queryset, empty_label=None, **kwargs) I need to remove the empty_label=None from the super class of ModelMultipleChoiceField so that it is not passing this argument twice. I tried: class MCQuestionMultipleChoiceField(ModelMultipleChoiceField): def __init__(self, queryset, **kwargs): super().__init__(queryset, empty_label="something", **kwargs) class MCQuestionForm(forms.ModelForm): quiz = MCQuestionMultipleChoiceField( queryset=None, required=False, widget=forms.CheckboxSelectMultiple, help_text='Which tests this question applies to.') ..but it still gives me: TypeError: init() got multiple values for keyword argument 'empty_label' So how do I override it? -
Save empty form field as None in Django
I have a trip model, and the form asks for a outbound flight and an inbound flight, that are both ForeignKeys. How can I save the inbound flight as None, if no flight is selected and actually allow this form field to be empty. This is my form: class NewTrip(ModelForm): def __init__(self, *args, **kwargs): super(NewTrip, self).__init__(*args, **kwargs) self.fields['trip_id'].widget = TextInput(attrs={'class': 'form-control'}) self.fields['destination'].widget = TextInput(attrs={'class': 'form-control'}) self.fields['client'].queryset = Clients.objects.all() class Meta: model = Trip fields = ('trip_id', 'destination', 'client', 'out_flight', 'hotel', 'in_flight') And this is my model: class Trip(models.Model): trip_id = models.CharField(max_length=20, verbose_name="Ref. Viagem") destination = models.CharField(max_length=200, null=True, verbose_name='Destino') client = models.ForeignKey(Clients, null=True, on_delete=models.CASCADE, verbose_name="Cliente") out_flight = models.ForeignKey(Flight, related_name="outbound_flight" ,null=True, on_delete=models.SET_NULL, verbose_name="Voo Ida") hotel = models.ForeignKey(Hotels, null=True, on_delete=models.SET_NULL, verbose_name="Hotel") in_flight = models.ForeignKey (Flight, related_name="inbound_flight", null=True, on_delete=models.SET_NULL, verbose_name="Voo Regresso") And this is the view: def newtrip(request): if request.method == 'POST': form = NewTrip(request.POST) if form.is_valid(): form.save() return redirect('trips') else: form = NewTrip() return render(request, 'backend/new_trip.html', {'form': form}) -
Deploying my first Django app to Heroku: Error message 'h12' status '503'
I'm working on my first app, and I've avoided having to ask any questions so far, but here we are at deployment. Here is my code: (Note: The majority of the program is in '/starWarsMeals/djangoStarWarsMeals/appStarWarsMeals/utils.py' and not 'models.py'. I didn't feel a database was my best choice for this app, as the 'swapi' API I am pulling data from may change. I figured it would be best to cache the results of the API vs. updating a database periodically.) https://github.com/RyanLegits/starWarsMeals I am trying to deploy my Django app to Heroku, but I get the following 'h12' error code: https://textuploader.com/16beh My suspicion is that the API calls at the beginning of the script in 'utils.py' are taking too long and causing Heroku to time out. However, I'd like a professional opinion before trying to refactor my code. Also, the last thing I changed in the app was setting the environment variables if that is helpful. I tried deploying to Python Anywhere just to see if I could find anymore information. I got the 'Something went wrong' page and related error log: https://textuploader.com/16bez Notes: I did make sure to change 'ALLOWED_HOSTS' in 'settings.py' for each attempted deploy. I tried setting it to … -
Using requests module with Django APITestCase and APIClient?
I'm trying to test my command line client with Django. I want to use the requests module in my client to fetch data from Django, but I'm testing this inside an APITestCase class so I can create factories using Factory_Boy. I get a connection refused error. The file in my front-end to call the view: from . import urls import requests, json HEADERS = {'content-type':'application/json'} BASE_URL = 'http://127.0.0.1:80/' def post(url, **data): query = json.dumps(data) r = requests.post(BASE_URL+url, data=query, headers=HEADERS) return r.json() def get(url, **data): query = json.dumps(data) r = requests.get(BASE_URL+url, data=query, headers=HEADERS) return r.json() The tests file for Django app, inside a APITestCase class: def setUp(self): self.client = APIClient() self.populate_addresses() self.populate_carriers() self.populate_drivers() def test_requests(self): a = query.query_address(err_msg='Stop not found.', conf_msg='Create new stop.') def populate_addresses(self): self.Address__A1 = factories.AddressFactory( name='BANDINI', city='CHATSWORTH', zip_code='92392', state='CA', street='12345 BANDINI BLVD') self.Address__A2 = factories.AddressFactory( name='BALL METAL', city='FAIRFIELD', zip_code='92392', state='CA', street='2400 HUNTINGTON BLVD') -
Cant start new app in django when I split settings.py file
I splited my settings.py like this: # __init__.py from .base import * # noqa try: from .local_settings import * # noqa except ImportError: message = 'ERROR: Unable to import local_settings. Make sure it exists.' raise ImportError(message) # base.py """ Django settings for app project. Generated by 'django-admin startproject' using Django 3.0.4. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # Add the apps folder to python path os.sys.path.append(os.path.join(BASE_DIR, 'apps')) # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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', ] ROOT_URLCONF = 'app.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'app.wsgi.application' # Password validation # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] try: from .local_settings import * # noqa except ImportError: message = 'ERROR: Unable to import local_settings. Make sure it exist.' raise ImportError(message) and: # local_settings.py import os … -
Django: ORA:01461: can bind a LONG value only for insert into a LONG column
I've made a binary field in my model (flal_file = models.BinaryField()) for inserting binary data in the database. Database column is blob field. I get that error when creating an object (insert). Commenting out flal_file prevents this error. I don't know why I get this error, since this is a binary field. Is that a bug with older versions of Django? Can anyone help me debug this issue? b = DocFileAllocation.objects.using('db_test_').create( flal_file=uploaded_data, #binary data flal_id_no=seq_doc_file, bmeta_id_no=seq_metadata, flal_file_subject=subject, ) b.save(using='db_test_') -
Not redirecting to other webpage after executing Django view
i have a view - user types some data in input (in scraping.html), data is subjected to action and score should be displayed on next webpage (scrapingscore.html). My problem is that after clicking submit button, website 'scraping' is refreshing and nothing happens, only input with textfield disappears. my view: def scraping(request): rootlink = 'https://www.transfermarkt.pl' link = 'https://www.transfermarkt.pl/schnellsuche/ergebnis/schnellsuche?query=' if request.method == 'POST': data = request.POST.get("textfield") if data is None: empty = 'Data is empty' return TemplateResponse(request, 'scrapingscore.html', {'empty':empty}) else: data = data.replace(" ", "+") search = link + data + '&x=0&y=0' req = Request( search, data=None, headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36' } ) req = urlopen(req).read() soup = BeautifulSoup( req, features="lxml" ) anchor = soup.find("a",{"class":"spielprofil_tooltip"}) link = anchor.get("href") original_link = rootlink + link return TemplateResponse(request, 'scrapingscore.html', {'original_link':original_link}) scraping.html <form action="{% url 'scraping' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <input name="text" type="text" /> <input type="submit" value="submit"> </form> my url to scraping, i don't have url to scrapingscore, maybe should i have with this view? path('scraping', views.scraping, name='scraping'), I don't know how to solve this problem - now 'scrapingscore' webpage does not appear. -
ValueError: The 'image' attribute has no file associated with it
is there something wrong with my code? i already run makemigrations and migrate, and i can see the picture i saved on the admin site, but why when i try to call this picture on my html i received this error? this is my html {% for perfume in s %} <img src="{{perfume.image.url}}" width="192px" height="192px" class="class"> {% endfor %} my views.py s = Perfume.objects.all() .... my models.py class Perfume(models.Model): image = models.ImageField(upload_to='image',null=True, blank=True) .... my settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') LOGIN_REDIRECT_URL = '/' import os MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') def get_success_url(self, request, user): return (get_success_url) my urls.py urlpatterns = [ .... ]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns +=static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
How do I create a table to keep track of occasional inventory status updates and how do I use in the django environment?
I have a table that has a list of all the devices that I have in my inventory. Occasionally an audit is performed and the database needs to be updated with the status of the devices (e.g. "Lost", "Found", etc.). For this example I'm just naming the audits "Audit 1" & "Audit 2" but there will be many more. In the past I would just add a new field to the device table for each audit, but I'm trying to make it so all can be done completely through the web ui. The following is an example of how I might do it through mysql. But in my new environment, I'm using django and don't have a clue on how to duplicate this. SELECT * FROM inventory_audit; +----+----------------+-----------+-----------+ | id | audit_phase_id | device_id | status_id | +----+----------------+-----------+-----------+ | 1 | 1 | 1 | 2 | | 2 | 1 | 5 | 2 | | 3 | 2 | 2 | 1 | | 4 | 2 | 5 | 1 | +----+----------------+-----------+-----------+ SELECT whole.device_id, l1.a1 AS "Audit 1", l2.a2 AS "Audit 2" FROM (SELECT device_id FROM inventory_audit GROUP BY device_id) AS whole LEFT JOIN (SELECT device_id,status_id AS … -
Display machine learning model's output on a html file i static in django
views.py from django.shortcuts import render from .models import questions from .serializers import approvalSerializers from django.http import JsonResponse from rest_framework.response import Response from rest_framework import status from rest_framework import viewsets from rest_framework.decorators import api_view # Create your views here. data = [] def landing_views(request): return render(request, "avasyuapp/landing.html") def ques_views(request): return render(request, "avasyuapp/ques.html") def store_db(request): if request.method == "POST": ans1 = request.POST["answer1"] ans2 = request.POST["answer2"] ans3 = request.POST["answer3"] ans4 = request.POST["answer4"] ans5 = request.POST["answer5"] ans6 = request.POST["answer6"] ans7 = request.POST["answer7"] ans8 = request.POST["answer8"] ans9 = request.POST["answer9"] data.append(ans1) data.append(ans2) data.append(ans3) data.append(ans4) data.append(ans5) data.append(ans6) o1 = questions( ques='Have you motivated yourself to become a good communicator?', ans=ans1) o1.save() o2 = questions( ques='Can you speak in front of group without any nervousness?', ans=ans2) o2.save() o3 = questions( ques='Can you justify you as a good communicator?', ans=ans3) o3.save() o4 = questions( ques='Are you really happy to make communication as your future passion?', ans=ans4) o4.save() o5 = questions( ques='Is your english vocabulary and comprehension strong?', ans=ans5) o5.save() o6 = questions(ques='Are you good at grammar?', ans=ans6) o6.save() o7 = questions( ques='Have you achieved anything till date as a good communicator ?', ans=ans7) o7.save() o8 = questions( ques='Are you a good listener,good reader and are you clear in your … -
Give print option to print database records in django administration
[![I waant to give the print option to print records through a printer from django administration just like the image posted where there is a print icon and when you click it it prints the page somewhat similar to that, I want to have a print option in the rightmost or leftmost top part of the django admin.I've given the search fields but I don't know how are we supposed to get that.Kindly help if Possible.Thanks][1]][1] [1]: https://i.stack.imgur.com/S0Ov1.pngstrong text -
JQuery didn't work as expected with ajax request in django
I am creating a cart( plus, minus and recalculate total) functionality, where I am using ajax and jquery. It works properly only in one button, that is either plus or minus. Sometimes minus button doing reverse that increases the cart number. I don't know where is the bug and which causes that error. Sometimes it updates with the server and suddenly stops and only workes in HTML not updating the backends. I am new with ajax and just following some fiddle for this workes.Here is the jquery and ajax implementation code............ <!-- templates/products/shopping-cart.html --> {% extends 'base.html' %} {% block jquery %} var taxRate = 0.15; var shippingRate = 20.00; var fadeTime = 300; function updateCart(item, qty, del){ var url = "{% url 'create_cart' %}" + '?' + 'item=' + item + '&qty=' + qty; if(del === true){ url += '&delete=y'; } <!-- XHR object or ajax method.Inside this there is a javasctipt object --> return $.ajax({ <!-- This is the URL of the call back function on the server. Remember the view function we created? {% url 'create_cart' %} This code will call that function without reloading the page. --> url: url, <!-- Type key:It takes in the method … -
tinymce has double text box in a blog
I am creating a blog app through django. Above is the post creation form. And Tinymce works fine except the text box inside the text box. This could be removed manually but I want for this not to show up at the first place. I want to remove this but I just cant. What should I do? I have those models, forms and html. models.py class BlogPost(models.Model): title = models.CharField(max_length=50, null=False, blank=False) body = HTMLField('Content') date_published = models.DateTimeField(auto_now_add=True, verbose_name="date published") date_updated = models.DateTimeField(auto_now=True, verbose_name="date updated") author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) #featured = models.BooleanField() #categories = models.ManyToManyField(Category) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:detail', kwargs={ 'id': self.id, 'title': self.title }) @property def get_comments(self): return self.comments.all().order_by('date_updated') @property def comment_count(self): return Comment.objects.filter(blogpost=self).count() @property def view_count(self): return PostView.objects.filter(blogpost=self).count() forms.py class CreateBlogPostForm(forms.ModelForm): class Meta: model = BlogPost fields = ['title', 'body'] html {% extends 'base.html' %} {% block content %} <style type="text/css"> .create-form { width: 100%; max-width: 100%; padding: 15px; margin: auto; } .submit-button{ max-width: 200px; } </style> <div class="container"> <div class="row"> <div class="col-lg-7 offset-lg-1"> <form class="create-form" method="post" enctype="multipart/form-data">{% csrf_token %} <!-- title --> <div class="form-group"> <label for="id_title">Title</label> <input class="form-control" type="text" name="title" id="id_title" placeholder="Title" required autofocus> </div> <!-- Body --> <div class="form-group"> <label for="id_body">Content</label> {{form.media}} … -
Django 'migration is applied before its dependency' when running any migration commands
I am using Django 3.0.2 that is connected to a local MySQL database.My project current has 2 apps, 'accounts' and 'home'. I dropped all the tables in my database after updating some of my model fields and I removed all the files in the migrations folder except __init__.py. Trying to start the dev server shows an error: Dependency on app with no migrations: accounts, so I ran python manage.py makemigrations which returned this Migrations for 'accounts': accounts\migrations\0001_initial.py - Create model User Migrations for 'home': home\migrations\0001_initial.py - Create model Idea - Create model Reply After this, running the server gives a warning saying You have 1 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): accounts. Run 'python manage.py migrate' to apply them. Doing so gives me an InconsistentMigrationHistory exception: Migration admin.0001_initial is applied before its dependency accounts.0001_initial on database 'default' Running python manage.py showmigrations returns this: accounts [ ] 0001_initial admin [X] 0001_initial [X] 0002_logentry_remove_auto_add [X] 0003_logentry_add_action_flag_choices auth [X] 0001_initial [X] 0002_alter_permission_name_max_length [X] 0003_alter_user_email_max_length [X] 0004_alter_user_username_opts [X] 0005_alter_user_last_login_null [X] 0006_require_contenttypes_0002 [X] 0007_alter_validators_add_error_messages [X] 0008_alter_user_username_max_length [X] 0009_alter_user_last_name_max_length [X] 0010_alter_group_name_max_length [X] 0011_update_proxy_permissions contenttypes [X] 0001_initial [X] 0002_remove_content_type_name home [X] 0001_initial sessions [X] 0001_initial I've tried runing … -
Calling Django ORM queries from within an async function running in an event loop
[Setup] I am using Django 3.0 as a wsgi application. I need to run the coroutine (shown below) from a view. This runs within an asyncio eventloop. From this event loop/coroutine I need to fetch some objects in the database using Django's ORM but django throws the following exception: django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async import asyncio import concurrent def get_users_from_db(): return User.objects.all() async def do_some_async_stuff(): executor = concurrent.futures.ThreadPoolExecutor(max_workers=3) loop = asyncio.get_event_loop() attachments = await loop.run_in_executor(executor, get_users_from_db) def view(request): task = LOOP.create_task(do_some_async_stuff) result = not LOOP.is_running() and LOOP.run_until_complete(task) I am not sure what I am doing wrong. As far as I understand Django's doc suggests I should be able to run synchronous tasks (like an ORM query) in a separate thread, but that still doesn't work. The interesting thing is, running the code locally using manage.py runserver works fine, however running it with `gunicorn --bind 127.0.0.1:8000 src.config.wsgi:application throws the above exception. -
How to solve error frame-ancestor iframe on mobile app
I try to embed an iframe on a website + mobile app. No problem with the website, but I get the error "Refused to display 'https://website.com' in a frame because an ancestor violates the following Content Security Policy directive: "frame-ancestors ' Do you know if a special CSP directive is specific to mobile apps ? Thanks! -
ModelForm object has no attribute 'fields'
I am using a django (3.0) ModelMultipleChoice field for a form. I am trying to modify the queryset to make some restrictions on it. here is the views : def nouvelle_tache(request,id_livrable): livrable=Livrable.objects.get(pk=id_livrable) projet = livrable.projet if request.method == "POST": form = NouvelleTache(request.POST,projet=projet) tache = form.save(commit=False) tache.livrable = livrable tache.id_tache = livrable.id_derniere_tache() + Decimal(0.01) tache.save() form.save_m2m() etat = Temps_etat_tache(etat=form.cleaned_data['etat_initial'],tache=tache) etat.save() return redirect('tache',tache.pk) else: form = NouvelleTache(projet=projet) return render(request, 'application_gestion_projets_AMVALOR/nouvelle_tache.html', locals()) And the forms : class NouvelleTache(forms.ModelForm): def __init__(self, *args, **kwargs): projet = kwargs.pop('projet', None) queryset = Utilisateur.objects.all() for utilisateur in projet.utilisateurs: queryset = queryset.exclude(pk=utilisateur.pk) self.fields['ressources'].queryset = queryset super(NouvelleTache, self).__init__(*args, **kwargs) ressources= forms.ModelMultipleChoiceField(queryset=Utilisateur.objects.all() ,widget =forms.CheckboxSelectMultiple ) etat_initial = forms.ModelChoiceField(queryset=Etat_tache.objects.none()) class Meta: model = Tache fields = ['libelle'] I have the followig error : 'NouvelleTache' object has no attribute 'fields' I don't understand why because many other users seems to have similar code and it works. Any help would be appreciate. -
Django_tables2 with delete buttom
How is going? I'm learning to programming in django. For the moment I'm building a simple app that utilizing a form update the referenced table. Now I'm try to add a delete button in each row of my table but, beside I have tried a lot of solutions, I didn't find one that works correctly. Below my code: urls from django.urls import path from app import views app_name = 'main' urlpatterns = [ path('', views.homepage, name='homepage'), path('delete_item/<int:pk>', views.delete_item, name="delete_item"), ] forms from django import forms from .models import Income class IncomeModelForm(forms.ModelForm): class Meta: model = Income fields = "__all__" tables import django_tables2 as tables from django_tables2.utils import A from .models import Income class PersonTable(tables.Table): delete = tables.LinkColumn('main:delete_item', args=[A('delete-id')], attrs={'a': {'class': 'btn'}}) class Meta: model = Income template_name = "django_tables2/bootstrap.html" views from django.shortcuts import render from django.http import HttpResponse from django.views.generic import ListView from .models import Income from .tables import PersonTable from .forms import IncomeModelForm def homepage(request): table = PersonTable(Income.objects.all()) if request.method == 'POST': form = IncomeModelForm(request.POST) if form.is_valid(): print("Il form è valido") new_input = form.save() else : form = IncomeModelForm() context= {"form": form, "table":table } return render(request, "app/base.html", context) def delete_item(request, pk): Income.objects.filter(id=pk).delete() items = Income.objects.all() context = { 'items': …