Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django form using choices against a queryset causes error if part of initial makemigrations
I would like to understand best practice for this issue. I have a Django form with something like: class AdvancedSearchForm(forms.Form): CATEGORY_OPTIONS = Category.objects.all().order_by('parent_id','primary') categoryAS = forms.ChoiceField( widget = forms.Select(attrs={'class': 'form-control', 'onchange' : 'changeCategory("id_categoryAS");'}), label = '', required = False, choices = ((x.id, x.primary) for x in CATEGORY_OPTIONS), ) If this is the first makemigrations I run for the project I invariably find I get an error message telling me Cateogry.parent_id doesn't exist. In order to run it I need to comment out the choices line, run makemigrations and migrate and then uncomment the choices line. Is this standard practice or what practice should I follow to ensure it works first time. Thanks -
Neo4j and Django, make a Graph for recommendations
We are using Django for our backend REST API and PostgreSQL as DB. Need to build a User graph which has Story as a property for recommendation system. I came across Neo4jDjango many answers here seem to suggest this lib. But the last commit on this was 3 years before. https://github.com/scholrly/neo4django Is there a uptodate lib I can use to seamlessly itegerate it with Django. Using Python2.7 and Django1.11 along side with PostgreSQL, want to use Neo4j just for graph querying. -
python manage.py createsuperuser error import
When i try to use command python manage.py createsuperuser, it gives me errors. Can someone help me please? ImportError: Could not import 'oauth2_provider.ext.rest_framework.OAuth2Authentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'. ImportError: No module named ext.rest_framework. Ubuntu 16 -
Passing context to view from template: NoReverseMatch error
Trying to pass context from template to my view (whether ad=True or False). Here's how I've tried to do it: urls.py url(r'^$', views.post, name='post'), template <a href="{% url 'post' ad='True' %}">Proceed</a> views def post(request, ad=False): ... the ad='True' in the template should pass onto the views and change the default ad=False to ad=True. Instead, I get this error message: NoReverseMatch at /advertise/ Reverse for 'post' with arguments '()' and keyword arguments '{'ad': 'True'}' not found. 1 pattern(s) tried: ['post/$'] Any idea what the problem is? -
Django says that MySQL does not allow unique CharFields to have a max_length > 255, but it does
I've got an existing mysql database with the following table: CREATE TABLE IF NOT EXISTS NetworkServerGroups ( GroupID INTEGER UNSIGNED PRIMARY KEY AUTO_INCREMENT, GroupName VARCHAR(2048) UNIQUE NOT NULL ) After running Django's inspectdb tool, it's generated the following model (I manually modified the class name to remove the trailing 's'): class Networkservergroup(models.Model): groupid = models.AutoField(db_column='GroupID', primary_key=True) # Field name made lowercase. groupname = models.CharField(db_column='GroupName', unique=True, max_length=2048) # Field name made lowercase. class Meta: managed = False db_table = 'NetworkServerGroups' But when I come to run the test server, it complains about the following errors: control_panel.Networkservergroup.groupname: (mysql.E001) MySQL does not allow unique CharFields to have a max_length > 255. But clearly, mysql does support unique CharFields with a length of > 255, because the table was created perfectly fine using the SQL statement above. How do I solve this problem? -
Fromating my url in Python, Django
i would to have my uri to be encoded get_customer_action_by_target_group_url = 'https://api4.optimove.net/current/customers/GetCustomerActionsByTargetGroup' for instance if i enter my campaignID = 19 and the date = 20 Juy 2017 i would like to have mu uri = 'https://api4.optimove.net/current/customers/GetCustomerActionsByTargetGroup?targetGroupID=19&date=20 july 2017' and the result is i cannot get my json response because it doesnt found the correct uri But this doesn't work.. Here is my function def get_customer_action_by_target_group(self): payload = {"TargetGroupID": "%s" % self.TargetGroupID, "Date":"%s" % self.date, } if not self.TargetGroupID or not self.date: get_target_group_id = int(raw_input("Please provide the target Group id:")) get_date = (raw_input("Please provide the date as required:")) self.TargetGroupID = get_target_group_id self.date = get_date response = self.send_request(self.get_customer_action_by_target_group_url + "?" + str(self.TargetGroupID) + "=" + str(self.date), json.dumps(payload), "GET") print response, response.text, response.reason return response -
Django-rest CORS issue
I have installed django-cors-headers and my seetings.py has following: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'rest_framework_docs', 'tasks' ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True However, I still get Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response error when I hit the url from my Angular frontend. Am I missing any configuration? -
request.user returns admin user and not the logged in user
I am building a Django web app with Token Authentication. When I am trying to get username on home page after logging in I get request.user as admin and not the logged in user. Deleted the admin token then too getting the same. My View is ` class GalleryView(TemplateView): template_name = "galleriesView.html" permission_classes = (IsAuthenticated,) def get_context_data(self): context = super(GalleryView, self).get_context_data() print (self.request.user) context['user'] = self.request.GET.get('user') print (context['user']) data = {} o = Organisation.objects.filter(org_user=(Account.objects.filter(email=context['user']))) for org in range(len(o)): g = Gallery.objects.get(organisation=Organisation.objects.filter(name=o[org])) data[o[org]] = g context['org'] = data.keys() context['gallery_results'] = data.values() return context` I get admin and None but not the logged in user -
Generate Text Field with List for Django ForeignKey Field
django ForeignKey field generates normal html select field to select a value from the list. But i want to generate a text filed so that i can search the option from list. Here is the html that need to be generated for a foreign key field. <input id="search-fld" type="text" name="param" placeholder="Find reports and more" data-autocomplete='[ "ActionScript", "Erlang", "Fortran", "Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl", "PHP", "Python", "Ruby", "Scala", "Scheme"]'> -
Import and register all classes from models in admin-django
In myApp, I have multiple classes in models. I would like to import all of these classes in admin.py and register. Is it possible without repetition such as from django.contrib import admin from .models import (classA,classB, classC) Could I import all the items without explicitly referring as done above Could I also register all at one time Thanks Jeff -
connection error of django with mongodb -
I want to connect my django application with mongodb(mongoengine) and sql . and i am using django1.8 and mongoengine. I am getting this error- command prompt- (orahienv) somya@somya-Inspiron-15-3555:/var/www/html/admin_python$ python manage.py runserver Traceback (most recent call last): File "manage.py", line 11, in <module> execute_from_command_line(sys.argv) File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 303, in execute settings.INSTALLED_APPS File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/conf/__init__.py", line 48, in __getattr__ self._setup(name) File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/conf/__init__.py", line 44, in _setup self._wrapped = Settings(settings_module) File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/conf/__init__.py", line 92, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/var/www/html/admin_python/admin_python/settings.py", line 117, in <module> mongoengine.connect("mongodb://root:root@localhost:27017/pom") File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/mongoengine/connection.py", line 257, in connect return get_connection(alias) File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/mongoengine/connection.py", line 215, in get_connection 'Cannot connect to database %s :\n%s' % (alias, e)) mongoengine.connection.MongoEngineConnectionError: Cannot connect to database default : [Errno 111] Connection refused setting.py- import mongoengine mongoengine.connect("mongodb://root:root@localhost:27017/pom") DBNAME = 'pom' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'pom', 'USER': 'root', 'PASSWORD': 'root', 'HOST': 'localhost', }, } -
How can I extract a list of years with django queryset?
I want to get a list of years from MyModel instances date attribute. This is the way I do this now: dates = MyModel.objects.filter(site=site).dates('date', 'year') years = [date.year for date in dates] The result looks like: dates = [datetime.date(2004, 2, 1), datetime.date(2005, 3, 1)] years = [2004, 2005] Does the simpler way to do this exist? -
'utf8' codec can't decode byte 0xdb in position 0: unexpected end of data. You passed in '\xdb' (<type 'str'>) [on hold]
This is my piece of code in which PK is int type. When i try to run my code. def decode_uid(pk): try: from django.utils.http import urlsafe_base64_decode from django.utils.encoding import force_text return force_text(urlsafe_base64_decode(pk)) except ImportError: from django.utils.http import base36_to_int return base36_to_int(pk) I get this error: 'utf8' codec can't decode byte 0xdb in position 0: unexpected end of data. You passed in '\xdb' (<type 'str'>) Thanks in advance. -
Upload any file in django
i was try to create an function for upload file in django. First time i running my code, it's cannot upload file. So, i was try to improve my code and what i got it's error. I thinked the error it's weird, because i was always use that and i never get error. I'll show my code. models.py class UploadFiles(models.Model): File = models.ImageField(upload_to = 'Images/', default='Images/') views.py def upload_file(request): if request.method == 'POST': form = UploadFile(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('home') else: form = UploadFile() return render(request, 'girl/upload.html', {'form': form}) forms.py class UploadFile(forms.Form): title = forms.CharField(max_length=50) file = forms.FileField upload.html {% extends 'girl/base.html' %} {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Upload</button> </form> <p><a href="{% url '/' %}">Return to home</a></p> {% endblock %} error: django.urls.exceptions.NoReverseMatch: Reverse for '/' not found. '/' is not a valid view function or pattern name. -
How to make div elements stand in one line, some divs cannot float left
I am using bootstrap with django templates, I am populating main content with product elements (divs with different height). Because of the difference in height some divs cannot float properly, I put a screenshot below. How can I fix it. Here is code which generates content: <div class="panel-body"> <div class="row product-container"> {% for product in products %} <div class="col-xs-6 col-sm-6 col-md-4 col-lg-3"> <div class="product_unit"> <img src="http://placehold.it/480x400" alt=""> <div id='quick-view'> <a href="#">product.name</a> </div> <div class="product_unit_desc"> <h4>{{ product.name }}</h4> <div class="ratings"> <p class>12 reviews</p> <p> <span class="glyphicon glyphicon-star"></span> <span class="glyphicon glyphicon-star"></span> <span class="glyphicon glyphicon-star"></span> <span class="glyphicon glyphicon-star"></span> <span class="glyphicon glyphicon-star-empty"></span> </p> </div> <p>$12.43</p> </div> </div> </div> {% endfor %} <!-- DYNAMIC GENERATED CONTENT BY DJANGO --> </div> <!-- END OF ROW --> </div> EDIT: float: left; did not help -
Using javascript with python and django
I made a web application using python in django framework, now I want to add a functionality that the data that I'm fetching from python, more data should get loaded on scrolling the webpage and this can be easily achieved by using JQuery. I wanted to know if it is possible or not, because we pass data into a data dictionary from python to html page. So is it possible to send data in chunks rather than sending the complete data in the data dictionary. I'm fetching this data from Elasticsearch into python, then giving this data into a data dictionary, passing this data dictionary to the html page and hence displaying the data on the webpage. Please help me with this.. I'm really stuck here, Your help is appreciated. -
Customization of Django admin page to add button
I want to add additional button in the admin page other than save , delete and save and continue button.I do know that I should change the default page of admin but I couldn't able to implement it.I can understand it theortically but not in practical.I want steps to change the default program of Django admin page.I need a demo for it.I need a little brief explaination. -
Zipping selected object's pdf in Python Django
I have an Index view that displays Trainer name, location, etc as well s a button to download their Profile(already in database as a pdf). I search and filter these based on some parameters. Now i want to be able to select a few of these and download the selected Trainer Profiles.Im new to Django and can't figure out how to do that. Here's my code. It says 'FieldFile object is not callable' views.py def download(request): import zipfile import os file = zipfile.ZipFile("C:\\Downloads\\test.zip", "w") filelist = [] filelist+= 'Trainer.checkboxoption' in request.REQUEST for i in filelist: file.write(i) file.close() return render(request,'trainer/index.html') index.html <form action="download/" method="post"> <div class="caption"> <div > <table style="width:100%" class="table"> <tr> <th>#</th> <th>Name</th> <th>Technology</th> <th>Location</th> <th> View</th> <th>Download</th> <th>Delete</th> </tr> {% for trainer in all_trainers %} <tr> <td><input type="checkbox" id="trainer{{ forloop.counter }}" name="trainer" value="{{ trainer.id }}"></td> <td> <a href="/trainer/{{ trainer.id }}">{{ trainer.name }}</td> <td>{{ trainer.technology }}</td></a> <td>{{ trainer.location }}</td> <!-- View Details --> <td><a href="/trainer/{{ trainer.id }}" class="btn btn-primary btn-sm">View Details</a></td> <td><a href="../media/{{ trainer.trainer_profile }}" class="btn">Download PDF</a></td> <!-- Delete Album --> <td><form action="trainer/{{trainer.id }}/delete/" method="post"> {% csrf_token %} <input type="hidden" name="trainer_id" value="{{ trainer.id }}" /> <button type="submit" class="btn btn-default btn-sm"> <span class="glyphicon glyphicon-trash"></span> </button> </form></td> </tr> {% endfor %} </table> … -
How to display all available choices of a manytomany field in django admin using filter_horizontal
I have two models that have many to many relationship. One model consists of all possible choices and the other model can have some or all of those choices. These are the two models: class LanguageDomains(models.Model): DOMAIN_CHOICES=( ('Choice1', _(u'Choice1')), ('Choice2', _(u'Choice2')), ('Choice3', _(u'Choice3')), ('Choice4', _(u'Choice4')), ) # There is many more choices in the actual code domains = models.CharField(max_length=255, choices=DOMAIN_CHOICES, default=None) def __unicode__(self): return self.domains class Revitalization(models.Model): code = models.ForeignKey(Codes, related_name ='revitalization') program_name = models.CharField(max_length=255, null=True, blank=True) year_founded = models.CharField(max_length=4, null=True, blank=True) some_domains = models.ManyToManyField(LanguageDomains, related_name='revitalization') def __unicode__(self): return self.code.primary_name My admin.py: class RevitalizationAdmin(admin.ModelAdmin): list_display = ('code','id') filter_horizontal = ('language_domains',) This is what the admin console looks like: The question is, is there a way to populate the "Available language domains" list with all the DOMAIN_CHOICES from LanguageDomains model? -
React using JQuery post+get data
I use this to get the todos from Django server: getTodos(){ $.ajax({url: "http://localhost:8000/todos/", success: function(data){ this.setState({todos:data},function(){console.log(data)})}.bind(this), cache: false}); } and this to post a new todo as well as update the state: handleAddTodo(title,text){ $.post("http://localhost:8000/todos/",{title:title,text:text},this.getTodos()); } So the callback function this.getTodos() will fetch the new data from the server. But it seems the server side is not updated? In the picture, the first log is from the initial data fetch. The last is from the callback function. -
Django-create filters based on each field using Q object and if elif condition
I am using Q objects and I want result for all combinations of input from CompanyUrl,Subject,Class fields. please suggest the right code for if else condition with Q object. elif (Q("CompanyUrl" in request) & Q("Subject" in request)): queryset = Product.objects.filter(Q(CompanyUrl=request['CompanyUrl']) | Q(Subject=request['Subject'])) elif (Q("CompanyUrl" in request) & Q("Class" in request)): queryset = Product.objects.filter(Q(CompanyUrl=request['CompanyUrl']) | Q(Class=request['Class'])) elif (Q("Subject" in request) & Q("Class" in request)): queryset = Product.objects.filter(Q(Subject=request['Subject']) | Q(Class=request['Class'])) elif (Q("CompanyUrl" in request) & Q("Subject" in request) & Q("Class" in request)): queryset = Product.objects.filter(Q(CompanyUrl=request['CompanyUrl']) | Q(Subject=request['Subject']) | Q(Class=request['Class'])) elif (Q("CompanyUrl" in request) | Q("Subject" in request) | Q("Class" in request)): queryset = Product.objects.filter(Q(CompanyUrl=request['CompanyUrl']) | Q(Subject=request['Subject']) | Q(Class=request['Class'])) serializer = ProductSerializer(queryset,many=True) for item in serializer.data: sendData.append({"ProductName":item['ProductName']}) it is giving result for some input and error for some....Am I doing it right??? please help..thnks -
Exact use of Django's forms.Form class
i have searched out that django's forms.Form class is used for maintaining and validating the HTML form but now we have HTML5 in which we validate form itself with brief rules so is it necessary to used django's forms.Form class? -
Django Unittest fails when run parallel on CircleCI
I am running Django Unit tests on CircleCI with 1 container setup. The tests run fine when I do not add Django's --parallel argument. However, when I add --parallel=2 to the test run, it fails with this cryptic error below. I've tried both versions: with and without --keepdb - both fail with exactly the same error. The code for _clode_test_db appears to suggest that passing --keepdb=True should fail fast and return. See django/db/backends/mysql/creation.py line: 29 here [https://github.com/django/django/pull/4761/files] Would appreciate any ideas on what is going on here Using existing clone for alias 'default' ('test_django_learned')... Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/circleci/sliderule/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/home/circleci/sliderule/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 345, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/circleci/sliderule/venv/lib/python2.7/site-packages/django/core/management/commands/test.py", line 30, in run_from_argv super(Command, self).run_from_argv(argv) File "/home/circleci/sliderule/venv/lib/python2.7/site-packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/home/circleci/sliderule/venv/lib/python2.7/site-packages/django/core/management/commands/test.py", line 74, in execute super(Command, self).execute(*args, **options) File "/home/circleci/sliderule/venv/lib/python2.7/site-packages/django/core/management/base.py", line 399, in execute output = self.handle(*args, **options) File "/home/circleci/sliderule/venv/lib/python2.7/site-packages/django/core/management/commands/test.py", line 90, in handle failures = test_runner.run_tests(test_labels) File "/home/circleci/sliderule/venv/lib/python2.7/site-packages/django/test/runner.py", line 532, in run_tests old_config = self.setup_databases() File "/home/circleci/sliderule/venv/lib/python2.7/site-packages/django/test/runner.py", line 482, in setup_databases self.parallel, **kwargs File "/home/circleci/sliderule/venv/lib/python2.7/site-packages/django/test/runner.py", line 733, in setup_databases keepdb=keepdb, File "/home/circleci/sliderule/venv/lib/python2.7/site-packages/django/db/backends/base/creation.py", line 219, in clone_test_db self._clone_test_db(number, verbosity, keepdb) File "/home/circleci/sliderule/venv/lib/python2.7/site-packages/django/db/backends/mysql/creation.py", line … -
image not saving on django models
I created an album with a photos as foreign key but somehow when i add a photo it does not save probably in my database or admin site Blockquote Heres my models: class AlbumPluginModel(CMSPlugin): name = models.CharField(max_length=255, help_text=_('e.g: Zuerich city, or Zuerich Hoengg')) slug = models.SlugField(_('Slug'), blank=True, null=True, unique=True, db_index=True) description = HTMLField(blank=True, null=True) cover_photo = models.ImageField(verbose_name=_('Add cover photo'), null=True, blank=True) is_active = models.BooleanField(_('active'), blank=True) date_created = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) sort = models.IntegerField(_("Sort Order"), null=True, blank=True, default=0) def __str__(self): if self.name: return u"File for %s" % self.name else: return u"%s" % self.name def get_absolute_url(self): return "/album_detail%i/" % self.id class Meta: ordering = ['sort'] verbose_name = "Album" verbose_name_plural = "Albums" class Photo(models.Model): photo = models.ForeignKey(AlbumPluginModel, verbose_name=_('choose album'), null=True, blank=True) image1 = models.ImageField(verbose_name=_('Photo'), null=True, blank=True, upload_to="/static/img/") sort = models.IntegerField(_("Sort Order"), null=True, blank=True, default=0) def __unicode__(self): return u"%s" % self.image1 def __str__(self): return u"%s" % self.image1 class Meta: ordering = ['sort'] verbose_name = _("photo") verbose_name_plural = _("Photos") forms.py class AlbumPluginForm(forms.ModelForm): class Meta: model = AlbumPluginModel fields = ['name', 'description', 'cover_photo', 'is_active',] class PhotoPluginForm(forms.ModelForm): photo = forms.ModelChoiceField(label='select album',aqueryset=AlbumPluginModel.objects.all(), required=False) class Meta: model = Photo fields = ('photo', 'image1', ) views.py def add_photo(request, id=None, **kwargs): if request.method == 'POST': all_photos = Photo.objects.all form = … -
Debugging Django in VSCode fails on imp.py
I am unable to debug my Django app. I am using virtualenv and have configured my VSCode workspace to point to the absolute path within my virtual environment for python. "python.pythonPath": "/Users/Me/PyProjs/proj_env/bin/python" When trying to debug, however, the editor jumps to the imp.py file (which is located at ~/proj_env/lib/python3.4) and fails at the new_module() method. def new_module(name): """**DEPRECATED** Create a new module. The module is not entered into sys.modules. """ return types.ModuleType(name) #Editor breaks here. Inspecting the name variable, I see it is set to "__main__". When stepping through, the editor exits debug mode and no errors or exceptions are logged in the Debug Console. Anybody know what my issue could possibly be? I just want to debug my application!