Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-hitcount | How to count hit, when clicking on button
I'm creating a blog, and I want to count a download, when an user pressed on a button/link. I want to use django-hitcount, because it has that spam-protection with ip, session etc. I'm already counting the views of my PostDetailView and it's working, but on the same page is a download button and I want to count how many users clicked on this button. I already tried to fix the problem using the documentation (https://django-hitcount.readthedocs.io/en/latest/installation.html#counting-hits), but I'm still not sure how to do it. I want to increase the "downloads" variable, when a hit counts. class Post(models.Model, HitCountMixin): title = models.CharField(max_length=40) content = RichTextField(max_length=20000) downloads = models.IntegerField(default=0) def __str__(self): return self.title def get_absolute_url(self): return reverse("post-detail", kwargs={"pk": self.pk}) -
Check if varible is an list in queryset django
I'm trying to check if my variables are in my querySet. Varialbes coming from a form: def magazine_new(request): if form.is_valid(): post.mag_no = request.POST.get('mag_no') post.cn1 = request.POST.get('cn1') post.cn2 = request.POST.get('cn2') post.cn3 = request.POST.get('cn3') post.cn4 = request.POST.get('cn4') Then, I want to check if these CNs exist in this mag_no I tried this, but didn't work. if Magazine.objects.filter(prodc_magt_no__in = [post.cn1,post.cn2,post.cn3,post.cn4] and mag_no=post.mag_no): form.save() return redirect('someview') else: return HttpResponse('Dind't exist or match to this magazine no') return render(request,'cnCreate.html',{'form':form}) I'm having the error "too many values to unpack (expected 2)" or in order tests, this query didn't work. How to do this query to check if these Cns exists in prodc_magt_no field in database The magazine must be the same: post.mag_no = mag_no -
Could not add new columns to model
I'm using PostegreSQL. What I've tryed already: python manage.py flush python manage.py makemigrations python manage.py migrate python manage.py makemigrations app python manage.py migrate app python manage.py migrate --run-syncdb There aren't any effect. The table have no recently added columns. Have no importaint data in tables, can remove it. -
Django CreateView with a ManyToMany field?
I've been working on something for a few days, I saw some similar posts here, but I am still having trouble getting it! I will post a small snippet. I have a Recipe model, with many fields but I will post the one that I am referring to. ingredients = models.ManyToManyField('recipes.Ingredient', related_name='in_recipes') And then I have an Ingredient model of course, with name, description, etc. I want to be able to have a CreateView where I can add any amount of ingredients to a single recipe. I got as far as only being able to list the Ingredients already in my database. I was looking for a single Recipe form that includes the Ingredient form and fields. Any help would be greatly appreciated! -
Checkboxes True or False not loading into form properly
I'm using a ModelForm to load a Form and all of the values are pulling properly except the checkboxes. They always load in unchecked whether or not their state is True or False. I've tried creating the checkbox fields like: <label> <input type="checkbox" checked='{{ form.instance.hot }}'> <span>Hot{{ form.hot }}</span> </label> Which results in the checkbox always being checked instead matching what's in the table for that client. models.Client class Client(models.Model): #Account Information client_status =[("1", "Active"), ("0", "Inactive")] WHOPAYS =[("0", "Not Applicable"), ("1", "They Pay"), ("2", "We Pay")] hot = models.BooleanField(default=False, required=False) region = models.ForeignKey('Region', to_field='region_id', on_delete=None, null=True, blank=True) sub_account = models.ForeignKey('self', on_delete=models.CASCADE, related_name='sub_account_of_client', null=True, blank=True) created = models.DateField('Account Creation', auto_now_add=True) client_class = models.ForeignKey('ClientClass', on_delete=None, null=True, blank=True) category = models.ForeignKey('ClientCategory', on_delete=None, null=True, blank=True) they_pay = models.BooleanField('They Pay', default = False, required=False) we_pay = models.BooleanField('We Pay', default = False, required=False) csr = models.ForeignKey(settings.AUTH_USER_MODEL, to_field='extension', on_delete=None, blank=True, null=True, limit_choices_to= Q( groups__name = 'Customer Service')) #Upload location /<ClientID>/documents/* documents = models.FileField(null=True, blank=True, upload_to=client_directory_path) notes = models.TextField(null=True, blank=True) active_status = models.CharField('Status', max_length=1, choices=client_status, default="1") client = models.CharField('Client/Company Name',max_length=200, null=True, blank=True) account_number = models.CharField(max_length=50, null=True, blank=True) #Contact Information first_name = models.CharField('First Name', max_length = 200, null=True, blank=True) last_name = models.CharField('Last Name', max_length = 200, null=True, blank=True) … -
DRF: Accept date data in any format like rather than default "YYYY-MM-DD" format and convert save in default format
I created a model ProjectInvoice class ProjectInvoice(models.Model): date = models.DateField() ......................... then I wrote a serializer class ProjectInvoiceSerializer like this class ProjectInvoiceSerializer(serializers.ModelSerializer): class Meta: model = ProjectInvoiceBooking fields = ['date',...] def update(self, instance, validated_data): instance.date = validated_data.get('date', instance.date) how can i modify the code so that i can accept date data in any format like rather than default "YYYY-MM-DD" format and convert save in default format -
Django add extend permissions
I need to make some specific permissions to view sections of the site. How can they be created so that they can be adjusted through the admin panel? -
ModelForm field included even when not in fields
I have the following model: class Test(models.Model): name = models.CharField(max_length=100) And the admin: class TestForm(forms.ModelForm): confirm_name = forms.CharField(max_length=100) ... @admin.register(Test) class TestAdmin(admin.ModelAdmin): form = TestForm fields = ('name',) create_fields = ('name', 'confirm_name') def get_fields(self, request, obj=None): fields = super().get_fields(request, obj) if not obj: fields = self.create_fields return fields Everything works fine. But when you add a record and then try to edit it, I get the error "Please correct the error below." without showing any field errors. I checked the form errors and it says confirm_name should not be empty. Why is it still being included if it's not added in fields? -
How to configure Mysql to avoid an error: Illegal mix of collations
Every time I run the django unit test, a test database is created. During the test, I encounter an error django.db.utils.DatabaseError: (1267, "Illegal mix of collations (latin1_swedish_ci,IMPLICIT) and (utf8_general_ci,COERCIBLE) for operation '='") I know there's a solution for a production database. Is it possible to override the mysql configuration so that the correct encoding is applied by default to each new test database? -
Getting error on django rest framework Unsupported lookup 'text' for JSONField or join on the field not permitted, perhaps you meant exact or iexact?
I'm getting this error=> Unsupported lookup 'text' for JSONField or join on the field not permitted, perhaps you meant exact or iexact? Unable to figure how to solve this. I'm getting this above error when trying to query on field that has nested json data. I'm using DB Mongodb and Djongo engine to connectand framework id Django rest framework. Please guide me to solve this issue. View===== @api_view(['GET']) def gettweets(request): if request.method == 'GET': tweets = TwitterMaster.objects.all() tt = request.query_params.get('tt') if tt: condition = Q(data__text__contains=tt) #condition = Q(tweet_text__contains=tt)&Q(tweet_favorite_count=13) tweets = tweets.filter(condition) # srz = serializers.serialize('json',tweets) #print(tweets.query) serializer = TwitterdashappSerializer(tweets, many=True) totCount = 0 if serializer.data is not None: totCount = len(serializer.data) respData = {"totCount":totCount} return Response({"message": "success", "data":respData},200) return Response({"message": "OOPS","error_code":"gettweets_404"},404) Model => from djongo import models from jsonfield import JSONField class TwitterMaster(models.Model): tweet_id = models.BigIntegerField(primary_key=True) data = JSONField(default='', blank=True) location = models.CharField(max_length=250, blank=True, null=True) latitude = models.CharField(max_length=250, blank=True, null=True) longitude = models.CharField(max_length=250, blank=True, null=True) Serializer======= class TwitterdashappSerializer(serializers.Serializer): tweet_id = serializers.CharField() data = serializers.JSONField() location = serializers.CharField() latitude = serializers.CharField() longitude = serializers.CharField() def create(self, validated_data): instance = TwitterMaster.objects.create(**validated_data) return instance -
How to clear suggestions from login form in django
I'm working on a project in Django and I have a login form. I have added and deleted some users with register new user form. Now when I enter new login it shows me suggestions of the names that I added earlier I want to remove these suggestions. I have no clue what to do. -
how to register user with email verification using django rest auth
I set up Django custom registration using the Django-rest-auth, I also want to verify the email by sending emails which I heard that Django all auth does out the box. but this doesn't seem to work. I don't know if to install any package or what. I created a custom register which ingeris from django-all-auth.but it doesnt seem to work still. my models.py from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.db import models from django.utils import timezone class UserManager(BaseUserManager): def _create_user(self, email, password, is_staff, is_superuser, **extra_fields): if not email: raise ValueError('Users must have an email address') now = timezone.now() email = self.normalize_email(email) user = self.model( email=email, is_staff=is_staff, is_active=True, is_superuser=is_superuser, last_login=now, date_joined=now, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password, **extra_fields): return self._create_user(email, password, False, False, **extra_fields) def create_superuser(self, email, password, **extra_fields): user=self._create_user(email, password, True, True, **extra_fields) user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): username = None email = models.EmailField(max_length=254, unique=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' # EMAIL_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email my custom register views.py from rest_auth.registration.views import RegisterView from django.contrib.auth import get_user_model class CustomRegisterView(RegisterView): def create(self, … -
DRF - How to change serializer.PrimaryKeyRelatedField's filter lookup key with condition?
I am trying to change serializers.PrimaryKeyRelatedField's filter lookup key based on other boolean field on serializer but I could not be successful. PrimaryKeyRelatedField filtering by pk key by default. In some condition (if condition field on serializer sent as True), I just want to change that filtering key with another field on related model's field like remote_id. class SomeSerializer(serializers.Serializer): condition = serializers.BooleanField(default=False) model_pks = serializer.PrimaryKeyRelatedField(queryset=Model.objects.all(), many=True) I tried to create new field which is inherited from PrimaryKeyRelatedField and override get_queryset method (not sure to override correct method) so far but I could not access condition and model_pks fields values. class CustomPrimaryKeyRelatedField(PrimaryKeyRelatedField): def get_queryset(self): queryset = self.queryset # model_pks = sent model_pks if condition: return queryset.filter(remote_id__in=model_pks) return queryset.filter(id__in=model_pks) Also, I tried to use SerializerMethodField instead of PrimaryKeyRelatedField like; class SomeSerializer(serializers.Serializer): condition = serializers.BooleanField(default=False) model_pks = serializer.SerializerMethodField() def get_model_pks(self, value): pks = self.initial_data.get('model_pks', []) if value.get('condition', False): return Model.objects.filter(remote_id__in=pks) return Model.objects.filter(pk__in=pks) It's provide changing lookup key based on condition but this time I could not access model_pks values with serializer.validated_data. Is there any way to make conditional lookup key filtering using PrimaryKeyRelatedField? -
Frontend editing stopped working in Django CMS after installing application
After installing the application djangocms_blog, and letting it run auto setup my ability to use the frontend editor broke. I installed using pip install djangocms-blog==1.0.0rc1. Normally, the content of placeholders is clickable to be edited. Right now, this feature is broken on all pages. -
How to correctly write custom Renderer to download file with django REST API
I am running a Django app where I can upload files. Now I want to download the files using django REST framework. I am trying to overwrite the custom renderer following the spare documentation on Renderers and on FileResponses as well as this question: How to return generated file download with Django REST Framework? My model: class FileCollection(models.Model): name = models.CharField(max_length=120, null=True, blank=True) store_file = models.FileField(storage=PrivateMediaStorage(), null=True, blank=True) creation_date = models.DateTimeField(null=True, blank=True) My views class PassthroughRenderer(renderers.BaseRenderer): media_type = 'application/pptx' format = 'pptx' def render(self, data, accepted_media_type=None, renderer_context=None): return data class FileView(viewsets.ReadOnlyModelViewSet): queryset = FileCollection.objects.first() Now I am lost.... It's not clear to me how I can use this renderer to create a download for my file. I'm very grateful for help or hints. Thanks so much -
Key error - "type" in django while migrating from existing mysql to mongodb through djongo
while migrating my existing database engine from SlqlLite to MongoDB through djongo ( a django ODM), I am facing this issue of key error, which simply means when a key and its associated value is not present in the dictionary of constraints, I am suspecting its because I am already having existing data model classes. The tutorials I followed were only about starting a fresh project through mongoDB. The key 'type' is not present in the dictionary within file scripts.py (library file). I got to know that through a simple modification of printing the dictionary, plz help me guys as I am a Django newbie! major suspect is identification_identification_slug_27be3d04': {'columns': ['slug'] in dictionary i dont even know type the type field stands for ? its not ven any constraints powershell screenshot settings.py affecting lines in schema.py -
Handle error of a specific time raised at any point
Occasionally we are getting OperationalError: FATAL and we have no idea why. I want to handle this error wherever it happens in the application and send me a personal email. I would also like to set up a system command call to inspect the database activity (I know this is a bad idea but it's the only thing I can think of to try to figure out why this is happening). How can I do this? Summarized: catch an error of a specific type raised at any point and handle it in a custom and granular way. -
How to generate models.py classes by xsd in django?
So, i am trying to generate models.py classes with django. I'm trying to do it with gends_run_gen_django.py. I watched this at this question : Generate Python Class and SQLAlchemy code from XSD to store XML on Postgres I'm trying this command. gends_run_gen_django.py -f -p C:\Users\test\AppData\Local\Programs\Python\Python38-32\Scripts\generateDS.py C:\Users\test\Documents\Files\XMLSchemaPersonAdress.xsd But i getting this error: Traceback (most recent call last): File "C:\Users\test\AppData\Local\Programs\Python\Python38-32\Scripts\gends_run_gen_django.py", line 201, in <module> main() File "C:\Users\test\AppData\Local\Programs\Python\Python38-32\Scripts\gends_run_gen_django.py", line 195, in main generate(options, schema_name) File "C:\Users\test\AppData\Local\Programs\Python\Python38-32\Scripts\gends_run_gen_django.py", line 91, in generate if not run_cmd(options, args): File "C:\Users\test\AppData\Local\Programs\Python\Python38-32\Scripts\gends_run_gen_django.py", line 118, in run_cmd process = Popen(args, stderr=PIPE, stdout=PIPE) File "c:\users\test\appdata\local\programs\python\python38-32\lib\subprocess.py", line 854, in __init__ self._execute_child(args, executable, preexec_fn, close_fds, File "c:\users\test\appdata\local\programs\python\python38-32\lib\subprocess.py", line 1307, in _execute_child hp, ht, pid, tid = _winapi.CreateProcess(executable, args, OSError: [WinError 193] %1 is not a valid Win32 application What i need to do? -
Django - Testing Carrying Over POST Variables
I am working on doing some code coverage unit testing for my Django application when I ran into this interesting predicament. tests/test_views.py class TestLogin(TestCase): def setUp(self): self.client = Client() self.url = reverse('account:login') self.template = 'account/login.html' # This test works def test_POST_invalid_login(self): response = self.client.post(self.url, { 'username': 'foo', 'password': 'bar' }) self.assertEqual(response.status_code, 401) self.assertTemplateUsed(response, self.template) # This is not working as intended. def test_POST_no_data(self): with self.assertRaises(MultiValueDictKeyError): self.client.post(self.url, None) views.py class Login(View): form_class = LoginForm template = 'account/login.html' def get(self, request): form = self.form_class(None) context = { 'form': form } return render(request, self.template, context) def post(self, request): try: # Retrieve the username and password username = request.POST['username'] password = request.POST['password'] # Create a user object from authentication, or return None user = authenticate(username=username, password=password) # Check if user was created if user is not None: # Login the user to the website login(request, user) messages.success(request, 'Login successful! Welcome ' + user.first_name + ' ' + user.last_name) # Eventually have this go to profile pages. return redirect('home', permanent=True) else: messages.error(request, 'Login failed: Invalid User.') except MultiValueDictKeyError: messages.error(request, 'Login failed: Invalid User.') # Clear the form since the login attempt failed. form = self.form_class(None) context = { 'form': form } return render(request, self.template, context, … -
Django ListView with post method, get_queryset does not come filtered
In my application i made a ListView, in this ListView i have to make a post so i'm defining the post method, in this post method i need the filtered get_queryset method, but it comes unfiltered as if it is default. I made some research and i've noticed method post() is ran before get_queryset(), my question is: Is there any way i can get the filtered get_queryset() in the post() method? Ex: def get_queryset(self): qs = super(FilteredListView, self).get_queryset() q = Q() if self.request.session.get('make_id'): q.add(Q(owner__make=self.request.session['auto_id']), Q.AND) if self.request.user.is_superuser: return qs.filter(q).distinct('id').order_by('-id') return qs.filter(q, owner=self.request.user.company).distinct('id').order_by('-id') def post(self, request, *args, **kwargs): if 'action' in self.request.POST: action = self.request.POST.get('action') if action == 'batch_approve': queryset = self.get_queryset() # i need the filtered queryset here, but it comes unfiltered return redirect('{}?{}'.format(reverse('flow:filtered_list'), request.GET.urlencode())) return redirect('flow:filtered_list') -
Django Record datetime with timezone
I'm having trouble with timezone time recording. I have on settings.py: TIME_ZONE = 'America/Sao_Paulo' USE_TZ = True I have in model: hour = models.DateTimeField(null=False) In the template I get string time 10:00:00: {% load tz %} {% localtime on %} 10:00:00 {% endlocaltime %} Before saving convert the string to datetime: import datetime form = Form(request.POST) data = form.data hour = datetime.datetime.strptime(data.get("hour"), "%H:%M:%S") When returning to the template, it is show 13:06:00: {% load tz %} {% localtime on %} 13:06:00 {% endlocaltime %} In the database, another different value, like the same timezone 09:59:32-03:06:28: db=# SHOW TIMEZONE; TimeZone ------------------- America/Sao_Paulo (1 registro) db=# select hour from supply; hour ------------------------------ 1900-01-01 09:59:32-03:06:28 (1 registro) I'm confused. Thanks for helping. -
Is it possible to forward processed (in views.py) form data for further use?
I am new to django so sorry if I will not succeed to express myself clear enough. To begin with: I have build simple form to perform simple calculations and return result based on user input. Now I would like to add an option for user to generate PDF from these results, but I am not sure what kind of approach should I use. My first idea was to store calculation data in some sort of global variable and pass it to the view responsible for generating PDF. According to answer to this question there should be few ways to do that (but I am not sure if they fit because for example my url never changes). My second idea that since url never changes maybe data is still somewhere and can be accessed somehow? What I am trying to say, that I have calculation results passed in dictionary form (named context in my code) to results html template. Can I still access this dictionary and use it in another views.py function? Can somebody provide some insights or direct me to what kind of literature I should search (since I do not exactly know what approach I should take and … -
The Celery in Django task is not performed correctly. No errors
I try start the basic celery task according to this tutorial. My configuration looked like this: My Django-Project >> app_rama __init__.py celery.py settings.py urls.py wsgi >> app tasks.py __int__.py in app_rama from __future__ import absolute_import from .celery import app as celery_app Settings.py # CELERY STUFF BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'Africa/Nairobi' tasks.py in app from celery.decorators import task @task(name="sum_two_numbers") def celery_task(): print('Celery Task - OK') def typical_task(): print('Typical Task - OK') views.py from django.shortcuts import render from .tasks import celery_task, typical_task def home(request): data = request.GET.get('data', False) if data: print('Start Test') celery_task.delay() typical_task() print('End Test') context = {'data': data} return render(request, 'home.html', context) home.html <h1>{{ data }}</h1> <br> <a href="?data=TEST_STARTING"> <button type="button">Test</button> </a> <br><br><br> <a href="{% url 'app:home' %}"> <button type="button">Come back to start</button> </a> I'm trying to make my celery task work properly. But I don't receive any action or error information. After clicking the test button, the Celery task should be completed. But this does not happen, only a test task is performed. The whole Redis configuration seems to be working properly. I can enable the server from the command line and he respond to the … -
No url other than domain.com are working in my django project production mode,
whole django project works fine on localhost. but when i uploaded it to linux shared server and deployed the project only domain.com works . other links like domain.com/admin or domain.com/xyz are redirecting to 500 Internal Server Error. most of the answers are linked to passenger server problem in passenger_wsgi.py but i can not find any error or problem in it passenger_wsgi.py import myapp.wsgi SCRIPT_NAME = '/home/username/myapp' class PassengerPathInfoFix(object): def __init__(self, app): self.app = app def __call__(self, environ, start_response): from urllib.parse import unquote environ['SCRIPT_NAME'] = SCRIPT_NAME request_uri = unquote(environ['REQUEST_URI']) script_name = unquote(environ.get('SCRIPT_NAME', '')) offset = request_uri.startswith(script_name) and len(environ['SCRIPT_NAME']) or 0 environ['PATH_INFO'] = request_uri[offset:].split('?', 1)[0] return self.app(environ, start_response) application = myapp.wsgi.application application = PassengerPathInfoFix(application) -
Issue with django POST requests and nginx
I have an nginx in front of my Django application, and I have a frustrating issue with POST requests. It seems that sometimes, the response of a POST request gets "lost" and is not returned to the browser. However, no error is generated. I have tested this with both uwsgi and gunicorn, and I can reproduce the same error under both application servers. My nginx config is quite simple: upstream django { server myapp:8000; # } server { listen 8000 default_server; location / { charset utf-8; #include uwsgi_params; #uwsgi_pass django; proxy_pass http://django; client_max_body_size 512M; # add_header X-XSS-Protection "1; mode=block" always; # add_header X-Content-Type-Options "nosniff" always; } location /media/ { alias /uploads/; add_header X-XSS-Protection "1; mode=block" always; add_header X-Frame-Options "SAMEORIGIN" always; add_header X-Content-Type-Options "nosniff" always; add_header Cache-Control "no-store" always; } location /static/ { alias /static/; add_header X-XSS-Protection "1; mode=block" always; add_header X-Frame-Options "SAMEORIGIN" always; add_header X-Content-Type-Options "nosniff" always; expires 1y; add_header Cache-Control "max-age=31536000"; } } The problem is, there is no consistent way to reproduce it. I can sometimes trigger it, by changing my password in django-admin. After changing my password by hitting the "change my password" button, my browser keeps waiting and it never seems to stop, it keeps waiting …