Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Filter many-to-many relationship by user and show in template Django
I'm stucked with a problem. I'm developing e-Learning application and have this model (simplified for better understanding): class Course(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=255) enrolled = models.ManyToManyField(get_user_model(), through='Enrol', related_name="course_enrolled") teacher = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name="course_teacher") class Section(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=255) course = models.ForeignKey(Course, on_delete=models.CASCADE) class Classe(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=255) content = models.TextField() section = models.ForeignKey(Section, on_delete=models.CASCADE) completed = models.ManyToManyField(get_user_model(), through='ClassCompleted', related_name="classes_completed") class Enrol(models.Model): student = models.ForeignKey(get_user_model()) course = models.ForeignKey(Course, on_delete=models.CASCADE) active = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class ClassCompleted(models.Model): student = models.ForeignKey(get_user_model()) classe = models.ForeignKey(Classe, on_delete=models.CASCADE) completed = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) My View for the Course page. This page has to show the Sections and Classes. @login_required def ead_course(request, course_id): try: course = Course.objects.get(id=course_id) except Course.DoesNotExist: raise Http404 # Check if student is enroll or is a teacher if request.user.course_enrolled.filter(id=course_id).exists() or course.teacher.id is request.user.id: return render(request, 'ead/ead_course.html', {'course': course}) return HttpResponse("Without permission") And finally my template ead_course.html: {% for section in course.section_set.all %} {{ section.name }} {% for class in section.classe_set.all %} {{ class.name }} {% endfor %} {% endfor %} Everything is fine until now, I'm showing for user all the sections and the classes. The big problem is: I โฆ -
How to create Django Model with combination of 2 models
I want to create one Django models which is the combination of 2 models like, class Employee(models.Model): name = models.CharField(max_length=45) age = models.IntegerField() dob = models.DateField() addr = models.CharField(max_length=45) class designtion(models.Model): emp_id = models.charField(max_length=45) role_name = models.charField(max_length=45) starts_from = models.DateField() ends_on = models.DateField() i want to create a combined models from these 2, class EmpDetails(models.Model): name = models.CharField(max_length=45) role_name = models.charField(max_length=45) i am using django-rest-framework is their any best way to do like this? -
Format a string into Date or any other datatype in Django
I am using Python 3.6 with Django 1.11. My Back-end DB is Salesforce. I am trying to save date field in Salesforce which is accepted from user in the form of String str_var = '11/09/2017' want it to be converted like not_a_str_var = 11/09/2017 I tried with several datetime, date functions but no success. I have also tried using strptime() and strftime() methods. Please suggest -
passing the input value of search bar as a parameter in button onclick
How can I pass the value entered by user in the search bar with the link in the button. <form> <input type="text" id="search" class="st-search-input search-field" value="abc"/> <button type="submit" onclick='window.open("test4?abcd=\"search.value\"");'>Submit</button> </form> -
`~Q` do not work in my filter?
I want to query the status != 4: from django.db.models import Q ... queryset = User.objects.filter(is_staff=True, is_admin=True, ~Q(status = 4), ) But I gets wrong: How to do with that? seems the ~Q do not work? -
cannot load image in html template in django application
I am trying to put an image in html template in my django applicarion but its is not displayed. When i inspect, it says image cannot be loaded. HTML code: <div class = "col-md-4"> <img src= "/static/images/abc.jpg" alt="sorry"/> </div> location of the image abc.png is /home/user/demo/mysite/mysite/static/images/abc.png and my django application is bookmark which resides in mysite(demo/mysite) Is it the correct way of giving path in a django application or something else needs to be done. -
How do I make Heroku run yarn install or npm installl in a subdirectory
Let's say I have a project with the following directory structure project/ ... subdir/ node_modules package.json yarn.lock As you can see my yarn.lock, package.json, and node_modules are a subdirectory. Heroku expects them to be in the root directory. Heroku just runs "yarn install" from the root of the project. I'm trying to figure out how to tell Heroku to run "yarn install" from the one_raft_first_site subdirectory. How do I do this? -
Restrict multiple user access to a model in django admin
I have multiple admin users in my system, and all of them can able to login into the system at a time into the django admin area (http://127.0.0.1:8000/admin). I have a model called Book and all of this users can able to view/edit/save this model at a time in the django admin interface. class Book(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=45) author = models.CharField(max_length=45) category = models.CharField(max_length=45) comment = models.CharField(max_length=1024, blank=True, null=True) class Meta: managed = False db_table = 'book' What i want to achieve is i want to restrict the multiple user access to the Book model. For example when a user1 viewing/editing/saving a book object in django admin interface i want to restrict other users to access this Book model, basically all actions should be restricted. -
request parameter cannot be gotten
Request parameter cannot be obtained. I want to search whether "file" is in request parameter or not. I written the following code: def common_logic(request): data = request.POST.get('data', None) if 'file' in request.POST: file = request.FILES['file'].temporary_file_path() else: file = None return file However, when I set file parameter, always else statement is read. When I print out print(request.POST), <QueryDict: {'data': ['100']}> is shown so file parameter cannot be obtained. I want to get file parameter and search whether request.POST has file or not. Why can't I get file parameter? How can I get this? -
How to view an image uploaded in Django
Hello I would like to ask on how to view an image that I uploaded in django admin to selected html page, this is my html, there is no problem with the object title but I cant seem to load the image. <h3>{{object.title}}</h3> {% if object.productimage_set.count > 0 %} <div> {% for img in object.productimage_set.all %} {{ img.image.file}} <img class='img-responsive' src='{{ img.image.url }}'/> {% endfor %} </div> def image_upload_to(instance, filename): title = instance.product.title slug = slugify(title) file_extension = filename.split(".")[1] new_filename = "%s.%s" %(instance.id, file_extension) return "products/%s/%s" %(slug, new_filename) class ProductImage(models.Model): product = models.ForeignKey(Product) image = models.ImageField(upload_to=image_upload_to) def __unicode__(self): return self.product.title -
Deploying django on azure - scriptprocessor could not be found
I am having some trouble setting up my website on Azure. My website is developed using Django and I am using wfastcgi to run it on the server; but the server keeps giving an error that says, "scriptProcessor could not be found in application configuration." Here is the error exactly: Here is my web.config file: <?xml version="1.0"?> <configuration> <appSettings> <add key="WSGI_HANDLER" value="django.core.wsgi.get_wsgi_application()" /> <add key="PYTHONPATH" value="D:\home\Python27" /> <add key="DJANGO_SETTINGS_MODULE" value="iasf.settings" /> </appSettings> <system.web> <compilation debug="true" targetFramework="4.0" /> </system.web> <system.webServer> <modules runAllManagedModulesForAllRequests="true" /> <handlers> <remove name="Python27_via_FastCGI" /> <remove name="Python34_via_FastCGI" /> <add name="Python FastCGI" path="handler.fcgi" verb="*" modules="FastCgiModule" scriptProcessor="D:\home\Python27\python.exe|D:\home\Python27\Lib\site-packages\wfastcgi.py" resourceType="Unspecified" requireAccess="Script" /> </handlers> <rewrite> <rules> <rule name="Static Files" stopProcessing="true"> <conditions> <add input="true" pattern="false" /> </conditions> </rule> <rule name="Configure Python" stopProcessing="true"> <match url="(.*)" ignoreCase="false" /> <conditions> <add input="{REQUEST_URI}" pattern="^/static/.*" ignoreCase="true" negate="true" /> </conditions> <action type="Rewrite" url="handler.fcgi/{R:1}" appendQueryString="true" /> </rule> </rules> </rewrite> </system.webServer> </configuration> -
Python3 + Google App Engine + MySQL
I have been struggling with this for quite awhile now and I cannot seem to find the answer anywhere... I am using this tutorial to set up a django app using Google app engine: https://cloud.google.com/python/django/appengine I am now on the step "Run the app from your local computer" I am recieving the following error when I try and run the django mirgate commands: django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on '127.0.0.1' ([Errno 61] Connection refused)") Any idea where how I can fix this? I tried to install mysqlclient using pip however i got the following error also: Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/yt/ykmtcb9j4tzfxh3rmzfmzxkh0000gp/T/pip-build-xzqmic32/mysqlclient/ Any help would be greatly appreciated! -
Django Manager isn't available; 'auth.User' has been swapped for 'users.MyUser'
I created Custom UserModel in Django 1.11 and I need a function which allows users to sign in I think my custom user model is incompatible with my function How can I fix? error message enter image description here users.models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from apps.teams.models import Team import uuid class MyUserManager(BaseUserManager): def _create_user(self, username, password, **extra_kwargs): user = self.model(username=username, **extra_kwargs) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, password, **extra_kwargs): extra_kwargs.setdefault('is_active', True) extra_kwargs.setdefault('is_superuser', True) extra_kwargs.setdefault('is_staff', True) if extra_kwargs.get('is_superuser', None) is not True: raise ValueError('๊ด๋ฆฌ์ ๊ถํ์ด ํ์ํฉ๋๋ค.') return self._create_user(username, password, **extra_kwargs) class MyUser(AbstractBaseUser): """ ์ ์ ๋ชจ๋ธ """ POSITION_TYPES = ( ('a', '๋ํ'), ('b', 'ํ์ฅ'), ('c', '๊ณผ์ฅ'), ('d', '๋๋ฆฌ'), ('e', '์ฃผ์'), ('f', '์ฌ์'), ('g', '์ธํด'), ) uid = models.UUIDField( primary_key=True, editable=False, default=uuid.uuid4, verbose_name='ํ ๊ณ ์ ์์ด๋' ) username = models.CharField( max_length=20, unique=True, verbose_name='์์ด๋' ) name = models.CharField( max_length=10, verbose_name='์ด๋ฆ' ) email = models.EmailField( verbose_name='์ด๋ฉ์ผ' ) team = models.ForeignKey( Team, verbose_name='์์', null=True, blank=True ) position = models.CharField( max_length=2, choices=POSITION_TYPES, default='g', verbose_name='์ง๊ธ' ) birth = models.DateField( null=True, blank=True, verbose_name='์์ผ' ) date_joined = models.DateField( null=True, blank=True, verbose_name='์ ์ฌ์ผ' ) date_exited = models.DateField( null=True, blank=True, verbose_name='ํด์ฌ์ผ' ) is_superuser = models.BooleanField( default=False, verbose_name='๊ด๋ฆฌ์ ์ฌ๋ถ' ) is_staff = models.BooleanField( default=False, verbose_name='์คํ๋ธ ์ฌ๋ถ' ) is_active = โฆ -
How can I configure GeoNode to PUBLIC IP?
I am new to GeoNode, I Installed geonode on my server with my local ip, then its work perfectly, then I linked PUBLIC IP to my server, after that I can access geonode from public IP, but layer preview not worked, So as here said Configuring GeoNode for Production I changed GeoServer Proxy URL (It was http://localhost:8080/geoserver and I changed it to http://PUBLIC_IP/geoserver and tried as http://PUBLIC_IP:8080/geoserver, from browser I can access geoserver from those 2 url ) now layer preview working fine, but file upload not working, Its time out. If I set GeoServer Proxy URL with local IP its working, I changed django_site postgres table domain to public IP but not worked. How can I fixed it.