Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to attached documents (pdf/images) to Django emailer using the S3 URL to the document creating a file?
I have some Images and PDFs, which are available via their respective S3 URLs. I want to attach these documents to the emails I am sending using the native Django Emailer. Is there any way I can do so without downloading the Documents on the servers and then attaching them, as it creates an overhead od deleting the documents post Email sent. Also, I don't want to give out the URLs in the Emails hence Images can't be embedded as a part of the HTML in the email. Im using Python 2.7 Django 1.9 DRF 3.4 -
how to delete an object in django
i want to delete a task from the database so i use this code this is my delete view class taskDelete(DeleteView): model = task success_url = reverse_lazy('home') and my url url(r'^home/?<task_id>[0-9]+/$', views.MyDeleteView.as_view(), name='task_Delete'), the html code of the button {% for task in tasks %} <tr> <td>{{ task.id }}</td> <td>{{ task.titre }}</td> <td>{{ task.objectif }}</td> <td>{{ task.date }}</td> <td>{{ task.theme }}</td> <td><a href="#"><button type="button"><span class="glyphicon glyphicon-pencil" aria-hidden="true" >edit</td> <td> <form action="{% url 'task_Delete' %}" method="post" > {% csrf_token %} <input type="hidden" name="task_id" value="{{task.id}}" /> <button type="submit" value="delete task"></button> </form></td> </tr> {% endfor %} when i click on the button delete nothing happend , thank's in advance -
Is it possible to generate Class diagram/Architecture diagram using Django Rest Framework
I'm working on an existing huge django 1.8 project which uses rest-framework and has about 90 models(tables). I'd like to generate a class diagram/architecture diagram for the tables. Is there any automated tool for this that I can use? Swagger helped me to create API documentation and I've become a fan of django-rest-framework already. -
Docker-compose dev and prod recreated containers
I have django project. For this project i have different settings(db, ...). I want run dev and prod containers. I want to work simultaneously dev and prod. My structure project: my docker-copose.yml version: '2.0' services: web: build: . container_name: api_prod volumes: - .:/usr/django/app/ expose: - "8000" env_file: env/main.env command: bash django_run.sh nginx: build: nginx container_name: ng_prod ports: - "8000:8000" volumes: - ./nginx/api.conf:/etc/nginx/conf.d/api.conf - .:/usr/django/app/ depends_on: - web links: - web:web my docker-compose.dev.yml version: '2.0' services: web: build: context: . dockerfile: Dockerfile.dev container_name: api_dev volumes: - .:/usr/django/app_dev/ expose: - "8001" env_file: env/dev.env command: bash django_run.sh nginx: build: nginx container_name: ng_dev ports: - "8001:8001" volumes: - ./nginx/api.conf:/etc/nginx/conf.d/dev_api.conf - .:/usr/django/app_dev/ depends_on: - web links: - web:web Dockerfile FROM python:3 RUN apt-get update # Install wkhtmltopdf RUN curl -L#o wk.tar.xz https://downloads.wkhtmltopdf.org/0.12/0.12.4/wkhtmltox-0.12.4_linux-generic-amd64.tar.xz \ && tar xf wk.tar.xz \ && cp wkhtmltox/bin/wkhtmltopdf /usr/bin \ && cp wkhtmltox/bin/wkhtmltoimage /usr/bin \ && rm wk.tar.xz \ && rm -r wkhtmltox RUN apt-get install -y cron # create directory for application source code RUN mkdir -p /usr/django/app COPY requirements.txt /usr/django/app/ COPY django_run.sh /usr/django/app/ WORKDIR /usr/django/app RUN pip install -r requirements.txt Dockerfile.dev FROM python:3 RUN apt-get update # Install wkhtmltopdf RUN curl -L#o wk.tar.xz https://downloads.wkhtmltopdf.org/0.12/0.12.4/wkhtmltox-0.12.4_linux-generic-amd64.tar.xz \ && tar xf wk.tar.xz \ … -
How to redirect users to unique callback url after authentication?
I'm using Lock and Django to authenthicate my users, whenever it's done I'd like to redirect them to the same page they were, problem is that my urls have unique UUID and I can't list all of them under Allowed Callback URLs, I originaly had two ways to do so: Specify callback url in Lock redirectUrl parameter - Problem : Callback URL mismatch. (can't specify each new unique url to Allowed Callback URLs ) Specifying my unique url under Lock POST and send it back from auth0 along with the user informations. - Problem: I don't think such feature exist. Are there any way I can achieve this? -
Where Is the error in my Django code?
I am trying to debug my code but can't find the error. I have a django project in which I want to open a page named 'locate' in Details page. I am facing the following error: NoReverseMatch at /incubators/1/ Reverse for 'locate' with arguments '('',)' not found. 1 pattern(s) tried: ['locate/(?P<incubator_id>\\d+)/$'] Request Method: GET Request URL: http://127.0.0.1:8000/incubators/1/ Django Version: 1.11.3 Exception Type: NoReverseMatch Exception Value: Reverse for 'locate' with arguments '('',)' not found. 1 pattern(s) tried: ['locate/(?P<incubator_id>\\d+)/$'] My views.py look something like this: def details(request, incubator_id): inc = get_object_or_404(Incubators, pk = incubator_id) details = Details.objects.get(pk = incubator_id) return render(request, 'main/details.html', {'inc': inc, 'details': details}) def locate(request, incubator_id): pos = Incubators.objects.values_list('latt', 'lonn').filter(pk = incubator_id) return render(request, 'main/locate.html', {'pos': pos, 'incubator_id': incubator_id}) And following is my relevant urls pattern: url(r'^locate/(?P<incubator_id>\d+)/$', views.locate, name = 'locate'), My reverse function in html for the locate page is this: <li> <a href="{% url "main:locate" incubator_id%}">Locate</a> </li> Help would be greatly appriciated -
print pdf file inside navigator weasyprint
I want to print pdf file inside my browser to let the choice to save. I am using weasyprint in django 2.0.2 i use this code in my views.py but firefox download it automaticaly and don't mind about the "inline". Any help? response['Content-Disposition'] = 'inline; filename="gene_detail_description_print.pdf"' -
Django's development server on Ubuntu not accessible via browser, only via -curl
I am trying to set up a Django website on an Ubuntu server hosted on DigitalOcean. After following the step-by-step DigitalOcean tutorial here: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04 I remain stuck as I cannot seem to access Django's development server launched on 0.0.0:8000 with the browser of my local machine. However, I do have a response using -curl from the server's bash terminal. So it seems it can only be accessed from the server itself. Django does not return any error while launching the development server. It lists successful connections (code 200) every time I access it via -curl, but does not show anything when I try to access it via my external browser, as if it is actually not being acecssed. What I did: followed this tutorial step-by-step until the launch of Django's development server, disabled Ubuntu's firewall and no DO firewall is used added '*' in ALLOWED_HOSTS in settings.py Any ideas? Thank you very much! -
Force F() expression to return a model instance rather than a primary key
In the documentation, is there a way to override this behavior? i.e. I want car.built_by to return a model instance i.e. <Manufacturer: Toyota> rather than a primary key since I need to maintain the foreign key relationship while annotating. -
raise UnknownBackendException embed_video.backends.UnknownBackendException
I am making my website using django-embed-video package of django. Since I'm thinking about starting with a configuration that is as simple as possible, I made a website only index.html, then I installed django-embed-video. Then I added following code base on the tutorial, however, it doesn't display youtube video and display following error message. My environment is as follows. django 2.0 python 3.6 django-embed-video 1.1.2 error message Backend wasn't recognised (``) Traceback (most recent call last): File "F:\django_project\virtualenv2\lib\site- packages\embed_video\templatetags\embed_video_tags.py", line 111, in render return self.embed(url, size, context=context, **options) File "F:\django_project\virtualenv2\lib\site- packages\embed_video\templatetags\embed_video_tags.py", line 185, in embed backend = cls.get_backend(url, context=context, **options) File "F:\django_project\virtualenv2\lib\site- packages\embed_video\templatetags\embed_video_tags.py", line 164, in get_backend else detect_backend(str(backend_or_url)) File "F:\django_project\virtualenv2\lib\site- packages\embed_video\backends.py", line 62, in detect_backend raise UnknownBackendException embed_video.backends.UnknownBackendException stteings.py INSTALLED_APPS = [ 'embed_video', ] It added 'django.template.context_processors.request' by default in 'context_processors' of TEMPLATES. models.py class Item(models.Model): name = models.CharField('Video name', max_length=100, null=True) video = models.URLField() # same like models.URLField() view.py from django.shortcuts import render def index(request): return render(request, 'app/index.html') admin.py from django.contrib import admin from embed_video.admin import AdminVideoMixin from .models import Item class MyModelAdmin(AdminVideoMixin, admin.ModelAdmin): pass admin.site.register(Item, MyModelAdmin) Custom backends have not made anything. What is the cause this problem? -
A CRUD api generator for django
I am looking to generate Basic CRUD endpoints for models defined in Django 2.0. For example, if there is a Dog model, with a few fields, I want to generate: a GET endpoint to get all dogs a GET endpoint to get a dog by ID a PUT endpoint to update a dog a POST endpoint to create a new dog I've followed a tutorial on how to create these endpoints, but I would prefer for this to be generated for many models. It seems like redundant work to do this for each model individually rather than have a generator. I've looked at both drf-generator and django-baker but they both seem incompatible with django 2.0. I've used Loopback in the past to do this with Node.js, so I'm looking for something similar for Django. Is there a fundamental aspect of Django I am missing, or am I simply missing some obvious way to generate these endpoints? Since the admin dashboard already seems to be able to perform these operations, it doesn't seem like such a stretch to expose them externally. Perhaps I should downgrade to an older version of Django? -
deleting an object in django
i want to delete a task from the database so i use this code this is my delete view def task_Delete(request,id=None): if request.method == 'POST': form = TaskForm() id = int(request.POST.get('task.id')) task = Task.objects.get(id=id) task.delete() messages.success(request,"successfully delete") return render_to_response('home.html', {'form': form}) and that is my urls.py url(r'^task_Delete/$', views.task_Delete, name='task_Delete') this the code of the button delete : <form action="{% url 'task_Delete' %}" method="post" > {% csrf_token %} <input type="hidden" name="task_id" value="{{task.id}}" /> <input type="submit" value="delete task"> </form></td> </tr> when i click on delete nothing happend i don't know why , please help thanks in advance -
DJANGO: CSRF token missing or incorrect, not/working random behaviour
I'm getting the following error on the console WARNING [django.request] Forbidden (CSRF token missing or incorrect.) This is the image when debug=True: This is working at times and not working sometimes. It's totally random, no pattern found. I've tried all the suggestions provided on other posts like: render_to_response.. -
__init__() takes 1 positional argument but 2 were given django
from django.shortcuts import render from .forms import PostForm from django.views.generic import TemplateView class createPost(TemplateView): template_name = 'forum/createPost.html' def get(self, request): form = HomeForm() return render(request, self.template_name, {'form': form}) -
Binding a field to another field in Django Admin Page?
I have writen a tool to make use of answer related questions. In my model I have a many to many relation between questions and answers like this: class Answer(models.Model): answer_id = models.AutoField(blank=False, null=False, primary_key=True) answer_text = models.CharField(blank=False, null=True, max_length=500, verbose_name=_(u'Text der Antwort')) class Question(models.Model): question_id = models.AutoField(blank=False, null=False, primary_key=True) answer = models.ManyToManyField('Answer', through='Question_Answer', related_name='+') question_text = models.CharField(blank=False, null=True, max_length=500, verbose_name=_(u'Text der Frage')) class Question_Answer(models.Model): question_answer_id = models.AutoField(blank=False, null=False, primary_key=True) question = models.ForeignKey('Question', on_delete=models.SET_NULL, null=True, related_name='+') answer = models.ForeignKey('Answer', related_name='+', on_delete=models.SET_NULL, null=True) next_question = models.IntegerField(blank=True, null=True, verbose_name=_(u'Naechste Frage(Verzw.)')) The relation between Answer and Question in my logic comes with the "next_question" field in my "Question_Answer" table. So the integer of next_question is the pk of the next question. I have customized my Admin page to manipulate the Database like this: from django.contrib import admin from survey.models import Answer, Question, Survey, Question_Answer, Survey_Question class Question_Answer_Inline(admin.TabularInline): model = Question_Answer extra = 0 class Survey_Question_Inline(admin.TabularInline): model = Survey_Question list_display = ('survey_titel') extra = 0 class AnswerAdmin(admin.ModelAdmin): inlines = (Question_Answer_Inline,) class QuestionAdmin(admin.ModelAdmin): inlines = (Question_Answer_Inline, Survey_Question_Inline,) class SurveyAdmin(admin.ModelAdmin): inlines = (Survey_Question_Inline,) admin.site.register(Answer, AnswerAdmin) admin.site.register(Question, QuestionAdmin) admin.site.register(Survey, SurveyAdmin) Now by using the admin page i figured out it is a mess binding all the the … -
Django. ForeignKey
I have a Post models for blog: сlass Post(models.Model): author = models.ForeignKey(User, related_name="blog_posts", on_delete=models.CASCADE) ........ ........ And I want to add a Tag to the project, so I made a Tag model: class Tag(models.Model): tag_name = models.CharField(max_length=20, blank=True) def __str__(self): return self.tag_name I added this to the Post model: tag = models.ForeignKey(Tag, related_name="blog_tag", on_delete=models.CASCADE) But makemigration give to me an error: You are trying to add a non-nullable field 'tag' to post without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py So why i have to populate existing rows? And how i can to live the rows empty? P.S. If i chose 1) i still have an error. -
Tempalte Widget in Django 2.0
I would like to change the way a widget is rendered in Django. I've read this guide https://docs.djangoproject.com/en/2.0/ref/forms/renderers/ but still I can't make it working. I've create this widget class MultiChoiceFilterWidget(forms.widgets.CheckboxSelectMultiple): template_name = 'web_admin/partial/checkbox.html' but it's not working in the sense that the default look-and-feel is displayed, there's no sign of my edits. In TEMPLATES I've the folder myproject.web and the folder structure is myproject/web/templates/web_admin/partial/checkbox.html What Am I missing? (I also tried to put a file in django/forms/widgets/checkbox_select.html that is the file the widget is looking for, but still not working) -
Using templatetags inside blocktrans django
I am using internationalization in a django project, and I can't find a way to use a custom template tag inside a blocktrans: {% blocktrans %} <p>Go to <a href="{% get_current_votations object.category %}.get_absolute_url ">current votations</a></p> {% endblocktrans %} I'd like to do something like that, but since I cannot enter it anywhere idk if it is even possible. I have tried using {% with %} but it doesn't work either. Is there any way to accomplish what I'm trying to do? Thank you for your time! -
Django admin is not getting from domain/admin/
urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/', include(router.urls)) ] This is the redirecting code for my file. But its working in localhost, but not in server. -
Django form: call 'clean' before 'clean_<form_field>'
Hi I have a django form in which I have a radio button and several character fields. As part of this form validation I want to clean each of these inputs, and then do some extra cleaning (i.e further cleaning of downstream data). However, when i put my 'extra cleaning' in clean() this is called after each of the clean_() methods. Is there a way I can call clean() last? form.py class UploadForm(forms.ModelForm): year = forms.IntegerField(label='Year:', required=True) number = forms.IntegerField(label='Number:', required=True) stored = forms.ChoiceField( required=True, label='Storage:', widget=forms.RadioSelect, choices=(('Routine', 'Routine',), ('Archive', 'Archive',)) ) def clean_year(self): self.year = self.cleaned_data['year'] year_check = re.compile("\d{4}$") if year_check.match(str(self.year)): return(self.year) else: msg = "Year '%s' is incorrect." %(str(self.year)) logger.error(msg) raise(forms.ValidationError(msg)) def clean_number(self): self.number = self.cleaned_data['number'] number_check = re.compile("\d{1,2}$") if number_check.match(str(self.number)): return(self.number) else: msg = "Year '%s' is incorrect." %(str(self.number)) logger.error(msg) raise(forms.ValidationError(msg)) def clean_stored(self): try: self.stored = self.cleaned_data['stored'] except: self.stored = False def clean(self): self.more_cleaning_methods() def more_cleaning_methods(): print(self.stored) This results in an error if stored radio button is not checked - instead of raising a form error. This is because clean() is called first - and therefore my class object does not have an "attribute 'stored'" is there a way I can call clean() after individually cleaning the … -
How can I access column in model?
How can I access income in NewUser model? I wanna filter Car model's data by user's income data.My ideal system is car name is shown in car.html if NewUser's income = Car income. I wrote in models.py class NewUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) income = models.CharField(max_length=20, null=True, default=None) class Car(models.Model): name = models.CharField(max_length=100, null=True, default=None) income = models.CharField(max_length=20, null=True, default=None) in views.py from app.models import Car from django.shortcuts import render def car(request): car_data = Car.objects.all().filter(income=request.user.income) return render(request, 'car.html', {'car_data': car_data}) When I access car method,AttributeError at /app/car/ 'User' object has no attribute 'income' error happens.I really cannot understand why such a error happens.I inherit User model in NewUser,so I think I can access income in request.user.How should I fix this?What is wrong in my codes? -
Django's jinja like block feature in ejs
I have a node-express project that have several page in it, I use ejs templating engine and currently how I handled base-template is copy-paste the template html to new page (Basically, it's bad) I want to use django's jinja 'block' like feature in ejs, is there that kind of feature in ejs? (I confused by ejs website) Is there a way to use base-template in ejs OR is there a templating engine that you recommend that have base-template feature in it OR should I stay with my current implementation of copy-pasting base-template? -
Problems configuring CircleCI config.yml
I have a Django project architecture like this: I need to configure my config.yml to integrate CircleCI into my project. I am an absolute beginner in Continuous Integration and looking forward to make myself learn. My config.yml looks like this: # Python CircleCI 2.0 configuration file # Check https://circleci.com/docs/2.0/language-python/ for more details # version: 2 jobs: build: docker: # specify the version you desire here # use `-browsers` prefix for selenium tests, e.g. `3.6.1-browsers` - image: circleci/python:3.6.1 # Specify service dependencies here if necessary # CircleCI maintains a library of pre-built images # documented at https://circleci.com/docs/2.0/circleci-images/ # - image: circleci/postgres:9.4 steps: - checkout # Download and cache dependencies - restore_cache: keys: - v1-dependencies-{{ checksum "requirements.txt" }} # fallback to using the latest cache if no exact match is found - v1-dependencies- - run: name: install dependencies command: | python3 -m venv venv . venv/bin/activate pip install -r requirements.txt - save_cache: paths: - ./venv key: v1-dependencies-{{ checksum "requirements.txt" }} # run tests! # this example uses Django's built-in test-runner # other common Python testing frameworks include pytest and nose # https://pytest.org # https://nose.readthedocs.io - run: name: run tests command: | . venv/bin/activate python manage.py test - store_artifacts: path: test-reports destination: test-reports … -
django-redis invalid DB index error and redis url's meaning
I'm using django-redis: https://niwinz.github.io/django-redis/latest/ While setting and testing cache, I have a question. From this: https://niwinz.github.io/django-redis/latest/#_installation There is code like this: CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } } When I use this unchanging any of this LOCATION code as: "LOCATION": "redis://127.0.0.1:6379/1", It is doing well. Even "LOCATION": "redis://127.0.0.1:6379/2" It seems to do works well. But I have to change this like "LOCATION": "redis://127.0.0.1:6379/220", It returns invalid DB index error. Question: Why this happened? What does parameter mean from "LOCATION": "redis://127.0.0.1:6379/parameter"? Here is traceback: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/test/ Django Version: 2.0.2 Python Version: 3.6.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'post', 'website'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware'] Traceback: File "D:\pythonDev\interpreters\forMultichat\lib\site-packages\django_redis\cache.py" in _decorator 32. return method(self, *args, **kwargs) File "D:\pythonDev\interpreters\forMultichat\lib\site-packages\django_redis\cache.py" in get 81. client=client) File "D:\pythonDev\interpreters\forMultichat\lib\site-packages\django_redis\client\default.py" in get 204. raise ConnectionInterrupted(connection=client, parent=e) During handling of the above exception (Redis ResponseError: invalid DB index), another exception occurred: File "D:\pythonDev\interpreters\forMultichat\lib\site-packages\django\core\handlers\exception.py" in inner 35. response = get_response(request) File "D:\pythonDev\interpreters\forMultichat\lib\site-packages\django\utils\deprecation.py" in __call__ 93. response = self.process_request(request) File "D:\pythonDev\interpreters\forMultichat\lib\site-packages\django\middleware\cache.py" in process_request 133. cache_key = get_cache_key(request, self.key_prefix, 'GET', cache=self.cache) File "D:\pythonDev\interpreters\forMultichat\lib\site-packages\django\utils\cache.py" in get_cache_key 360. headerlist = cache.get(cache_key) … -
Mapping the AUTH_LDAP_USER_ATTR_MAP in Django
I am trying to map certain attributes of an ldap user by using django-auth-ldap. Trying to map the AUTH_LDAP_PROFILE_ATTR_MAP does not work for me but AUTH_LDAP_USER_ATTR_MAP works because it compatible with the user-model in django. Settings.py AUTH_LDAP_USER_ATTR_MAP = { "first_name": "givenName", "last_name": "sn", "email": "mail", } AUTH_LDAP_PROFILE_ATTR_MAP = { "title": "titel", "phone": "telephoneNumber", "mobile": "mobile", } views.py def view_profile(request, pk=None): if pk: user = User.object.get(pk=pk) else: user = request.user args = {'user': user} return render(request, ('accounts/profile.html'), args) profile template <input value="{{ user.first_name}}"></input> <input value="{{ user.last_name}}"></input> <input value="{{ user.email}}"></input> <input value="{{ user.title}}"></input> <input value="{{ user.phone}}"></input> <input value="{{ user.mobile}}"></input> Is there a way to work with models and to copple the ldap attributes to the model? Thanks in advance.