Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to filter objects by ignoring upper and lower case letter django
recently I started learning django and I have several questions. And one of them has relationship with __icontains. Company.objects.filter(name__icontains=receiver_company_name) And let's assume that I have one company which called for example Dota-2, and when I search in my db this company by typing "D", it's return for me Dota-2. And my question will be about, if my company "Dota-2" it's saved in db like this "Dota-2", and when I trying to search like this lowercase "d", it's return me empty array. How to make name_icontains search by ignoring lower and uppercase letter? -
Failed: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it
My problem is the one bellow. If I try to run the test, it says there is no database permission and that I have to add that fixture. The problem is that I have added that fixture to any possible method I have, and still nothing. So I assume I don't know where to add this marker. Shouldn't it be in the method of the class I am calling the creation of these objects: test_can_get_page_details? If I remove UserFactory from assigning users to those attributes the test works. pytest.ini [pytest] DJANGO_SETTINGS_MODULE=core.settings_test test_pages.py import pytest from bs4 import BeautifulSoup import datetime from django.core.urlresolvers import reverse from interface.tests import factories class TestPageDetail: @pytest.fixture def defaults(self, db): page = factories.PageFactory() url = page.get_absolute_url() return { 'page': page, 'url': url } @pytest.mark.integration def test_can_get_page_details(self, defaults, db, admin_client): response = admin_client.get(defaults['url']) assert 200 == response.status_code factories.py import factory import datetime import pytest from interface import models class UserFactory(factory.django.DjangoModelFactory): class Meta: model = models.User django_get_or_create = ('username',) username = factory.Sequence(lambda n: "staffman-%d" % n) email = factory.LazyAttribute(lambda obj: '%s@example.com' % obj.username) first_name = factory.Sequence(lambda n: "John-%d" % n) last_name = "Doe" password = "1234" @classmethod def _create(cls, model_class, *args, **kwargs): """Override the default ``_create`` with our … -
django code to edit the Song and Album (object) model
i am getting error everytime i try to write the 'edit' view for the Album and Song instance. could anyone provide me the code to edit my albums and songs ? models.py - from django.db import models class Album(models.Model): album_title=models.CharField(max_length=50) date=models.DateTimeField(blank=True,null=True) def __str__(self): return self.album_title class Song(models.Model): song_title=models.CharField(max_length=50) genre=models.CharField(max_length=50) album=models.ForeignKey(Album,on_delete=models.CASCADE) def __str__(self): return self.song_title views.py- def formm(request): if request.method=='POST': songform = SongForm(request.POST) albumform=AlbumForm(request.POST) if songform.is_valid() and albumform.is_valid(): album = albumform.save(commit=False) album.date = timezone.now() album.save() song = songform.save(commit=False) song.album = album song.save() return redirect("result") else: albumform=AlbumForm() songform=SongForm() return render(request,"musicapp/formmpage.html", {'songform':songform,'albumform':albumform}) i just need to have 'edit.py' which can let us edit our saved album and song. Thanks. -
You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path
I am new to django ! When I use the commad, git push heroku master I get this error. remote: remote: -----> $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "manage.py", line 22, in <module> remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.6/sit-packages/django/core/management/__init__.py", line 355, in execute remote: self.fetch_command(subcommand).run_from_argv(self.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv remote: self.execute(*args, **cmd_options) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute remote: output = self.handle(*args, **options) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 199, in handle remote: collected = self.collect() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 124, in collect remote: handler(path, prefixed_path, storage) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 354, in copy_file remote: if not self.delete_file(path, prefixed_path, source_storage): remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 260, in delete_file remote: if self.storage.exists(prefixed_path): remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/files/storage.py", line 392, in exists remote: return os.path.exists(self.path(name)) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/storage.py", line 50, in path remote: raise ImproperlyConfigured("You're using the staticfiles app " remote: django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. remote: remote: ! Error while running '$ python manage.py collectstatic --noinput'. remote: See traceback above for details. remote: remote: You may need to update application code to resolve this error. remote: Or, … -
Postgres type "{field type}" is only a shell
I use Django & postgres. My migration contains something like this : db.create_table('location_locationlevel', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('name_0', self.gf('django.db.models.fields.CharField')(max_length=75, null=True, blank=True)), ('name_1', self.gf('django.db.models.fields.CharField')(max_length=75, null=True, blank=True)), ('name_2', self.gf('django.db.models.fields.CharField')(max_length=75, null=True, blank=True)), ('name_3', self.gf('django.db.models.fields.CharField')(max_length=75, null=True, blank=True)), ('name_4', self.gf('django.db.models.fields.CharField')(max_length=100, null=True, blank=True)), ('geom', self.gf('django.contrib.gis.db.models.fields.MultiPolygonField')()), )) When I run migration, I get error like below: django.db.utils.DatabaseError: type "geometry" is only a shell LINE 1: ...ABLE public.location_locationlevel ADD COLUMN geom geometry ^ QUERY: ALTER TABLE public.location_locationlevel ADD COLUMN geom geometry CONTEXT: PL/pgSQL function addgeometrycolumn(character varying,character varying,character varying,character varying,integer,character varying,integer) Did anyone have experienced something like this before, and what was the solution? -
How to run requests or beautiful soup library on django server? [on hold]
So there's this input field in my django form in which the user enters the ISBN number of a book. I have to use this ISBN number to get data about the book from Google Books. Where should my function live? Views/models/forms? Any idea on how to do it? -
Do Django delete db_index?
I am using postgresql for my django app. Managed to delete almost 500000 rows, but size of my DB didn't lower significantly. Deleted them with smth like lots.objects.filter(id__in=[ids]).delete() in chunks (because it's too hard to delete so many rows in one query). Some columns have db_index=True, so I think indexes were not deleted. Do I have the possibility to delete also indexes for deleted objects from django? Maybe there is also a way to see unused indexes from Django? -
How import and use csrf token in django 1.11?
Pease help use csrf token in django 1.11 in view.py i use follow code: from django.shortcuts import render_to_response, redirect from django.contrib import auth from django.views.decorators.csrf import csrf def login(request): args = {} args.update(csrf(request)) if request.POST: username = request.POST.get('username', '') password = request.POST.get('password', '') user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) return redirect('/') else: args['login_error'] = 'Пользователь не найден'; return render_to_response('login.html', args) else: return render_to_response('login.html', args) but console display follow error message: File "/home/kalinin/django/login/views.py", line 3, in from django.views.decorators.csrf import csrf ImportError: cannot import name 'csrf' in django 1.8 i use similar code, but import csrf: from django.core.context_processors import csrf and applications is running without problems Please help run my application for django 1.11 -
Django:permission denied for relation django_migrations, PostgreSql - django user?
I ve been struggling about figuring out relation between postgre users and linux users and the permissions between them.First question I want to ask is that ,let s assume I have tom linux user and tom postgre user which I created with psql command.What is the relation between those two? The reason I am asking is realated with following question: I am using vagrant and ubuntu in it.There is 2 userss , first one is Linux "vagrant" user , second one is PostgreSql "vagrant" user which I created through following commands: CREATE USER vagrant WITH PASSWORD '123.123'; GRANT ALL PRIVILEGES ON DATABASE cashier to vagrant; which should means and also is that vagrant have all permissions on cashier database. I should also mention as an aside note that I am using provisioning and vagrant uses root user when executing provisions , so root should also have all permissions on the cashier databse because I am importing dump into cashier database on provisioning. so you can easily assume root have granted permissions through : CREATE USER root WITH PASSWORD 'vagrant'; GRANT ALL PRIVILEGES ON DATABASE cashier to root; Here is the problem: When I try to runserver in django python manage.py … -
Check for existence of a related object in a Case queryset statement?
I want to annotate a queryset with a related object, if that object exists, or with another field if it doesn't: #models.py class MyModel(Model): f1 = ForeignKey(MyRelated, related_name='f1') f2 = ForeignKey(MyRelated, related_name='f2', null=True) #queryset MyModel.objects.annotate( f=Case( When( *something* ,then=F('f2')), default=F('f1') ) ) What I need to know is what to put in in place of *something* to check if the foreign key exists or not. -
Request object not available in template tags in Django 1.11
I had been using Django 1.9 and now I am upgrading my code to 1.11 I had this template tag which worked fine in 1.9 @register.simple_tag def active(request, pattern): import re pattern = "^" + pattern + "$" #request = context['request'] if re.search(pattern, request.path): return 'active' return '' And my base.html {% url "test:index" as home_url %} <li class="{% active request home_url %}"><a href="{% url 'test:index' %}">Calendar</a></li> But now an empty string is being passed instead of request object and so i am getting this error 'str' object has no attribute 'path' This is the Templates settings I am using TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'test', 'templates')], 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.debug', 'django.template.context_processors.i18n', 'django.template.context_processors.media', 'django.template.context_processors.static', 'django.contrib.messages.context_processors.messages', ], 'loaders': [ 'admin_tools.template_loaders.Loader', 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ], }, }, ] Here is the traceback Traceback: File "/spare/local/venv/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/spare/local/venv/lib/python2.7/site-packages/django/core/handlers/base.py" in _legacy_get_response 249. response = self._get_response(request) File "/spare/local/venv/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/spare/local/venv/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/spare/local/projects/towerportal/apps/tower_common/decorators.py" in _fn 42. return t.render(context,request) File "/spare/local/venv/lib/python2.7/site-packages/django/template/backends/django.py" in render 66. return self.template.render(context) File "/spare/local/venv/lib/python2.7/site-packages/django/template/base.py" in render 207. return self._render(context) File "/spare/local/venv/lib/python2.7/site-packages/django/template/base.py" in _render 199. return self.nodelist.render(context) File … -
Django/Python : How to fill my html array with my data?
From my previous post here Django/Dictionnary/Python that i solved, i need to fill an html array with all the datas included in my forms. I work with Django/Fobi and use Python/html. In my Views.py, i declare my variable to get the headers of my form and the data such as : entries = SavedFormDataEntry._default_manager \ .filter(user__pk=request.user.pk) \ .select_related('form_entry') headers = json.loads(entries[0].form_data_headers) headersLoop = headers.items() data = json.loads(entries[1].saved_data) valuesData = data.items() Then i add these variables into the context: context = {'entries': entries, 'form_entry_id': form_entry_id, 'headers': headers, 'data': data, 'valuesData': valuesData,'headersLoop': headersLoop} After that, these datas are sent to the template.html where i made this loop : <tr> {% for cle, valeur in headersLoop %} {% for cleVD, valeurVD in valuesData %} {% if cle == cleVD %} <td> <p> {{cle}}{{valeurVD}} </p> </td> {% endif %} {% endfor %} {% endfor %} </tr> And it prints the headers which match to the right data. name = nom, geom = 1352.457878, etc. Everything works. My question is : " How can i pull all the data from my entries ( came from my forms ) in this html array ? " In python shell : I do for entry in entries: entry.saved_data … -
CheckBox MultiSelectField in Django does not update DataBase
I can't see where the issue is. I am trying to update preselected article topics in the database. For instance, from a prechecked Business-Sport article, the user could classify it in a Music-Art article. Topics are the only information the user has the permission to modify. I want these corrections updated in the database (but they are not currently...) Hence I have these following files class.py: an Article class with MultiSelectField class Article(models.Model): newspaper = models.CharField(max_length=200) writer = models.CharField(max_length=1000) TOPIC_TYPE = ( ('Sport', 'Sport'), ('Food', 'Food'), ('Business', 'Business'), ('Music', 'Music'), ('Art', 'Art'),) filiere = MultiSelectField(choices = TOPIC_TYPE) forms.py: class ArticleForm(forms.ModelForm): class Meta: model = Article fields = ('filiere',) views.py: def detail(request, article_id): article= get_object_or_404(Article, siret=article_id) form = ArticleForm(instance=article) if request.method == 'POST': form = ArticleForm(request.POST or None, instance=article) if form.is_valid(): instance = form.save(commit=False) instance.save() return redirect('myarticles:index') context = { 'article': article, 'form':form} return render(request, 'myarticles/detail.html', context) and finally the file.html: <form action="{% url 'myarticles:index' %}" method="post"> {% csrf_token %} {{ form.as_p }} <br> {% if user.is_authenticated %} <input class ="btn btn-default" type="submit" value="Valider"/> {% endif %} </form> Ty -
Database update values django
i am a beginner in django, so i have made a model in models.py and wanted to update the database when anyone clicks on the row through the id of the row. Here are all my files urls.py from django.conf.urls import url,include from . import views from django.contrib.auth.views import login urlpatterns = [ url(r'^',views.get_contract, name='contract'), url(r'^update/', views.edit_vendor,name='update'), ] views.py from django.shortcuts import render from .models import vendor,vendorForm from django.http import HttpResponse,HttpResponseRedirect from django.views.generic import UpdateView # Create your views here. def get_contract(request): # if this is a POST request we need to process the form data form_class = vendorForm if request.method == 'POST': # create a form instance and populate it with data from the request: form=form_class(request.POST) # check whether it's valid: if form.is_valid(): party_name = form.cleaned_data['party_name'] contact_person = form.cleaned_data['contact_person'] phone_no = form.cleaned_data['phone_no'] email = form.cleaned_data['email'] material_description = form.cleaned_data['material_description'] type_of_person = form.cleaned_data['type_of_person'] type_of_dealer = form.cleaned_data['type_of_dealer'] message = form.cleaned_data['message'] form.save() else: # In reality we'd use a form class # to get proper validation errors. return HttpResponse('Make sure all fields are entered and valid.') return HttpResponseRedirect('contract') else: form = vendorForm() vendors = vendor.objects.all() return render(request,'vendors/contract.html',{'vendors': vendors,'form':form,}) def edit_vendor(request,id): if request.POST: vendor_form = vendorForm(request.POST) if vendor_form.is_valid(): self.model, vendor = vendor.objects.get(id) vendor_form = … -
Django Model filtering on foreignkey
My model.py class Book(models.Model): name = models.CharField(max_length=200, blank=False, null=False) .... class BookDetails(models.Model): book_name = models.ForeignKey(Book, on_delete = models.CASCADE) chapter_name = models.CharField(max_length=300, blank=False, null=False) chapter_details = models.TextField() View.py class BookDetailView(generic.DetailView): """docstring for BookIndex""" template_name = 'books/book_detail.html' model = Book I want to filter data of BookDetails which book name are same and also how to get data from template? -
Copying django users from one project to another project
I am designing the tools for our organization. Previously I have designed the one tool in which all the users have been registered.Now I am designing the new tool in which I want to copy all the users from the previous tool to this new tool so that there is no need for users to register with new tool again. The copying of the users include all their models and password. Is there any way to do this? -
Is there any way to embed images in Javascript in Django framework
How we can add static images in .js files used in Djnago framework? -
image is not showing in django template
I am facing problem showing image file in the django ecommerce project.Can anyone help in this issue? home.html {% for product in products %} <div class='col-sm-4'> <div class="thumbnail"> {% if product.productimage_set.all %} {% for item in product.productimage_set.all %} <img class='img-responsive' src="{{ MEDIA_URL }}{{ item.image}}" /> {% endfor %} {% else %} <img class='img-responsive' src="{% static "img/placeholder.svg" %}" /> {% endif %} <div class="caption"> <a href='{{ product.get_absolute_url }}'> <h3>{{ product.title }}</h3></a> <p>{{ product.description|truncatewords:15}}</p> <p><a href="{{ product.get_absolute_url }}" class="btn btn-primary" role="button">View</a> <a href="#" class="btn btn-default" role="button">Button</a></p> </div> </div> </div> {% endfor %} model.py class ProductImage(models.Model): product = models.ForeignKey(Product) image = models.ImageField(upload_to='products/images/') featured = models.BooleanField(default=False) thumbnail = models.BooleanField(default=False) active = models.BooleanField(default=True) updated = models.DateTimeField(auto_now_add=False, auto_now=True) def __unicode__(self): return self.product.title settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR),"static","media") -
Cant See Print in Celery
I just started with Django celery and included in my project but I cant see the print statements or return statements in my console i looked here : Print statement in Celery scheduled task doesn't appear in terminal simple celery test with Print doesn't go to Terminal System : Windows, Pycharm , Python3, django 1.9, Celery 4.02, django-celery-beat 1.01 drive/celery.py from __future__ import absolute_import, unicode_literals from celery import Celery from celery.schedules import crontab import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'advocate.local_settings') app = Celery( 'drive', broker='redis://localhost:6379/0', include=['drive.celery_tasks'] ) app.config_from_object('django.conf:settings', namespace='CELERY') app.conf.beat_schedule = { 'add-every-minute': { 'task': 'drive.celery_tasks.add', 'schedule': crontab(), }, } app.conf.timezone = 'UTC' # Optional configuration, see the application user guide. app.conf.update( result_expires=3600, ) if __name__ == '__main__': app.start() drive/celery_tasks.py from __future__ import absolute_import, unicode_literals from drive.celery import app from datetime import datetime @app.task def add(): temp = str(datetime.now()) print(temp) return 2 + 3 Celery Run Command celery -A drive beat -l info Display in console LocalTime -> 2017-07-12 14:07:58 Configuration -> . broker -> redis://localhost:6379/0 . loader -> celery.loaders.app.AppLoader . scheduler -> celery.beat.PersistentScheduler . db -> celerybeat-schedule . logfile -> [stderr]@%INFO . maxinterval -> 5.00 minutes (300s) [2017-07-12 14:07:58,548: INFO/MainProcess] beat: Starting... [2017-07-12 14:07:59,688: INFO/MainProcess] Scheduler: Sending due task add-every-minute (drive.celery_tasks.add) [2017-07-12 … -
Are these models with Django Manytomanyfield correct?
I am modeling actors an movies with Django and its manytomanyfield. An actor can play in many movies and a movie has a cast composed of many actors. class Actor(models.Model): first_name = models.CharField(max_length=100,null=True) last_name = models.CharField(max_length=100,null=True) date_of_birth = models.DateField(null=True, blank=True) date_of_death = models.DateField(null=True, blank=True) movies = models.ManyToManyField(Movie) class Movie(models.Model): title = models.CharField(max_length=100,blank=False,null=False) date = models.DateField(null=False, blank=False) cast=models.ManyToManyField(Actor,null=True,blank=True) For each model, I would like to use inline display of the other model in admin page. Is this code correct? Thanks -
Custom Templatetags not working properly
i'm trying to send data to a TemplateTags called order_details. This templatetags looks for info in database then render the informations list calling another template. When i print just before returning i got the html showing up in the logfile. But nothing show in the rendered page. @register.filter def order_details(data): params = EParamCmd.objects.filter(command=data.id, default=False) dictfunction = {} for p in params: if p.param.typ == 'function': dictfunction[p.param.name_inf] = CustomFunction.objects.get(name_inf=p.value) t = get_template('Formulaire/order-details-params.html') c = {'params': params, 'func': dictfunction} LOG.info(t.render(c)) return str(t.render(c)) The LOG.info shows the html that should be displayed in this template: {% load tags %} <h4>Liste des paramètres :</h4> {{order|order_details}} When i return 'Hello' in the templatetags it show up. Thanks. -
Chronometer script with Javascript in my Django application
I'm looking for implement a Chronometer script in with JS in my Django web application. This chronometer has multiple functions : User can start the chronometer (0:0s --> 1:2s) User can stop the chronometer and start again (stop at 3:3s than if user click one more time on start --> 3:4, 3:5 ....) User can reset the chronometer I'm a beginner with Javascript and I would get your help in order to improve my script : // Here set the minutes, seconds, and tenths-of-second when you want the chronometer to stop // If all these values are set to 0, the chronometer not stop automatically var stmints = 0; var stseconds = 0; var stzecsec = 0; // function to be executed when the chronometer stops function toAutoStop() { alert('Vous avez stoppé le chronomètre'); } // the initial tenths-of-second, seconds, and minutes var zecsec = 0; var seconds = 0; var mints = 0; var startchron = 0; function chronometer() { if (startchron == 1) { zecsec += 1; // set tenths of a second // set seconds if (zecsec > 9) { zecsec = 0; seconds += 1; } // set minutes if (seconds > 59) { seconds = … -
Django AttributeError: 'GeoQuerySet' object has no attribute 'extent'
My django code is broken and raises the following AttributeError: AttributeError: 'GeoQuerySet' object has no attribute 'extent' In my code I try to call extent on a django geoqueryset: if raster and bbox: self.extent = qs.extent() My Django version is currently 1.10 and has recently been upgraded from Django 1.9. -
Django - Display loading image while a bash process is running
I need your help, In my view i run a bash process that takes time depending on the size of the image; while it process i want to display a loading gif image and a sentence (such as "Please wait, the image is being processed"). I tried to did that with a template but it is rendered at the end of execution of the script not while it process. Can someone help me to do that ? I've found a similar question "Django - show loading message during long processing" but the answer wasn't very clear for me because i never used ajax. This is my view : def process(request): var = Image.objects.order_by('id').last() subprocess.call("./step1.sh %s" % (str(var)), shell=True) subprocess.call("./step2.sh %s" % (str(var)), shell=True) return render(request, 'endexecut.html') Template that will be displayed at the end of processing: "endexecut.html" {% extends 'base.html' %} {% block content %} <div class="container"> <div class="row"> <div class="jumbotron"> <div class="row"> <center> <p> Your image is processed succesfully ! </p> </center> </div> </div> </div> {% endblock %} -
django rest detail_route testing
Good day! I have a view with detail_route like this: class PostView(viewsets.ModelViewSet): queryset = Post.objects.all() serializer_class = PostSerializer @detail_route(methods=['POST']) def like(self, request, pk=None): post = self.get_object() post.like(request.user) return Response({'result': 'success'}) So, url for like function is /api/posts/{id}/like I try testing it with django.test.TestCase like this: post = Post.objects.first() url = reverse('api:post-detail', args=[post.id]) url = urljoin(url, 'like') response = self.client.post(url, content_type='application/json', follow=True) I have to use follow=True because I get code 300 redirect, but redirect return me GET request when I need POST. I have tried use APIClient and APIRequestFactory and got same error or myapp.models.DoesNotExist Tanks for your attention!