Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Display all model fields in template
I am trying to display all the fields of a model called company as a list in my template. But can't seem to make it work. Code <ul> {% for field in company.fields.all %} <li>{{ fields.name }}</li> {% endfor %} </ul> -
Django: How to load javascript from static files with template usage
I have a problem: in addWorkout.html: {% extends "workout/base.html" %} {% block footer %} <script type="text/javascript" src="{% static js/addWorkout.js %}"></script> {% endblock %} in base.html: {% load static %} <!DOCTYPE html> <html lang="en"> <body> {% block content %}{% endblock %} {% block footer %}{% endblock %} </body> </html> This will generate an error: Invalid block tag on line 49: 'static', expected 'endblock'. Did you forget to register or load this tag? This error stems from the src attribute of the script tag in addWorkout.html. Apparently, django doesn't allow for the static tag to be inside of a block tag. But how can I then import javascript from static by using the script-tag at the bottom of the body element? -
Python - Get all the variable in template passed from views.py render() function
Code in my views.py from django.shortcuts import render def webapppage(request): parameter = { 'key1':'hello', 'key2':['hiiii','whats up','buddy'] } return render(request, 'template2.html', parameter) How can I get both {{key1}} and {{key2}} in one single variable like (parameter) in my template file? Code inside template2.html {% for c in parameter %} `{{c}} {% endfor %} I want output like hello ['hiiii','whats up','buddy'] -
How to add/use javascript code in Django textfield in the condition that safe filter is used?
How to add/use javascript code in Django textfield in the condition that safe filter is used? I want to add some interactive charts by javascript, namely using<script>...</script>in my blog article, but all the content of the article is in the textfield of Django models. The chart can not be shown in the article, but it can be shown outside the article in the web page. What's reason for that? Please help me. -
Get current db migration status from db, not models in django
What i need is to get a migration describing the current structure in db and not what i defined in my models file because my models are not aligned to the structure of db, so i would like to get the current status and then apply my modifies defined in my models and make them aligned. Is it possible? And how? -
easy-thumbnails.. Is it a good option to use to reposition a cover profile photo?
I'm trying to add a function of repositioning a cover profile photo and I found a useful tutorial to add a cover profile into my web application that could be repositionned The backend code is in PHP and I'm working with PYTHON and Django . I have translated the server side code to python .. but things are not working as expected (maybe error when translating) I have used an Alternative for PHP GD library in python to translate some functions like imagecreatefromjpeg , imageSY , imagedestroy..etc what I noticed is that the PHP server side code is based on making a thumbnail of the original repositionned image and save it .. I wonder if easy-thumbnails package does the same thing . Do somebody worked with this plugin ? Is it a good option for my case ? Or I focus more on my code to correct the errors ? -
Running existing Django project
I've installed existing Django project very 1st time and I've the problem with starting servers python manage.py runserver Here it's what I've done 1.Clone the repo, 2.Make a virtual environment 3.Pip install requirements.txt 4.Generate access token and secret key and put in secrets.sh. I've the same SECRET_KEY in settings.py and secrets.sh and I've added secrets.sh to .gitignore 5.Change settings.py as follows: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 'USER': 'name', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '', } } And I cannot run python manage.py migrate results below: (tag_gen) local_user@local_user:~/Repo/tag_gen/generator$ python manage.py runserver Performing system checks... Unhandled exception in thread started by <function wrapper at 0x7febe4712488> Traceback (most recent call last): File "/home/local_user/Repo/tag_gen/tag_gen/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/home/local_user/Repo/tag_gen/tag_gen/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "/home/local_user/Repo/tag_gen/tag_gen/local/lib/python2.7/site-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/home/local_user/Repo/tag_gen/tag_gen/local/lib/python2.7/site-packages/django/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/home/local_user/Repo/tag_gen/tag_gen/local/lib/python2.7/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/home/local_user/Repo/tag_gen/tag_gen/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 16, in check_url_config return check_resolver(resolver) File "/home/local_user/Repo/tag_gen/tag_gen/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 26, in check_resolver return check_method() File "/home/local_user/Repo/tag_gen/tag_gen/local/lib/python2.7/site-packages/django/urls/resolvers.py", line 254, in check for pattern in self.url_patterns: File "/home/local_user/Repo/tag_gen/tag_gen/local/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/local_user/Repo/tag_gen/tag_gen/local/lib/python2.7/site-packages/django/urls/resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) … -
Djoser - User Registration - How to store non required user fields
I am using Djoser and Django Rest Framework for user registration with a custom user model. When I try to add NON REQUIRED fields to my custom user models and pass them (as **kwargs) , these additional fields do not get saved. Is this by design or is there a trick to saving these? class UserManager(BaseUserManager): def create_user(self, email, phone, password, **kwargs): user = self.model( email=email, phone=phone, **kwargs ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, phone, password, **kwargs): user = self.model( email=email, phone=phone, is_staff=True, is_active=True, **kwargs ) user.set_password(password) user.save(using=self._db) return user class User(AbstractBaseUser): userId = models.AutoField(primary_key=True) email = models.CharField(unique=True, max_length=45, null=False) phone = models.CharField(max_length=15, unique=True, null=False) password = models.CharField(max_length=255, blank=True, null=True) is_active = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'User' objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['phone'] def get_full_name(self): return self.email def get_short_name(self): return self.email def natural_key(self): return self.email def __str__(self): return self.email -
At which point in UpdateView is the data saved?
I was wondering when the data given to the UpdateView was saved. I have the following situation: I update a model object via a form. I would expect the changes to the model only to be saved after the Update View's form_valid is through. But when I print the object attributes right at the start of form_valid, they have already changed to the new ones inserted into the form. So when exactly is the change to the model saved and how would I go about if I wanted to do something with the previous values? I am relatively new to Django and I hope that this question is not too far off track. -
Django-helpdesk "Reverse for 'auth_password_change' not found"
I am trying to enable users to change their passwords in django-helpdesk. In the docs, this is done by adding this to settings.py: HELPDESK_SHOW_CHANGE_PASSWORD = True Doing so results in the following error: NoReverseMatch at /helpdesk/tickets/ Reverse for 'auth_password_change' not found. 'auth_password_change' is not a valid view function or pattern name. And points to line 75 in python2.7/site-packages/helpdesk/templates/helpdesk/navigation.html which reads: <li><a href="{% url 'auth_password_change' %}"><i class="fa fa-user-secret fa-fw"></i> {% trans "Change password" %}</a></li> Is this a Django-helpdesk bug or am I missing something? -
Django DRF TemplateHMLRenderer
Trying to display the django rest framework data in an html template: view.py class TestView(viewsets.ModelViewSet): """ test rest""" queryset = models.Pippo.objects.all() serializer_class = PippoSerializer renderer_classes = (JSONRenderer, TemplateHTMLRenderer) template_name = 'pippo_app/test.html' url.py app_name = 'pippo_app' router = routers.DefaultRouter() router.register(r'ertest', views.PippoView) template.html {% load rest_framework %} <html><body> <h1>Profile - {{ dim_spessore }}</h1> {{form}} {% load rest_framework %} <form action="{% url 'pippo_app:pippo-list' %}" method="post"> {% csrf_token %} {% render_form serializer%} <input type="submit" value="Save" /> </form> </body></html> result in : builtins.AttributeError AttributeError: 'str' object has no attribute 'data' the Json call works: Response 200 Status: Ok -
How to update database courses in openedx
I am trying to update my database entries. after restoring sql file, it is showing in database. but not updated in openedx site (lms /cms). also in home page it shows old entries. How can i update gui entries?? -
django on_delete
I have two models in django Photos and Posts (foreign key between them). post = Posts.objects.get(pk=1) post.delete() # all photos is deleted. cascade delete. it's fine but when I want delete from pgadmin DETAIL: Key (id)=(1) is still referenced from table "photos". why I can not delete from pgadmin ? -
How to get multiple places names in Google Places API?
In my Django project, I let users to mark in which city they were recently. I use for this Google Places API - autocomplete with map. I have multiple use cases which I can't figure out to work with Google Places API T&C and this is one of them: There is a filter of users. Each user have chosen their last visited place (so I can store place_id). When user filtered 100 users, they are showed one by one by their cards in results. The card should contain the user's last visited place. So I have to show 100 cards with 100 places (cities). How to do that if I have only place_id's? Should I send 100 detail requests to Google Places API to get name of each city? def user_filter(request): filtered_users = .... for user in filtered_users: api_result = request.get('https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJN1t_tDeuEmsRUsoyG83frY4&key=MY_API_KEY') recent_city_name = parse_from_result(api_result) .... return render(request,....) Although this should teoretically work, it is a big overkill - time consuming and API requests consuming. Is there a better way to do that? I didn't find any bulk request option. -
django stand alone script execute with import fail
python 2.7.11 django 1.8.2 ide pycharm when i execute the script standalone have the import error see the picture: https://i.stack.imgur.com/aIvos.png default the pycharm put the project root into sys.path -
Django template won't let my datetime field pop up or open
I've been experiencing a weird error when using django for loop template, whenever I use my "{% for groups in groups %}" for loop, my datetime field won't open, however when I try to use other context for my loop, it just works. I also just simply copy pasted this modal from my other html page since it has the same function. Already checked if there are any conflicts with id and other loops. Also tried inspecting element on the modal's button, and it shows the correct group id. I have been using the same loop for other functions in this html page and it seems to be working fine as well. Any idea on how to debug this issue? {% for groups in groups %} <!--start ALLOCATE MODAL --> <div id="allocateModal-{{groups.id}}" class="modal fade" role="dialog" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="form-horizontal form-label-left"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span> </button> <h3 class="modal-title" id="myModalLabel">Allocate Device</h3> </div> <div class="modal-body"> <h2>Device List</h2> <table class="table-width table table-striped jambo_table"> <thead> <tr> <th style="width: 10%"></th> <th style="width: 30%">Device</th> <th>Quantity</th> </tr> </thead> <tbody> <tr> <td class="a-center "> <input type="checkbox" id="routerBox" onchange="enableRQty(this)"> </td> <td>Router</td> <td> <div class="col-md-4"> <input type="text" id="routerQty" class="form-control" data-inputmask="'mask': '9'" placeholder="0" disabled> </div> … -
Django Serializer Method Field with 2 or more fields
I need to extend my serializer from existing table. class SER_Assets(serializers.ModelSerializer): asset_id = serializers.SerializerMethodField() asset_name = serializers.SerializerMethodField() def get_asset_id(self, obj): t1 = Tbl.objects.get(tbl_id=obj.id) return t1.asset_id def get_asset_name(self, obj): .. i know this method.. both function going to call same table i want to reduce function. so i need to call single function to return multiple fields. is that possible? -
Pulling data from heroku for django website
I made a website on django and hosted it on heroku. It uses the default sqlite3 database. When adding some entry on the website, the heroku db is updated. I am unable to pull that entry on my local db. When I push any changes to the heroku, all those entries that were added from the website are deleted. How can I pull those entries from heroku? -
forms field not loading
I have designed a model in Django and a form according to it. The below are the both files. models.py from django.db import models class TotalEvent(models.Model): CustomerID = models.CharField(max_length=30) eventID = models.CharField(max_length=100) eventPlace = models.CharField(max_length=100) eventStartTime = models.TimeField(auto_now=False) eventDate = models.DateField(auto_now=False) forms.py from django import forms from django.forms import ModelForm from catering.models import TotalEvent class TotalEventForm(ModelForm): class Meta: model = TotalEvent fields = '__all__' Now, When in my html file I tried this: {% extends "base.html" %} {% block title %}Log-in{% endblock %} {% block content %} <h1>Detail page</h1> <p>Enter your schedule details here</p> <form method="post">{% csrf_token %} {% for field in forms %} {{field}} <input type="submit" value="Submit"/> {% endfor %} </form> {% endblock %} In the output it shows no input fields except the following output Enter your schedule details here Please have a look and let me know where is the error. -
How to make Django forms dynamic (with clickable fields and appearing fields)
In my Django project I have the following model: models.py class Paper(models.Model): title = models.CharField(max_length=500) description = models.CharField(max_length=1500) chapter_1 = models.CharField(max_length=50, default='Intro') chapter_1_status = models.CharField(max_length=3, choices=[('On','On'), ('Off','Off')], blank=True, null=True) chapter_1_description = models.CharField(max_length=1500) chapter_1_word_count = models.IntegerField() chapter_1_reading_time = models.DurationField(blank=True, null=True) chapter_2 = models.CharField(max_length=50, default='Hypothesis') chapter_2_status = models.CharField(max_length=3, choices=[('On','On'), ('Off','Off')], blank=True, null=True) chapter_2_description = models.CharField(max_length=1500) chapter_2_word_count = models.IntegerField() chapter_2_reading_time = models.DurationField(blank=True, null=True) As you can see, apart from title and description all the other fields are repetitive (chapter 1, chapter 2, chapter 3 and so on till chapter 9 which is the maximum for the assigned Paper). I'm using the field status to check whether that chapter will actually be included in the paper or not. If someone picks Off, the chapter won't be showed in the paper. I now need to translate this concept into something more advanced: instead of having the regular Django form for this model, I would like to have a model where users see: title description a list of the chapters available (intro, hypothesis...) and when they click on the specific chapter they want to include all the fields related to that chapter appear. All the chapters that do no get selected or clicked on should be … -
ScreenShot with Selenium no working on the server
I have the following code that works correctly on localhost but does not work on my production server (Ubuntu 16.04). The permissions and ownership of the folder is correct, but yet the screenshot does not save. display = Display(visible=0, size=(800, 1200)) display.start() driver = webdriver.Firefox() driver.get("http://google.com") filename_photo = "test.jpg" driver.save_screenshot(settings.BASE_DIR + filename_photo) time.sleep(0.1) driver.execute_script("window.scrollTo(0, document.body.scrollHeight)") time.sleep(0.1) driver.quit() display.stop() What I am doing wrong? -
Django using email authentication with djoser for login
So i tried using djoser recently and i want to use email instead of username to login. Djoser : http://djoser.readthedocs.io/en/latest/index.html Then i try to customise the token create/login to change from username to email in the serializers.py Original class TokenCreateSerializer(serializers.Serializer): password = serializers.CharField( required=False, style={'input_type': 'password'} ) default_error_messages = { 'invalid_credentials': constants.INVALID_CREDENTIALS_ERROR, 'inactive_account': constants.INACTIVE_ACCOUNT_ERROR, } def __init__(self, *args, **kwargs): super(TokenCreateSerializer, self).__init__(*args, **kwargs) self.user = None self.fields[User.USERNAME_FIELD] = serializers.CharField( required=False ) def validate(self, attrs): self.user = authenticate( username=attrs.get(User.USERNAME_FIELD), password=attrs.get('password') ) self._validate_user_exists(self.user) self._validate_user_is_active(self.user) return attrs def _validate_user_exists(self, user): if not user: self.fail('invalid_credentials') def _validate_user_is_active(self, user): if not user.is_active: self.fail('inactive_account') Edited class TokenCreateSerializer(serializers.Serializer): password = serializers.CharField( required=False, style={'input_type': 'password'} ) default_error_messages = { 'invalid_credentials': constants.INVALID_CREDENTIALS_ERROR, 'inactive_account': constants.INACTIVE_ACCOUNT_ERROR, } def __init__(self, *args, **kwargs): super(TokenCreateSerializer, self).__init__(*args, **kwargs) self.user = None self.fields[User.EMAIL_FIELD] = serializers.EmailField( required=False ) def validate(self, attrs): self.user = authenticate( email=attrs.get(User.EMAIL_FIELD), password=attrs.get('password') ) self._validate_user_exists(self.user) self._validate_user_is_active(self.user) return attrs def _validate_user_exists(self, user): if not user: self.fail('invalid_credentials') def _validate_user_is_active(self, user): if not user.is_active: self.fail('inactive_account') but the result i get in the api is this { "non_field_errors": [ "Unable to login with provided credentials." ] I did try other method but all have same result. Is there a way to make it using of email to authenticate instead … -
Django bulk requests to get status code
I have a text file containing thousand of domains. I want to process text file to get the status code. By reading text file and process domains one by one is working but it taking too long time to press such a large data. f = open('/var/www/api/media/data.txt']), 'rb') key_str = f.read() url_list = key_str.split('\r\n') for url1 in url_list: s = requests.Session() status = s.head(str(url1)) s_code = status.status_code is doing the same whatever I want. I want to process these urls in bulk of 10 or 20 instead of one by one. something like multithreading. Is there other way in django to process these data in faster way???? -
How to get parent pk in django rest framework nested route using GenericAPIView?
I've create the nested route by using https://github.com/alanjds/drf-nested-routers, but I don't know how to get the parent pk inside viewset Sample route: /group/8/users In view.py class UserViewSet(ListModelMixin, generics.GenericAPIView, viewsets.ViewSet): queryset = User.objects.filter(group_pk=group_pk) <-------how to get group_pk serializer_class = UserSerializer -
django migrations how to refer to an inner class inside model
I am looking to refer to a inner class 'Code' under the model 'Evaluation'. Basically both of these options DO NOT work (Option:1) code = apps.get_model('my_project', 'Evaluation.Code') OR (Option:2) evaluation = apps.get_model('my_project', 'Evaluation') code = evaluation.Code Option:1 throws me this error: grzsqrrel@grzsqrreld:~/PycharmProjects/my_project/my_project$ python manage.py migrate local_settings.py not found Operations to perform: Apply all migrations: admin, auth, contenttypes, django_cron, sessions, my_project_app Running migrations: Applying my_project_app.0002_load_items...Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/grzsqrrel/.virtualenvs/my_project/lib/python3.5/site-packages/django/core/management/__init__.py", line 363,... File "/home/grzsqrrel/.virtualenvs/my_project/lib/python3.5/site-packages/django/db/migrations/operations/special.py", line 193, in database_forwards self.code(from_state.apps, schema_editor) File "/home/grzsqrrel/PycharmProjects/my_project/my_project/my_project_app/migrations/0002_load_items.py", line 7, in load_data code = evaluation.Code AttributeError: type object 'Evaluation' has no attribute 'Code' models.py: class Evaluation(models.Model): class Code: 0002_load_items.py def load_data(apps, schema_editor): evaluation = apps.get_model('my_project', 'Evaluation') code = evaluation.Code class Migration(migrations.Migration): dependencies = [ ('my_project', '0001_initial'), ] operations = [ migrations.RunPython(load_data) ] What'd be the fix? Thank you.