Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Search result filter - Django based website
I'm new in django and I'm developing a website which let user discover free online Spanish courses. I need a lead in how to code a front-end filter which filter the search results base on price, acceding and descending. Something like.... And to let the filter selected after changing page in pagination. Thank you for you time -
breadcrumb does not show any contents in browser
I have such a breadcrumb to trace the path: <div class='row'> <div class="col-xs-12 col-md-12"> <ol class="breadcrumb"> <li><a href="/">Home</a></li> <li class="active">{{ b.name }}</li> </ol> <p> <a href="/article/create/{{ b.id }}" class="btn btn-primary pull-right">Create Article</a> </p> <br> <hr> </div> </div><!-- breadcrumb-row --> However, the breadcrumb was not presented as intended, It just displayed the navbar from the base.html and create article bar without a breadcrumb in the middle. -
Django expected string or bytes-like object when creating model
I have a model that I'm trying to create a new instance of. However, I'm getting an error when I'm running the basic create command. C.objects.create(). I can still create a instance through the admin, but can't seem to outside of it. Code Run: qs_a = A.objects.all().first() qs_b = B.objects.all().first() C.objects.create(a=qs_a, b=qs_b) model class C(models.Model): a = models.ForeignKey(A, blank=True, default=False) b = models.ForeignKey(B, blank=True, default=False) the_id = models.CharField(max_length=120, blank=True) # AB31DE3 status = models.CharField(max_length=120, default='initiated', choices=STATUS_CHOICES) start_date = models.DateField(default=False, blank=True, null=True) end_date = models.DateField(default=False, blank=True, null=True) ... updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) stacktrace: >> C.objects.create(a=qs_a, b=qs_b) Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\myApp\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\myApp\lib\site-packages\django\db\models\query.py", line 394, in create obj.save(force_insert=True, using=self.db) File "C:\myApp\lib\site-packages\django\db\models\base.py", line 807, in save force_update=force_update, update_fields=update_fields) File "C:\myApp\lib\site-packages\django\db\models\base.py", line 837, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "C:\myApp\lib\site-packages\django\db\models\base.py", line 923, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "C:\myApp\lib\site-packages\django\db\models\base.py", line 962, in _do_insert using=using, raw=raw) File "C:\myApp\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\myApp\lib\site-packages\django\db\models\query.py", line 1076, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "C:\myApp\lib\site-packages\django\db\models\sql\compiler.py", line 1106, in execute_sql for sql, params in self.as_sql(): File "C:\myApp\lib\site-packages\django\db\models\sql\compiler.py", … -
How can I make a pdf file already existed available to download by users in django?
I'm using django for a small project and I would make users able to download a pdf that's already existed in media/doc/ path so I wrote this code with open('media/doc/document.pdf', 'r',encoding='latin1',errors='replace') as pdf: response = FileResponse(pdf.read(), content_type='application/pdf') response['Content-Disposition'] = 'inline;filename=some_file.pdf' return response but when the pdf file get downloaded it's shown pages empty btw I have already tried utf-8 encoding and doesn't work for me even this doesn't work for me So How can I make pages visible? -
django boolean field in template
I am trying to display a message on a template that varies based on the boolean field in my model. For my model I have: Class Example(models.Model): completed = models.BooleanField(default=False) Views.py def home(request): example = Example.objects return render(request, 'home.html', {'example': example}) home.html {% for x in example.all %} {% if x.completed %} <p>Congratulations!</p> {% else %} <p>Try again!</p> {% endif %} {% endfor %} The template always displays "Try again!" even though through the Admin I have ensured that some are True and some are False. -
nginx not working at all
I try to set my server according to https://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html. So my uwsgi works well. but nginx doesn't show me media files when i try to open 127.0.0.1:8000/media/1.jpg (my test file), and seems that it doesn't work at all. Error log file is empty. Don't have any idea what to do now and how can i find the problem. upstream django { server unix:///home/django/momstyle/momstyle.sock; } server { listen 8000; server_name momstyle-kzn.ru; charset utf-8; client_max_body_size 75M; location /media { alias /home/django/momstyle/media; } location /static { alias /home/django/momstyle/static; } location / { uwsgi_pass django; include /home/django/momstyle/uwsgi_params; } } i have a link on this file in etc/nginx/sites-enabled/. i set static roots and media root correctly in my setting.py file. When i run only wsgi by uwsgi --http :8000 --module my_site.wsgi everything works well. Please give some advices on how to solve this problem or how can i find possible reason of this problem. Thanks! -
Django: authtools do create the user profile when the user is created
I am using the authtools plugin to manage the user and its profile in django, but when I create the user, it does not create its profile, I have to go to the admin part of the site and create it manually. I separated the applications into account and profile. This is the profiles model: class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, primary_key=True) slug = models.UUIDField(default=uuid.uuid4, blank=True, editable=False) email_verified = models.BooleanField("Email verified", default=True) This is the signal.py, that is inside of the profiles application: @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_profile_handler(sender, instance, created, **kwargs): if not created: return profile = models.Profile(user=instance) profile.save() logger.info('New user profile for {} created'.format(instance)) This is the admin.py of the account app: class UserProfileInline(admin.StackedInline): model = Profile class NewUserAdmin(NamedUserAdmin): inlines = [UserProfileInline] list_display = ('is_active', 'email', 'name', 'permalink', 'is_superuser', 'is_staff',) # 'View on site' didn't work since the original User model needs to # have get_absolute_url defined. So showing on the list display # was a workaround. def permalink(self, obj): url = reverse("profiles:show", kwargs={"slug": obj.profile.slug}) # Unicode hex b6 is the Pilcrow sign return format_html('<a href="{}">{}</a>'.format(url, '\xb6')) admin.site.unregister(User) admin.site.register(User, NewUserAdmin) admin.site.register(Profile) When I signup a user, both the user and the profile objects are created, only they are not linked. … -
If else statement + AND OR in django templates
Hello Awesome People! Such a simple question, in python I can handle if else statement well, make it explicitly understandable by adding expressions inside parentheses like the following: if ((user.is_active and user.is_administrator) or user.is_superuser) or (user.group.is_active and user.group.is_safe): Parentheses are important to let python understands what this means. This is just an example, I know that I could do it another way, but what I want to know is, if is it possible to have AND and OR combined in a long if else statement in template? {% if user.is_active and user.is_administrator or user.is_superuser or user.group.is_active and user.group.is_safe %} {% endif %} Obviously Django will render this not the way I expect. Thank you in advance! -
Django modal display based on the class id list
I would like to allow the modal to be displayed on the basis of the id set from the database. Having different fruit/vegetables displayed in the container divided into tiles, I put their id in the id field of the class. In other words, pressing a button in the overlay class for a particular fruit displays a single modal with the rest of the information. HTML CODE: {% block body_block %} <div class="container-fruits"> <div class="row"> {% for t in thumb %} <div class="col-lg-3 col-md-4 col-sm-6 col-xs-12 box"> {% thumbnail t.image "255x189" crop="center" as im %} <div class="hovereffect"> <img class="img-responsive" src="{{ im.url }}" alt="Card image cap"> <div class="overlay"> <h2>{{ t.name }}</h2> <a id="{{ t.id }}" class="info" data-target="#{{ t.id }}" href="#">show details</a> </div> </div> {% endthumbnail %} </div> {% endfor %} </div> </div> {% for t in thumb %} <div id="{{ t.id }}" class="fruitsModal" tabindex="-1" style="display: none"> <div class="modal-dialog modal-lg "> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <h2 class="modal-title">{{ t.name }} information</h2> </div> <div class="modal-body"> <h2 class="modal-body-text">{{ t.description }}</h2> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div> {% endfor %} <script src="{% static 'javascript/fruits.js' %}"></script> {% endblock %} Javascript/Jquery $(document).ready(function () { $('.info').click(function (e) { … -
How to make email validation of new users work for both web and RESTful API
I’m using social-auth-app-django (v 2.1.0) and django-rest-framework-social-oauth2 (v 1.0.6) in my Django project. My goal is to allow registrations and logins with both the traditional username/password method and with social logins like Facebook, Google, Twitter, etc. I would also like to ensure people use validated emails. So my pipeline in settings.py is: SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'accounts.email.require_email', 'social_core.pipeline.user.get_username', 'social_core.pipeline.mail.mail_validation', 'social_core.pipeline.social_auth.associate_by_email', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) Where accounts.email.require_email looks like: # Ensure there's an email set in the user details. # If there isn't, request it from the backend. # If the backend doesn't give it to you, prompt the user for it. # def require_email(strategy, details, user=None, is_new=False, *args, **kwargs): backend = kwargs.get('backend') if user and user.email: return # The user we're logging in already has their email attribute set elif is_new and not details.get('email'): # If we're creating a new user, and we can't find the email in the details # we'll attempt to request it from the data returned from our backend strategy user_email = strategy.request_data().get('email') if user_email: details['email'] = user_email else: # If there's no email information to be had, we need to ask the user to fill it in # This should redirect … -
Auto-fill form field
I have made a form field with drop down list with various choices(lets say A,B,C,D). The next field in the form is dependent on the option selected in the drop down list. How can I autofill the next field if option A is selected with a fixed value and make it charfield when other options are selected? -
Why doesn't Django use formfield_for_foreignkey result to populate list_filter?
I have overriden formfield_for_foreignkey on a model to limit the choices for a foreign key. When I want to use the same foreign key field as a list_filer, it pulls all values instead of filters version. All values in the filter don't make sense. I expect list_filter values come form field_for_foreignkey as well. Is there any workaround ? -
Complex ORM query in django
This is my User class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True, max_length=255) mobile = PhoneNumberField(null=True) username = models.CharField(null=False, unique=True, max_length=255) full_name = models.CharField(max_length=255, blank=True, null=True) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=False) And this is my Quiz model, class Quiz(Base): category = models.ForeignKey(Category, related_name='quizzes', on_delete=models.CASCADE) winners = models.ManyToManyField(User, related_name='quizzes_won') losers = models.ManyToManyField(User, related_name='quizzes_lost') I want to query all quizzes that an user has not played, thus winners and losers does not contain user id. How do I do this. Sorry I'm new to django. -
Error when using conditional annotation in Django: select_format
When trying to annotate a query set, I get a TypeError from a django method. I'm using Django 1.11.12 and MySQL 5.7.22 on Ubuntu. Here is my models.py: class Group(models.Model): name = models.CharField(max_length=100) class ActivationRecord(models.Model): group = models.ForeignKey('directory.Group') year = models.PositiveIntegerField() A group is "active" if it has a record for a given year. I'm trying to annotate whether groups are active using the following query: Group.objects.annotate(active=Case( When(activationrecord__year=2018, then=True), default=False, output_field=BooleanField)) When I run that I get the following error: File "/home/vagrant/Envs/think/lib/python3.5/site-packages/django/db/models/query.py", line 226, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "/home/vagrant/Envs/think/lib/python3.5/site-packages/django/db/models/query.py", line 250, in __iter__ self._fetch_all() File "/home/vagrant/Envs/think/lib/python3.5/site-packages/django/db/models/query.py", line 1118, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/home/vagrant/Envs/think/lib/python3.5/site-packages/django/db/models/query.py", line 53, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch) File "/home/vagrant/Envs/think/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 877, in execute_sql sql, params = self.as_sql() File "/home/vagrant/Envs/think/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 429, in as_sql extra_select, order_by, group_by = self.pre_sql_setup() File "/home/vagrant/Envs/think/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 46, in pre_sql_setup self.setup_query() File "/home/vagrant/Envs/think/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 37, in setup_query self.select, self.klass_info, self.annotation_col_map = self.get_select() File "/home/vagrant/Envs/think/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 227, in get_select sql, params = self.compile(col, select_format=True) File "/home/vagrant/Envs/think/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 375, in compile return node.output_field.select_format(self, sql, params) TypeError: select_format() missing 1 required positional argument: 'params' -
Return object when aggregating grouped fields in Django
Assuming the following example model: # models.py class event(models.Model): location = models.CharField(max_length=10) type = models.CharField(max_length=10) date = models.DateTimeField() attendance = models.IntegerField() I want to get the attendance number for the latest date of each event location and type combination, using Django ORM. According to the Django Aggregation documentation, we can achieve something close to this, using values preceding the annotation. ... the original results are grouped according to the unique combinations of the fields specified in the values() clause. An annotation is then provided for each unique group; the annotation is computed over all members of the group. So using the example model, we can write: event.objects.values('location', 'type').annotate(latest_date=Max('date')) which does indeed group events by location and type, but does not return the value field, which is the desired behavior. Another approach I tried was to use distinct i.e.: event.objects.distinct('location', 'type').annotate(latest_date=Max('date')) but I get an error NotImplementedError: annotate() + distinct(fields) is not implemented. I found some answers which rely on database specific features of Django, but I would like to find a solution which is agnostic to the underlying database. -
Get checkbox option names when redndering manually
I'm trying to get the name of each option associated with a particular checkbox element. For example when I allow django to render the checkbox it produces <label for="id_amenities_0"><input name="amenities" value="1" id="id_amenities_0" type="checkbox"> Care Parking</label> Now I'm trying to render the forms manually and I want to find a way of displaying 'Care Parking'. This is what I have done but it doesn't display anything {% for box in form.amenities %} <div class="col-12 col-md-4"> <label class="custom-checkbox" for="id_amenities_{{ forloop.counter0 }}"> {{ box.html_name }} <input type="checkbox" id="id_amenities_{{ forloop.counter0 }}" name="amenities"> <span class="checkmark"></span> </label> </div> {% endfor %} -
PythonAnywhere: manage.py returns "Access denied for user 'user'@'%' to database 'user'"
I am having very frustrating issues with PythonAnywhere. I've managed to get my site up and running by doing some hacky work arounds whenever I need to run manage.py but now that I need to set an automated task, this is no longer an option. The issue lies in the fact that in PythonAnywhere databases have to be named in the convention "user$database". Because of the dollar sign, whenever I run something like python manage.py inspectdb I get the error mentioned in the title as anything attached to the dollar signed is assumed to be an environment variable by the shell. Currently, I am storing my production environment variables in a .env file and setting them in to the settings.py file. This works internally with Django but does not work when running manage.py commands in the shell. I've attempted to fix the problem by adding the following code in my manage.py file: # update DATABASE_NAME to use \$ instead of $ else bash commands wont work os.putenv( "DATABASE_NAME", str(os.getenv("DATABASE_NAME")).replace('$', '\\$') ) however, this does not resolve the issue. I've also attempted to resolve the by creating a file called production_settings.py containing my DATABASES settings and wrapping the database name in … -
%5E being inserted into reverse url
I'm having a problem with a url resolving as it should. It's resolving as http://localhost:8000/%5Ewebsites/?value=1&id=1 when it should be resolving as http://localhost:8000/websites/?value=1&id=1 I've got the following urls.py inside of an app. app_name = 'websites' urlpatterns = [ url(r'^$', website_views.homepage, name="homepage"), url(r'^aboutus/$', website_views.aboutus, name="aboutus"), url(r'^blog/$', website_views.blog, name="blog"), url(r'^blog/(?P<id>\d+)/$', website_views.blogpost, name="blogpost"), url(r'^(?P<slug>[\w-]+)/$', website_views.bonus, name="bonus"), ] I've got this inside of my project urls.py file: urlpatterns = [ url(r'^websites/', include('websites.customerurls')), The link that is resolving incorrectly is this: <a href="{% url 'websites:homepage' %}?value=1&id=1" target="_blank"> Any help would be appreciated! Thanks! -
Linux using Python 2 instead of 3
I recently installed linux minut on my laptop and am curretley trying to learn databases with django and python. My issue is that Linux seems to be using python 2 instead of python 3. So when pip installing django it installs the 1.11 version instead of the 2.0. I think it has something to do with this error message The directory '/home/zac/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. -
django.db.utils.OperationalError: (1054) -- elasticsearch ---> search_index --rebuild
I am using django 1.9 and MySQL database. i made modifications in my database and deleted the column name 'state_id' then if typed command: python manage.py search_index --rebuild i am getting the following error: django.db.utils.OperationalError: (1054, "Unknown column 'login_suser.state_id' in 'field list'") Any idea ?? -
404 from missing URL parameters?
Currently I have the following URL parameter: urlpatterns = [ path('pixel/iframe/<mp_id>/<tid>/<price>/', views.PixelIFrame.as_view(), name='pixel-iframe'), This works with url such as pixel/iframe/my_mpid/my_tid/12.00' However, I learned from my server logs that tid might be missing sometimes. So this is being accessed: /prelander/pixel/iframe//997860/85.0000/ This results in a 404. How can I make mp_id optional in my URL parameters? -
For what kind of web applications flask framework performs better than Django?
My instructor has given me a task to implement a web application using Flask framework with the caveat that "You should focus on the overall aspects of the tool, as opposed to lists of features" Therefore, I was wondering what kind of web applications should I try to build for which flask would be the best option. -
How can I use Django model externally from the app?
I have Django models Driver and Trip. Nothing in my views and no urls. I'm using Django as mere Database, using scripts to store stuff there in DB. Here is my tree of how every thing looks: loadmngr/ models.py views.py urls.py management/ commands/ > it.py < Assume I have init.py inside management and commands. All I'm doing is a simple import of my Django models. Here is it.py: import sys parent = '/Users/work/TM/loadmngr' sys.path.insert(0, parent) from models import Trip I run python manage.py it and I get a RunTimeError: RunTimeError: Model class models.Driver doesn't declare an explicit app_label and either isn't in an application in INSTALLED_APPS or else was imported before its application was loaded. The latter part of the error ...or else was imported before its application was loaded is what I believe could be the problem. Question is: How can I properly use my Django models externally with properly configured settings? -
Delete Django model with AJAX call
I am writing an app, which is using Django Rest Framework API. I fill the data (text and images) in Django models with said API using AJAX (specifically axios) from my frontend application. The question is - is it possible not only to POST data, but to delete it - I mean model instance - like it's done in the admin interface or even delete all model instances. -
Authenticating Django-Website with external Json Web Token
I have the following setup: Apache Webserver running a Django Frontend Webpage Application Server running a Django REST Framework I now have to integrate the the Django Frontend into a 3rd party project which is written in java and angular. The authentication is completely handled by this 3rd party. Users login over LDAP and create a JWT token. Is it possible to simply receive the token in Django and authenticate the User after successfully decoding the token? And how would this work with the @login_required decorator when I have protected functions? Is there some sort of project where I can orient on, or do I have to write all myself?