Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Parameterized property in Django
For example, I have two models: class Page(models.Model): # Some fields ... @property def title(self): return PageTranslation.objects.get(page=self, language=language).title # I can not pass property to the parameter class PageTranslation(models.Model): page = models.ForeignKey(Page) title = models.CharField() And some DRF view, which get_queryset method looks like this: def get_queryset(self): return Page.objects.all() And serializer: class PageSerializer(serializers.ModelSerializer): class Meta: model = Page fields = (..., 'title',) # title = property I want to return QuerySet with Page model instances, and use title property in serializer, but I can not pass language (that is set somewhere in the request — headers, query param, etc) there. What is the correct way to do this? -
I can POST to Django REST API using form-data but not using JSON
I have a simple app with one model in it, which is connected to REST API. I can easily access it and post new data using PostMan, where I fill in the data in form-data. But when I try to access it using curl or using PostMan 'raw' option providing json there the API returns me the response this field is required So the command I provide in curl is curl localhost:8888/api/mymodel -d "{'sender_id': '123'}" and I get back 'sender_id':['this field is required']' While if I post it via postman (form-data), everything works fine. What am I doing wrong? -
Django stipe js blocking of inline script
I'm trying to implement stripe payment system in Django. For adding card payments, I followed the guide in this link. After adding HTML markup in Django template and CSS and JS code as separate static files, I got the following console error in Firefox: Content Security Policy: The page’s settings blocked the loading of a resource at inline (“script-src”) What I understand from above error message is that, <script src="https://js.stripe.com/v3/"></script> JS file contains links to other JS files and Firefox blocks such connections. It should be noted that, at this stage test credit card payment is working as expected and amount debited by client is added to my stripe account's test balance. To address this blocking problem, I followed the instructions in this link. As such, I added following meta tag to my Django template: <meta http-equiv="Content-Security-Policy" content="connect-src https://api.stripe.com; frame-src https://js.stripe.com https://hooks.stripe.com; script-src https://js.stripe.com" /> After adding above Content-Security-Policy directives, Firefox console no longer shows aforementioned blocking errors, but this time my static JS files are blocked. I have modified directives as below for allowing my JS files (added 'self' to 'script-src' directive): <meta http-equiv="Content-Security-Policy" content="connect-src https://api.stripe.com; frame-src https://js.stripe.com https://hooks.stripe.com; script-src 'self' https://js.stripe.com" /> And this time before mentioned inline-script … -
How to get current url with filter parametres?
I have an url like this : http://127.0.0.1:8000/uk/events/?title=qwerty&age_filter=1&date_filter=2` How to get current url with filter parametres without language code? `/events/?title=qwerty&age_filter=1&date_filter=2` When I am trying request.resolver_match.url_name I am getting /events/. -
Is the following enough to protect my secret key and database password for heroku deployment?
I have added the environment variables through to get secret key database name and password. Now anything else to make it more secure.Let me know. Used "Advance system settings" and under that added environment variables in "User variables" . Also this is going to be my first deployment on 'heroku' that's why following a tutorial. SECRET_KEY = os.environ['DB_SECRET'] databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'portfoliodb', 'USER': os.environ.get['DB_USER'], 'PASSWORD': os.environ.get['DB_PASS'], 'HOST': 'localhost', 'PORT': '5432', } } -
How to link to the most recent object of a model in Django
I'm making a polling app and have a generic list view which is linking to generic detail views correctly, but I would like to have a button which links directly to the most recently submitted poll. I've got a few lines of code: #Views def currentIssue(req): ciLink = motion.objects.filter(submitTime__isnull=False).latest() return render(req, 'voting/motion_detail.html', context={'ciLink': motion}) #urls path('current-issue', views.currentIssue, name='current-issue'), This returns an empty version of the template, but I can't work out how to link to the most recent motion. Anything I've tried fails to work, and often breaks the links in the generic list view. Thank-you in advance for any help -
What does djangos unique=true actually do?
I assume it verifies that the field is unique to all other entries in the same table. But what happens if there actually is a collision? Does django just crash? Or does it just keep rerunning the default generator until it has found a value that is unique? Can I just use any crappy random number/string generator I want and assume that django will ensure that a unique value is always set? In which case, if all values are taken, does it just fall into an endless loop? -
AWS ElasticBeanstalk Django - module 'bcrypt' has no attribute 'checkpw'
I am getting this error on my AWS Server if bcrypt.checkpw(password, usrPassword): Exception Type: AttributeError at /api/user/login/ Exception Value: module 'bcrypt' has no attribute 'checkpw' Request information: USER: AnonymousUser I installed the PIP Bcrypt Library pip install bcrypt But Still I am getting same error -
Django Dynamically Remove form from formset with jQuery (extension of previous SO question)
I followed the examplespresented in SO question code. It works for me, but as I am not too good with jQuery I am having issues extending this dynamic add to also allow a user to remove forms. My template HTML is: {% csrf_token %} {{ form_2.management_form }} <div id="form_set"> {% for form in form_2 %} {{form.non_field_errors}} {{form.errors}} <table class='no_error'> {{ form }} </table> {% endfor %} </div> <input type="button" value="Add More" id="add_more"> <div id="empty_form" style="display:none"> <table class='no_error'> {{ form_2.empty_form }} </table> </div> <input type="button" value="Remove" id="remove"> <div id="empty_form" style="display:none"> <table class='no_error'> {{ form_2.empty_form }} </table> </div> The jQuery script I used to get the Add More button to work was taken from the linked SO as $('#add_more').click(function() { var form_idx = $('#id_form-TOTAL_FORMS').val(); $('#form_set').append($('#empty_form').html().replace(/__prefix__/g, form_idx)); $('#id_form-TOTAL_FORMS').val(parseInt(form_idx) + 1); }) This code works really nicely, I just wanted some code to allow users to remove forms also. My naive attempt was $('#remove').click(function() { var form_idx = $('#id_form-TOTAL_FORMS').val(); $('#form_set').remove($('#empty_form').html().replace(/__prefix__/g, form_idx)); $('#id_form-TOTAL_FORMS').val(parseInt(form_idx) - 1); }) </script> But this isn't working. I have seen things online here which allow removal, but the code is very verbose and not easy for me to follow, and the remove function isn't working. Any jQuery implementations I could use … -
DRF serializer to group data by attributes into arrays
I would like to create a Django Rest Framework serializer which can group my data based on attributes of each object. My models are described as follows: class Courses(models.Model): coursenum = models.AutoField(db_column='courseNum', primary_key=True) coursecode = models.CharField(db_column='courseCode', max_length=10, blank=True, null=False) class Meta: managed = False db_table = 'courses' class Sections(models.Model): sectionnum = models.AutoField(db_column='sectionNum', primary_key=True) semester = models.CharField(max_length=1, blank=True, null=False) section = models.CharField(max_length=2, blank=True, null=False) class Meta: managed = False db_table = 'sections' class Teachers(models.Model): teachernum = models.AutoField(db_column='teacherNum', primary_key=True) teachername = models.CharField(max_length=60, blank=True, null=False) class Meta: managed = False db_table = 'teachers' class Timeslots(models.Model): timeslotnum = models.AutoField(db_column='timeSlotNum', primary_key=True) starttime = models.TimeField(db_column='startTime', blank=True, null=False) endtime = models.TimeField(db_column='endTime', blank=True, null=False) class Meta: managed = False db_table = 'timeslots' class Venues(models.Model): venuenum = models.AutoField(db_column='venueNum', primary_key=True) venuename = models.CharField(db_column='venueName', max_length=6, blank=False, null=False) class Meta: managed = False db_table = 'venues' class Slots(models.Model): daynum = models.IntegerField(db_column='dayNum', primary_key=True) venuenum = models.ForeignKey(Venues, models.CASCADE, db_column='venueNum') timeslot = models.ForeignKey(Timeslots, models.CASCADE, db_column='timeSlot') coursenum = models.ForeignKey(Courses, models.CASCADE, db_column='courseNum', blank=True, null=True) teachernum = models.ForeignKey(Teachers, models.CASCADE, db_column='teacherNum', blank=True, null=True) sectionnum = models.ForeignKey(Sections, models.CASCADE, db_column='sectionNum', blank=True, null=True) class Meta: managed = False db_table = 'slots' unique_together = (('daynum', 'venuenum', 'timeslot'),) Using a simple Model serializer with nested sibling serializer calls, I can get the data as … -
Mobile css boilerplate for Django?
I noticed mobile-django is incompatible with the latest releases of Django. Are there any good resources for a css boilerplate for Django mobile development? -
In Django i'm trying templates folder but it is not going in templates folder. i facing following error. please help to solve this
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/check.html Using the URLconf defined in myproject.urls, Django tried these URL patterns, in this order: webapp/ [name='index'] check [name='check'] admin/ The current path, check.html, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. -
Django-MySQL, 5 dynamic dependent dropdown list using only one model
I have a search field where I have 5 drop downs that will help me filter my search results. In my database, (MySQL) I have one Equip model with 21 columns that is the only model to be used in the search parameters. I only need to use 5 of the 21 columns to get the results needed, they are: eqtype, eqmfg, eqeff, eqmfgmodeldescrip and eqconfig. The first drop down is filter by eqtype and the second is filter by eqmfg, the third by eqeff, the fourth by eqmfgmodeldescrip , and the fifth by eqconfig. As I have it coded now, they return all options for their respected fields. However, I am trying to set the second drop down dynamically meaning that depending on the first drop down (eqtype) only those eqmfg should be displayed in the second drop down that match the respective eqtype selected. The third would be based on the first and second selections. The fourth would be based on the first, second, and third selections. The fifth would be based on the first, second, third, and fourth selections. Seeing that I have just gotten into coding, (started 4 months ago) I've been trying several tutorials that … -
SessionNotCreatedException at / Message: Unable to find a matching set of capabilities
I am trying to deploy a app (selenium with geckodriver python3). I am getting following trace back: Traceback: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view 54. return view_func(*args, **kwargs) File "/app/mp3/views.py" in search 20. driver = webdriver.Firefox(options=options, executable_path=geckodriver) File "/app/.heroku/python/lib/python3.6/site-packages/selenium/webdriver/firefox/webdriver.py" in init 167. keep_alive=True) File "/app/.heroku/python/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py" in init 156. self.start_session(capabilities, browser_profile) File "/app/.heroku/python/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py" in start_session 251. response = self.execute(Command.NEW_SESSION, parameters) File "/app/.heroku/python/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py" in execute 320. self.error_handler.check_response(response) File "/app/.heroku/python/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py" in check_response 242. raise exception_class(message, screen, stacktrace) Exception Type: SessionNotCreatedException at / Exception Value: Message: Unable to find a matching set of capabilities -
How to use django-push-notifications with an APNS .p8 certificate
Has anybody used the django-push-notifications library recently? It looks useful, but it seems like it needs an update. The documentation at https://github.com/jazzband/django-push-notifications/blob/master/docs/APNS.rst only discusses how to generate the required .pem file from a .p12 certificate, but now Apple gives you a .p8 certificate. Any ideas how to get this working? -
Creating a custom super user as part of a class Im taking
I'm currently taking a custom rest API class that is teaching me to build my own custom REST APIs for authentication, as well as creating custom user models. Im running into a slight problem with the following code base: from django.db import models from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.models import BaseUserManager # Create your models here. class UserProfileManager(BaseUserManager): """ Manager for User Profiles""" def create_user(self, email, name, password=None): """ Create a new user profile""" if not email: raise ValueError('Users must have an email address') email = self.normalize_email(email) user = self.model(email=email, name=name) """ user.set_password(password) encrypts the passwords as a hash """ user.set_password(password) """ This allows you to specify which database to use for the user accounts. Django Supports multiple Databases!!! 8D """ user.save(using=self._db) return user def create_superusr(self, email, name, password): """ Create and save a new superuser with given details """ user = self.create_user(email, name, password) user.is_superuser = True user.is_staff = True user.save(using=self._db) return user class UserProfile(AbstractBaseUser, PermissionsMixin): """ Database model for users in system """ email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserProfileManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] def get_full_name(self): """ Retrieve Full Name of User""" return … -
Django modelformset_factory() adding field manually in views
Disclaimer: I am new at Django so I'm sure my code is ugly. Problem: My current Model is built as follows: class person(models.Model): email = models.EmailField() date = models.DateField() phone_number = models.IntegerField() name = models.CharField(max_length = 50) belongs_to_group = models.ForeignKey(Group, related_name='group', on_delete=models.SET_NULL, null=True) belongs_to_user = models.ForeignKey(User, related_name='user', on_delete=models.SET_NULL, null=True) def __str__(self): return self.student_name I have built a modelformset_factory for this using the following code: personModelFormset = modelformset_factory( person, fields=('email', 'date' , 'phone_number', 'name'), extra=1) This makes the fields the form renders in the HTML email, date , phone_number, and name. This means that to successfully save the form to the database, I need to also add the fields belongs_to_group and belongs_to_user manually since the website user shouldn't be able to edit these (they should be automatically generated). Attempted Solution: To try to do this, I used the following view: def classes(request): #add form creation method here user = request.user group = value #taken from another form if request.method == 'POST': form_2 = personModelFormset (request.POST) if form_2.is_valid(): for form in form_2: form.belongs_to_group = value form.belongs_to_user = user form.save() return redirect('home') But this does not append the information to the form. This method works for me in a normal modelform, so I … -
Django form with two submit buttons with ajax
I use this question and all works: Referencing multiple submit buttons in django However when I use ajax, it fails, here is my code: html <form method="post" id="idForm" name="fmr1" action = "/myproject/save/" enctype="multipart/form-data"> .... <input type="submit" name="save" value="Save"> <input type="submit" name="calc" value="Calculate"> </form> js $("#idForm").submit(function(e) { e.preventDefault(); // avoid to execute the actual submit of the form. var frm = $('#idForm'); $.ajax({ type: frm.attr('method'), url: frm.attr('action'), data: frm.serialize(), success: function (data) { alert(data.mylist) }, error: function (data) { alert("ajax fails") } }); }); views if request.method == 'POST' and 'calc' in request.POST: print("runs calc form") mylist= [5] return JsonResponse({'mylist':mylist}) Question Now the difficulty is in "'calc' in request.POST", so it does not run when I add ajax or id="idForm" to the form. I need "'calc' in request.POST" since I have to run "save" as well. Both will have to run inside one method in views. Do you have any idea how to make it run? -
How to validate modalform for errors and show them in the same modalform?
I have a django form to create/update records that is showed on a bootstrap modal (launched through JQuery script), I can create records but when I enter information that already exists in de DDBB I get the error: "django.db.utils.IntegrityError: duplicate key value violates unique constraint DETAIL: Key (descripcion)=(OC) already exists." I understand the error is because I set the propierty of the field in the model as unique. I have tried to override the clean() method in the form to catch the errors, that works partially, now I don't receive the integrity error message but I receive the form clean as a result but not in the modal, in his case is showed in this way: form What I'm looking for is validate the information in the modalform and in case of error (like duplicate values) show the message in the same modal and not continue with the form submission. I'm very noob on JQuery and any idea or guide will be very useful. Thanks in advance. As a reference the code I have until now is: The model: class Categoria(models.Model): descripcion = models.CharField( max_length=100, help_text='Descripción de la categoría', unique=True, ) def __str__(self): return '{}'.format(self.descripcion) def save(self): self.descripcion=self.descripcion.upper() super(Categoria, self).save() … -
Raw html forms submission without using foreign key instances in django
models.py class Link_list(models.Model): link_id=models.AutoField(primary_key=True) link_episode_season_id=models.ForeignKey(Episode_list,on_delete=models.PROTECT) link_user_id=models.ForeignKey(User, on_delete=models.PROTECT,blank=True) name=models.CharField(max_length=50) link=models.TextField() upvote=models.PositiveIntegerField(default=0) downvote=models.PositiveIntegerField(default=0) views=models.PositiveIntegerField(default=0) link_type=models.ForeignKey(Content_type_list,on_delete=models.PROTECT) subtitle=models.ManyToManyField(Subtitle_list) link_created_at=models.DateTimeField(default=timezone.now) quality=models.ForeignKey(Quality_list,on_delete=models.PROTECT) def __str__(self): return f'{self.name}' class Meta: verbose_name_plural='Link' forms.py class Create_Link_form(forms.Form): name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': '','maxlength':50})) link = forms.CharField(widget=forms.Textarea(attrs={'placeholder': ''})) link_type = forms.ModelChoiceField(queryset=Content_type_list.objects.all()) quality = forms.ModelChoiceField(queryset=Quality_list.objects.all()) views.py @login_required def Link_create(request): form=Create_Link_form( data=(request.POST or None), files=(request.FILES or None), ) if form.is_valid(): if request.user.is_active: r=Link_list.objects.create( name=request.POST["name"], link=request.POST["link"], link_type=request.POST["link_type"], quality=request.POST["quality"], link_episode_season_id=x, link_user_id=request.user, ) r.save() messages.success(request, f'Season has been created!') else: messages.warning(request, f'Please Login to create movies!') else: print(form.errors) context={ "form":form, "form_name":url } return render(request,'movies_list/link_list_create.html',context) USing modelsForm it work just fine.But to create custom ManytoMany Field i implemented using custom formField.Views grab every data that needed to create link object.BUt i dont know how to create link objects without using foreign Instances. ValueError at /link/new/ Cannot assign "'1'": "Link_list.link_type" must be a "Content_type_list" instance. -
Django CMS Toolbar not showing correctly?
Im working on a project ( a news website ) to practice some Django. I used cookiecutter to start my project, and then integrated Django CMS into it. Im near the end of my project and everything is working fine, except my Django CMS toolbar is not displaying properly. It looks literally like this: Double-click to edit Tap to edit django CMS django_news_blog Pages... Users... Administration... ----- User settings... ----- Clipboard... Clear clipboard ----- Disable toolbar ----- Shortcuts... ----- Logout admin Page Create Page New Page... New Sub Page... Duplicate this Page... ----- Edit this Page Page settings... Advanced settings... Templates Home Template ----- Inherit the template of the nearest ancestor Save as Page Type... ----- Publishing dates... ----- Hide in navigation Unpublish page ----- Revert to live ----- Delete page... Language English German ----- Add Translation German... Delete Translation English... More... Create View published If I go into the admin area, and create a new site, the cms toolbar works normally, until I try to load a template or display it on another site. All of my plugins are working properly. I have tried completely deleting the template, and refreshing the page but the toolbar still appears broken. There … -
Can django superuser first and last name be updated? If yes, how do I go about it?
I'm want to render superuser first and last name on my html page. But django tutorials don't show how to add these fields to the superuser. How can I go about it? Thanks -
How can I get some value from the select option django form?
I would like to know if django-forms have some way to get the value from select > option html tag. I know I can do it using something like JQuery, but I would like to know if there is some way to handle this in the client side using any django feature. -
ImportError: Could not import 'formshare.libs.authentication.DigestAuthentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'
My Django Application is not giving any error when I run python manage.py runserver but still not running after full set-up. Below is the error log trace back. class APIView(View): File "/opt/formshare/lib/python2.7/site-packages/rest_framework/views.py", line 88, in APIView authentication_classes = api_settings.DEFAULT_AUTHENTICATION_CLASSES File "/opt/formshare/lib/python2.7/site-packages/rest_framework/settings.py", line 197, in __getattr__ val = perform_import(val, attr) File "/opt/formshare/lib/python2.7/site-packages/rest_framework/settings.py", line 149, in perform_import return [import_from_string(item, setting_name) for item in val] File "/opt/formshare/lib/python2.7/site-packages/rest_framework/settings.py", line 165, in import_from_string raise ImportError(msg) ImportError: Could not import 'formshare.libs.authentication.DigestAuthentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'. ImportError: No module named related. Installed application requirements # Django pybamboo==0.5.8.1 Django>=1.6,<1.7 django-guardian==1.2.4 django-registration-redux==1.1 django-templated-email==0.4.9 gdata==2.0.18 httplib2==0.9 mock==1.0.1 httmock==1.2.2 modilabs-python-utils==0.1.5 Pillow==2.5.3 poster==0.8.1 psycopg2==2.8.3 pymongo==2.7.2 lxml==3.4.0 django-nose==1.4.2 pandas==0.20.3 South==1.0 django-reversion==1.8.4 xlrd==1.1.0 xlwt==0.7.5 openpyxl==2.0.5 celery==3.1.23 django-celery==3.1.17 librabbitmq==1.5.2 python-digest==1.7 django-digest==1.13 requests==2.4.1 elaphe==0.5.6 # sms support dict2xml==1.3 # api support djangorestframework==2.4.3 djangorestframework-csv==1.3.3 # cors django-cors-headers==0.13 Markdown==2.5 django-filter==0.7 # captcha recaptcha-client==1.0.6 unicodecsv==0.14.1 dpath==1.2-70 # tagging django-taggit==0.12.1 # oath2 support django-oauth-toolkit==0.7.2 # spss savReaderWriter # JSON data type support jsonfield<1.0 django-db-readonly==0.3.2 # memcached support pylibmc==1.3.0 kombu==3.0.35 billiard==3.3.0.23 python-dateutil==2.6.0 Any advice on how to fix this would be highly appreciated. Thank you. Collins -
Want to make a user detail page as 'example.com/username' displaying their info, posts etc
I'm making a django site and using 'allauth' module for authentication. I've used the adapters so that the user is redirected to example.com/username but instead of it leading to homepage, i want it to lead to a page dedicated to the user profile containing their posts, info etc. and they can add more info to it. I have tried searching on the internet but couldn't find an appropriate solution. this is the adapter code i've used to redirect after login, i found this code in the documentation of allauth. class MyAccountAdapter(DefaultAccountAdapter): def get_login_redirect_url(self, request): path = "/{username}/" return path.format(username=request.user.username) So, I want to know how can i create a separate profile page for users, and when someone not logged in opens that profile link, they can see their posts etc. like in instagram.