Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Regist form cannot be sent
Regist form cannot be sent. I wrote in views.py def login(request): login_form = LoginForm(request.POST) regist_form = RegisterForm(request.POST) if login_form.is_valid(): user = login_form.save() login(request, user) context = { 'user': request.user, 'login_form': login_form, 'regist_form': regist_form, } return redirect('profile') context = { 'login_form': login_form, 'regist_form': regist_form, } return render(request, 'registration/accounts/login.html', context) in login.html <body> <ul class="top-menu"> <h3 class="login">Login</h3> <div class="container"> <form action="{% url 'login' %}" method="post" role="form"> {% csrf_token %} <div class="form-group"> <label class="email_form">Email</label> <input for="id_email" name="email" type="text" value="" placeholder="Email" class="form-control"/> </div> <div class="form-group"> <label class="password_form">Password</label> <input id="id_password" name="password" type="password" value="" minlength="8" maxlength="12" placeholder="Password" class="form-control"/> </div> <button type="submit" class="btn btn-primary btn-lg">Login</button> <input name="next" type="hidden" value="{{ next }}"/> </form> </div> </ul> <div class="newaccount"> <h2>New Account registration</h2> <form class="form-inline" action="{% url 'accounts:detail' %}" method="POST"> <div class="form-group"> <label for="id_username">Username</label> {{ form.username }} {{ form.username.errors }} </div> <div class="form-group"> <label for="id_email">Email</label> {{ form.email }} {{ form.email.errors }} </div> <div class="form-group"> <label for="id_password">Password</label> {{ form.password1 }} {{ form.password1.errors }} </div> <div class="form-group"> <label for="id_password">Password(conformation)</label> {{ form.password2 }} {{ form.password2.errors }} <p class="help-block">{{ form.password2.help_text }}</p> </div> <button type="submit" class="btn btn-primary btn-lg">Regist</button> <input name="next" type="hidden"/> {% csrf_token %} </form> </div> </body> in forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.forms import AuthenticationForm from .models import User class … -
Access Django's class model and display on template
I am new to django and is working on my pet project. I am having a bit of problem accessing the data from one of my classes in models.py models.py class Team_Region(models.Model): name = models.CharField(max_length=50) # String representation def __str__(self): return self.name class Team_Name(models.Model): t_name = models.CharField(max_length=100) logo = models.ImageField(upload_to='team_logos', blank=True) region_member = models.ForeignKey(Team_Region, related_name='regions') def __str__(self): return self.t_name + ' - ' + str(self.region_member) class Team_Member(models.Model): mem_name = models.CharField(max_length=100) position = models.CharField(max_length=50) member_of_team = models.ForeignKey(Team_Name, related_name='teams') def __str__(self): return self.mem_name + ' - ' + self.position + ' - ' + str(self.member_of_team) views.py # Display regions in list class TeamRegionListView(ListView): context_object_name = 'regions_list' model = Team_Region template_name = 'dota_teams/team_regions_list.html' # Display all teams associated to the region class TeamRegionDetailView(DetailView): context_object_name = 'region_teams' model = Team_Region template_name = 'dota_teams/team_regions_detail.html' class MemberDetailView(DetailView): context_object_name = 'team_members' model = Team_Name template_name = 'dota_teams/member_detail.html' urls.py url(r'^$', views.TeamRegionListView.as_view(), name='all_regions'), url(r'^(?P<pk>\d+)/$', views.TeamRegionDetailView.as_view(), name='region_teams'), url(r'^(?P<pk>\d+)/(\d+)/$', views.MemberDetailView.as_view(), name='member_details'), I'm not sure how to access the mem_name and position variables under the Team_Member class. In my views.py, if I use the model Team_Name, the ID is not properly assigned to the region and team. I have tried accessing the Team_Member by using a For loop from Team_Region and use … -
Python Django button not redirecting correctly according to URL
I implemented my own map-search form such that once map-search is clicked it would use the onclick search function. function search() { var query = document.getElementById("search").value; if (query == ""){ $("#button-group").addClass("hidden"); }else{ $("#button-group").removeClass("hidden"); jsonLayer.clearLayers(); $.getJSON('http://localhost:8000/search/'+ query, function (boundary) { jsonData = boundary[0].geojson; jsonLayer.addData(jsonData); lon = boundary[0].lon; lat = boundary[0].lat; boundingbox = boundary[0].boundingbox; map.fitBounds([ [boundingbox[0],boundingbox[2]], [boundingbox[1],boundingbox[3]] ]); }); } } After that function is fired, the button-group, that is initially hidden will be revealed. I tried clicking one of the buttons that was revealed which I have set to go to another template in Django but instead it will append in the url my query resulting to: http://localhost:8000/?search=Test <div class="col-lg-offset-3 col-lg-6"> <div class="input-group"> <input id="search" name="search" type="text" class="map-search form-control input-sm"> <span class="input-group-btn"> <button class="map-search btn btn-default btn-sm" type="button" onclick="search()"> <span class="glyphicon glyphicon-search"></span> </button> </span> </div> <div id="button-group" class="button-group hidden"> <a href="{% url 'trips_view' %}"><button class="btn btn-primary btn-lg btn-space col-sm-3">View Trips</button></a> <a href="{% url 'manage' %}"><button class="btn btn-primary btn-lg btn-space col-sm-3">Manage Trips</button></a> </div> </div> My Url url(r'^view/', views.trips_view, name='trips_view') I checked my network and it would go in this order: 1.) localhost:8000 2.) Click map-search -> it loads query 3.) Click button from button-group with url to another template 4.) It will … -
Django 1.8 csrf NameError: Undefined
I am using Django_Mako_Plus on top of Django. And as I try to put a ${csrf_input} after my form. I am getting a NameError: Undefined. The middleware is correct. What am I doing wrong? Below is my code: <div class="backgroundregister"> <form id="registerform" action="/homepage/register" method="post" style="margin-top: -7vh;">${csrf_input} <div class="form-group" id="register-id"> ${ form.as_table() } <button style="margin-top:15px; height:40px; width:300px; margin-left:3px; margin-top:30px;" type="submit" class="dissimulation"> </div> </form> </div> I am using Django 1.8 Thank you for all your help in advance. -
How filter by a foreign key on Django 1.11
I'm trying to search on CRUD by a field that's a foreign key, but I allways get the error: Related Field got invalid lookup: icontains That's was my admin.py: from django.contrib import admin from .models import Subject class SubjectAdmin(admin.ModelAdmin): list_display = ['owner', 'name', 'slug'] search_fields = ['owner', 'name', 'slug'] prepopulated_fields = {'slug': ('name',)} admin.site.register(Subject, SubjectAdmin) I saw on a forum that I need to change the "owner" by "owner__name", but now I get another error: Related Field got invalid lookup: name -
Cannot connect to remote PostgreSQL instance from Django app running within Docker container
I am trying to connect a Django app running inside of a docker container to a PostgreSQL database running on another computer (lets say with an IP address of 192.168.1.22). Thus far in my experimentation, I always get the following error when attempting to connect to the PostgreSQL instance from a docker container (my code works fine outside of the docker container): Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432? I've made sure that I allow all inbound connections to the PostgreSQL database (by changing the config file for my PostgreSQL server as recommended here. Here is my settings code in my Django app for the database connection: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'sa_server_db', 'USER': 'sa_admin', 'PASSWORD': 'PAfk17!x!?', 'HOST': '192.168.1.22', 'PORT': '5432', } } Here is my Dockerfile: FROM python:3.6 ENV PYTHONUNBUFFERED 1 # Install dependencies RUN mkdir /config ADD /config/requirements.pip /config/ RUN pip install -r /config/requirements.pip # Install source code RUN mkdir /src WORKDIR /src COPY ./src/ /src/ ENV UWSGI_WSGI_FILE=/src/xxxxxxxxx/wsgi.py UWSGI_HTTP=:8000 UWSGI_MASTER=1 UWSGI_WORKERS=2 UWSGI_THREADS=8 UWSGI_UID=1000 UWSGI_GID=2000 UWSGI_LAZY_APPS=1 UWSGI_WSGI_ENV_BEHAVIOR=holy RUN python /src/manage.py collectstatic --noinput EXPOSE 8000 CMD ["uwsgi", "--http-auto-chunked", "--http-keepalive"] Here is the script I use to build (& run) my … -
csfr token needed for form created in template - django
I have a django project and I want to create a form within an html template that is dynamic in the sense that it changes based on what is grabbed from the database. If I want to create a form in this manner - within the html. Do i need to include the csfr tocken to the form before processing the form? -
data How to keep form when user gets redirected back to the form when they fail a validation (Python, Django)?
I know this might be a duplicate question, but the previous one was an older question and those questions uses a form instance which doesn't really help me. How do I keep my form data after a failed validation? I have multiple dropdowns and input fields and I hate to see my users re-do and re-type everything when they fail validation in the backend. Let's say I have this very simple form: HTML: <form class="" action="/register" method="post"> <label for="">First Name</label> <input type="text" name="" value=""> <label for="">Last Name</label> <input type="text" name="" value=""> <label for="">Password</label> <input type="password" name="" value=""> </form> views.py: def register(self): ..... if errors: for err in errors messages.errors(request, err) return redirect('/') else: messages.success(request, "Welcome User!") return redirect('/dashboard') Most examples that I came across were using the form instance which uses form.save() etc. I opted out on that one. Is there a way to auto-populate my form with the data that the user submitted if they were to fail validation? Thanks! -
ModelSerializer is not saving changes to DATA when passed back to the view in DRF but are shown in the serializer
I've seen several questions that sound related on SO and GitHub, but I haven't been able to resolve my issue. Also read through the ModelSerializer section in the DRF documentation: http://www.django-rest-framework.org/api-guide/serializers/#modelserializer Anyway, I am sending part of unique URL that is emailed to the user to DRF for validation. When it has been validated it should allow the user to answer the security questions associated with the account. It is supposed to update the data object with the security questions so that they can be rendered in React. When I print(data), it shows the sq1 and sq2 that I set while still in the serializer. When it gets back to the view.py, and I print out print(new_data), it is just showing the original data sent from React to the API. From what I gather it is related to ModelSerializer, but am not finding a fix for my situation. How do I update the data so it returns my changes back to the ./view.py and React? # ./views.py class ValidateKeyAPIView(APIView): permission_classes = [AllowAny] serializer_class = ValidateKeySerializer def post(self, request, *args, **kwargs): data = request.data serializer = ValidateKeySerializer(data=data) if serializer.is_valid(raise_exception=True): new_data = serializer.data print(new_data) return Response(new_data, status=HTTP_200_OK) return Response(serializer.errors, status=HTTP_400_BAD_REQUEST) # ./serializers.py … -
different text depending on if user has liked a post
I have this if statement in my template to display different buttons depending on if a user had like a post. There are the same trigger link, url, and view, however the text either says "Like" or "Unlike" depending on if the user has previously liked that post or not. However it is not working, no errors, just not working. likes is a ManyToManyField in the UserPost model. Template: {% if request.user.username in post.likes %} <a class="link right-margin" href="{% url 'feed:post_like' post.id %}"> Unlike: {{ post.likes.count }} </a> {% else %} <a class="link right-margin" href="{% url 'feed:post_like' post.id %}"> Like: {{ post.likes.count }} </a> {% endif %} -
Django: Cannot access variable set in middleware
I am trying to add a variable to my request variable in my custom middleware. Later I want to access that variable from my view. Here are the relevant bits: middleware.py class DomainInterceptMiddleware(object): def process_request(self, request): request.myvar = 'whatever' settings.py - Added this above CommonMiddleware MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'page.middleware.DomainInterceptMiddleware', # 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] views.py def index(request): output = request.myvar return HttpResponse(output) However, on trying to access /index, I get this error File "/path/to/views.py", line 32, in index output = request.myvar AttributeError: 'WSGIRequest' object has no attribute 'myvar' Where am I going wrong? -
Deploying with zappa, Django project in subfolder
I'm new to Docker, AWS Lambda and Zappa, but I'm trying to configure a project with very little success. I connect to Docker (docker-compose run web bash), activate the environment, configure the AWS credentials and run zappa init and zappa deploy. However, after deployment I get an error (executing zappa tail): ModuleNotFoundError: No module named 'project' I believe that that's because my dir structure is not the standard: Dockerfile zappa_settings.json requirements.txt project\ - manage.py - root\ - settings.py - wsgi.py - ... So, my django project is inside the project folder, as I don't like having all the files thrown there and mixed with other configuration files. My zappa config file looks like this: { "dev": { "aws_region": "us-east-2", "django_settings": "project.root.settings", "profile_name": "default", "project_name": "task", "runtime": "python3.6", "s3_bucket": "bucket-name" } } And Dockerfile: FROM lambci/lambda:build-python3.6 # Copy in your requirements file ADD requirements.txt /requirements.txt # Copy your application code to the container RUN mkdir /code/ WORKDIR /code/ ADD . /code/ ENV PS1 'zappa@$(pwd | sed "s@^/var/task/\?@@")\$ ' ADD zappa_settings.json /var/task/zappa_settings.json WORKDIR /var/task RUN virtualenv /var/venv && \ source /var/venv/bin/activate && \ pip install -U pip zappa && \ pip install -r /requirements.txt && \ deactivate CMD ["zappa"] Can you tell … -
Django custom filter error. Returns "invalid filter"
I've been trying to create this custom filter in Django, and I can't for the life of me make it work. in my templatetags folder I have the files __init__.py and alcextra.py in my template I first load the static files and then the templatetags. I've tried reseting the server and deleting and creating the files again. {% load staticfiles %} {% load alcextra %} Which is then extended to my main html file. I have tried putting it in the main html file. in alcextra.py I have written from django import template register = template.Library() @register.filter def multiply(value, arg): return value * arg I have tried loads of different @register versions like @register.filter("multiply", multiply) @register.filter(name="multiply") @register.filter() @register.simple_tag(takes_context=True And all return the same error, invalid filter: 'multiply'. At this point I don't know what to do or what to try. Overview of the directory -
Wagtail admin - default ordering of child pages
In the admin area I have to activate the "Enable ordering of child pages" every time. Is there a way to set this as a permanent option? The main problem is that the listing in the child pages view changes depending on if this is activated or not(if you have changed the ordering), which might be a bit confusing for some. Potentially one could change the default ordering of the children list to match the manually ordered list somehow? -
How to route a multi-part form in django
I'd like my users to be able to place orders. For this kind of order, the user uploads a csv. The app parses, the CSV, serializes the data, and then needs to show the user a new view with the data and a "confirm order" button. I'm not sure how to do this in django. class UploadSampleSheetView(LoginRequiredMixin, FormView): form_class = UploadSampleSheetForm template_name = 'pages/upload.html' def form_valid(self, form): uploaded_sample_sheet = self.request.FILES['uploaded_sample_sheet'] sample = _parse_sample_sheet_to_sample_model(uploaded_sample_sheet) sample.save() return super().form_valid(form) def get_success_url(self): return reverse("orders:create") # how do I get the data over? class CreateOrderView(LoginRequiredMixin, CreateView): model = Order form_class = NewOrderForm template_name = 'pages/complete_order.html' What I'm looking for is some way that, on success, the UploadSampleSheetView can return a CreateOrderView with sample data. In general, I'd love to be pointed to a reference about how to build user flows like this one. How does one view defer to another? I'm seeing a lot of return HttpResponseRedirect('url') which seems a little messy. How do I pass data around views? -
Django 1.11 don't included urls.py
Hello I'm working in my first Django App and I have the next problem: The included URLconf 'eventus.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. . ├── eventus │ ├── eventus │ │ ├── __init__.py │ │ ├── __pycache__ │ │ │ ├── __init__.cpython-36.pyc │ │ │ ├── urls.cpython-36.pyc │ │ │ └── wsgi.cpython-36.pyc │ │ ├── db.sqlite3 │ │ ├── settings │ │ │ ├── __init__.py │ │ │ ├── __pycache__ │ │ │ │ ├── __init__.cpython-36.pyc │ │ │ │ ├── base.cpython-36.pyc │ │ │ │ └── local.cpython-36.pyc │ │ │ ├── base.py │ │ │ ├── local.py │ │ │ ├── prod.py │ │ │ └── staging.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── manage.py │ └── myapps │ ├── __init__.py │ ├── __pycache__ │ │ └── __init__.cpython-36.pyc │ ├── events │ │ ├── __init__.py │ │ ├── __pycache__ │ │ │ ├── __init__.cpython-36.pyc │ │ │ ├── admin.cpython-36.pyc │ │ │ ├── forms.cpython-36.pyc │ │ │ ├── models.cpython-36.pyc │ │ │ ├── urls.cpython-36.pyc │ │ │ └── views.cpython-36.pyc │ │ ├── admin.py │ … -
geodjango with mysql not migrating
I am working on geodjango and just got an issue here geodjango with mysql database resolved. When I ran migrate I got the following error Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/core/management/base.py", line 327, in execute self.check() File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 62, in _run_checks issues.extend(super(Command, self)._run_checks(**kwargs)) File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/core/checks/model_checks.py", line 30, in check_all_models errors.extend(model.check(**kwargs)) File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/db/models/base.py", line 1283, in check errors.extend(cls._check_fields(**kwargs)) File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/db/models/base.py", line 1358, in _check_fields errors.extend(field.check(**kwargs)) File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 219, in check errors.extend(self._check_backend_specific_checks(**kwargs)) File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 322, in _check_backend_specific_checks return connections[db].validation.check_field(self, **kwargs) File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/db/backends/mysql/validation.py", line 49, in check_field field_type = field.db_type(self.connection) File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/contrib/gis/db/models/fields.py", line 126, in db_type return connection.ops.geo_db_type(self) AttributeError: 'DatabaseOperations' object has no attribute 'geo_db_type' This is my database settings DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'arbithub', 'USER': 'root', 'PASSWORD': 'root', 'HOST': 'localhost', 'PORT': '3306', } } further codes would be supplied on request -
Right strategy for segmenting Mongo/Postgres database by customer?
I’m building a web app (python/Django) where customers create an account, each customer creates/adds as many locations as they want and a separate server generates large amounts of data for each location several times a day. For example: User A -> [locationA, locationB] User B -> [locationC, locationD, locationE] Where each location is an object that includes name, address, etc. Every 3 hours a separate server gathers data from various sources like weather, check-ins etc for each location and I need to store each item from each iteration so I can then perform per-user-per-location queries. E.g. “all the checkins in the last week group by location for User A” Right now I am using MongoDB and storing a collection of venues with a field of ownerId which is the ObjectID of the owning user. What is the best strategy to store the records of data? The naïve approach seems to be a collection for checkins, a collection for weather records etc and each document would have a “location” field. But this seems to have both performance and security problems (all the access logic would be in web app code). Would it be better to have a completely separate DB for … -
Django - check if a request has timed out
I have a Django app where multiple users could edit the same object at the same time, which would result in data loss/corruption. I want to prevent this. Therefore, I am using a flag in the database (ID of a user currently editing the object) alongside with atomic locking (I am using Redis for this) for as much thread safety as possible. However, the following scenario might still happen: User A clicks that they want to edit an object. The request gets stuck, so they click it again. This time everything gets alright and they edit and save the object. The lock is returned. User B now edits the object and saves it. Now, the request which got stuck wakes up. If it managed to acquire the lock for user A before and user B has already returned it, the request is ready to make some mess here. Please, be aware that this is really simplified (and probably does not make that much sense, but I do not want to explain all the stuff going on, as it is not that much relevant). I know that this scenario is very unlikely, but I want to be 100% thread safe. The … -
Django: include html saved as string in template rendering
I build an HTML table in my view.py function and I want to include it in a template that I already have when rendering. I see that the div is created, but the HTML table is not created. What is the problem? this is the line in view.py: render(request, 'aztracker/import_data.html', {'my_html':html_data}) where html_data is like "<table><tr><th>column1</th></tr><tr><td>data1</td></tr> ....</table>" and I have this section in my import_data.html: <div class="bootstrap-iso"> <div class="tbl_container_numbers"> {{ my_html }} </div> </div> -
geodjango with mysql database
I am developing an application with geodjango and I have been running into some difficulties. following the procedures on the official django website https://docs.djangoproject.com/en/1.11/ref/contrib/gis/tutorial/#use-ogrinfo-to-examine-spatial-data . I first used the orginfo to check spatial data I got a failed message FAILURE: Unable to open datasource `world/data/TM_WORLD_BORDERS-0.3.shp' with the following drivers. then I followed the remaining process creating the models and the error I got when I ran migration was Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/core/management/__init__.py", line 337, in execute django.setup() File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/Olar/Desktop/arbithub/src/geolocation/models.py", line 5, in <module> from django.contrib.gis.db import models File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/contrib/gis/db/models/__init__.py", line 3, in <module> from django.contrib.gis.db.models.aggregates import * # NOQA File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/contrib/gis/db/models/aggregates.py", line 1, in <module> from django.contrib.gis.db.models.fields import ExtentField File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/contrib/gis/db/models/fields.py", line 3, in <module> from django.contrib.gis import forms, gdal File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/contrib/gis/forms/__init__.py", line 3, in <module> from .fields import ( # NOQA File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/contrib/gis/forms/fields.py", line 4, in <module> from django.contrib.gis.geos import GEOSException, GEOSGeometry File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/contrib/gis/geos/__init__.py", line 18, in <module> HAS_GEOS = geos_version_info()['version'] >= … -
Unable to upload external file on server for graph(d3 js) , Django
I am trying to upload file on the server in Django and wants to populate data in the graph, I tried in xampp server it is working. But Django I have no idea, Any help would be appreciated. My code is- var bardata = []; d3.tsv('data.txt', function(data) { console.log(data); for (key in data) { bardata.push(data[key].value) } while uploading in django, in console error is coming Failed to load resource: the server responded with a status of 404 (Not Found) -
Django - Issues passing String correctly to template after replacing characters in view
I'm having a bizarre issue with passing a particular string from a view to a template. The string originates from a form, and contains text that I want to simplify into a split-able string later. So, I substitute potential separator characters with a comma like so: # views.py mystring = myform.cleanedData['mystring'] mystring = str(mystring) # convert from unicode mystring = mystring.replace("\n", ",").replace("\r\n", ",").replace(" ", ",").replace(";", ",") # Then I pass it to the template: return render(request, 'html/mytemplate.html', {'mystring': mystring}) Now, take this form data for example: %15 %16 If I print out mystring to a file just before rendering the template, it looks like this: %15,%16 All good so far. The problem, though, comes from trying to render this string into the template. If I try to render the string like this: {{ mystring }} The result is this (leading spaces included): %15 ,%16 It preserves the comma, but adds some other funky stuff, which I don't want because it makes some of my JS get pretty darn confused. I've tried to prevent escaping with the safe filter, but it doesn't seem to change anything in this case. Another thing to note is that if the original form data is … -
Is there a way to declare a mock model in Django unit tests?
Title says it all. I'll illustrate the question by showing what I'm trying to do. I have extended Django's ModelForm class to create a ResourceForm, which has some functionality built into its clean() method for working with Resources, the details of which are unimportant. The ResourceForm is basically a library class, and there are no models in the app where the ResourceForm class is defined, so I can't just use an existing model from the app. I am trying to unit test ResourceForm, but I can't figure out the right way to mock a Django Model, which is required since ResourceForm inherits from ModelForm. This is one of several efforts I have tried (not using mock in this case, but it serves to illustrate what is being attempted): class ResourceFormTestCase(TestCase): class SampleModel(Model): sample_field = CharField() class SampleResourceForm(ResourceForm): class Meta(): model = SampleModel fields = ['sample_field'] def test_unsupported_field_raise_validation_error(self): print('Test validation error is raised when unsupported field is provided') form_data = {'sample_field': 'FooBar', 'unsupported_field': 'Baz'} form = self.SampleResourceForm(data=form_data) But that raises: RuntimeError: Model class customer.tests.tests_lib_restless_ext.SampleModel doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. I'm open to suggestions if I'm way off-base in how I'm trying to test this. -
manage.py: error: unrecognized arguments: runserver 8000, Google Analytics API Django
Here is my Models.py import argparse import os from django.db import models from django.db import models from django.contrib.auth.models import User from oauth2client import tools from oauth2client.client import flow_from_clientsecrets, Storage CLIENT_SECRETS = os.path.join( os.path.dirname(__file__), 'client_secrets.json') TOKEN_FILE_NAME = 'credentials.dat' FLOW = flow_from_clientsecrets( CLIENT_SECRETS, scope='https://www.googleapis.com/auth/analytics.readonly', message='%s is missing' % CLIENT_SECRETS ) def prepare_credentials(): parser = argparse.ArgumentParser(parents=[tools.argparser]) flags = parser.parse_args() # Retrieve existing credendials storage = Storage(TOKEN_FILE_NAME) credentials = storage.get() # If no credentials exist, we create new ones if credentials is None or credentials.invalid: credentials = tools.run_flow(FLOW, storage, flags) return credentials class FlowModel(models.Model): id = models.ForeignKey(User, primary_key=True) flow = FLOW class CredentialsModel(models.Model): id = models.ForeignKey(User, primary_key=True) credential = prepare_credentials() When I run python manage.py runserver It gives me the error below usage: manage.py [-h] [--auth_host_name AUTH_HOST_NAME] [--noauth_local_webserver] [--auth_host_port [AUTH_HOST_PORT [AUTH_HOST_PORT ...]]] [--logging_level {DEBUG,INFO,WARNING,ERROR,CRITICAL}] manage.py: error: unrecognized arguments: runserver 8000 I have tried searching for solutions but this error still persists. Kindly help me solve this as I am running out of time.