Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django override model unique when saving formsets
If I have a model class MyModel(models.Model) my_field = models.CharField( ... unique=True ) and it has two instances: instance1 = 'One' instance2 = 'Two' and then have a modelformset in which I switch them so that form[0] has the value 'Two', and form[1] has the value 'One', the model with always raise a unique error, even though when formset.save() completes it will be unique. Is there a way around that, or is that just crazy talk? -
Using environment-dependent storages without triggering "ungenerated migration" warnings
Say I have a codebase that uses FileSystemStorage for file uploads in dev environments and S3Boto3Storage on test/production environments. By default, files are uploaded to S3 without a public URL. This is set by a parameter. For some fields, I want to use the publically accessible equivalent of DEFAULT_FILE_STORAGE. I could implement it like this: my_file = models.FileField( upload_to='uploads/my_file/', storage=get_public_storage_backend(), ) The function would return a different storage backend depending on your environment. Thing is, this will work fine in dev environments but cause test/production to think I have an ungenerated migration: operations = [ migrations.AlterField( model_name='my_model', name='my_file', field=models.FileField(storage=my_codebase.storages.S3Boto3PublicStorage(), upload_to='uploads/my_file/'), ), ] Is there a clean way to define additional file storages? Or some other way to avoid this migration quirk? -
How can i fix "too many values to unpack" value error while file uploading in model serializer
I'm facing below issue in ModelSerializer file upload. Issue 1) I'm trying to upload files using ModelSerializer. I have two models BlogFilesSerializer and BlogSerializer. when trying to upload a file it shows too many values to unpack error and I know its meaning why is this occurring but don't know how to handle these exceptions. serializers.py class BlogFilesSerializer(ModelSerializer): created_at = serializers.SerializerMethodField() updated_at = serializers.SerializerMethodField() class Meta: model = BlogFilesModel fields = ('blog_files_id', 'blog', 'path', 'created_at', 'updated_at') class BlogSerializer(ModelSerializer): blog_files = serializers.SerializerMethodField() uploaded_files = serializers.FileField(required=True, source='*') blog_created_at = serializers.SerializerMethodField() def get_blog_files(self, obj): info = BlogFilesSerializer(BlogFilesModel.objects.filter( blog=obj).order_by('-pk'), many=True) if info.data: for i in info.data: user_detail = User.objects.get(pk=obj.user.id) i.__setitem__('user_detail', UserSerializer(user_detail).data) if i.get('user_detail'): try: del i['user_detail']['password'] except expression as identifier: pass return info.data def get_blog_created_at(self, obj): formatted_date = obj.created_at.strftime("%d-%m-%Y") return formatted_date class Meta: model = BlogModel fields = ('blog_id', 'user', 'title', 'content', 'status', 'blog_files', 'blog_created_at', 'uploaded_files' ) def create(self, validated_data): instance = BlogModel.objects.create(**validated_data) return instance views.py class BlogViewSet(viewsets.ModelViewSet): queryset = BlogModel.objects.all() lookup_field = 'blog_id' serializer_class = BlogSerializer parser_classes = (MultiPartParser, FormParser,FileUploadParser) models.py class BlogModel(models.Model): BLOG_STATUS = ( ('PUBLISH', 'Publish'), ('DRAFT', 'Draft'), ) blog_id = models.AutoField(primary_key=True) user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='blogs') title = models.CharField(max_length=255) content = models.TextField(blank=True, null=True) status = models.CharField(max_length=7, choices=BLOG_STATUS) created_at = … -
why If condition is not working inside of clean method in django form?
I am trying to put nested if condition inside of clean method but first condition (if (cascade!= 'Satyendra')&(cascade!='Niranjan')) is working while other(if RET is None:) is not working. I must be doing something wrong here but i am unable to figure it out. For more info pl.. see the code. could you Guys help me out of this problem ? Here is my code: def clean(self, *args, **kwargs): cascade = self.cleaned_data.get('cascade') Type = self.cleaned_data.get('type') RET = self.cleaned_data.get('ret') cascade = self.cleaned_data['cascade'] if (cascade!= 'Satyendra')&(cascade!='Niranjan'): msg = "Must fill something." self.fields['RET'].required=True self.add_error('Type', msg) self.add_error('cascade', msg) else: if RET is None: msg = "Must fill something." self.add_error('RET', msg) return self.cleaned_data -
Django admin shows wrong list_display in changelist
I am trying to display different fields for different users in Django admin list view (I guess it is called changelist). Django shows correct set of fields for non-super user, but switches between sets of fields for superuser. I have a superuser and non-super user with a custom permission perm1 on model defined in some_app. The permission is set on non-super user via group. Below is the code I use to switch list_display depending on user. def changelist_view(self, request, **kwargs): user = request.user if user.has_perm('some_app.perm1'): self.list_display = ( 'field1', 'field2', ) make_log('non super-user') else: self.list_display = ( 'field1', 'field2', 'field3', 'field4', ) make_log('superuser') return super(CustomAdmin, self).changelist_view(request, **kwargs) I've tried with and without list_display in class definition. No difference. Django correctly outputs logs (make_log()) depending on who accesses that view. But almost half of the time Django shows to superuser set of fields intended for non-super user. And it always shows correct set of fields for the user with the permission perm1. I also tried to use if not user.is_superuser and user.has_perm('some_app.perm1') as condition also with no difference. I guess superuser can do everything they want, but doesn't have permissions according to Django. What am I doing wrong? -
Read and save new records from csv file by using Django
I started to learn Django. I want to read from CSV file records and save them in Sqllite when the server just loaded (after running the command python manage.py runserver ) I don't understand where should I write the code that does it. it should be on the view? it should be on the command? Thanks for any help! -
Django / FactoryBoy - unable to generate instance for abstract models
I am writing tests for a Django application and I am currently running into the following problem: I have this (abstract) model: class HeroContent(models.Model): title = models.CharField( max_length=100, blank=True, null=True, default=None) subtitle = models.CharField( max_length=255, blank=True, null=True, default=None) class Meta: abstract = True For which I created the following factory: class HeroContentFactory(factory.DjangoModelFactory): class Meta: model = HeroContent abstract = True title = factory.Faker('company') subtitle = factory.Faker('company') I consulted the documentation on how to handle abstract models, but when I run the following test: class HeroContentFactoryTest(TestCase): def test_init(self): hero_content = HeroContentFactory() The following error gets raised: FactoryError: Cannot generate instances of abstract factory HeroContentFactory; Ensure HeroContentFactory.Meta.model is set and HeroContentFactory.Meta.abstract is either not set or False. But this seems to go directly against the course recommended in the official documentation, which states that when If a DjangoModelFactory relates to an abstract model, be sure to declare the DjangoModelFactory as abstract Removing the abstract = True setting from the Factory Raises the following error: AttributeError: 'NoneType' object has no attribute 'create' calling .create on a abstract model should fail ofcourse, but now I am wondering what would be the proper way to test these kind of models using factory - especially sinds … -
Django Authentication on Apache Separate Remote Docker Container
I have a Django-app which communicates with a file server via NFS and authenticate users via auth0. Now I'm trying to integrate a GIT-server with the app. All services run independently in Docker. If a user creates a project in Django, files end up in a specific location on the file server. The same user should be able to push/pull the files from the file-server via the GIT-server. Access control should be in Django and the user authentication through Auth0 via Django (or directly on the git-server?). See overview image: https://i.imgur.com/VYSATKH.png Which method should I use to solve such a scenario? I cant figure out the best way to tackle this. I have tried with mod_wsgi by mounting the wsgi.py remotely but ended up needing to install Django and all the pip requirements. It appears that mod_wsgi is meant to be used when the app and Apache are running on the same server (docker). I have looked at mounting the user database and using apache mod_authn_dbd, this could work but seems cumbersome. Is there no way to request access control and user authentication from Apache to Django via IP? I tried using mod_wsgi but got lots of errors. I needed … -
Django makemigrations command generate the same migrations everytime
My project is base on django framework, the makemigrations command not work correctly. The makemigrations command generate the same script everytime , but my code has not changed. I upgraded the django version, but the problem remains. The django is 2.2 now models.py class BatchUploadRecord(models.Model): create_date = models.DateTimeField(_("date created"), auto_now_add=True) update_date = models.DateTimeField(_("date updated"), auto_now=True) course = models.ForeignKey(Course, related_name='course_batchtemp', on_delete=models.SET_NULL, null=True) lesson = models.ForeignKey(Lesson, related_name='lesson_batchtemp', on_delete=models.SET_NULL, null=True) migrations class Migration(migrations.Migration): dependencies = [ ('courses', '0025_auto_20190130_1634'), ] operations = [ migrations.AlterField( model_name='batchuploadrecord', name='lesson', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='lesson_batchtemp', to='courses.Lesson'), ), ] Run the makemigrations command (rinpoche) ➜ rinpoche_ask_api git:(develop) ✗ ./manage.py makemigrations Migrations for 'courses': applications/courses/migrations/0027_auto_20190409_1658.py - Alter field lesson on batchuploadrecord (rinpoche) ➜ rinpoche_ask_api git:(develop) ✗ ./manage.py makemigrations Migrations for 'courses': applications/courses/migrations/0028_auto_20190409_1658.py - Alter field lesson on batchuploadrecord (rinpoche) ➜ rinpoche_ask_api git:(develop) ✗ ./manage.py makemigrations Migrations for 'courses': applications/courses/migrations/0029_auto_20190409_1658.py - Alter field lesson on batchuploadrecord I don't how to fix it. -
Django DJANGO_SETTINGS_MODULE changing back to 'config.settings.local'
I know my .env file is loading but for some reason it seems to be jumping back to 'config.settings.local'? this is my .env settings. here is what I get back from Ubuntu after it can not find the local host setting. The DJANGO_ALLOWED_HOSTS is set for the correct address but I get back an error about not being set. Than I noticed some setting like the DJANGO_SETTINGS_MODULE have changed back to the local host. Any ideas why? Here is what I get back from my development server. Not the change in the config.setting. Thanks. And here is my disallowed host back from Ubuntu. As you can see the local host is set for this address. All this admin stuff is not my thing. Sorry if it is foolish question. Thanks. -
How to remove many to many relation for queryset?
I have a many to many relationship in my models like this. class Shift(models.Model): employees = models.ManyToManyField('account.Employee', related_name='allocated_in', blank=True) Say I have a particular instance of employee employee. I can remove him from single shift instance shift like this. shift.employees.remove(employee) How can I remove employee from every instance of a queryset of Shift? shift_qs = Shift.objects.filter(date__gt=timezone.now().date) I want to remove employee from every instance in shift_qs in a single query. Preferably without looping over queryset. -
check date_join of user with specific datetime
im new in python and django. i want check user.date_join with specific datetime but i dont know what is correct syntax. for more information : i have a SignIn function in view.py and i want check if user.date_join < yyyy/mm/dd i do something . view.py: from datetime import datetime from django.contrib.auth.models import User if request.method == "POST": if request.user.is_authenticated: if user.date_joined < (yyyy/mm/dd): # <==== here i have problem #do smt else: #do smt else: #blah blah else: #blah blah -
column hiding using column().visible() in datatable is not working
I have done one application in Django. In that application, i want to hide datatable column based on selection of one flag.I have tried column().visible() method but its not working.Any suggestions please. My code is : var table = $('#utmrejectedTable').DataTable(); alert( 'Column index 0 is '+(table.column( 0 ).visible() === true ? 'visible' : 'not visible')); table.column(0).visible( false ); alert( 'Column index 0 is '+(table.column( 0 ).visible() === true ? 'visible' : 'not visible')); 2nd alert says as not visible but column is visible in Frontend. Is there any other best ways hide column. If yes, suggestions please . -
Add an author to blogpost model
I am trying to add an author field to my blogpost model to be referenced later in my HTML: author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, default=None) But the first time I tried to migrate I got this error: (1452, 'Cannot add or update a child row: a foreign key constraint fails (`db`.`#sql-1_9a`, CONSTRAINT `blog_blogpage_author_id_8c179cec_fk_users_user_id` FOREIGN KEY (`author_id`) REFERENCES `users_user` (`id`))' Which to me actually reads like what I want to archive, i.e. 'reference the user id'. When I run makemigrations again, this error shows: (1060, "Duplicate column name 'author_id'") Am I so far off here? How to add an author field in Wagtail? -
How to pass variable values for oracle connection in python
Im able to connect to Oracle Db successfully when i hardcode the Db details like " connection = cx_Oracle.connect("uname/pass@192.168.xxx.yyy:port/db")" but how to pass the variable values to connect to the db? I tried some like this. connection = cx_Oracle.connect("{}/{}@{}:{}/{}".format(uname,password,IP,port,db)) which is not working as expected so please share some thought on this to make it work. def knowcobrand(request): value_type = request.POST.get('CobranSelection') cobrand_value = request.POST.get('cobrand') env = request.POST.get('NewEnvName') print(value_type) print(cobrand_value) print(env) # feed = Environments.objects.get(Q(Env_name__icontains=env)) # print(feed.user_name) connection = cx_Oracle.connect("app/app@192.168.xxx.yy:port/db") I want to use the variable's value of value_type and env for Db connection -
Django ModelForm: How to display user specific data in a drop-down field?
I have a drop-down field called Label as part of a model called Birthday. My problem is that the drop-down field shows the Labels from all users. How can I make sure it only shows the Labels specific to the User? I assume that a query is required in the form model but I have no clue how to do this. forms class BirthdayForm(forms.ModelForm): class Meta: model = Birthday fields = ('name', 'day', 'label') class LabelForm(forms.ModelForm): class Meta: model = Label fields = ('tag',) models class Label(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) tag = models.CharField(max_length=25) def __str__(self): return self.tag class Birthday(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=25, default="") day = models.DateField() label = models.ForeignKey(Label, on_delete=models.SET_NULL, default=0, null=True, blank=True) def __str__(self): return self.name view @login_required def index(request): if request.method == "POST": form = BirthdayForm(request.POST) if form.is_valid(): birthday = form.save(commit=False) birthday.user = request.user birthday.save() return redirect('index') else: form = BirthdayForm() birthday = Birthday.objects.filter(user=request.user) username = request.user return render(request, 'bd_calendar/index.html', {'form': form, 'birthday': birthday, 'username': username }) template <form method="POST">{% csrf_token %} <table border="0"> {{ form }} </table> <button class="submitButton" type="submit">Submit</button> </form> -
Psycopg2 changing password value before saving to db
I am using bcrypt to hash password before saving to database. Database used is postgressql and module used with django is psycopg2. Problem: Hashed password and password that gets saved in db is entirely different. Couldn't figure out why. salt = bcrypt.gensalt(); hashedPass = bcrypt.hashpw(newPass.encode('utf-8'), salt); print(hashedPass) # b'$2b$12$5zbvakw7gD/BAW9jqrQ98eWUG4R8L6d68J5vvc9A16n..ypaMHbm6' success = changePassword(user["id"], hashedPass) def changePassword(id, newPassword): try: q = ( "UPDATE user_account SET password = %(newPassword)s " "WHERE id = %(id)s " ) with connection.cursor() as cursor: print(newPassword) #b'$2b$12$5zbvakw7gD/BAW9jqrQ98eWUG4R8L6d68J5vvc9A16n..ypaMHbm6' cursor.execute(q, { "id": id, "newPassword": newPassword }) return True except Exception as e: return False #password field defination in model password = models.CharField(max_length=200) Value of hashed password b'$2b$12$5zbvakw7gD/BAW9jqrQ98eWUG4R8L6d68J5vvc9A16n..ypaMHbm6' Value of password when it gets stored in db. \x24326224313224357a6276616b773767442f424157396a7172513938655755473452384c366436384a35767663394131366e2e2e7970614d48626d36 I want hashed password to be saved in db without any change. -
django-storages dropbox.stone_validators.ValidationError
I am trying to use dropbox as media sotrage. I am trying to implement through django-storages. settings.py DEFAULT_FILE_STORAGE = 'storages.backends.dropbox.DropBoxStorage' DROPBOX_OAUTH2_TOKEN = 'token' DROPBOX_ROOT_PATH = '/media/' models.py logo = models.ImageField(upload_to=r'logo/%Y/%m/') image = models.ImageField(upload_to=r'photos/%Y/%m/', help_text='Image size: Width=1080 pixel. Height=1920 pixel',) error Request Method: | POST Request URL: | http://127.0.0.1:8000/add Django Version: | 2.1.8 Exception Type: | ValidationError Exception Value: | 'D:/media/10506738_10150004552801856_220367501106153455_o.jpg' did not match pattern '(/(.|[\r\n])|id:.)|(rev:[0-9a-f]{9,})|(ns:[0-9]+(/.*)?)' console dropbox.stone_validators.ValidationError: 'D:/media/10506738_10150004552801856_220367501106153455_o.jpg' did not match pattern '(/(.|[\r\n])|id:.)|(rev:[0-9a-f]{9,})|(ns:[0-9]+(/.*)?)' I can't figure out why this error is happening? -
Openpyxl security vulnerability solution
I am using Openpyxl for manipulating xls/xlsm files for a project. For Openpyxl there are some security issues mentioned in doc. Anyone know how to protect Openpyxl from security vulnerabilities. Doc says just install defusedxml. Just installing defusedxml will do protect or we need to configure it, then how? -
How can I use filtered dropbox for my external database values
I am learning Django to make a frontend for my python project where I need to create a credential form to make a connection with the database tool e.q. PostgreSQL that I have created. Now I want a dropdown to list all the databases available in my PostgreSQL and then another dropdown to list all schemas present in the selected database in the first dropdown and then another dropdown for tables present in the selected schema using the second dropdown. I have checked many videos for this but all are showing with the models. But I want these dropdown values from an external database not from models. I have tried to create a python file to create a form inside my Django app where I am using forms.ChoiceField to list the database values. But unable to get the selected value for of the dropdown. So that I can query the schemas -
How to filter a dataframe by user inputs in Django filter?
I want to filter a dataframe that is pivoted from a model. Model.py is: class MTD(models.Model): RGN = models.CharField(max_length = 60, db_column = 'RGN') Channel = models.CharField(max_length = 60, db_column = 'Channel') Vertical = models.CharField(max_length = 60, db_column = 'Vertical') Brand = models.CharField(max_length = 60, db_column = 'Brand') Sales_Value = models.CharField(max_length = 60, db_column = 'Sales Value') Month = models.CharField(max_length = 60, db_column = 'Month') City = models.CharField(max_length = 60, db_column = 'City') objects = models.Manager() pdobjects = DataFrameManager() def __str__(self): field_values = [] for field in self._meta.get_fields(): field_values.append(str(getattr(self, field.name, ''))) return ' '.join(field_values) I am filtering only three columns from my model ('VERTICAL', 'CHANNEL', 'SALES VALUE') and I am converting this into a dataframe. From the derived dataframe I am not able to filter the data as requested by the user. I am posting the code which I have tried so far. Table.html <!DOCTYPE html> <html lang="en" dir="ltr"> <head> {% load static %} <meta charset="utf-8"> <title></title> </head> <body class="hold-transition skin-blue sidebar-mini"> <h1>Pandas dataframe from MyModel</h1> <form method="GET"> {{ filter.form.as_p }} <button type="submit">Search</button> </form> {{ filter|safe }} {{ Table|safe }} </body> </html> Filter.py from dash.models import MTD import django_filters class UserFilter(django_filters.FilterSet): class Meta: model = MTD fields = ['Vertical', 'Channel', … -
How to solve ConnectionResetError in Django?
I am working on a login view that takes a ajax request from my JS. The request is received properly but when executing the rest of the code an ConnectionResetError occurs. I have no clue why this is happening. This is the traceback of the error - Exception happened during processing of request from ('127.0.0.1', 49785) Traceback (most recent call last): File "/anaconda3/lib/python3.6/socketserver.py", line 654, in process_request_thread self.finish_request(request, client_address) File "/anaconda3/lib/python3.6/socketserver.py", line 364, in finish_request self.RequestHandlerClass(request, client_address, self) File "/anaconda3/lib/python3.6/socketserver.py", line 724, in __init__ self.handle() File "/anaconda3/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 171, in handle self.handle_one_request() File "/anaconda3/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 179, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "/anaconda3/lib/python3.6/socket.py", line 586, in readinto return self._sock.recv_into(b) ConnectionResetError: [Errno 54] Connection reset by peer I have tried different things like "request.method == 'POST'". But still not getting why this error occurs. This is my view function - def login_view(request): if request.is_ajax(): print(len(request.body)) username = request.POST.get('uname') password = request.POST.get('pass') print(username, password) try: user = User_Master.objects.get( username=request.POST.get('uname'), password=request.POST.get('pass')) print(user) dpt_codes = Code_lookup.objects.filter(lookup_code='User Department') status_codes = Code_lookup.objects.filter(lookup_code="User Status") user_count = User_Master.objects.all().count() active_count = User_Master.objects.filter(status=0).count() inactive_count = User_Master.objects.filter(status=1).count() usr_role = User_role_link.objects.distinct() print(usr_role) users = User_Master.objects.all() # print(users) roles = Roles.objects.all() return render( request, 'pd/Users.html', { 'users': users, 'roles': roles, 'dpt_codes': dpt_codes, 'status_codes': … -
How to remove the app name from the url in Django admin
I have a Pages model in the Django admin and my app name is admin_site. So my listing page url is looking like this : http://example.com/admin/admin_site/page/ So I want to remove admin_site from the url. -
Need to implement django-filter with ajax call
I am using django-filter==2.1.0 for my search filter. Now i need to add ajax call in my search filter. My codes are given below: views.py def test_view(request): book_list = Book.objects.all() book_filter = BookFilter(request.GET, queryset=book_list) return render(request, 'test.html', {'filter': book_filter}) test.html {% extends 'base.html' %} {% load widget_tweaks %} {% block content %} <form method="get"> {{ filter.form.as_p }} <button type="submit">Search</button> </form> <ul> {% for book in filter.qs %} <li>{{ book.name }}</li> {% endfor %} </ul> {% endblock %} filters.py class BookFilter(django_filters.FilterSet): publication = django_filters.ModelMultipleChoiceFilter(queryset=Publication.objects.all(), widget=forms.CheckboxSelectMultiple) authors = django_filters.ModelMultipleChoiceFilter(queryset=Author.objects.all(), widget=forms.CheckboxSelectMultiple) categories = django_filters.ModelMultipleChoiceFilter(queryset=Category.objects.all(), widget=forms.CheckboxSelectMultiple) class Meta: model = Book fields = ['publication', 'authors', 'categories', ] models.py class Book(models.Model): name = models.CharField(max_length=100) publication = models.ForeignKey(Publication, on_delete=models.CASCADE) authors = models.ManyToManyField(Author, through='AuthorBook') categories = models.ManyToManyField(Category, through='BookCategory') In ajax there is needed url value. django-filter works automatically. So, i can't understand how to implement ajax call with django_filter. Thanks in advance. -
Django redundant migration files are being created
class Agency(models.Model): uuid = models.UUIDField(editable=False, default=uuid.uuid4()) name = models.CharField( verbose_name='Name', max_length=50 ) Whenever, I am applying python manage.py makemigrations new migration files are being created. It is worth mentioning that, I am not touching models.py file. The migration file content is. class Migration(migrations.Migration): dependencies = [ ('dashboard', '0001_initial'), ] operations = [ migrations.AlterField( model_name='agency', name='uuid', field=models.UUIDField(default=uuid.UUID('890eb162-c485-49f0-87a6-ebc3e95a12b3'), editable=False), ), migrations.AlterField( model_name='agencycontract', name='uuid', field=models.UUIDField(default=uuid.UUID('f6500cbe-69ee-42c0-ad1e-80377f2a9dcf'), editable=False), ), migrations.AlterField( model_name='contractproduct', name='uuid', field=models.UUIDField(default=uuid.UUID('7bc66e61-c752-4333-b508-14b53c903e83'), editable=False), ), ] I know that, hence I am using uuid function that is why those are being created. How do I stop that file creation? Before that is that really necessary to stop this migration file creation?