Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to not ignore compiled css files in django-livereload-server
I'm using django-livereload-server in a small Django project, and otherwise it's plenty enough for this project but it ignores the CSS files compiled from SASS. Since it is based on python-livereload, I can give it the w argument to wait for a given number of seconds before reloading, but first of all it's very inconvenient and annoying to have to wait for a couple seconds every time you want to see a change, but more importantly it's quite unreliable. Sometimes the wait period does help in showing the compiled CSS changes, but often times I have to reload manually anyway. Is there a simple way to not ignore the compiled CSS files? Or better yet, ignore the .sass files and just watch the .css files. (Or, if there are better alternatives that do not require extensive setup, feel free to suggest those instead.) -
Use additional request param to generate a model field in DRF 3
I am new to Djnago Rest Framework 3 and not able to understand how to achieve this: I have following model: class Interface(models.Model): name = models.CharField(max_length=25) current_location = models.CharField(max_length=25, blank=True) And in request param, I am expecting latitude, longitude field which will generate the geohash from latitude, longitude and store in current_location. I tried using following serializer, but it is giving error 'Interface' object has no attribute 'latitude'. class InterfaceSerializer(serializers.ModelSerializer): latitude = serializers.FloatField() longitude = serializers.FloatField() class Meta: model = Interface fields = ('id', 'imei', 'latitude', 'longitude',) read_only_fields = ('id',) Even using the serializers.Serializer instead of serializers.ModelSerializer gives same error. What is wrong here ? How to structure the serializer for for given model and requirement ? -
south.exceptions.NoMigration – djcelery
I just added a many-to-many relationship to my model and generated the new migration file: py manage.py schemamigration myapp --auto Then tried running the migration: py manage.py migrate myapp It did not complete successfully, raising a south.exceptions.NoMigrations exception: south.exceptions.NoMigrations: Application '<module 'djcelery' from 'C:\Python27\lib\site-packages\djcelery\__init__.pyc'>' has no migrations. No more information is given, and I cannot figure out what might be wrong. Has anybody experienced this issue before? I am using Python 2.7 and Django 1.4.22. -
python - can't install psycopg2 on centos 7
I'm trying to config django on centos 7 According to this article Here I installed sudo yum install python-pip python-devel postgresql-server postgresql-devel postgresql-contrib gcc nginx After setup PostgreSQL for django like creating database, ... I try installing psycopg2 on virtualenv pip install django gunicorn psycopg2 but I got this error , Anyone can help me ? Collecting psycopg2 Using cached psycopg2-2.6.2.tar.gz Installing collected packages: psycopg2 Running setup.py install for psycopg2 ... error Complete output from command /usr/bin/python3.4 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-n0buiow5/psycopg2/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-jk1w8dv1-record/install-record.txt --single-version-externally-managed --compile: running install running build running build_py creating build creating build/lib.linux-x86_64-3.4 creating build/lib.linux-x86_64-3.4/psycopg2 copying lib/tz.py -> build/lib.linux-x86_64-3.4/psycopg2 copying lib/pool.py -> build/lib.linux-x86_64-3.4/psycopg2 copying lib/extras.py -> build/lib.linux-x86_64-3.4/psycopg2 copying lib/extensions.py -> build/lib.linux-x86_64-3.4/psycopg2 copying lib/_range.py -> build/lib.linux-x86_64-3.4/psycopg2 copying lib/__init__.py -> build/lib.linux-x86_64-3.4/psycopg2 copying lib/psycopg1.py -> build/lib.linux-x86_64-3.4/psycopg2 copying lib/_json.py -> build/lib.linux-x86_64-3.4/psycopg2 copying lib/errorcodes.py -> build/lib.linux-x86_64-3.4/psycopg2 creating build/lib.linux-x86_64-3.4/psycopg2/tests copying tests/test_errcodes.py -> build/lib.linux-x86_64-3.4/psycopg2/tests copying tests/dbapi20.py -> build/lib.linux-x86_64-3.4/psycopg2/tests copying tests/test_bug_gc.py -> build/lib.linux-x86_64-3.4/psycopg2/tests copying tests/test_async.py -> build/lib.linux-x86_64-3.4/psycopg2/tests copying tests/testconfig.py -> build/lib.linux-x86_64-3.4/psycopg2/tests copying tests/test_quote.py -> build/lib.linux-x86_64-3.4/psycopg2/tests copying tests/test_extras_dictcursor.py -> build/lib.linux-x86_64-3.4/psycopg2/tests copying tests/test_types_basic.py -> build/lib.linux-x86_64-3.4/psycopg2/tests copying tests/test_transaction.py -> build/lib.linux-x86_64-3.4/psycopg2/tests copying tests/test_cancel.py -> build/lib.linux-x86_64-3.4/psycopg2/tests copying tests/test_dates.py -> build/lib.linux-x86_64-3.4/psycopg2/tests copying tests/test_lobject.py -> build/lib.linux-x86_64-3.4/psycopg2/tests copying tests/dbapi20_tpc.py -> build/lib.linux-x86_64-3.4/psycopg2/tests copying tests/test_copy.py -> build/lib.linux-x86_64-3.4/psycopg2/tests copying tests/test_types_extras.py … -
Django : ManyToMany relation error ( object has no attribute)
I am trying to define some ManyToMany relations in Django, but I have an error when I try to create related objects. My models.py : class PerfumeBrand(models.Model): class Meta: verbose_name = "Marque de parfum" verbose_name_plural = "Marques de parfum" name = models.CharField(max_length=32) def __str__(self): return self.person.first_name + ' ' + self.person.last_name.upper() + ': ' + self.name class Person(models.Model): class Meta: verbose_name = "Personne" verbose_name_plural = "Personnes" first_name = models.CharField(max_length=32, ) last_name = models.CharField(max_length=32) email = models.EmailField(unique=True) # Here is the ManyToMany relation perfume_brands = models.ManyToManyField(PerfumeBrand) The problem is that when I try to save a PerfumeBrand object in my database, I get this error : AttributeError at /admin/visualize/perfumebrand/add/ 'PerfumeBrand' object has no attribute 'person' I tried to save both in code and admin panel, the same error occurs. As this is the first time I need a ManyToMany relation in a Django project, I am a bit confused, and I didn't find any solution to my problem. Have you any idea ? -
How to put in clean method authentificated user object?
I need to validate form and if authentificated user id is not in form data then raise Validation Error. How can I give to clean method the information about this user? -
Django One-To-One relationships on forms
I have the following model that links to "user": class Profile(models.Model): user = models.OneToOneField(User) title = models.CharField(max_length=10) dob = models.DateField(max_length=8) class Meta: managed = True db_table = 'fbf_profile' I then have the following registration form: class RegistrationForm(BootstrapModelForm, UserCreationForm): def __init__(self, *args, **kwargs): super(RegistrationForm, self).__init__(*args, **kwargs) # The default Django user model doesn't require these fields to be set # but we do. self.fields['first_name'].required = True self.fields['last_name'].required = True self.fields['email'].required = True def clean_email(self): email = self.cleaned_data['email'] if User.objects.filter(email__iexact=email).exists(): raise ValidationError('There is already an account registered with this e-mail address.') return email class Meta: model = User fields = ['first_name', 'last_name', 'email', 'username'] I am then able to use them in my templates like so: <div class="form-group"> <label class="col-sm-5 control-label">{{ form.first_name.label }}:</label> <div class="col-sm-7"> {{ form.first_name }} <div class="text-danger"> {% for error in form.first_name.errors %}{{ error }}<br/>{% endfor %} </div> </div> </div> However, how can I use the "dob" from the Profile model within the template in much the same way as I have done with form.first_name.label and form.first_name above. Many thanks in advance, Alan. -
Saving AWS Environment Variables to File - How to handle special character '&'
I am trying to run a django manage.py task via cron, on AWS Elasticbeanstalk (EB). */10 * * * * root /usr/local/bin/notification_cron.sh > /dev/null The notification_cron.sh script calls a django manage.py task. Django needs EB's environment variables (like RDS_PORT, RDS_DB_NAME, RDS_PASSWORD etc). So I am saving these environment variables into a file at deployment, and reloading those in the bash script that also calls the manage.py task. This is part of my deployment config in .ebextensions: commands: 001_envvars_to_bash_source_file: command: | # source our elastic beanstalk environment variables /opt/elasticbeanstalk/bin/get-config --output YAML environment|perl -ne "/^\w/ or next; s/: /=/; print qq|\$_|" > /usr/local/bin/envvars chmod 755 /usr/local/bin/envvars files: "/usr/local/bin/notification_cron.sh": mode: "000755" owner: root group: root content: | #!/usr/bin/env bash AWS_CONFIG_FILE="/home/ec2-user/.aws/config" set -o allexport # Loading environment data source /usr/local/bin/envvars set +o allexport cd /opt/python/current/app/ source /opt/python/run/venv/bin/activate python manage.py my_management_task The problem is caused by the line /opt/elasticbeanstalk/bin/get-config --output YAML environment|perl -ne "/^\w/ or next; s/: /=/; print qq|\$_|" > /usr/local/bin/envvars or the alternate sed equivalent /opt/elasticbeanstalk/bin/get-config environment --output yaml | sed -n '1!p' | sed -e 's/^\(.*\): /\1=/g' > /usr/local/bin/envvars The contents of /usr/local/bin/envvars are not always in quotes: PYTHONPATH="/opt/python/current/app/mydjangoapp:$PYTHONPATH" DJANGO_SETTINGS_MODULE=mydjangoapp.settings AWS_ACTIVE='true' RDS_PORT='5432' RDS_HOSTNAME=hostname.host.us-east-1.rds.amazonaws.com RDS_USERNAME=master RDS_DB_NAME=ebdb RDS_PASSWORD=My&Password This causes trouble where an environment … -
How to Make Different Urls For same viewset in Django Rest Framework
I have a Serializer in my code like this class SampleSerializer(serializers.ModelSerializer): class Meta: model = Model and Viewset like this class SampleViewSet(GenericAPIView): serializer_class = SampleSerializer def get(self, request, *args, **kwargs): pass def post(self, request, *args, **kwargs): pass def put(self, request, *args, **kwargs): pass I have url like this for this viewset Url #1: url(r'^sample/$', SampleViewSet.as_view()) This makes url for all methods I have in my viewset like get, post and put etc. I want to make separate url for my get method but using same serializer. This url will look like this Url #2: url(r'^sample/(?P\d+)/$', SampleViewSet.as_view()) How can I do this using same Viewset and Serializer? When I write Url #2 in urls.py, Swagger shows me all three type (get, post and put) of methods for that Url. -
Django PostgreSQL one model on multiple schema
We have an app that supports multiple cities, each city has its schema in the database and a table with a list of addresses. We have a model for the addresses (that is to say one model for various tables each in a separate schema). To display in the apps, we use a middleware to switch between schemas depending on the url arguments. That works like a charm. However in the admin, we would like to "merge" all the possible address tables to allow for search etc.. Do you know how to do it ? I have searched in the doc but found nothing.. -
how to django decorator use to login user redirect to multiple pages
class Login(FormView): template_name = 'login.html' form_class = LoginForm success_url = '.' def form_valid(self, form): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(username=username, password=password) if user is not None: login(self.request, user) return HttpResponseRedirect("/") else: return super(Login, self).form_valid(form) -
Iter over dict and display object.item django template
I have three contacts to display on my page, and instead of writing three times the contact div div div object.first /div /div /div div div div object.second /div /div /div div div div object.last /div /div /div I would prefer to do something like contacts = ['first', 'second', 'third'] In python view {% for contact in contacts %} div div div {{ object.contact }} /div /div /div {% endfor %} Any idea ? -
how to open multiple templates in new tabs Django
In Django Admin I want to mention checkboxes records that I want to open the template. The Action dropdown I choose Print . Each entry is transferred to a separate template that opens in a new tab. admin.py @admin.register(Salary) class SalaryAdmin (admin.ModelAdmin): list_display = ('worker', 'salary_uah', 'dates') search_fields = ('worker', 'salary_uah', 'dates') list_filter = ('worker', 'date') actions = ['button'] def button(self, request, queryset): select = request.POST.getlist(admin.ACTION_CHECKBOX_NAME) for i in select: return '<a target="_blank" href="{}"></a>'.format(reverse('act', args=[i])) button.short_description = 'Print' button.allow_tags = True views.py def acts (request, obj): if not request.user.is_authenticated(): return redirect('admin:login') salary = Salary.objects.get(id=obj) workers = Worker.objects.filter(id=salary.worker.pk).values() salary = Salary.objects.filter(id=obj).values() return render(request, 'zpapp/act.html', {'workers':workers, 'salary':salary } urls.py urlpatterns = [ url(r'^$',home, name='home'), url(r'^add/$',add_worker, name='add'), url(r'^act/(?P<obj>[\w-]+)$',acts, name='act') Can someone help me? -
Making Django forms return forms.instance in templates
What I want to achieve is best described by example. I don't even know what key words to use in google to see which Django tools are designed to solve such issues. So please bear me. Currently, I have the following code in my Django template {%if user.has_permission_to_edit %} {{my_form.my_field}} {% else %} {{my_form.instance.my_field}} {% endif %} And here's my_form: class MyForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) for field_name, field in self.fields.items(): field.widget.attrs['class'] = 'form-control input-sm' if field.required == True: field.widget.attrs['required'] = '' class Meta: model = MyModel fields = ('my_field',) I am relatively new to Django, and I know that there is plethora of advanced tools making Django code potentially super DRY, so I want to asked you guys, what is the most DRY method to organize what I described in the template. Specifically, is there any way to make Django forms return instance values based on some condition specified inside the form definition? Or do I have to some used-defined tag ? Or maybe some totally different architecture is used to achieve such goals -
has any one embeded SAPUI5 MVC with django mvc ? how do integrate two technologies?
I have an django application but instead of loading normal HTML template, I want to use SAPUI5 application as rendering template. can anyone suggest how to do that? -
Test a Class based Django View with RequestFactory, middleware, session and template context processor
I've a couple of views that are used as a mixin for other views. I want to test them by using a RequestFactory as the mixin themselves don't have a urlconf and I want to test some cornercases also. As the webapp uses all kinds of extra context in the form of Template Context Processors to determine how to render the templates I need the info in the template context processors also. The below code uses a simplified setup where I only use a template context processor version that could be used in a template like this {{ version }}. The templates would display certain info based on the version, which I would like to assert. After investigating I managed to get it working like this. The code uses py.test fixtures and py.test runner: class TestDynamicViewSettings(object): def add_session_to_request(self, request): """Annotate a request object with a session""" middleware = SessionMiddleware() middleware.process_request(request) request.session.save() def test_view(self, admin_user, list_view_data): factory = RequestFactory() request = factory.get('/test/list') request.user = admin_user self.add_session_to_request(request) response = DummyListView.as_view()(request) # add the info that would normally be added by the template context processor response.context_data['version'] = '1.0' content = response.render() assert 'version 1.0 related stuff' in smart_str(content) Just to be complete here … -
Validate Admin Inline form
I the Admin interface, I need to validate a field which is inside an Inline. Site has a name which has to be stored in lowercase. How can I access to the name field in the inline to perform that validation? I could also override its save method in models but I'd like to know how to do it in admin. class SiteInline(admin.TabularInline): model = Site classes = ('grp-collapse grp-open',) inline_classes = ('grp-collapse grp-open',) class CompanyAdmin(admin.ModelAdmin): ordering = ['name'] inlines = (SiteInline, ) -
Django save only first form of formset
I've looked throung every similar question (and tried them), but still couldn't find answer. Probably, just too dumb. I have two models: class Project(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) name = models.CharField(max_length=120, verbose_name = "Название проекта") url = models.URLField(max_length=120, unique=True, verbose_name = "Полный адрес сайта") robots_length = models.CharField(max_length=5, default=0) updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) def __unicode__(self): return self.name def __str__(self): return self.name def get_absolute_url(self): from django.urls import reverse return reverse('projects:detail', args=[str(self.id)]) class ProjectPage(models.Model): page_project = models.ForeignKey(Project, on_delete=models.CASCADE) page_url = models.URLField(verbose_name = "Адрес страницы") page_title = models.CharField(max_length=300, blank=True, verbose_name = "meta-title",default="") page_description = models.CharField(max_length=300, blank=True, verbose_name = "meta-description",default="") page_h1 = models.CharField(max_length=300, blank=True, verbose_name = "Заголовок h1",default="") def __unicode__(self): return self.page_url def __str__(self): return self.page_url For each model there is a form: class ProjectFormUpdate(forms.ModelForm): class Meta: model = Project fields = [ "name", "url", ] widgets = { 'name': forms.TextInput(attrs={'placeholder': 'Произвольное название'}), } class ProjectPageForm(forms.ModelForm): class Meta: model = ProjectPage fields = [ 'page_project', 'page_url', 'page_title', 'page_description', 'page_h1', ] widgets = { 'page_project': forms.HiddenInput() } In views.py I have: def projects_update(request, proj=None): instance = get_object_or_404(Project, id=proj) form = ProjectFormUpdate(request.POST or None, instance=instance) formset_f = modelformset_factory(ProjectPage, form=ProjectPageForm, extra=3) formset = formset_f(queryset=ProjectPage.objects.filter(page_project__id=proj), initial =[{'page_project': proj}]) if request.method == 'POST': formset = formset_f(request.POST) … -
serve user-uploaded media files in local development doesn't work
I know there is alot of questions being ask regarding this topic, but I'm still stuck. I can't serve user-uploaded media files in local development to work. I've been over and over the documentation on this, I can't see what I've misconfigured or is missing. I can upload files from the admin and they added correctly to the specified folder, but it's when I'm trying to use the images in my template that nothing happens, it is just blank. When inspecting the HTML I see: <img src="/media/team_images/adr.jpg" alt="">. The code settings.py # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', # Disable Django's own staticfiles handling in favour of WhiteNoise, for # greater consistency between gunicorn and `./manage.py runserver`. See: # http://whitenoise.evans.io/en/stable/django.html#using-whitenoise-in-development 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ ... 'django.template.context_processors.media', ], 'debug': DEBUG, }, }, ] # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.9/howto/static-files/ STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles') STATIC_URL = '/static/' # Extra places for collectstatic to find static files. STATICFILES_DIRS = [ os.path.join(PROJECT_ROOT, 'static'), ] # Simplified static file serving. # https://warehouse.python.org/project/whitenoise/ … -
How to get all dict data
I using python 2.7.11 and djnago 1.10.2. Created category api. How to get json dict data in Django views. I tryed two days but it get only List data. This is my api example and i need "parent" filed data. [ { "url": "", "category_image": [], "price_rule": null, "parent": { "id": 12, "category_image": [], "name": "cat1", "slug": "cat1", "category_description": "", "page_title": "", "meta_keywords": "", "meta_description": "", "default_product_listing_sort_by": "", "order": 0, "created_by": 1, "created_at": "2016-12-23T13:01:20.689936", "modified_by": 1, "modified_at": "2016-12-23T13:47:55.338865", "sort_position": null, "lft": 1, "rght": 10, "tree_id": 1, "level": 0, "parent": null, "price_rule": null }, "name": "cat2", "slug": "cat2", "category_description": "", "page_title": "", "meta_keywords": "", "meta_description": "", "default_product_listing_sort_by": "", "order": 1, "created_by": 1, "created_at": "2016-12-23T13:01:54.003769", "modified_by": 1, "modified_at": "2016-12-23T13:47:57.848614", "sort_position": null, "lft": 2, "rght": 3, "tree_id": 1, "level": 1 }, ] -
which one uses connection pool django cache[] or get_redis_connection() when using django-redis
There are 2 methods to get the redis connection when using django-redis (https://niwinz.github.io/django-redis/latest/) lib method-1 from django.core.cache import caches # get redis cache from settings rcache = caches['redis'] method-2 from django_redis import get_redis_connection rcache = get_redis_connection("redis") I tried checking internals and looks like get_redis_connection uses a connection pool, but the object it returns is of the strictredis client and not the default client - hence one cannot exactly jump from one to another. That being said, can someone confirm which one to use if you want to use connection pool when using the django-redis library Note: I am using memcache as the default django cache backend at present, with redis for some other caching purposes. Please let me know if the question or description sounds confusing, i can update. -
rq-scheduler in Django seems to have no effect
I have referred to rq-scheduler's documentation trying to schedule jobs in Django. I try to enqueue jobs in an django-rest-framework view, so when I call this view, the enqueue could be triggered. I have written the following code: from redis import Redis from rq_scheduler import Scheduler from datetime import timedelta def create_education: # Messing with my database here # here is a django-rest-framework view @api_view() def test(request): scheduler = Scheduler(queue_name='default', connection=Redis()) scheduler.enqueue_in(timedelta(minutes=1), create_education) return Response() After I ran the command rqscheduler and called test(), my database didn't change a bit. I could see the job enqueued using scheduler.get_jobs(with_times=True) and later watched it being pushed into the queue: Pushing e6064839-8666-4965-a543-3866132c83a6 to default But why can't I see the results? What did I do wrong? Please help. -
Django rest framework APIView same code for all methods
Is it possible to have a method in my APIView class which runs the same piece of code independent of the method i.e. GET/POST/PUT. -
Django REST Framework Filtering
I am using Django REST Framework Generic Filtering and wish to accomplish two goals: Get only the last result of a queryset. For example, http://my_server/users/?last will return only the last user (the one with the greatest id). Get the number of results in a query set. For example, http://my_server/users/?category=admin&count will return the number of admin users. What is the most elegant way of doing this? -
Django - CSRF Token generation - render_to_response vs render
I am trying out a simple user registration form in Django. CSRF token is not getting generated when I use render_to_response return render_to_response('registration/register.html', RequestContext(request, {'form': RegistrationForm()})) where as, CSRF token is getting generated when I use render return render(request, 'registration/register.html', {'form':RegistrationForm()}) Am I doing anything wrong with render_to_response Following is the relevant code block views.py @csrf_protect def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): user = User.objects.create_user( username=form.cleaned_data['username'], password=form.cleaned_data['password1'], email=form.cleaned_data['email'] ) return HttpResponseRedirect('/register_success/') else: return render_to_response('registration/register.html', RequestContext(request, {'form': RegistrationForm()})) register.html {% extends "base.html" %} {% block title %}User Registration{% endblock %} {% block content %} <form method="post" action="."> {% csrf_token %} <table border="0"> {{ form.as_table }} </table> <input type="submit" value="Register" /> </form> {% endblock %}