Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django `TransactionTestCase` test cases with AWS RDS are very slow
I am trying to set up Django tests to use AWS RDS as a Postgres database backnend (tests are executed on Heroku CI which does not allow you create and destroy test databases). The tests are running, but test cases that use TransactionTestCase are extremely slow (sometimes up to a minute compared to fraction of a second when not using RDS). I am using RDS in the same region as my Heroku deployment (EU/Ireland) and test cases based on TestCase class run as usual. Any ideas what could be causing this? -
How to use two tables with same name in two different schema in mysql with django
I am using two mysql schemas X and Y, both contains multiple tables but there is one table that has same name in both the schemas. Both the schemas are as follows: +--------------+--+--------------+ | X | | Y | +--------------+--+--------------+ | name | | photo | +--------------+--+--------------+ | invite | | photo_info | +--------------+--+--------------+ | photo | | album_detail | +--------------+--+--------------+ | user_details | | temp | +--------------+--+--------------+ Now, I want to query on both the tables but when I write the table structure in models.py file with same name it throws error/exception. I declared both table in routers.py file as below: modelDatabaseMap = { . 'photo': 'default', . . . 'photo': 'y', } (X is my default schema). Declared i models.py as below: class Photo(models.Model): id = models.AutoField(db_column='ID', primary_key=True) has_tagged_with = models.IntegerField() has_reposted_with = models.IntegerField() . . class Meta: managed = False db_table = 'photo' class Photo(models.Model): id = models.AutoField(db_column='ID', primary_key=True) account_id = models.IntegerField() p_id = models.IntegerField() is_profile = models.IntegerField() . . class Meta: managed = False db_table = 'photo' Now, the ambiguity is first in name, in declaration in models.py and secondly in querying. I am stuck at how to query on both the tables separately through orm. … -
apache2 and django wagtail stop responding
I have a problem with Apache2 and Django Wagtail. I used the following steps to configure. And it serves my pages fine for a very short time, I suspect it has to do with when i publish pages or upload images. There is simply no item in my access log or error log its like my request never reached. However when I restart Apache it works again shortly and the same issue appears. It doesn't seem to be file descriptors though as I am the only on accessing the system. When I run wireshark on my client system I get this. -
Django: POST form with status view (ajax?)
I am new to Django, so please pardon my lack of knowledge about it. I did, however, complete the 7 part tutorial and am now working on my own application. For the most part things are going quite smoothly. I am having trouble figuring out how to do the following: I have a form which takes some user input, posts to a view, does some calculations and then redirects to the output. While the calculations are running I can see the little wheel spinning in my browser tab, but the user has to look at their form just sitting there while they wait. I would like to make a status view of sorts, where while the calculations are underway at certain parts it shows the user a message regarding its progress e.g. "at part 3 of the process", and when it is done then redirects to the results. I have tried looking at other questions related to this, but I can not seem to find one that answers my question in a way I understand. Many of them suggest using ajax or having JS function poll the server. I once found a link about Django status messages (but I cant … -
Filter Products
I have a filter block for my categories and my goal to filter products by it. My filter app models are: class FilterCategory(CreationModificationDateMixin): category = TreeForeignKey( 'category.Category', verbose_name='Категория фильтра' ) name = models.CharField( 'Название фильтра для категории', max_length=250 ) slug = models.SlugField( 'Название фильтра для URL', max_length=250 ) def __str__(self): return '{name}: {category}'.format(name=self.name, category=self.category.name) class Meta: verbose_name = 'Фильр' verbose_name_plural = 'Фильтры' class FilterSelect(CreationModificationDateMixin): filter_category = models.ForeignKey( FilterCategory, verbose_name='Фильтр Категории', related_name='values' ) name = models.CharField( 'Значение фильтра', max_length=250 ) slug = models.SlugField( 'Значение фильтра для URL', max_length=250 ) def __str__(self): return self.name class Meta: verbose_name = 'Занчение фильтра' verbose_name_plural = 'Значение фильтров' class ProductFilter(models.Model): product = models.ForeignKey( 'products.Product', on_delete=models.CASCADE, verbose_name='Товар' ) filter_category = models.ForeignKey( FilterCategory, null=True, on_delete=models.CASCADE, verbose_name='Фильтр категории' ) value = models.ForeignKey( FilterSelect, blank=True, null=True, verbose_name='Значения фильтра' ) def __str__(self): return self.filter_category.name class Meta: verbose_name = 'Фильтр товаров' verbose_name_plural = 'Фильтры товаров' So for my category i use the view: class CategoryView(ListView): template_name = '__index.html' context_object_name = 'products' paginate_by = 20 def get_queryset(self): return Product.objects.filter(category__slug=self.kwargs.get('slug')).order_by('-created') def get_context_data(self, **kwargs): context = super(CategoryView, self).get_context_data(**kwargs) # Get Current Category category = get_object_or_404(Category, slug=self.kwargs['slug'], id=self.kwargs['id']) # Paginator if context.get('is_paginated', False): paginator = context.get('paginator') num_pages = paginator.num_pages current_page = context.get('page_obj') page_no = current_page.number if … -
How to get Ubuntu Server plus Domain running with uwsgi nginx? (from scratch)
This is my first post so I apologize if it isn't up with stack overflow standards. I just purchased a dedicated vps server at nfoservers.com. I have two ip's on my server which is running ubuntu 16.04-LTS x64. I have never set up a server from scratch. My biggest issue is getting my domain to point to the server IP. I have the name server set to ns1.nfoservers.com & ns2.nfoservers.com. I also have apache2 installed and my /etc/apache2/sites-enabled/domain.com.conf and /etc/apache2/sites-available/domain.com.conf look like so: https://pastebin.com/nd7eMH9H ServerName domain.com ServerAlias www.domain.com ServerAdmin webmaster@localhost DocumentRoot /var/www/html/domain.com/public_html ErrorLog /var/www/html/domain.com/logs/error.log CustomLog /var/www/html/domain.com/logs/access.log combined ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined I do not have nginx set up yet but I didn't think my problem was nginx because from my understanding apache can serve the site to and ip or domain. Lastly I might add that my goal is to clone my django web app to the server once I can get my domain working... Please Help I am desperate. -
Static Files not working after few days
Static files - bootstrap.min.css and the js files - worked last week and today they are not! I am using Django 1.11 on Python 3. My static files are stored in - final/static folder. Final is the name of my project, ie. it is stored in the roor settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) // End STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') base.html: <!DOCTYPE html> {% load staticfiles %} <html lang="en"> <head> <title>{% block title %}QUIZ{% endblock %}</title> <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet"> {% block x_css %} {% endblock %} </head> Still, the css and js won't work to give a very plain and undesirable look. -
Trying to send value from javascript to python server
I have multiple input tags, my task is to collect the values entered by the user and send it back to the server. I am using Django as my framework. I am successful in sending the data to the client side (javascript). To return back the data from javascript function to my python function, I used XMLHttpRequest. I have added my code below: html_string=html_string+' <html><head><style>label{ text-align:center; width:250px; color:blue; display:inline-block}</style> <script type="text/javascript" src="'+url_read+'"></script> <script>function submit_this(url){var i,j;var arr=[];for(i=0; i<Hello.length; i++) {arr[i]=[];for(j=0;j<Hello[i].length; j++) {arr[i].push(document.getElementById(Hello[i][j]).value);}}alert(document.getElementById(Hello[1][0]).value); xmlHttpReq = new XMLHttpRequest(); xmlHttp.open('POST', '/button_click',true); xmlHttpReq.send('w=' + encodeURI(arr));}</script></head><body>' The plan was to use HttpResponse to send the html and render the html page in return. I understand that I need to make one POST function in one of the classes in views.py. But unable to understand how to approach this problem. I have to somehow send the javascript data structure named arr back to the server side. -
How to create custom list filters based on month and year in Django admin
I have a Django model which has a date field and I want to create a list filter which will show the following options, Current 2017 2016 2015 upon clicking the year it will show the months as, 01 02 03 04 ... I tried the default DateFieldListFilter but it has only the following options, Any Today Past 7 days This month This year I was trying to solve this using SimpleListFilter but could not succeed. class MonthFilter(admin.SimpleListFilter): title = 'Month' parameter_name = 'month' def lookups(self, request, model_admin): months = [["current", "Current"]] qs = model_admin.model.objects.exclude(ts_from=None).order_by('ts_from') last= qs[0] last_year = last.ts_from.year current = timezone.now() current_year = current.year months.append([current_year, current_year]) months.append([last_year, last_year]) return months def queryset(self, request, queryset): if self.value(): return queryset.filter(ts_from__contains=self.value()) else: return queryset -
Error during template rendering, python django-static-precompiler
I want to deploy using nginx, uwsgi , python django and use django-static-precompiler if I put on command, python manage.py runserver perfect work. But using uwsgi, nginx print error message Error during template rendering equest Method: GET Request URL: http://my.host/ Django Version: 1.8.18 Exception Type: StaticCompilationError Exception Value: Aborting... Exception Location: /lib/python3.4/site-packages/static_precompiler/compilers/less.py in compile_file, line 72 Python Executable: /usr/local/bin/uwsgi Python Version: 3.4.3 error occured here <link rel="stylesheet" href=" {% static 'myproject/myfile.less'|compile %} " /> what can I do? I already do "npm install -g less" -
Redirect to node app in Django
So I'm running a server with Django, and I want the root url to point to a meteor app on the same server. I'm trying to figure how how to call that from within django. I'm new to Django and meteor and nginx.. I'm usually a LAMP guy. So am I supposed to use the URLs thing in Django and point to main.js? Or do I need to create a view and have the view execute the main.js? Thank you -
Django or Nodejs for Amazon redshift?
I want to build an app which uses Amazon redshift. Which is the best to use among Django and Nodejs? Which one is more compatible and optimized for redshift? -
Django Forms Not Setting Initial Values
I want to use def clean(self) to raise Validation Errors if necessary. However before I can use it all my fields have to be populated. THus I set inital values in my views.py like so: offering = DirectOffering.objects.get(id=offering_id) current_user = InvestorProfile.objects.get(user=request.user) form = DirectInvestmentForm(request.POST or None, initial={'offering': offering, 'user': current_user}) form.fields['user'].widget = forms.HiddenInput() form.fields['offering'].widget = forms.HiddenInput() if form.is_valid(): investment = form.save(commit=False) investment.save() However when I look at Local Vars on my error page I see: cleaned_data {'offering': None, 'quantity': 12345678, 'user': None} Quantity is what i entered the other two fields should have been autopopulated by initial={} -
implementing models.py on home page (NOT admin)
I have been watching tutorials about creating a blog but they are developing blogs in admin page - I do not want that. I want it on home page, accessible for whole public. Here is the code from my models.py (app name is called 'signups') from __future__ import unicode_literals from django.db import models # Create your models here. class SignUp (models.Model): name1 = models.CharField (max_length = 120, null = True, blank = False) name2 = models.CharField (max_length = 120, null = True, blank = False) how should I change my views.py to implement this model? also, what should my html file include? here's what i have done so far: <!DOCTYPE html> <html> <head> <title>Home</title> </head> <body> <h2> Please enter data in two text fields below </h2> </form> </body> </html> Basically, the task is simple. Two text fields on a webpage and a submit button. Then whatever data user adds in the fields, i should take it as a string and pass it into my word_count function and display the total count on a new web page. Please help. I am new to Django -
Django 1.11 Unexpected change in generation of password reset token
I have been successful in generating password reset links and sending them to mail using django builtin password reset and also used my own templates wherever needed. Above was the case when I implemented it in my test project (just to not break my actual project). but when I copy pasted my codes from test project to actual project, there was change in generation of reset password links Token when was working in my test project http://localhost:8000/reset/MQ-4mv-a71bc30f3eddfc12bd21/ Token when was working in my actual project http://localhost:8000/reset/Mg/4mv-66daf7703ee57c98aaa8/ There is a change MQ- and Mg/ My problem: 1) I am unable to match the regular expression in the URL and show my template instead of django default template which is being shown url(r'^reset/password/success/$', AuthHandler().reset_success, name="auth.success"), url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>.+)/$',AuthHandler().reset_password, name="password_reset_confirm"), url(r'^reset/done/$', auth_views.password_reset_complete,name="auth.complete"), In view.py def forgot_password(self, request): # Forgot password form try: error_flag = True if request.method == "GET": error_flag = False form = auth.ForgotPassword() return auth_views.password_reset( request, template_name='forgot_password.html', extra_context={'form': form, 'error': error_flag}, password_reset_form=auth.EmailValidationOnForgotPassword, post_reset_redirect='auth.success', ) except Exception as e: print(e) def reset_success(self, request): # Reset email sent to email try: return auth_views.password_reset_done(request, template_name='reset_password_success.html') except Exception as e: print(e) def reset_password(self, request, uidb64, token): # Reset password page try: reset_form = auth.ResetPassword() # template_name='te/reset_password.html', return … -
A good method for user creation in Django Rest Framework
I customize model as below. from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser, _user_has_perm ) from django.core import validators from django.utils.translation import ugettext_lazy as _ from django.utils import timezone class AccountManager(BaseUserManager): def create_user(self, request_data, **kwargs): now = timezone.now() if not request_data['email']: raise ValueError('Users must have an email address.') if request_data['profile']: profile = request_data['profile'] else: profile = None user = self.model( username=request_data['username'], email=self.normalize_email(request_data['email']), is_active=True, last_login=now, date_joined=now, profile=profile ) user.set_password(request_data['password']) user.save(using=self._db) return user def create_superuser(self, username, email, password, **extra_fields): request_data = { 'username': username, 'email': email, 'password': password } user = self.create_user(request_data) user.is_active = True user.is_staff = True user.is_admin = True # user.is_superuser = True user.save(using=self._db) return user class Account(AbstractBaseUser): username = models.CharField(_('username'), max_length=30, unique=True) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) email = models.EmailField(verbose_name='email address', max_length=255, unique=True) profile = models.CharField(_('profile'), max_length=255, blank=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) delete = models.BooleanField(default=0) objects = AccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] def user_has_perm(user, perm, obj): return _user_has_perm(user, perm, obj) def has_perm(self, perm, obj=None): return _user_has_perm(self, perm, obj=obj) def has_module_perms(self, app_label): return self.is_admin def get_short_name(self): return self.first_name @property def is_superuser(self): return self.is_admin class Meta: db_table = 'api_user' swappable … -
Filtering Django ModelViewSet List From kwargs
Hi I have a model like: class Appointment(models.Model): hospital = models.ForeignKey(Hospital, on_delete=models.CASCADE) patient = models.ForeignKey(Patient, on_delete=models.CASCADE) My View looks like: class AppointmentViewSet(viewsets.ModelViewSet): queryset = Appointment.objects.all() serializer_class = AppointmentSerializer In my urls: router.register(r'appointments', AppointmentViewSet) Now I want to filter the list of appointments by some patient id. This id should be given by the requester through url. I'm thinking about using kwargs to catch it. But I have no idea how to do it. I know I have to override the list method. def list(self, request, *args, **kwargs): # what do I write here? so that the queryset would be filtered by patient id sent through the url? How do I customize the url and/or the view to accommodate the patient id parameter? I just want to modify the list request, all other actions(create, details, destroy) should be handled by the modelviewset's default behavior. Thanks. -
issue with interdependent drop down django and ajax
My View def ajax_get_department(request): if request.POST['company_name'] == "": return HttpResponse('<option value=""></option>') Company_Name = request.POST['company_name'] departments = Department.objects.filter(company_name=Company_Name).filter(status="Enabled") return render(request, 'application_settings/filter_department.html', {'departments': departments}) My Jquery and Ajax function updateDepartment(control){ var department_sel = $("#{{form.department.auto_id }}").find(':selected').val(); $.ajax({ type: 'POST', url: (location.href.includes('modify_dept') ? '../../filter_department': 'filter_department'), data: {'department': $(control).find(':selected').val() }, success: function(departmentHTML){ $('#{{form.department.auto_id }}').html(departmentHTML); $('#{{form.department.auto_id }}').val(department_sel); } }); } $(document).ready(function(){ $('#{{form.department.auto_id }}').change(function(){ updateDepartment(this); }); updateDepartment('#{{form.department.auto_id }}'); }); filter department html <option value=""></option> {% for department in departments %} <option value="{{ department.id }}">{{ department.department_name }}</option> {% endfor %} I'm trying to filter certain items that get retrieved from the database depending on the company that that was chosen, and to display the departments that apply to the chosen department. But it doesn't filter just shows me every department. -
build Apache with cosign and wsgi inside a docker container
I'm trying to build apache inside an ubuntu based container . apache has to be build with cosign filter . In ddition the container will serve django files via wsgi here is my docker file : FROM ubuntu:16.04 RUN apt-get update RUN apt-get install -y apt-utils vim curl apache2 apache2-utils RUN apt-get -y install python3 libapache2-mod-wsgi-py3 RUN apt-get -y install postgresql postgresql-contrib pwgen RUN apt-get update \ && apt-get install -y wget gcc libssl-dev=$OPENSSL_VERSION make openssl RUN wget "$COSIGN_URL" \ && mkdir -p src/cosign \ && tar -xvf cosign-3.2.0.tar.gz -C src/cosign --strip-components=1 \ && rm cosign-3.2.0.tar.gz \ && cd src/cosign \ && ./configure --enable-apache2=/usr/local/apache2/bin/apxs \ && sed -i 's/remote_ip/client_ip/g' ./filters/apache2/mod_cosign.c \ && make \ && make install \ && cd ../../ \ && rm -r src/cosign \ && mkdir -p /var/cosign/filter \ && chmod 777 /var/cosign/filter COPY start.sh . RUN chmod +x start.sh CMD /usr/local/apache2/start.sh RUN ln /usr/bin/python3 /usr/bin/python RUN apt-get -y install python3-pip RUN ln /usr/bin/pip3 /usr/bin/pip RUN pip install --upgrade pip RUN pip install django ptvsd ADD ./demo_site.conf /etc/apache2/sites-available/000-default.conf EXPOSE 80 3500 CMD ["apache2ctl", "-D", "FOREGROUND"] ` to be honnest its just copy past from the internet . I need to know how to build this . -
i18n Internationalization and Localization in React Django
I am working on a Project where I am using React js for Front-End and Django for backend. I need to implement i18n Internationalization and Localization I saw Django documentation and came across django I18n javascript_catalog. How to use the same using getText() in React JS?. Is there any other way to implement?. Thanks in Advance -
django urls keeping the last path
so i have this 2 forms <form action="adicionar" accept-charset="utf-8"> <input class="searchfield" id="searchbox" name="txtSearch" type="text" placeholder="Search"> <button class="searchbutton" type="submit"> Adicionar<i class="fa fa-search"></i> </button> </form> <form action="novo"> {% csrf_token %} <h2> Bem vindo {{ user.getNome }}</h2> <input type="text" name="txtPost"> <button type="submit">Salvar</button> </form> and these views def novo(request): texto = request.GET.get('txtPost') user = request.session['usuario'] p = Post(texto=texto, fk_user=user,likes=10) p.save() usuario = Usuario.objects.get(id=user) return posts(request,id_user=usuario) def adicionar(request): nome = request.GET.get('txtSearch') usuario = Usuario.objects.get(id=request.session['usuario']) amigo = Usuario.objects.get(nome=nome) a = AmigoTemp(id_user=request.session['usuario'], id_amigo=amigo.id) a.save() return posts(request,id_user=usuario) the only relation between them is their .html file, which is the same everytime i click in any of the buttons to call their respective function in the views, they just clone the last path for example: i'm on my localhos..../ i click on the searchButton to call the 'adicionar' method and my url is now localhost.../adicionar i do what i gotta do and get back to localhos.../, but when i click on the another form i get this url localhost.../adicionar/novo and if i click again, just keep cloning like: localhost.../adicionar/novo/novo and so on... i don't really know if made my problem clear enough, but i dind't find anything about it my urls.py is this: url(r'^autentificacao/novo/',novo), url(r'^autentificacao/adicionar/',adicionar), -
Deploying Django app on pythonanywhere.com
I am facing issues during migration with MySql database during my Django app deployment on PythonAnywhere.com. Following is the error: django.db.utils.OperationalError: (1170, "BLOB/TEXT column 'examname' used in key specification without a key length") 'examname' is not a primary key in my model. But, I still get the error. -
How to connect redis with django project?
As i'am new to channels and redis i don't able to fix the issue. The issue is when i tried testing the redis whether it is working or not? it passes the test. But when i run the project i cant able to see the index page. I have explained the issue in detail below. Someone help me out. Thanks in advance. Installed packages python 3.4 django 1.10 redis 2.10 channels sockets When i test redis it works fine. Attached the screenshot below. Testing Redis Screenshot When i run the project i got the below error message in the terminal. Attached the screenshot below. python manage.py runserver 8000 [screenshot] I have attached my code blocks below. routing.py from channels.routing import route from chat_room.consumers import ws_connect, ws_disconnect channel_routing = [ route('websocket.connect', ws_connect), route('websocket.disconnect', ws_disconnect), ] settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'channels', 'chat_room', ] CHANNEL_LAYERS = { 'default': { 'BACKEND': 'asgi_redis.RedisChannelLayer', 'CONFIG': { 'hosts': [('localhost', 6379)], }, 'ROUTING': 'chat_application.routing.channel_routing', } } consumers.py from channels import Group def ws_connect(message): Group('users').add(message.reply_channel) def ws_disconnect(message): Group('users').discard(message.reply_channel) index.html ....some code.... <script> var socket = new WebSocket('ws://' + window.location.host + '/users/'); socket.onopen = function open() { console.log('WebSockets connection created.'); }; socket.onmessage = function … -
Django password_change doesn't work
I have trouble implementing password_change in django. Here is my code : url('^password-change/$',password_change,{'post_change_redirect': 'users:password_change_done'},name='password_change'), url('^password- change/done/',password_change_done,name='users_password_change_done'), The html code is : <h1>Change Password</h1> <form action="." method="post"> {% csrf_token %} {{form.as_p}} <input type="submit" value="Change password"> </form> The error that I get is : NoReverseMatch at /users/password-change/ Reverse for 'password_change_done' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] I have looked at other posts that deal with similar issues but I have not been able to fix my code based on those answers. -
Django dev server STILL won't serve static files
Okay, all. I know this is a question that many people have solved in various cases, but I cannot for the life of me get my Django 1.9 development server to serve static content on my local computer. Static files worked fine pre-deployment, and are totally fine on my deployment server, but now in my test environment (local computer with runserver going) everything is broken, and I really need to be able to test stylesheets in a dev environment. I have tried all of these solutions and more, followed the documentation guide, used collectstatic again in the development repo... nothing has worked, and I am at my wits' end. Currently, I have DEBUG = True, and the following setup: Folder Hierarchy project/ manage.py (&c) app/ urls.py models.py (&c) project/ settings.py urls.py (&c) static/ styles/ images/ (&c) settings.py Static Files Settings STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = ( os.path.join(STATIC_ROOT, 'styles/'), os.path.join(STATIC_ROOT, 'js/'), os.path.join(STATIC_ROOT, 'audio/'), os.path.join(STATIC_ROOT, 'images/'), os.path.join(STATIC_ROOT, 'admin/'), os.path.join(STATIC_ROOT, 'documents/'), ) urls.py URL Patterns from django.conf.urls import include, url, patterns from django.conf import settings from django.conf.urls.static import static from django.contrib import admin urlpatterns = [ # ... project url patterns blah blah ... ] if settings.DEBUG: urlpatterns += …