Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to test the value of variable in overridden function before it is passed to the function of parent class
I have overridden a function in my Django admin class MyAdmin(admin.ModelAdmin): def get_some_results(self, request, input_string): input_string = input_string.encode('utf-8') end_of_string = 'some_value' input_string += end_of_string return super(MyAdmin, self).get_some_results(request, input_string) I want to write a test that will check the input value for the function 'get_some_results' of a parent class ModelAdmin. In other words I want to check the value of 'input_string' after string: input_string += end_of_string In my test.py file I have a class class TestAdminSearch(AppTestCase, MyAdmin): def __init__(self, *args, **kwargs): super(TestAdminSearch, self).__init__(*args, **kwargs) self.url = '/admin/some_value/.../' # with this url get_some_results() is called @mock.patch('django.contrib.admin.ModelAdmin.get_some_results') def test_get_some_results(self, mock_some_result): search_string = 'some_string' expected_string = 'other_string' request_factory = RequestFactory() request = request_factory.get(self.url + search_string) result = mock_some_result.call_args_list self.assertEqual(result, (request, expected_string.encode('utf-8'))) But I get an AssertionError. It seems to me that mocked function is called with input_string but not with expected_string. But after the line input_string += end_of_string input string is equal to expected_string. Do you have an idea of what I'm doing wrong or how else can I check the value of input_string before the line? return super(MyAdmin, self).get_some_results(request, input_string) Thank you very much in advance! -
gunicorn setup for django channels
My django app works fine on local machine as well as on Heroku, however I'm having troubles to deploy it do Digital Ocean Ubuntu 16.04 droplet. Followed this tutorial, app has started but websockets didn't work. By running in terminal virtual environment: daphne -b 0.0.0.0 -p 8000 slist.asgi:channel_layer and in second terminal window: ./manage.py runworker The app works but only on port 8000. I can't access it on mydomain.com but only on mydomain.com:8000. When I close terminal windows the site cannot be accessed. What and how needs to be set for the site to run without my terminal windows and without the ':8000'? My gunicorn.service file: [Unit] Description=gunicorn daemon After=network.target [Service] User=kuba1 Group=www-data WorkingDirectory=/home/kuba1/slistproject ExecStart=/home/kuba1/slistproject/slistvenv/bin/gunicorn --workers 3 --bind unix:/home/kuba1/slistproject/slistvenv/src/slist.sock slist.wsgi:application [Install] WantedBy=multi-user.target my Nginx settings: server { listen 80; server_name server_name fortests.ovh; client_max_body_size 20M; location /static/ { root /home/kuba1/slistproject/slistvenv/src; } location / { proxy_pass http://unix:/home/kuba1/slistproject/slistvenv/src/slist.sock; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } } -
Django get fields of ForeignKey object in models
I have these two models defined with a one to many relationship class Template(models.Model): name = models.CharField(max_length=100) fields = models.IntegerField() def __str__(self): return self.name class Page(models.Model): template = models.ForeignKey(Template, related_name='pages') title = models.CharField(max_length=100) for i in range(template.fields): #Error occuring here text[i] = models.TextField() def __str__(self): return self.title I want to get the value of template.fields, but I get this error for i in range(template.fields): AttributeError: 'ForeignKey' object has no attribute 'fields' Am I using the ForeignKey Object wrong? Any help would be much appreciated -
JS static files issues in AWS Production Django Application
I am having a weird issue where angular is undefined when application is deployed in AWS but locally there are no issues in my angular or javascript code. Update: My static files (JS, CSS, Images, etc) all live in an S3 static files bucket. There is no problem in retrieving the files, but it seems like suddenly a working commit that has been deployed for months just started raising JS issues when static files are being loaded. Here are my JS files in my base template: {% compress js %} <script src="{{STATIC_URL}}shared/stacktrace-js/dist/stacktrace.js"></script> <script src="{{STATIC_URL}}shared/jquery/2.1.1/jquery.min.js"></script> <script src="{{STATIC_URL}}shared/jquery-growl/1.2.3/jquery.growl.js"></script> <script src="{{STATIC_URL}}shared/jquery-ui-1.12.1.custom/jquery-ui.min.js"></script> <script src="{{STATIC_URL}}ckeditor/ckeditor-init.js"></script> <script src="{{STATIC_URL}}shared/ckeditor-custom/ckeditor-custom.js"></script> <script src="{{STATIC_URL}}shared/bootstrap/3.3.5/dist/js/bootstrap.min.js"></script> <script src="{{STATIC_URL}}shared/utils.js"></script> <script src="{{STATIC_URL}}shared/angular/1.3.11/angular.min.js"></script> <script src="{{STATIC_URL}}shared/angular/1.3.11/angular-route.min.js"></script> <script src="{{STATIC_URL}}shared/angular/1.3.11/angular-cookies.min.js"></script> <script src="{{STATIC_URL}}shared/angular-bootstrap/0.11.0/ui-bootstrap-tpls-0.11.0.min.js"></script> <script src="{{STATIC_URL}}shared/bootstrap-multiselect/bootstrap-multiselect.js"></script> <script src="{{STATIC_URL}}shared/introjs/intro.js"></script> <script type="text/django" src="{{STATIC_URL}}shared/ch-error-logging.js"></script> <script type="text/django" src="{{STATIC_URL}}shared/ch-config.js"></script> <script src="{{STATIC_URL}}shared/angulartics/dist/angulartics.min.js"></script> <script src="{{STATIC_URL}}shared/angulartics-segment/dist/angulartics-segment.min.js"></script> <script src="{{STATIC_URL}}shared/chart.js/dist/Chart.min.js"></script> <script src="{{STATIC_URL}}shared/select2/dist/js/select2.min.js"></script> <script src="{{STATIC_URL}}shared/angular-chart.js/dist/angular-chart.js"></script> <script src="{{STATIC_URL}}shared/jquery-validation/dist/jquery.validate.min.js"></script> <script type="text/django" src="{{STATIC_URL}}shared/ch-track.js"></script> <script type="text/django" src="{{STATIC_URL}}shared/ch-file.js"></script> <script src="{{STATIC_URL}}shared/offline.js"></script> {% endcompress %} I thought the issue had to do with compressing jquery.min.js since it is already minified. If I change it from jquery.min.js to jquery.js and keep it in the compress block, the deployment fails when trying to compress the templates and files. If I move the jquery.min.js or jquery.js outside the compress block, then … -
Running supervisord process as root
My goal is to run sudo inside one of the programs: [program:doStaff] command=sudo python manage.py doStaff autostart=true autorestart=true stderr_logfile=/var/log/doStaff.err.log stdout_logfile=/var/log/doStaff.out.log Here is [unix_http_server] from supervisord.conf: [unix_http_server] file=/var/run/supervisor.sock chmod=0770 Tried to set the supervisord user to root inside supervisord.conf but it didn't help. -
The built-in API Django documentation doesn't display anything
I am trying to add documentation to my Django app. I did everything in accordance with official Django Built-in API documentation. However when I open for instance localhost:8000/docs/ I don't get any result. There is only white screen. I would like to get something like this. I have no idea what is wrong. Everything seems to be done properly. I added coreapi, markdown and pygments to requirements.txt file. My settings.py: from rest_framework.documentation import include_docs_urls API_TITLE = 'API title' API_DESCRIPTION = '...' urlpatterns = [ url(r'^docs/', include_docs_urls(title=API_TITLE, description=API_DESCRIPTION)) ] Logs: django_1 | [16/Jul/2017 14:39:39] "GET /docs/ HTTP/1.1" 200 10156 django_1 | [16/Jul/2017 14:39:39] "GET /static/rest_framework/docs/css/bootstrap-theme.min.017404ba6919.css HTTP/1.1" 304 0 django_1 | [16/Jul/2017 14:39:39] "GET /static/rest_framework/docs/css/bootstrap.min.1825bc9de3d6.css HTTP/1.1" 304 0 django_1 | [16/Jul/2017 14:39:39] "GET /static/rest_framework/docs/css/font-awesome-4.0.3.3c6725a71cd2.css HTTP/1.1" 304 0 django_1 | [16/Jul/2017 14:39:39] "GET /static/rest_framework/js/coreapi-0.1.0.b8a6a6e33df8.js HTTP/1.1" 304 0 django_1 | [16/Jul/2017 14:39:39] "GET /static/rest_framework/docs/css/base.4fca6813aaab.css HTTP/1.1" 304 0 django_1 | [16/Jul/2017 14:39:39] "GET /static/rest_framework/docs/css/jquery.json-view.min.a2e6beeb6710.css HTTP/1.1" 304 0 django_1 | [16/Jul/2017 14:39:39] "GET /static/rest_framework/docs/js/jquery.json-view.min.b7c2d6981377.js HTTP/1.1" 304 0 django_1 | [16/Jul/2017 14:39:39] "GET /static/rest_framework/docs/js/jquery-1.10.2.min.628072e7212d.js HTTP/1.1" 304 0 django_1 | [16/Jul/2017 14:39:39] "GET /static/rest_framework/docs/js/api.d5c3cd5658db.js HTTP/1.1" 304 0 django_1 | [16/Jul/2017 14:39:39] "GET /static/rest_framework/docs/js/bootstrap.min.79b5346433d3.js HTTP/1.1" 304 0 django_1 | [16/Jul/2017 14:39:40] "GET /docs/schema.js HTTP/1.1" 200 7456 -
Django authentication is alway false for non superuser
here is the trouble i try to autheticate the users for my website but authenticate() return alway the None value for the user created with the registration page. I can correctly log user after their user user creation and the entry is in the database. I have a custom user model extended form AbstractBaseUser. So here is the portion of code not working : <!-- language-all: python --> def login(request): error = False if request.method == "POST": form = forms.LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data["username"] password = form.cleaned_data["password"] user = authenticate(username=username, password=password) print("Validated form.") print(username) print(password) print(user) if user: print("Logged user.") authlog(request, user) return redirect(to='home') else: print("Not logged user.") error = True else: form = forms.LoginForm() return render(request, 'users/login.html', locals()) And in the following block of code the user is sccessfully logged after it's registration. def register(request): form = forms.RegisterForm(request.POST or None) if form.is_valid(): user = form.save() authlog(request, user) return redirect(to='home') print('Registered new user') return render(request, 'users/register.html', locals()) Whet i don't understant is des it work with the admin account i created with ./manage.py createsuperuser work and not the others. And also i can't create user in the admin panel and i don't know why. Thanks :D -
build_filters() got an unexpected keyword argument 'ignore_bad_filters'
I just updated my code from django 1.8 to 1.11 and so i also had to update tasty pie. Before update everything worked fine but now I am getting this error on one of my tests. Here is the test case def test_does_not_return_restricted_fields_when_insufficient_permissions(self): self.user.user_permissions.all().delete() response = self.api_client.get(url, format='json', authentication=self.create_apikey(username=self.username, api_key=self.api_key), data=data) Here is the full Trace, Traceback (most recent call last): File "/spare/local/projects/towerportal/apps/exchangedb/tests/test_api.py", line 68, in test_does_not_return_restricted_fields_when_insufficient_permissions response = self.get_response(self.detail_url) File "/spare/local/projects/towerportal/apps/exchangedb/tests/test_api.py", line 26, in get_response data=data) File "/spare/local/venv/lib/python2.7/site-packages/tastypie/test.py", line 70, in get return self.client.get(uri, **kwargs) File "/spare/local/venv/lib/python2.7/site-packages/django/test/client.py", line 536, in get **extra) File "/spare/local/venv/lib/python2.7/site-packages/django/test/client.py", line 340, in get return self.generic('GET', path, secure=secure, **r) File "/spare/local/venv/lib/python2.7/site-packages/django/test/client.py", line 416, in generic return self.request(**r) File "/spare/local/venv/lib/python2.7/site-packages/django/test/client.py", line 501, in request six.reraise(*exc_info) File "/spare/local/venv/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/spare/local/venv/lib/python2.7/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response response = self._get_response(request) File "/spare/local/venv/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/spare/local/venv/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/spare/local/venv/lib/python2.7/site-packages/django/utils/decorators.py", line 185, in inner return func(*args, **kwargs) File "/spare/local/venv/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/spare/local/venv/lib/python2.7/site-packages/tastypie/resources.py", line 221, in wrapper response = callback(request, *args, **kwargs) File "/spare/local/venv/lib/python2.7/site-packages/tastypie/resources.py", line 470, in dispatch_detail return self.dispatch('detail', request, **kwargs) File "/spare/local/venv/lib/python2.7/site-packages/tastypie/resources.py", line … -
Django - Manage.py ModuleNotFoundError: No module named 'mysite' on windows
I'm trying to get Django to work. I just installed Django and project created "mysite" mysite -- manage.py -- mysite now I'm when I run python manage.py runserver I get this error Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\MySoftware\python361\lib\site-packages\django\core\management\__init__.py", line 363, in execute_from_command_line utility.execute() File "C:\MySoftware\python361\lib\site-packages\django\core\management\__init__.py", line 307, in execute settings.INSTALLED_APPS File "C:\MySoftware\python361\lib\site-packages\django\conf\__init__.py", line 56, in __getattr__ self._setup(name) File "C:\MySoftware\python361\lib\site-packages\django\conf\__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "C:\MySoftware\python361\lib\site-packages\django\conf\__init__.py", line 110, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "importlib\__init__.py", line 126, in import_module File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 936, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 948, in _find_and_load_unlocked ModuleNotFoundError: No module named 'mysite' Python cannot find 'mysite' I've tried PYTHONPATH = 'my director' but so far nothing has worked. -
lost form labels after installed a new theme on mezzanine Django projects
I created a mezzanine projects on a staging host. I found a theme was great for my project looking nice. So i downloaded the theme to my projects and changed theme name in settings.py. I also used mezzanine public accounts application by uncomment it. Here is the code in settings.py INSTALLED_APPS = ( "flat", "django.contrib.admin", "django.contrib.auth", ... "mezzanine.accounts", ... ) That works great. Homepage looks nice. but when i tested the account signup, unfortunately it lost all form labels. I thought it was the static files problem at the first time, so i modified html class label and updated the mezzanine latest css files to the flat app. After many tries, spending lots of time on the problem, it didn't changed anything. here is the link of theme flat So i started to focus {% fields_for form %} which i found on templates accounts/account_form.html {% extends "base.html" %} {% load i18n mezzanine_tags %} {% block meta_title %}{{ title }}{% endblock %} {% block title %}{{ title }}{% endblock %} {% block body_id %}account{% endblock %} {% block breadcrumb_menu %} {{ block.super }} <li>{{ title }}</li> {% endblock %} {% block main %} {% errors_for form %} <form method="post"{% if form.is_multipart … -
Filtering Queryset and designing correct urls.py and templates in Django
I am designing a video rendering kids website. The app has parent categories for eg: Cartoons, Education shows etc. Each category has multiple posts such as Jungle_book,Duck_tales etc for cartoons. Each post has multiple episodes. I am using generic views(listview, Detailview) for views. Here are my Models.py from django.db import models from personal.models import Post class cartoons_post(models.Model): category= models.ForeignKey(Post, on_delete=models.CASCADE) title = models.CharField(max_length = 140) thumbnail=models.ImageField() date=models.DateField() def __unicode__(self): return self.title def __str__(self): return self.title def get_absolute_url(self): return reverse("posts:detail", kwargs={"id": self.id}) class post_episode(models.Model): post_id= models.ForeignKey(cartoons_post, on_delete=models.CASCADE) title = models.CharField(max_length = 140) thumbnail=models.ImageField() date=models.DateField() video=models.FileField() def __unicode__(self): return self.title def __str__(self): return self.title def get_absolute_url(self): return reverse("posts:detail", kwargs={"id": self.id}) Here is my urls.py from django.conf.urls import url, include from django.views.generic import ListView, DetailView from cartoons.models import cartoons_post,post_episode from django.contrib.auth.decorators import login_required urlpatterns = [ url(r'^$', login_required(ListView.as_view( queryset=cartoons_post.objects.all().order_by("-date")[:10], template_name="cartoons/cartoons.html"))), url(r'^(?P<pk>\d+)$', login_required(ListView.as_view( queryset=post_episode.objects.filter(post_id=1).order_by("-date"), template_name="cartoons/post.html"))), url(r'^(?P<pk>\d+\d+)$',login_required(DetailView.as_view( model = post_episode, template_name="cartoons/post_episode.html"))), ] Here are my three templates cartoons.html {% extends "personal/header.html" %} {% load staticfiles %} {% block content %} {% for cartoons_post in object_list %} <a href="/cartoons/{{cartoons_post.id}}"> <img src= "{{cartoons_post.thumbnail.url}}" width="200" height="220"> </a> {% endfor %} {% endblock %} post.html {% extends "personal/header.html" %} {% load staticfiles %} {% block content %} {% for … -
The built-in API Django documentation doesn't work
I am trying to add documentation to my Django app. I did everything in accordance with official Django Built-in API documentation. However when I open for instance localhost:8000/docs/ I don't get any result. There is only white screen. I would like to get something like this. I have no idea what is wrong. Everything seems to be done properly. I added coreapi, markdown and pygments to requirements.txt file. My settings.py: from rest_framework.documentation import include_docs_urls API_TITLE = 'API title' API_DESCRIPTION = '...' urlpatterns = [ ... url(r'^docs/', include_docs_urls(title=API_TITLE, description=API_DESCRIPTION)) ] -
How to properly register dynamically created modeded in admin pannel
I am creating my models using the create_model that is proposed in documentation and here is how I call this function to create multiple model with different names: def create_servers(server_names_path): with open(server_names_path) as f: server_names = json.load(f) def set_file_names(cls, args): cls.file_names = json.dumps(args) def get_file_names(cls): return json.loads(cls.file_names) for name in server_names: model_class = create_model(name, fields={'path': models.CharField(max_length=200), 'file_names': models.TextField(), 'set_file_names': set_file_names, 'get_file_names': get_file_names, '__str__': lambda self: self.__name__}, app_label='SearchEngine', module='SearchEngine.models', options=None, admin_opts={}) # with connection.schema_editor() as editor: # editor.create_model(model_class) call_command('makemigrations') call_command('migrate') reload(import_module(settings.ROOT_URLCONF)) clear_url_caches() As you can see I'm passing an empty dictionary as the admin_opts so that in ceate_model the registration gets executed. Now, my problem is that after running the code it creates the migrations in migrations directory but the new models don't appear in admin panel. I also ran the code multiple times by unquoting the quoted lines and/or running the reload before and after the migrations. The weired thing is that after this it creates the modes but doesn't show them in admin panel and when I run the makemigrations and then migrate commands in terminal it removes my dynamic models. -
Django DRF Update User
Im trying to create an api using the Django-Rest-Framework (DRF) to CRUD a User. I have managed to create and read a user, but for some reason update will not work. It seems to be that it is trying to create a User rather than update it as it responds with a 'username already exists' error message. When I try passing an email that isn't already in the database it just creates a new user. Does anyone know why this is happening? Here is my User Serializer: class UserSerializer(FriendlyErrorMessagesMixin, serializers.ModelSerializer): password = serializers.CharField( max_length=128, min_length=8, write_only=True ) class Meta: model = User fields = ('username', 'email', 'password', 'name', 'house_number', 'address_line_one', 'address_line_two', 'address_line_three', 'city', 'postcode', 'phone_number') read_only_fields = ('date_created', 'date_modified', 'username') def update(self, instance, validated_data): password = validated_data.pop('password', None) for (key, value) in validated_data.items(): setattr(instance, key, value) if password is not None: instance.set_password(password) instance.save() return instance and here is my view: class UserRetrieveUpdateAPIView(RetrieveUpdateAPIView): permission_classes = (IsAuthenticated,) serializer_class = UserSerializer def retrieve(self, request, *args, **kwargs): serializer = self.serializer_class(request.user) return Response(serializer.data, status=status.HTTP_200_OK) def update(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) -
NoReverseMatch at /user/password_reset/ Reverse for 'password_reset_done' not found
I'm trying to use the Django authentication system, but I'm getting the error: enter image description here 'user' is an app name. Project's urls.py: from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), ... url(r'^user/', include('user.urls', namespace='user')), ... ] user/urls.py: from django.conf.urls import url, include from . import views urlpatterns = [ url(r'^register/$', views.register, name='register'), url(r'^settings/$', views.settings, name='settings'), url(r'^settings/password/$', views.password, name='password'), url(r'^settings/accounts/$', views.configure_accounts, name='configure_accounts'), url(r'^settings/accounts/error/$', views.configure_accounts_error, name='configure_accounts_error'), url('^', include('django.contrib.auth.urls')), ] I can access /user/login/, /user/logout/. When I go to /user/password_reset/, I can enter email, and, after pressing 'Submit' button, an error occurs (shown at picture): NoReverseMatch at /user/password_reset/ Reverse for 'password_reset_done' not found. 'password_reset_done' is not a valid view function or pattern name. Any ideas how to fix this? Thanks a lot. -
django 'taggit' tag of my record is not displaying in template
the tags which are bounded to the each record is not displaying in the template. can anyone please help me out. models.view- from django.db import models from django.utils import timezone from django.contrib.auth.models import User from taggit.managers import TaggableManager class Book(models.Model): status_choices=( ('writing','writing'), ('editing','editing'), ) title=models.CharField(max_length=50) slug = models.SlugField(max_length=50, unique_for_date="publish_date") body=models.TextField(max_length=500) create_date=models.DateTimeField(auto_now_add=True) update_date = models.DateTimeField(auto_now=True) publish_date=models.DateTimeField(default=timezone.now) author=models.ForeignKey(User,related_name="ibook_book") status=models.CharField(max_length=50,choices=status_choices, default="writing") tags=TaggableManager() views.py- def list_view(request,tag_slug=None): book=Book.objects.all() tag=None if tag_slug: tag=get_object_or_404(Tag,slug=tag_slug) book=book.filter(tags__in=[tag]) return render(request,"ibook/list.html",{'book':book,'tag':tag}) list.html- {% extends "ibook/basepage.html" %} {% block title %} my book {% endblock %} {% block content %} <h1>My book</h1> <hr> {% if tag %} <h2>Posts tagged with "{{ tag.name }}"</h2> {% endif %} {% for b in book %} <h2 class="somecolor"> <a href="{{ b.get_absolute_url }}">{{ b.title }}</a></h2> <p> Tags: {% for tag in book.tags.all %} <a href="{% url "list_view_tag" tag.slug %}"> {{ tag }} </a> {% if not forloop.last %}, {% endif %} {% endfor %} </p> <i class="date">{{ b.publish_date }}</i> <h4>{{ b.body }}</h4><hr> {% endfor %} {% endblock %} here, i am trying to display the tags below the each book(record) but i am getting no tags displaying below the book. -
The built-in API Django documentation doesn't work
I am trying to add documentation to my Django app. I did everything in accordance with official Django Built-in API documentation. However when I open for instance localhost:8000/docs/ I don't get any result. There is only white screen. It seems to me that I should get something like this. I have no idea what is wrong. Everything seems to be done properly. I added to requirements.txt - coreapi, markdown and pygments. My settings.py: from rest_framework.documentation import include_docs_urls API_TITLE = 'API title' API_DESCRIPTION = '...' urlpatterns = [ ... url(r'^docs/', include_docs_urls(title=API_TITLE, description=API_DESCRIPTION)) ] -
How can i pop up a Notification in python
I need to pop up a notification (like facebook) when back end requested URL in my tool (i need something always listen and when specific URL is requested, will do something) so i wanna know if Python can do it or i need to use socket.io thanks in advance -
Buiding a website with user login using Ruby on Rails or Python
I'm trying to make a website that has a user login option, and once logged in users can answer different questions, gain points and level up. I know html, css, js and python, but I'm completely new to backend development. For the purpose of creating a user profile system, will it be easier for me to just use Python and Django, or should I learn Ruby on Rails or PHP? -
Only the alternate(even rows) are getting imported into the database in django
I'm working on an excel file upload in django Using the same method I've populated another model using a xlsx file.But in the second model I cant upload and I'm facing an issue which I mentioned below. views.py def import_source(request): if request.method == "POST": form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): request.FILES['file'].save_to_database( name_columns_by_row=0, model=Tracker, mapdict=['sl_no','dot','branch','sname','snum','can_name','sdetail','main_skills','uname','cus_name','ep_num','day','doi','status','cont_num','email_id','texp','rexp','cu_org','cu_loc','pref_loc','cu_ctc','exp_ctc','notice_period']) return HttpResponse("OK") else: return HttpResponseBadRequest() else: form = UploadFileForm() return render( request, 'upload_form.html', {'form': form}) models.py class Tracker(models.Model): sl_no = models.IntegerField() dot = models.DateTimeField() branch = models.CharField(max_length=200) sname = models.CharField(max_length=200) snum = models.CharField(max_length=200) can_name = models.CharField(max_length=200) sdetail = models.CharField(max_length=200) main_skills = models.TextField() uname = models.CharField(max_length=200) cus_name = models.CharField(max_length=200) ep_num = models.CharField(max_length=200,primary_key=True) day = models.CharField(max_length=200) doi = models.DateTimeField() status = models.CharField(max_length=200) cont_num = models.IntegerField() email_id = models.EmailField(max_length=200) texp = models.DecimalField(max_digits=4,decimal_places=2) rexp = models.DecimalField(max_digits=4,decimal_places=2) cu_org = models.CharField(max_length=200) cu_loc = models.CharField(max_length=200) pref_loc = models.CharField(max_length=200) cu_ctc = models.DecimalField(max_digits=4,decimal_places=2) exp_ctc = models.DecimalField(max_digits=4,decimal_places=2) notice_period = models.IntegerField() Excel file .xlsx file which I'm tryig to upload in the above image only the rows with sl_no 1,3,5 are uploaded result enter image description here -
Django - How to extend the swagger with additional functionalities?
I am using Django with Swagger documentation. I wonder if there is any way to extend functionalities. At this moment I use only base schema in settings. I see only URLs. When I click Django Logout it doesn't work. Is there a possibility to add an option to send an example body in methods? For instance I have also optional searching like GET /users/{user_id}/object?sth=123 is it possible to include it in swagger documentation, too? I was looking in the documentation but there isn't much information. My settings at this moment look in this way: schema_view = get_swagger_view(title='PRI API') urlpatterns = [ url(r'^', schema_view), ] -
Change Values of User Model while it has OneToOneField Connection to another model in ModelForms django
i have problems with Django ModelForms and here is one of them i wanna have some extra fields for User Model in Django and so made an CustomeUser Model in models.py models.py class CustomeUser(models.Model): user = models.OneToOneField(User) City = models.ForeignKey(City, on_delete=models.CASCADE, blank=True, null=True) Gender = models.ForeignKey(Gender, null=True, blank=True) DateOfBirth = models.DateField(null=True, blank=True) ProfilePicture = models.ImageField(verbose_name="Profile Picture", upload_to=user_directory_path, null=True, blank=True, max_length=255) Address = models.CharField(max_length=255, blank=True, null=True) def __str__(self): return str(self.user) and now i wanna make EditProfileForm with ModelForm, here is what i did: forms.py class EditProfileForm(forms.ModelForm): firstname = forms.CharField(max_length=35,required=False) lastname = forms.CharField(max_length=35, required=False) cityid = forms.ModelChoiceField(queryset=City.objects.values('id').all(), required=False) genderid = forms.ModelChoiceField(queryset=Gender.objects.values('id').all(), required=False) dateofbirth = forms.DateField(required=False) profilepicture = forms.ImageField(required=False, max_length=255) address = forms.CharField(max_length=255, required=False) class Meta: model = CustomeUser fields = ['firstname' ,'lastname' ,'cityid' , 'genderid', 'dateofbirth', 'profilepicture', 'address' ] i really have no idea how to do it in the best way -
Django: Multiple login redirects based on path
I have the following two urls: url(r'^login/$',django.contrib.auth.views.login,{'template_name': 'meta/login.html'},name='login'), url(r'^loginiOS/$', django.contrib.auth.views.login, {'template_name': 'meta/login.html'}, name='loginiOS'), They load the login page but the "loginiOS" URL allows me to hide certain options on the iPhone version such as the menu. An example can be seen below: {% if 'iOS' in request.path %} {% else %} {% include "meta/fragments/navbar.html" %} {% block header %}{% endblock %} {% endif %} However, whenever I login it always redirects me to "https://str8red.com/welcome" which is set in the settings file. What I would like to do is have the login page redirect as follows: If its from str8red.com/login then redirect to stre8red.com/welcome If its from str8red.com/loginiOS then redirect to str8red.com/welcomeiOS I have tried a few ideas out and had a look on stackoverflow without success. Any help would be greatly appreciated. Many thanks, Alan. -
'user' is an invalid keyword argument for this function
I am using Custom User Model for user registration and login functionality. User login is running correctly but when i am trying to register a user, it throws me following error In database, this user gets save but here it throws me error. Here is my views.py file from django.shortcuts import render , render_to_response from django.http import HttpResponseRedirect from django.contrib import auth from django.template.context_processors import csrf from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import login, authenticate # Create your views here. def invalid_login (request): return render_to_response('invalid_login.html') def register_user(request): if request.method=='POST': form=UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) #return render_to_response('register_success.html') return HttpResponseRedirect('/user_login/register_success') else: return HttpResponseRedirect('/user_login/invalid') args={} args.update(csrf(request)) args['form']=UserCreationForm() return render_to_response('register.html' ,args) def register_success(request): return render_to_response('register_success.html') This is my register.html file <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h2>Sign up</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Sign up</button> </form> </body> </html> -
Bulk insert into SQLite DB when ManyToMany and ForeignKey relationships
I have a database table structure with ManytoMany relationships and ForeignKeys. I am doing a web scraping from the IEEE Xplore website to build a database of publications for researchers. The web scraping can return bulk data (max 1000 publications). I have the program up and running where I successfully extract data from the website, and write it to the database. But due to the relationships, I need to save every row and then add the many-to-many elements. This makes the writes very slow (several minutes). I read about bulk_create and atomic decorators but the documentation says they won't work with many-to-many relationships. Which kind of makes sense since every record needs to be saved before adding the many-to-many relationships. The only way to go seems to do a raw SQL insert - into a temporary table and then merge into the main table. The data structure is below. Before I start finding an SQL answer, I thought I would post to check if there was another way out or any other documents or suggestions. Thanks in advance. from django.db import models from django import forms from django.forms import ModelForm, Textarea # Create your models here. class Journal(models.Model): name = …