Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
WHEN TRYING TO CREATE HTML FILES IN DJANGO TEMPLATE IT IS CREATING ONE WITH BUT DOES NOT SUPPORT HTML AUTO TAG AND OTHER OPTIONS
I was doing my project. and i needed to include html files in it for that i created a templates folder in my app and created a html file in it. but the created html file has a problem. the icon created does not seem as a html file and the html file is not auto closing the tags and no suggestions for the tags are showing i tried installing auto tag , auto complete and html snippets extensions. i expect there is a solution for this problem. i think i have done the installation right but the html files are not working properly -
Adding returning form_invalid (or something) with custom form errors in custom signup form with django-allauth
I am trying to prohibit duplicate signups from a single ip. Here is my code. class SignupForm(forms.Form): def signup(self, request, user): ip = get_client_ip(request) if UserProfile.objects.filter(registration_ip=ip).exists(): self.add_error( None, "You cannot register more than one account from the same IP") else: user.userprofile.registration_ip = ip user.userprofile.save() user.save() Currently, when a user registers having the same ip as another registered user, the form still validates. I need the form to return an error. Can anyone help? Thanks in advance. -
edit response json python
anyway to editing the response in json django? I'm using view.viewset { "title": "Cloister", "number": 2, "summary": "Erasmas describes several buildings of the Concent, namely the Scriptiorium...", "page_count": 14 }, for example: first I get return in json like this "title": "Cloister", and I want to add something after get string, final result must be: "title": "Cloister+somethinghere"! my task is get the product name, and check if the name >40 characters then just take 40 character and plus "..." after 40character -
How to properly prepopulate ModelForm with data from .csv file?
I'm using data from .csv file to prepopulate options for ModelForm. Let me explain how It should work: I need a simple django-app which will allow user to load data from file to be feed as choices for each form field. After clicking 'Submit' the row data will be serialized in JSON file if all fields are valid, corresponding to abstract models. Otherwise the row should be skipped manually by user and the data from next row should be loaded and form should be "refreshed". I know that the code I've listed below is a complete madness, but yep, I've tried at least. models.py class Article(models.Model): identifier = models.CharField(unique=True, max_length=255) number = models.CharField(max_length=255) ... collection = models.CharField(max_length=255) verified = models.IntegerField() class Meta: abstract = True class ArticleTranslation(models.Model): name = models.CharField(max_length=255, blank=True, null=True) description = models.TextField(blank=True, null=True) ... lightproofness = models.CharField(max_length=255, blank=True, null=True) kind_of_removal = models.CharField(max_length=255, blank=True, null=True) class Meta: abstract = True forms.py class ArticleForm(forms.ModelForm): class Meta: model = Article fields = ['identifier', 'number', ..., 'collection', 'verified'] class ArticleTranslationForm(forms.ModelForm): class Meta: model = ArticleTranslation fields = ['name', 'description', ..., 'lightproofness', 'kind_of_removal'] views.py def mapper(request): data = list(read_file(path='export_full.csv')) row = data.pop() json_data = [] if request.method == 'POST': article_form = ArticleForm(request.POST) … -
Setup SSL for Django with gunicorn on Debian 9 on Compute Engine
I'm working on a project which has been deployed on compute engine on Debian 9 VM instance. Here's are the steps I have performed: Create Instance and ssh into Install Python (3.6) directly by using these commands: a): sudo apt-get update && sudo apt-get upgrade b): sudo apt-get install -y make build-essential libssl-dev zlib1g-dev c): sudo apt-get install -y libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm d): sudo apt-get install -y libncurses5-dev libncursesw5-dev xz-utils tk-dev e): wget https://www.python.org/ftp/python/3.6.4/Python-3.6.4.tgz f): tar xvf Python-3.6.4.tgz and some other build commands to .... Then install virtualenv and activate it Clone the django project from github and install the requirements And run the gunicorn and the project is working fine. But now, I want to set up the ssl for my Django projects, I have googled it but the tutorials are for nginx, I don't have setup nginx on my VM instance, so how can I set up SSL on my instance? I want to use Lets Encrypt. -
Multistep Form in django
I was working with normal crispy forms in django. I changed the form to multi step form, now the submit doesnt work. So when i click on submit data doesnt get stored in the db. This is how the updated template looks like: index.html index.html <ul id="progressbar"> <li class="active">Account Setup</li> <li>Social Profiles</li> <li>Personal Details</li> </ul> <!-- fieldsets --> <fieldset> <h2 class="fs-title">Help me know you better</h2> <h3 class="fs-subtitle">This is step 1</h3> {{ form.associate_image|as_crispy_field}} <input type="button" name="next" class="next action-button" value="Next" /> </fieldset> <fieldset> <h2 class="fs-title">Social Profiles</h2> <h3 class="fs-subtitle">Your presence on the social network</h3> {{ form.title|as_crispy_field}} {{ form.client|as_crispy_field }} {{ form.lob|as_crispy_field }} <input type="button" name="previous" class="previous action-button" value="Previous" /> <input type="button" name="next" class="next action-button" value="Next" /> </fieldset> <fieldset> <h2 class="fs-title">Personal Details</h2> <h3 class="fs-subtitle">We will never sell it</h3> {{ form.gender|as_crispy_field }} {{ form.phone_number|as_crispy_field }} <textarea name="address" placeholder="Address"></textarea> <input type="button" name="previous" class="previous action-button" value="Previous" /> </fieldset> This is the view function : views.py @login_required def save_information(request): associate_id = id_to_numeric(request.user.username) ldap = Ldap() current_user = UserDetails.objects.filter(associate_nbr=associate_id) if current_user.exists(): current_user.delete() associate_details = ldap.search(associate_id=associate_id)[0] details = UserDetails( associate_name=associate_details['name'], associate_nbr=associate_id, associate_email=associate_details['email'], associate_department_id=id_to_numeric(associate_details['department']), associate_mgr=associate_details['xxx'], associate_exec=associate_details['xxx'], associate_org=associate_details['org'], associate_image=request.FILES['associate_image'], gender=request.POST['gender'], title=request.POST['title'], client=request.POST['client'], lob=request.POST['lob'], phone_number=request.POST['phone_number'] , ) details.save() return redirect('/?submit=true') -
Django redirect is not working with dropzone.js
Redirect in Django is not working when files are uploaded using Dropzone.js, so I used windows.href in the Dropzone's success event but I have to pass a parameter. # views.py if request.method == 'POST' and request.FILES['files']: ... if form.is_valid(): .... user = User.objects.get(email=email) id = user.id return redirect(reverse('success', kwargs={'id': id})) <<-- not working #JQuery - Dropzone this.on('success', function() { window.location.href = '/success/'; }) I don't reckon there is a way to pass the 'id' to JQuery in this case, so I have to use redirect in Django. How can it get done? -
Multiple date selection in django-admin
Is it possible to select multiple dates from calendar or DateField in Django-Admin and store? I want to make a calendar using in which user can choose multiple dates from that calendar and store in the database. -
How to make a Bangladeshi phone number field in the model of django?
Is there any package or widgets to do so? Example numbers: [+880][17][59219191], [+880][16][59219090] Here [+880] is country code, which is constant, [14],[16],[17]...etc are service provider numbers [59219090],[59219191]...etc are third part of mobile numbers in Bangladesh. -
Django: how to order query set by OneToOneField's date?
I have two classes: class Foo(models.Model): date = models.DateTimeField(auto_now_add = True) ... class Bar(models.Model): foo = models.OneToOneField( Foo, on_delete = models.CASCADE, primary_key = True ) ... How can I order Bar's objects like this: query_set = Bar.objects.all().order_by('-foo.date') -
Using Django “rules” with CBVs don't work
I am running into a problem using rules with CBV. I initialized rules like this: rules.add_perm('core.change_user', is_myuser) Where: @rules.predicate def is_myuser(user): print('Checking inside from rules') return False And I am calling: class UserUpdateView(PermissionRequiredMixin, UpdateView): model = User form_class = UserForm template_name = 'forms/user_form.html' permission_required = 'core.change_user' However this is not working. I have checked the solution from another question and I correctly have: AUTHENTICATION_BACKENDS = [ 'rules.permissions.ObjectPermissionBackend', 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ] I am not able to figure out the problem here. Even the debug message inside my predicate "is_myuser" doesn't print I also tried changing the permission name and using add_rule(). I am using Django==2.0.8 and rules==2.0 Other pieces of Code: Initialize Permissions in AppConfig: class CoreConfig(AppConfig): name = 'app.core' verbose_name = 'My App Config' def ready(self): from .rules import init_rules import logging logger = logging.getLogger(__name__) logger.info('Initializing permissions') rules.add_perm('core.change_user', is_myuser) I am getting 'Initializing permissions' in logs. When I check for permission in get_context_data of CBV print(f"User has permission: {self.request.user.has_perm(self.permission_required, self.get_object())}") Output: User has permission: True Expected Output: User has permission: False Note: I have created an issue regarding the same on Django-rules. Github -
Django: Selenium not finding image source of simple HTML
Very simple HTML here: <html> <img src={% static '/img/default_profile.png' %} id="profile-thumbnail" class="img-thumbnail"> </html> And a similarly simple test: ... thumbnail_source = self.browser.find_element_by_id("profile-thumbnail").get_attribute("src") self.assertIn('default_profile.png', thumbnail_source) For some reason, I'm getting this error: self.assertIn('default_profile.png', str(thumbnail_source)) AssertionError: 'default_profile.png' not found in 'None' I've tried adding a sleep(5) call before the assert, just in case it was a weird loading issue, but this didn't help anything. Is this some kind of bug by chance, or am I missing something trivial? Selenium finds the element, but apparently the element's src is None. If one watches the browser, it certainly shows up alright. What could be wrong? -
EncodeError at (POST Method ) in django python. Post respose 500
I have my python class below. My question is what this error actually means EncodeError at /api/v1/jobs/apply/ > is not JSON serializable. What is it trying to point based on my code below ? can anyone give an idea? Code class ApplyJob(APIView): def email(self, data): email_ins = Email() c_task.delay(email_ins.new_application, data) authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,IsApplicant) def post(self, request, format=None): data = request.data job_applicant_ser = JobApplicantSerializer(data=data) applicant = get_applicant_ins(request) if applicant.profile_completeness <= 60: return Response("You have not complete filling up your profile yet. Please complete it atleast 80% and above percentage..", status=status.HTTP_400_BAD_REQUEST) if not applicant.resume: return Response("Sorry, Please upload your resume.", status=status.HTTP_400_BAD_REQUEST) job = data.get("job" , None) cover_letter = data.get("cover_letter", None) if not cover_letter or cover_letter == "": return Response("Sorry, please fill your cover letter.", status=status.HTTP_400_BAD_REQUEST) apply_job_checker_ins = JobApplicant.objects.filter(job=job,applicant=applicant).count() if apply_job_checker_ins > 0: return Response("Sorry but you cant apply to this company, it appears that you have already applied.", status=status.HTTP_400_BAD_REQUEST) if job: job = JobModel.objects.get(pk=job) else: return Response("Sorry but there is a problem with the application, please refresh page.", status=status.HTTP_400_BAD_REQUEST) if job_applicant_ser.is_valid(raise_exception=True): job_applicants = job_applicant_ser.save(applicant=applicant,job=job) data = {} data["job"] = job_applicants.job.title data["account_url"] = APP_URL+"/account/job_applicants" data["email"] = job_applicants.job.company.user.email data["resume"] = STATIC_ROOT+"/uploads/resume/"+str(job_applicants.applicant.resume) data["company_email"] = job_applicants.job.company.user.email self.email(data) return Response("You have applied to the … -
Storing and serving different sized images
I have a website where the user will upload their profile picture. The picture will then be separated out to 3 images. 1 as the original image, 2 as a medium sized thumbnail, and 3 as a small sized thumbnail. What is the best way to store a process like this in a database? I was thinking something like this: Image table id user_id size img 1 2 S /img/s/avatars/ex.jpg 2 2 M /img/m/avatars/ex.jpg 3 2 L /img/l/avatars/ex.jpg We take the original image and split them off like this. Does this look like a good idea, or is there a better way to something like this. I am using Django as my backend. -
specify annotate field on subtables
I have a parent table Image and subtable Resized_image, so i have stored images data in resized_image table. I want to filter the data using aspect ratio. This is my model: class Image(models.Model): name=models.CharField(max_length=40,unique=False) class Resized_image(models.Model): img = models.ForeignKey(Image, related_name='images', on_delete=models.CASCADE) image=models.ImageField(upload_to=config.date_format,width_field='width', height_field='height',) width=models.PositiveIntegerField(null=True, blank=False, editable=False) height=models.PositiveIntegerField(null=True, blank=False, editable=False) size=models.IntegerField(null=True, blank=False,editable=False) status = models.CharField(max_length=30, default='inserted') class Meta: db_table = 'resized_images' def __str__(self): return self.status def save(self,force_insert=False, force_update=False, using=None): if not self.image: return super(Resized_image, self).save() self.size = os.stat(str(self.image)).st_size super(Resized_image, self).save() This is my view: class ImagePostAPIView(mixins.CreateModelMixin,generics.ListAPIView): queryset = Image.objects.all() serializer_class = imagesSerializer def get(self, request): print("inside get views.py") return super(mixins.CreateModelMixin,self).get(request) def myfilter(self, queryset, queryparam, queryarg): param = self.request.query_params.get(queryparam, None) #print("param",param) if param is not None: try: newarg = {queryarg : int(param)} #print("newarg",newarg) queryset = queryset.filter(**newarg) except ValueError: pass return queryset def get_queryset(self): queryset = Image.objects.all() queryset = self.myfilter(queryset, 'minheight', 'images__height__gte') queryset = self.myfilter(queryset, 'maxheight', 'images__height__lte') here i am filtering data in GET request using minheight which is present in Resized_image table similarly i want to filter data using aspect ratio i.e., i want to add aspect_ratio field using table_name.objects.annotate and then filter the data... How can i do that?? -
how to remove duplicate varible django view.py
I'm getting a duplicate code in query, how can i merge 2 variable into 1 line def destroy(self, request, pk=None): date_time = datetime.now() user = get_object_or_404(User, pk=request.user.id) transaction = TransactionVariant.objects.filter(transaction__pk=pk).update(deleted_at=date_time) transaction = Transaction.objects.filter(id=pk).update(deleted_at=date_time) serializer = TransactionSerializer(transaction, many=True) return Response(serializer.data, many=True) my model: transaction.py class Transaction(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) address = models.TextField() status = models.CharField(max_length=100) total = models.BigIntegerField() phone_number = models.CharField(max_length=10) created_at = models.DateTimeField(auto_now_add=True, blank=True) updated_at = models.DateTimeField(auto_now_add=True, blank=True) deleted_at = models.DateTimeField(null=True, blank=True) class Meta: db_table = "transaction" transaction_variant.py class TransactionVariant(models.Model): transaction = models.ForeignKey(Transaction, on_delete=models.CASCADE) variant = models.ForeignKey(Variant, on_delete=models.CASCADE) quantity = models.IntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True, blank=True) updated_at = models.DateTimeField(auto_now_add=True, blank=True) deleted_at = models.DateTimeField(null=True, blank=True) class Meta: db_table = "transaction_variant" -
Django 2: how to force a foreignkey in admin interface
I'm new to Django and Python. Let's say I'm building an app to manage devices used by users in companies. I have multiple companies, with multiple users and rooms in each. Rooms and users are always linked to a company. A device can be linked to: An user ("Joe's iPhone", "Anna's Laptop") A room ("Conference Room's Computer") A device is always linked to a company. So, I can have a device, that is linked to a company only. So here's my code : #models.py class Company(models.Model): name=models.CharField(max_length=50) class User(models.Model): name=models.CharField(max_length=50) company=models.ForeignKey('Company', on_delete=models.CASCADE) class Room(models.Model): name=models.CharField(max_length=50) company=models.ForeignKey('Company', on_delete=models.CASCADE) class Device(models.Model): company=models.ForeignKey('Company', on_delete=models.CASCADE) user=models.ForeignKey('User', on_delete=models.CASCADE, blank=True, null=True) room=models.ForeignKey('Room', on_delete=models.CASCADE, blank=True, null=True) #admin.py class DevicesInline(admin.TabularInline): model = Device extra = 0 def formfield_for_foreignkey(self, db_field, request=None, **kwargs): if db_field == "Company": kwargs['queryset'] = ## Here I don't know ## return super().formfield_for_foreignkey(db_field, request, **kwargs) class UserAdmin(admin.ModelAdmin): inlines = [DeviceInline] What I want is pretty simple : when I'm editing a user (or a room), I want to be able to add a device for it. But the field "Company" has to be filled with the company for the user or room, and it can't be modified. That's all :) Thanks in advance ! PS: I … -
bootstrap 3.3.0:submenu of submenu is not shown using codepen example
I copied codes from this codepen example. Submenus are shown finely, while the submenus of submenus are not. I have removed some redundant ul/lis in order to let answerer see my question easily without destroying the HTML tree structure written by the original author--J.S. Negley. For example, Dropdown Submenu Link 4.1 is not shown. Bootstrap version: 3.3.0 Jquery version: 1.12.4 Django version : 2.1.5(djangorestframework 3.9.1) Python version: 3.5.0 in my index.js(and inside ready function) $('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) { event.preventDefault(); event.stopPropagation(); $(this).parent().siblings().removeClass('open'); $(this).parent().toggleClass('open'); }); inside my head tag: <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> {% load staticfiles %} <link rel="stylesheet" href='{% static "css/bootstrap/bootstrap.min.css" %}'> <script src='{% static "js/jquery-1.12.4.js" %}'></script> <script src='{% static "js/bootstrap.min-3.3.0.js" %}'></script> <link rel="stylesheet" href='{% static "css/bootstrap/bootstrap.css" %}'> <link rel="stylesheet" href='{% static "css/index.css" %}'> <script src='{% static "js/index.js" %}'></script> <title>MultiLingualNoteTaking</title> inside my body tag: <div class="container pen" style=""> <div class="row"> <div class="col-sm-12"> <nav class="navbar navbar-default navbar-fixed-top" role="navigation"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#" >MultiLingualNoteTaking</a> </div> <div class="collapse navbar-collapse" id="navbar-collapse-1"> <ul class="nav navbar-nav"> <li><a href="#">About</a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Create Books<b class="caret"></b></a> <ul class="dropdown-menu"> <li><a class="menu-item" id="menu1-createbook" href="#">Step 1. Create Books</a></li> <li><a class="menu-item" id="menu1-createchapter" href="#">Step 2. Create … -
How do I do date math in a Django ORM query?
I'm using Django with Python 3.7. I have teh below model ... class Article(models.Model): ... title = models.TextField(null=False) created_on = models.DateTimeField(default=datetime.now) I would like to write a Django ORM query where I find all articles that are older than 5 minutes. But I'm not sure how to write such a query. I tried Article.objects.filter((datetime.now(timezone.utc) - created_on)__gte==300) But this results in a SyntaxError: invalid syntax error. -
Running a script parallel to a Django Application at start up (manage.py runserver)
I'm looking to run another script as soon as my Django Application starts up. I wrote a python script to continuously update/create records in my database (SQLiteDB) that is connected to my Django Application. I tried to put the function call in my apps.py (def ready(self)) function, but that is never called. I also tried to add my function in both the urls.py and wsgi.py files, however, this function runs forever, and interacts with the database. Would it be possible to spawn a parallel process to the Django application within the application? (instead of running a separate script). -
Google SSO / Google Login in Django Admin
Need help adding google login in my django admin tried this https://pypi.org/project/django-admin-sso/ but can't make it work it seems to be outdated it currently goes to the google login page and when i click my google account it just goes back my current django admin page without doing anything. Any suggestions the login should only be in the django admin page? -
How to covert two ListAPIViews that are different into a single ModelViewSet
I have a django project I am working on that needs a users and account model. I am using and integrating Django Rest Framework. I was initially using individual API generic views from DRF. I am thinking of converting the individual generic views into a view set. I was able to do it for the user model. I wan to convert the Account model views to a view set. My issue is that I have two versions of the same ListAPIView for the profile model. The top View lists all of the accounts in the database and the second one list all the accounts for an idividual user based on the User__Username foreignkey in the Account model. class UserViewSet(viewsets.ModelViewSet): serializer_class = UserSerializer queryset = User.objects.all() lookup_field = 'username' class AccountListView(ListAPIView): queryset = Account.objects.all() serializer_class = AccountSerializer class AccountUserListView(ListAPIView): queryset = Account.objects.all() serializer_class = AccountSerializer filter_backends = (filters.DjangoFilterBackend,) filterset_fields = ('user', '_id', '_class') def get_queryset(self): return self.queryset.filter(user_username=self.kwargs.get('username')) It says that I can specifically define the properties of a view within the viewset but I want to define two versions of the ListAPIView for the single model. Is there a way to double define the same view in a single viewset. I … -
remove duplicate varible django view.py
Is there any ideas for the duplicate transaction variable? def destroy(self, request, pk=None): date_time = datetime.now() user = get_object_or_404(User, pk=request.user.id) transaction = TransactionVariant.objects.filter(transaction__pk=pk).update(deleted_at=date_time) transaction = Transaction.objects.filter(id=pk).update(deleted_at=date_time) serializer = TransactionSerializer(transaction, many=True) return Response(serializer.data, many=True) -
Django Autocomplete form media tag problem
in my html file i use {{ form.media }} tag but not see included js files in chrome browser {% extends 'base.html' %} {# Don't forget that one ! #} {% load static %} {% block content %} <div> <form action="" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" /> </form> </div> {% endblock %} {% block footer %} <script type="text/javascript" src="{% static 'admin/js/vendor/jquery/jquery.js' %}"></script> {{ form.media }} {% endblock %} Can someone help me ? -
Django 1.11 get_template with full path of template
I have the following search order of directories in settings.py 'DIRS': [os.path.join(DATA_ROOT, 'templates'), os.path.join(PROJECT_ROOT, 'src', 'py', 'my_project', 'app1', 'templates'), os.path.join(PROJECT_ROOT, 'src', 'py', 'my_project', 'app2', 'templates')), ], There is a template 'test_template.html' under app1 and app2. I want to programatically load app1/test_template1.html or 'app2\test_template2.html'by giving django.template.loader.get_template() the full path to the file (so that the correct template be loaded). But despite giving the full path it still loads the app/test_template1.htmlbecause it has higher priority in search order. Reversing the order will not help because then it will start loadingapp2/test_template.html`. I can keep the filenames unique but it should be something simpler. Any idea. Thanks.