Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Proper way to write 'request.POST.post' in class based views
I'm trying to use CBV. I'm new to it. I'm having problem requesting a POST data inside a form. Here is my view: form_class = LocatarioForm template_name = 'contrato/locatario_form.html' def get_initial(self): return { 'contrato': self.kwargs["pk"] } def post(self, request, pk): segundolocatario = request.POST['segundolocatario'] return segundolocatario def get_success_url(request): # if request.POST.post('segundolocatario') == 'Sim' # return reverse('contrato:locatario', kwargs={'pk': self.object.pk}) return reverse('contrato:conjugec', kwargs={'pk': self.object.pk}) Here is the template: <form method="post"> {% csrf_token %} {{form}} <label for="segundolocatario">Deseja cadastrar um segundo locatário para este contrato?</label> <select name="segundolocatario" id=""> <option value="sim">Sim</option> <option value="nao">Não</option> </select> <br><br> <button type="submit">Próxima etapa</button> </form> I need to request 'segundolocatario' to flow control my templates. How can I do this in CBV? Thank you. -
Display django form errors with js after ajax call
i have this signup form that works fine and saves the user correctly when there are no errors but when there are errors in the inputs like two password fields didn't match ,i couldn't display those errors that are sent to the front-end with form.errors.as_json() so i need someone to guide me how to display those errors with the js here is the form in my forms.py file: class SignupForm(UserCreationForm): password1 = forms.CharField(widget=forms.PasswordInput( attrs={'placeholder': 'Password', 'class': 'form-control mt-3','id':'password1'})) password2 = forms.CharField(widget=forms.PasswordInput( attrs={'placeholder': 'Confirm your password', 'class': 'form-control mt-3 mb-3','id':'password2'})) class Meta: model = User fields = ("full_name", "email", "password1", "password2") widgets = { 'full_name': forms.TextInput(attrs={'placeholder': 'Full name', 'class': 'form-control mb-3','id':'full_name'}), 'email': forms.EmailInput(attrs={'placeholder': 'Email', 'class': 'form-control','id':'email'}), } here the view of the form in my view.py: if request.is_ajax(): signup_form = SignupForm(request.POST) if signup_form.is_valid(): signup_form.save() full_name = signup_form.cleaned_data.get('full_name') email = signup_form.cleaned_data.get('email') raw_password = signup_form.cleaned_data.get('password1') account = authenticate(email=email, password=raw_password) login(request, account) return JsonResponse({"success" : True}, status=200) else: return JsonResponse({'success': False} ,signup_form.errors.as_json() , status=400) the ajax request in my javascript file var $signupForm = $('#form-signup'); $signupForm.submit(function (event) { event.preventDefault(); var $signupData = $signupForm.serialize(); $.ajax({ url: "http://localhost:8000", method: 'POST', data: $signupData, success: function() { location.reload() }, error: function () { // display the errors in … -
django Channels with subdomains served over https - Chanel development server NOT taking over from development server (runsslserver)
I am using Django 3.1 I am following the online tutorial for django Channels, to build a simple chat server/room. However, I am using django_hosts as well as django_sslserver (in order to serve HTTPS on local host and on a subdomain), so I am having to modify the tutorial code slightly because my environment is different. These are the changes I've had to make: Integrating the Channels library with Django # mysite/asgi.py import os from channels.routing import ProtocolTypeRouter from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') application = ProtocolTypeRouter({ "https": get_asgi_application(), # <- Note: I am using HTTPS }) According to the Channels documentation, I should see the following line in the console: Starting ASGI/Channels version 3.0.0 development server at http://127.0.0.1:8000/ However, in my console, I still see the line: Starting development server at https://127.0.0.1:8000/ Using SSL certificate: /path/to/env/lib/python3.6/site-packages/sslserver/certs/development.crt Using SSL key: /path/to/env/lib/python3.6/site-packages/sslserver/certs/development.key From this point on, I am unable to replicate app behaviour following the example. My question is: How do I get django Channels to work with HTTPS (e.g. django_sslserver) ? -
Multiple generic class based DetailView's for the SAME model
I am attempting to use two detail views that will render different templates for the same model, at different URLs of course. Is it possible to have different generic detail views for the same model? If not I'll just have to write my own I suppose. All my detail views route to the absoluteurl but in this case I want each detail view to route to the template I have defined in the class. I used the method below to successfully create multiple list views and update views, but it just doesn't work on detail views, I always end up at "course_detail" even though I declared "course_detail_producer_view." models.py title = models.CharField(max_length=200) slug = AutoSlugField(max_length=100, help_text="course title", populate_from=['title', 'date'], unique=True, ) start_time = models.TimeField(blank=True, null=True) end_time = models.TimeField(blank=True, null=True) date = models.DateField(blank=True, null=True) new_course = models.BooleanField(default=False) new_instructor = models.BooleanField(default=False) katacoda = models.BooleanField(default=False) jupyterhub = models.BooleanField(default=False) released = models.BooleanField(default=False) status = models.CharField(max_length=50, choices=status_choices, blank=False ) pub_partner = models.CharField(max_length=50, choices=pub_partner_choices, blank=False) course_notes = models.TextField(max_length=500, blank=True, ) producer_notes = models.TextField(max_length=500, blank=True) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False ) producer = models.ManyToManyField(Producer, related_name="course", blank=True, ) def get_absolute_url(self): """Return URL to detail page of a Course""" return reverse( "course_detail", kwargs={"slug": self.slug} ) def __str__(self): date_time = f"{self.date} … -
How can I get a ModelMultipleChoiceFilter to search two fields simultaneously?
I have a model with two 'slots', both of are ForeignKeys to the same separate model: class Car(models.Model): ... paint_colour1 = models.ForeignKey(Paint, on_delete=models.CASCADE) paint_colour2 = models.ForeignKey(Paint, on_delete=models.CASCADE) ... I want my filter to return, say, all cars that use blue paint whether the blue paint is in slot 1 or 2 (e.g. Car1.paint_colour1='blue' and Car2.paint_colour2='blue' would both be returned). Here is the filter I am using right now: class CarFilter(django_filters.FilterSet): paint_colour1 = django_filters.ModelMultipleChoiceFilter(queryset=Paint.objects.all(), label='Paint 1') class Meta: model = Car fields=[] As it stands right now, I can select as many paint colours as I want, but only the results with those colours in slot 1 are returned. However, if I add a second field for paint_colour2, only results with the colours in slot 2 are returned. I have tried using the following filter instead: class CarFilter(django_filters.FilterSet): paint_colour = django_filters.ModelChoiceFilter(queryset=Paint.objects.all(), method='search_both_colours', label='Search by colour:') class Meta: model = Car fields = [] def search_both_colours(self, queryset, name, value): return Paint.objects.filter(Q(paint_colour1__exact=value) | Q(paint_colour2__exact=value)) This allows me to return all results for a single colour whether the colour is in slot 1 or slot 2, but I want to be able to return results of cars with as many colours as are specified. -
Add property to model of other app in django
I am currently working on a project that should be deployed to several different clients with slightly different configurations and features. To achieve that, for each feature I wanted to create a new app in django. As an example we have one base app which contains a model for Patient (pretty simple, name, id, ...). For some clients I would like to create a parent app that will include an additional app called case_type which contains a model called CaseType. In that app one patient can have one caseType. But here is the catch. The patient app should work with or without the case_type app. Therefore I would like to kind of "inject" a new property into the model and serializer of Patient from within the case_type app. So this way when deploying with the case_type app the user will receive a JSON like this when calling /patient/<id>: { "name": "Bob", "id": "123", "caseType": { "type": "a", "comment": "something" } } but when calling the same route without the case_type app I want it to return { "name": "Bob", "id": "123" } This means I will have to dynamically adapt the serializer and model in a "dependency-injection"-kind of way. There … -
How can I ovveride Django Admin page?
I've read many answers but I don't know what am I missing. I did the same steps as they are mentioned in Django Docs (https://docs.djangoproject.com/en/3.0/ref/contrib/admin/#admin-overriding-templates) but nothing happened. Here is my actual configuration : INSTALLED_APPS = [ 'app1.apps.App1Config', 'app2.apps.App2Config', '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 = 'rida.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')],#i modified this line 'APP_DIRS': False, #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', ], 'loaders': [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ] } } ] the contents of admin.py file of app1 : from django.contrib import admin from django.conf.urls import url from app1.models import Modele admin.site.register(Modele) I want to override the template base.html, so I copied it from django\contrib\admin\templates\admin and put it in myproject\templates\admin\app1, then I made some changes on this file but nothing happened, so I have no idea why it doesn't work and what am I missing. thank you in advance. -
Can't Edit and Delete posts from my Django post_detail.html template
I've added Edit and Delete buttons to my post_details.html. This is to edit or delete a post added by the owner of the post. It's unfortunate that I'm always running into errors when I access the post_details.html page. Please I need your help... Below is the code snippets: models.py class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset(). \ filter(status='published') class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') header_image = models.ImageField(null=True, blank=True, upload_to='post') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='published') objects = models.Manager() # Default manager published = PublishedManager() # Custom manager tags = TaggableManager() class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug]) def save(self, *args, **kwargs): # new if not self.slug: self.slug = slugify(self.title) return super().save(*args, **kwargs) views.py class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Post fields = ['title', 'body', 'tags', 'status'] template_name = 'blog/post/post_form.html' def form_valid(self, form): form.instance.author = self.request.user return super(PostUpdateView, self).form_valid(form) def test_func(self): post = self.get_object() if self.request.user == post.author: return True return False class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Post template_name = 'blog/post/post_confirm_delete.html' success_url = … -
Replacing the default ManyToMany widget with CheckboxSelectMultiple widget doesn't insert the checked boxes in the database
I'm trying to insert change the default widget of the ManyToMany field in a Django form and I want to use the CheckboxSelectMultiple widget instead. No matter if I use CheckboxSelectMultiple widget or the default widget for ManyToMany field, the rows corresponding to the checkboxes don't get inserted at all. I looked at the solutions here, here and here, but I don't understand what I'm doing wrong. Here's the relevant code: models.py: class Employer(models.Model): # user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) name = models.CharField(max_length=100, unique=True) location = models.CharField(max_length=MAXIMUM_LOCATION_LENGTH, choices=COUNTRY_CITY_CHOICES, blank=True) short_bio = models.TextField(blank=True, null=True) website = models.URLField(blank=True) profile_picture = models.ImageField(upload_to=get_upload_path_profile_picture, blank=True, null=True) admin_approved = models.BooleanField(default=False) def __str__(self): return self.name class Category(models.Model): name = models.CharField(max_length=MAXIMUM_CATEGORY_LENGTH) def __str__(self): return self.name class JobListing(models.Model): employer = models.ForeignKey(Employer, on_delete=models.CASCADE) job_title = models.CharField(max_length=100) job_description = models.TextField() job_requirements = models.TextField(); what_we_offer = models.TextField(); # https://stackoverflow.com/questions/2771676/django-datetime-issues-default-datetime-now time_added = models.DateField(default=now) job_application_url = models.URLField(unique=True) admin_approved = models.BooleanField(default=False) categories = models.ManyToManyField(Category) def __str__(self): return self.job_title forms.py: EmployerForm = modelform_factory(Employer, fields=["name", "location", "short_bio", "website", "profile_picture"], widgets={"location": s2forms.Select2Widget}) class JobListingForm(forms.ModelForm): job_title = forms.CharField(max_length=100) job_description = forms.CharField(widget=forms.Textarea) job_requirements = forms.CharField(widget=forms.Textarea) what_we_offer = forms.CharField(widget=forms.Textarea) job_application_url = forms.URLField() categories = forms.ModelMultipleChoiceField( queryset=Category.objects.all(), widget=forms.CheckboxSelectMultiple, required=True) class Meta: model = JobListing fields = ["job_title", "job_description", "job_requirements", "what_we_offer", "job_application_url", "categories"] views.py: … -
"AssertionError: False is not true" keeps popping up whenever i run tests.py on my django project
I am following a tutorial by Tom Aratyn in which i would test whether pagination works properly. Here is the tests.py file: from django.test import TestCase from django.test.client import \ RequestFactory from django.urls.base import reverse from core.models import Movie from core.views import MovieList class MovieListPaginationTestCase(TestCase): ACTIVE_PAGINATION_HTML = """ <li class="page-item active"> <a href="{}?page={}" class="page-link">{}</a> </li> """ def setUp(self): for n in range(15): Movie.objects.create( title='Title {}'.format(n), year=1990 + n, runtime=100, ) def testFirstPage(self): movie_list_path = reverse('core:MovieList') request = RequestFactory().get(path=movie_list_path) response = MovieList.as_view()(request) self.assertEqual(200, response.status_code) self.assertTrue( response.context_data['is_paginated']) self.assertInHTML( self.ACTIVE_PAGINATION_HTML.format( movie_list_path, 1, 1), response.rendered_content) This is already a copy-paste code from the book, however, the AssertionError keeps popping up. (m_env) C:\Users\mrblu\MyMDB\django>python manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). F ====================================================================== FAIL: testFirstPage (core.tests.MovieListPaginationTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\mrblu\MyMDB\django\core\tests.py", line 31, in testFirstPage self.assertTrue( response.context_data['is_paginated']) AssertionError: False is not true ---------------------------------------------------------------------- Ran 1 test in 0.021s FAILED (failures=1) Destroying test database for alias 'default'... Thank you guys in advance. newbie here. I started coding only this feb 2020, and im already 25 yrs old. Im taking this on. -
Django: How to make a Grouped Choice Field that doesn't show children until hovered?
Currently, I have: Code in forms.py: class ExpenseForm(forms.Form): CHOICES = ( ('Debt', ( (11, 'Credit Card'), (12, 'Student Loans'), (13, 'Taxes'), )), ('Entertainment', ( (21, 'Books'), (22, 'Games'), )), ('Everyday', ( (31, 'Groceries'), (32, 'Restaurants'), )), ) amount = forms.DecimalField() date = forms.DateField() category = forms.ChoiceField(choices=CHOICES) In production, I have much more categories than the example above so if I show the children of each category as well in the first drop-down, it'll take the user a lot of scrolling to find the right child. What I want to do is have the children of each category only displayed in a separate drop-down beside the first one when the mouse is hovering on the category. This would cut down the amount of irrelevant entries in the first drop-down. How can I do that? -
first name and last name does not save in django admin profiles app
when i create a new user,first name and lastname field only saves to user model. my profile model for first name and lastname fields are blank in my admin panel, it only shows when i check the users model in the admin and because of this it i cannot use the full_name field in my templates. models.py from django.db import models from django.contrib.auth.models import User from django.contrib.auth import get_user_model from django.db.models.signals import post_save from django.dispatch import receiver from django.conf import settings from django.utils.text import slugify from django.contrib.auth.models import AbstractBaseUser get_user_model().objects.filter(is_superuser=True).update(first_name='Super', last_name='User') # superusers = User.objects.filter(is_superuser=True) class Profile(AbstractBaseUser): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) last_name = models.CharField(max_length=100, blank=True) first_name = models.CharField(max_length=100, blank=True) last_name = models.CharField(max_length=100, blank=True) full_name = models.CharField(max_length=128, blank=True) next_of_kin = models.CharField(max_length=100, blank=True) dob = models.CharField(max_length=100, blank=True) state = models.CharField(max_length=100, blank=True) password = models.CharField(max_length=100, blank=True) email = models.EmailField(max_length=150) signup_confirmation = models.BooleanField(default=False) address = models.CharField(max_length=255, null=True) country = models.CharField(max_length=255, null=True) phonenumber = models.CharField(max_length=20, null=True) appointment_with = models.ManyToManyField(User, related_name='appontment_with', blank=True) slug = models.SlugField(max_length=200, null=True) USERNAME_FIELD ='user' def save(self, *args, **kw): self.full_name = '{0} {1}'.format(self.first_name, self.last_name) super(Profile, self).save(*args, **kw) def save(self, *args, **kwargs): self.slug = slugify(f"{self.last_name}-{self.first_name}") super(Profile, self).save(*args, **kwargs) def __str__(self): return self.user.username views.py def signup_view(request): form = SignUpForm(request.POST) if form.is_valid(): print ("form is … -
how can i can do Auto Number in Pisa django template?
can i do auto number in pisa django template? cause when i use java scripts, its not working how can i do that auto number?, any tips? this is my views.py template_path = 'pengurusan/report_bulan_lurah.html' postingan_list4 = Pengajuan_SKTM.objects.filter(uploaded_at__year=pkk, uploaded_at__month=pk, kelurahan=request.user.profile.kelurahan, status_diterima_lurah="Diproses" ) usernya = request.user.profile.kelurahan items = request.GET.get('page', 1) context = { 'report2' : postingan_list4, 'items' : items, 'usernya':usernya, } response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="report.pdf"' template = get_template(template_path) html = template.render(context) pisa_status = pisa.CreatePDF( html, dest=response, link_callback=link_callback) if pisa_status.err: return HttpResponse('We had some errors <pre>' + html + '</pre>') return response this is my html <table class="test" align="center" width="621px" border="1" align="left" style='margin-top:0cm;margin-right:0cm; margin-bottom:5pt;margin-left: 0cm;padding-left:0cm;mso-add-space:auto; font-size:12.0pt;line-height:150%;font-family:"Times New Roman",serif'> <tr> <th style="padding-top: 0.05cm;" align=center width="18">No</th> <th style="padding-top: 0.05cm;" align=center width="170px">Nama Lengkap</th> </tr> {% for hitung2 in report2 %} <tr> <td style="padding-left: 0.02cm;padding-top: 0.050cm;">{{hitung2.nama_lengkap}}</td> </tr> {% endfor %} </table> and this is my script in html <script type="text/javascript"> var addNumeration = function(cl){ var table = document.querySelector('table.' + cl) var trs = table.querySelectorAll('tr') var counter = 1 Array.prototype.forEach.call(trs, function(x,i){ var firstChild = x.children[0] if (firstChild.tagName === 'TD') { var cell = document.createElement('td') cell.textContent = counter ++ x.insertBefore(cell,firstChild) } else { firstChild.setAttribute('colspan',1) }})} addNumeration("test") </script> -
Serializing objects runs too much SQL queries
I'm trying to serialize related field set to list. The problem is serializing a QuerySet is very inefficient. class ZipCode(..): city = ForeignKey... code = CharField... class CityManager(models.Manager): def get_queryset(self): return super().get_queryset().select_related('county').prefetch_related('zipcodes').annotate( realestate_count=Count('zipcodes__realestates')).order_by('name', ) class City(..): .... @property def zip_codes_list(self): return self.zipcodes.values_list('code', flat=True) As you can see, I'm prefetching zipcodes so I suppose it shouldn't do so many queries. class CitySerializer(serializers.ModelSerializer): county = CountySerializer(read_only=True) zip_codes_list = serializers.ListField(read_only=True) realestate_count = serializers.IntegerField(default=0, read_only=True) indexed_at_hmnz = serializers.CharField(read_only=True) index_status_display = serializers.CharField(source='get_index_status_display', read_only=True) class Meta: model = City fields = ['id', 'name', 'county', 'realestate_count', 'zip_codes_list','indexed_at', 'indexed_at_hmnz', 'index_status_display', 'is_followed'] According to the Django debug toolbar, it queries zipcodes for every object separately. Do you know how to make it more efficient? -
SearchFilter: return .none() as long no ?search input given
I created the following view in my REST API. It works as intended, the only issue I still have is that if NO search term is defined, the first 15 results from my database are returned (without any filtering). Is there are a way to return User.objects.none() as long no ?search input is given? class UserRetrieve(generics.ListAPIView): permission_classes = [RetoolPermissions] queryset = User.objects.all() serializer_class = UserSerializer filter_backends = [filters.SearchFilter] search_fields = ["email", "first_name", "last_name"] -
how to create a dynamic link in Django
how can i build dynamic link in Django? I have a blog and each post need to have a unique link. content of blog's post must show on linked page. I searched in google but i'm was a little confused. Thanks -
How do I get Django Admin to delete files when I remove an object from the database/model when there's two classes?
I use this to delete a file and it works: @receiver(post_delete, sender=mymodel) def submission_delete(sender, instance, **kwargs): instance.file.delete(False) but I have two models with files and when I copy paste that code and just changing the name of my model it doesn't work anymore like this: @receiver(post_delete, sender=mymodel) def submission_delete(sender, instance, **kwargs): instance.file.delete(False) @receiver(post_delete, sender=mymodel2) def submission_delete(sender, instance, **kwargs): instance.file2.delete(False) how can I fix that? -
deploy django app with nginx and gunicorn on subdirectory besides static pages
I have developed a django application which I want to deploy to a linux server with gunicorn and nginx. So far, the server is already hosting several static web pages with nginx. The root is still the default page of nginx, while on two subdirectories, say domain.com/a and domain.com/b, two static homepages are deployed. Now, this app shall be run under domain.com/apps/viewer. I have setup the app in a virtual environment in the home directory of user c. Serving static files etc works fines, but only if I deploy the app in root with the nginx config below: server { listen 80; server_name domain.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/c/viewer/; } location / { include proxy_params; proxy_pass http://unix:/home/c/viewer/viewer.sock; } } server { listen [::]:443 ssl; # managed by Certbot listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/.../fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/.../privkey.pem; include /etc/letsencrypt/options-ssl-nginx.conf; ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; root /home/c/viewer/; server_name domain.com; location /static/ { root /home/c/viewer/; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://unix:/home/c/viewer/viewer.sock; } } With this config, the static pages are not accessible anymore and return the error that Django does not find the … -
Django ArrayField Default Should be a Callable
I'm trying to use postgresql ArrayField in my django project setting it a default, but I can't get rid of the warning ArrayField default should be a callable instead of an instance so that it's not shared between all field instances. HINT: Use a callable instead, e.g. use list instead of [] This is my code: def get_default_subscriptions(): return 'Noticias, Promociones, Pagos, Compras'.split(', ') # this returns a list class myModel(models.model): # other fields subscriptions = ArrayField(models.CharField(max_length=200), default=get_default_subscriptions()) # this is a callable, so, why the warning? Docs say about this: If you give the field a default, ensure it’s a callable such as list (for an empty default) or a callable that returns a list (such as a function). Incorrectly using default=[] creates a mutable default that is shared between all instances of ArrayField. Can you give me an idea of what am I doing wrong? -
Django Edit Or Delete Selected Rows In A Table - ListView
I have a table with checkboxes and I would like to be able to delete or edit a specific field value for all the selected rows in the table. Here's an example table that would be awesome to recreate but I have not found examples anywhere how this may work in the view and template. https://examples.bootstrap-table.com/# My current view, which is working with a table. Where can I start to make the leap from a basic table to an interactive one like in the example above? Views.py class EntryList(LoginRequiredMixin, ListView): context_object_name = 'entry_list' paginate_by = 100 # paginate_by = 5 #ordering = ['-pk'] model = Entry template_name = "portfolios/entry_list.html" def get_queryset(self): return Entry.objects.filter(created_by=self.request.user).order_by('-pk') def post(self, request, *args, **kwargs): ids = self.request.POST.get('ids', "") # ids if string like "1,2,3,4" ids = ids.split(",") try: # Check ids are valid numbers ids = map(int, ids) except ValueError as e: return JsonResponse(status=400) # delete items self.model.objects.filter(id__in=ids).delete() return JsonResponse({"status": "ok"}, status=204) -
How to find open-source projects from Remote Companies on GitHub?
I want to find GitHub repositories to work to improve my skills and maybe get a job -
how to host Django (sqlite database ) website on Google app engine
I have made my dream website with the help of Django and using sqlite as my database but while I was trying to host on heroku via my udemy course tutorial it was showing some error that python version was not matching and I tried a lot to resolve it but I was not able to and also I thought that why not to try some more trusted company service so I thought of Amazon aws and Google app engine but the only thing with amaZon was that it is really complicated so I thought of using Google app engine but when I read tutorials and reviews I wasn't sure that if Google app engine supports sqlite or not so if anyone has any type of knowledge about does Google app engine support sqlite or not please tell me. -
Django channels - connection timed out
I created a django-channels app that works without any problem in local. I'm now trying to deploy it to a DigitalOcean droplet. The whole Django WSGI part works, the only part not working is Django-Channels. If i try to connect to any consumer like below: ws://MYURL:9000/main I get the following error on my Chrome console: WebSocket connection to 'ws://MYURL:9000/main' failed: Error in connection establishment: net::ERR_CONNECTION_TIMED_OUT Daphne service: [Unit] Description=Daphne service After=network.target [Service] PIDFile=/run/daphne/pid User=root Group=root WorkingDirectory=/django-vue-mpa ExecStart=/django-vue-mpa/venv/bin/daphne --bind 0.0.0.0 --port 9000 --verbosity 0 django_vue_mpa.asgi:application ExecReload=/bin/kill -s HUP $MAINPID ExecStop=/bin/kill -s TERM $MAINPID Restart=on-abort PrivateTmp=true [Install] WantedBy=multi-user.target And here is my actual nginx conf: server { listen 80; server_name http://MYURL/; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /django-vue-mpa/django_vue_mpa; } location / { include proxy_params; proxy_pass http://unix:/django-vue-mpa/django-vue-mpa.sock; } } -
Unable to use override_settings class decorator with setUpClass and tearDownClass Django
I am trying to write unittests in django. I encountered different behaviours of override_settings decorator when used with setUpClass and tearDownClass classmethods. Following is the code which doesn't work: import logging from django.test import SimpleTestCase, override_settings from django.http import Http404 from django.core.exceptions import SuspiciousOperation, PermissionDenied from django.urls import path from django.views.defaults import server_error def http_400_view(request): """Test view for 400 """ raise SuspiciousOperation def http_403_view(request): """Test view for 403 """ raise PermissionDenied def http_404_view(request): """Test view for 404 """ raise Http404 def http_500_view(request): """Test view for 500 """ return server_error(request) urlpatterns = [ path('400/', http_400_view), path('403/', http_403_view), path('404/', http_404_view), path('500/', http_500_view), ] @override_settings(ROOT_URLCONF=__name__) class ErrorCodeHandlerTests(SimpleTestCase): """ Tests for error code handlers """ @classmethod def setUpClass(cls): logging.disable(logging.CRITICAL) @classmethod def tearDownClass(cls): logging.disable(logging.NOTSET) status_codes = [400, 403, 404, 500] templates = ['400.html', '403.html', '404.html', '500.html'] user_messages = ['Bad request', 'Permission denied', 'Page not found', 'Internal server error'] def test_correct_html_rendered_on_error_code(self): """Test if correct template and error code exists in response after http errors """ for i in range(len(self.status_codes)): with self.subTest(i=i): response = self.client.get('/' + str(self.status_codes[i]) + '/') self.assertTemplateUsed(response, self.templates[i]) self.assertContains( response, self.user_messages[i], status_code=self.status_codes[i], html=True ) In above code, settings are not overriden and I get 404 for all the urls. Following is the code which … -
how to filter posts in which substring of a field is included in a given list of strings in django?
I have a list of strings as below: items = ['apple', 'shoes', 'milk', 'blue', 'black', 'phone'] and a field in my django model field which has strings separated by (,)comma like below: tag = 'apple, phone, tenis, telvision' I want to filter those posts which have at least one item in their tag field which also listed in the given list. This is what I tried but does not give me result: posts = Post.objects.filter(tag__in=items)