Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
PermissionError: [Errno 13] Permission denied - Python/Django Locallibrary
So I'm following this tutorial: https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Home_page Using this code in my urls.py: urlpatterns += [ path('catalog/', include('catalog.urls')), ] Throws me the error PermissionError: [Errno 13] Permission denied: '/home/jakoubu/django_projects/locallibrary/catalog/urls.py' Anyone knows what's up? I've searched the entire internet for answers... -
Database creation failing during django testing
I have a functional Django project with a functional database. When I try to run tests on this project, I get this error during database creation: django.db.utils.InternalError: (1553, "Cannot drop index 'One response per question per level': needed in a foreign key constraint") I had a unique_together constraint in one of the tables which I later removed. This line 'One response per question per level' is related to that unique_together constraint and is present in two migration files - first time during the creation of the table and second time during the removal. When I run the tests, it is throwing this error and the database is not getting created. How can I solve this problem? -
Django Model with non-unique names
I'm trying to create a simple kanban style board for my task manager app in Django 3.0.3. I've already written the code for projects and tasks, but I'm having trouble figuring out the best way to create the models for the kanban boards. I currently have two models, but can I do this in one for simplicity? My basic requirement is that every project can have its own board, and each board will have multiple panels. Here is an example: Board: Development Backlog Started Development etc... Board: Operations Requested Working Pending etc... With only one model, I'm not sure if this will have the flexibility I need to fully design it. But having multiple models may be too cumbersome to manage for the ultimate user. Here are my current models: class Board(models.Model): """ Defines Kanban boards """ name = models.CharField(max_length=25) slug = models.SlugField(default="") project = models.ForeignKey(Project, on_delete=models.CASCADE) tags = TaggableManager(blank=True) def __str__(self): board_name = self.project.name + ":" + self.name return board_name class BoardPanel(models.Model): """ Defines panels in project board """ title = models.CharField(max_length=30) slug = models.SlugField(default="") board = models.ForeignKey(Board, on_delete=models.CASCADE) tasks = models.ManyToManyField(Task) def __str__(self): panel_name = self.board.name + ":" + self.title return panel_name -
How to use coreapi to create custom API schema with reponse stauts?
I have written an API using DRF's APIView class. I don't have models and directly call another API end from my API. I want to document my API, hence using Django rest swagger. Its recent version does not support YAML docstring. So I have written manual coreapi.Document schema for generating parameters. I have taken reference from this answer .But i am struggling to add response status code to it, otherwise, it is rendering empty response section with by default 201 code. Is there any way i can add custom response status? -
Static file 404 error when DEBUG=False in django
I made django project for localhost, it fetch the static files ex) http://127.0.0.1:8000/static/myapp/test.img It works well when DEBUG=True in setting.py Now I changed to DEBUG=False This http://127.0.0.1:8000/static/myapp/test.img returns net::ERR_ABORTED 404 (Not Found) DEBUG = True if DEBUG: ALLOWED_HOSTS=['*'] else: ALLOWED_HOSTS=['*'] -
Django DetailView Two Forms Only One Works
I am struggling to debug this as it doesn't show an error when I submit the form that doesn't work, I can't figure out why it isn't working any help is appreciated... class ProfileDetailView(FormMixin, DetailView): template_name = 'users/profile_detail.html' model = Profile form_class = ReviewForm other_form = ProfileContactForm success_url = '/' def get(self, request, *args, **kwargs): self.other_form = ProfileContactForm return super(ProfileDetailView, self).get(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) profile = self.object reviews = Review.objects.filter(user_id=self.kwargs['pk']).order_by('-review_date') imgs = ProfileImages.objects.filter(profile_id=self.kwargs['pk']) context['reviews'] = reviews context['imgs'] = imgs context['profile'] = profile context['other_form'] = self.other_form return context def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() other_form = self.other_form() if form.is_valid(): Review = form.save(commit=False) Review.user = self.object Review.reviewer = request.user Review.save() return self.form_valid(form) if other_form.is_valid(): subject = other_form.cleaned_data['date'] message = other_form.cleaned_data['service'] your_email = request.user.email try: send_mail(subject, message, your_email, ['anthonya1@live.co.uk']) except BadHeaderError: return HttpResponse('Invalid header found.') else: return self.form_invalid(form) Form_class (ReviewForm) is working fine... Other_form is the one I'm having issues with, I just need it to go through the send mail code but it doesn't seem to be reaching it as it doesn't send mail and my server doesn't show an attempt to send mail... -
Django internationalization not working for REST API custon JSON response in view.py
In my django project, I am using internationalization. It's working fine for REST framework viewsets like ModelViewSet but fails for function based JSON response views. Here are code: #settings.py from django.utils.translation import ugettext_lazy as _ LANGUAGES = [ ('en', _('English')), ('tr', _('Turkish')), ] LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', ] Views.py includes: #views.py from django.utils.translation import ugettext as _, get_language from rest_framework.response import Response from django.views.decorators.csrf import csrf_exempt from rest_framework.permissions import AllowAny from rest_framework.decorators import api_view, permission_classes @csrf_exempt @api_view(["POST"]) @permission_classes((AllowAny,)) def LoginwithUsernameApi(request): username = request.data.get("username") password = request.data.get("password") if username is None: return Response({'detail': _('Please provide username.')}, status=HTTP_400_BAD_REQUEST) user = authenticate(username=username, password=password) if not user: return Response({'error': _('Invalid username or password.')}, status=HTTP_404_NOT_FOUND) serializer = UserSerializer(user) return Response(serializer.data, status=HTTP_200_OK) In request header sending Accept-Language:tr , Also print(get_language()) returns tr as output. django.po also contains message: #django.po #: registration/views.py:145 registration/views.py:181 #: registration/views.py:199 registration/views.py:252 msgid "Please provide all required data." msgstr "" -
Using pip on OSX Mojave forces me to install recently release python packages
So I recently updated an old macbook pro up to Mojave (osx 10.14) and decided to use it as a side laptop for development. Using python 3.7, I created a virtualenv like so: python3.7 -m venv myvirtualenv Pulled the repo I am working on, enabled my virtualenv and started installing requirements: billiard==3.6.1.0 boto3==1.9.248 botocore==1.12.248 celery==4.3.0 certifi==2018.8.24 chardet==3.0.4 defusedxml==0.5.0 dj-database-url==0.5.0 Django==2.2 django-appconf==1.0.3 django-autoslug==1.9.6 django-celery==3.3.1 django-cors-headers==3.1.0 django-heroku==0.3.1 django-mailing==0.1.3 django-storages==1.7.2 django-otp==0.5.0 django-redis-cache==2.1.0 django-templated-mail==1.1.1 djangorestframework==3.8.2 djangorestframework-jwt==1.11.0 djoser==1.7.0 docutils==0.15.2 idna==2.7 importlib-metadata==0.23 jmespath==0.9.4 kombu==4.6.5 more-itertools==7.2.0 oauthlib==2.1.0 Pillow==6.2.0 psycopg2==2.8.3 PyJWT==1.6.4 python-dateutil==2.8.0 python-http-client==3.2.1 python3-openid==3.1.0 pytz==2018.5 redis==3.3.8 requests==2.19.1 requests-oauthlib==1.0.0 rest-social-auth==1.4.0 s3transfer==0.2.1 sendgrid==6.1.0 six==1.11.0 social-auth-app-django==2.1.0 social-auth-core==1.7.0 sqlparse==0.3.0 urllib3==1.23 vine==1.3.0 gunicorn==19.9.0 whitenoise==4.1.4 zipp==0.6.0 django-celery-beat==1.5.0 Thing is, pip refuses to install this versions and force me to use updated packages. For example, I cant install Django 2.2.12 (only 3.0.5 and onwards): pip install django==2.2.12 Looking in indexes: https://pypi.python.org/pypi/ Collecting django==2.2.12 ERROR: Could not find a version that satisfies the requirement django==2.2.12 **(from versions: 3.0.5)** ERROR: No matching distribution found for django==2.2.12 Same for pretty much all the packages on my requirements. Ive tested with several python versions (from 3.4 to 3.8) and several pip versiones (from 10 to 20, downloading the get-pi.py script and running it). I am pretty sure I am … -
Django Rest Framework throws IntegrityError. null value in column "creator_id" violates not-null constraint
Django Rest Framework keeps throwing an integrity error at /posts/ with the message: null value in column "creator_id" violates not-null constraint. Not entirely sure what is causing this issue. From the admin panel, I can create a post without an issue. Here's my Post Model. the User is a foreign key: class Post(models.Model): """Post object""" creator = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) title = models.CharField(max_length=255, null=False, blank=False) content = models.TextField(blank=True, null=True) audio_file = models.FileField( null=False, blank=False, upload_to='audio_directory', validators=[validate_file_extension, validate_file_size] ) cover_image = models.ImageField( upload_to='images/post_covers', default='images/defaults/default_cover.png', blank=False, null=False ) tags = models.ManyToManyField(Tag, blank=True) duration = models.CharField( max_length=6, blank=True, default=0, help_text='Length of post in minutes' ) category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=False) featured = models.BooleanField(u'Featured', default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() sorted_objects = PostQuerySet.as_manager() class Meta: verbose_name = _('post') verbose_name_plural = _('post') ordering = ('-featured', '-created_at',) def __str__(self): return self.title @property def is_featured(self): return self.featured Here's thePost view uses ModelViewSet as shown in the code below: class PostViewSet(viewsets.ModelViewSet): serializer_class = PostSerializer search_fields = (['title', 'creator', 'category']) def get_queryset(self): sorting = self.request.query_params.get('sorting', None) if sorting == 'newest': return Post.sorted_objects.newest() if sorting == 'trending': return Post.sorted_objects.likes_last_week() return Post.sorted_objects.likes() def get_permissions(self): return (permissions.IsAuthenticated(),) @method_decorator(cache_page(60)) def dispatch(self, *args, **kwargs): return super(PostViewSet, self).dispatch(*args, **kwargs) @action(methods=['post'], permission_classes=[permissions.IsAuthenticated], detail=True) … -
hosting Django on Apache
I'm following a tutorial trying to host Django on apache server, now as I finally installed mod_wsgi using cmd, I try to use the command: mod_wsgi-express module-config now i get another bugging error - which is: "syntaxError: Unicode error unicodeescape codec can’t decode bytes in position 2-4: truncated\xXX escape" I'm looking for help! thanks, -
create a publish file in django like that asp.net core
I am a beginner to Django, currently, I have developed a simple Django project with postgres database and want to create a publish file like of Asp.net core project publish file, how can I create it, or can't we create. I want to host my django project in iis like that of asp.net core project -
A for loop works in Python but doest work in Django
I need to parse h2 tags from the site. I use BeautifulSoup Here is the Views.py part. I search for all the H2 tags h2_all = soup.find_all('h2') h2_num = len(h2_all) And than pass the in the context: 'h2_all':h2_all, 'h2_num':h2_num, In the template part. When I try to display h2_all - it works. The result is: [<h2>Запись к врачу</h2>, <h2>Запись на диагностику</h2>] But when I'm trying to loop to get each of h2 tag. {% for h2 in h2_all %} {{ h2 }} {% endfor %} The result is the following: [] [] I'a a beginner and this is my first project on Django. I've already spent several hours trying to solve the problem, but have no result... Please help... -
Django AJAX reload part of the HTML
I have a problem rendering the HTML element 'live'. This is my idea, I have a topbar which is included(not extending anything) in the 'base.html' like this : ... base.html <div id="content-wrapper" class="d-flex flex-column"> <!-- Main Content --> <div id="content"> <!-- Top Bar --> {% include 'topbar.html' %} ... And this is the 'topbar.html' itself : topbar.html <!-- Topbar --> {% load static %} {% load custom_tags %} {% notification_tag as notifications %} {% current_time as current_time %} {% events as all_events %} ... <ul class="navbar-nav ml-auto"> <!-- Nav Item - Alerts --> <li class="nav-item dropdown no-arrow mx-1"> <a class="nav-link dropdown-toggle" href="#" id="alertsDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <i class="fas fa-bell fa-fw"></i> <!-- Counter - Alerts --> {% if notifications %} {% for notif in notifications %} {% if notif.date_to_remind <= current_time %} <span class="badge badge-danger badge-counter">{{ notifications.count }}</span> {% endif %} {% endfor %} {% endif %} </a> <!-- Dropdown - Alerts --> <div class="dropdown-list dropdown-menu dropdown-menu-right shadow animated--grow-in" aria-labelledby="alertsDropdown"> <h6 class="dropdown-header"> Obaveštenja </h6> {% for n in notifications %} {% if not n.viewed %} <a class="dropdown-item d-flex align-items-center" href="{% url 'notification' n.pk %}"> <div class="mr-3"> <div class="icon-circle bg-primary"> <i class="fas fa-file-alt text-white"></i> </div> </div> <div> <div class="small text-gray-500">{{ n.eluid_posla … -
How to access json object passed from django?
I have an object from Django view as follows: [{ 'id': 49, 'user': { 'username': 'somename', 'id': 1 }, 'category': 4, 'sub_category': 49, 'title': 'amazing stuff', 'content': 'amazing stuff' }, { 'result': 'success' }] A portion of the view function: ret = get_forums() result = { 'result': 'success' } // used as indicator that the new post is saved ret.append(result) print(ret) return JsonResponse(ret, safe = False) jQuery AJAX: success: function(data) { if (data.result == 'success') { console.log(data); alert("Data sending was successful"); data = JSON.parse(data); update_forum_posts(data); } else { console.log(data); alert("Data sending was unsuccessful"); } }, The if condition is not valid if (data.result == 'success') The question is: how can I access the data which is ret in the view function and satisfy the if condition? NOTE: when I send a POST it is saved successfully but I get alert("Data sending was unsuccessful") -
How to upload large files to Google Storage using Google App Enginer + Django and JQuery File Upload
There is literally no example source code for Django and Large resumable file upload to Google Storage but only this https://cloud.google.com/storage/docs/performing-resumable-uploads#upload-resumable. Are there any examples on how I may achieve this ? -
How to dsiplay value from another model based on the same if form another model in django
I have db and the following classes: in models.py class Student(models.Model): name=models.CharField(max_length=200) surname=models.CharField(max_length=500) class Class101(models.Model): name=models.CharField(max_length=200) math=models.DecimalField(max_length=200) english=models.DecimalField(max_length=200) in views.py total_grade=Class101.objects.filter(Q(math__gt=70) & Q(english__gt=58)) context ={'tg':total_grade} in template.html {% for grade in tg %} <p> {{grade.name}} </p> {% endfor %} it lists name of students however i want to put in the template : {{grade.name}} - {{grade.surname}} {{grade.surname}} where surname is from model Student This code does display surname . How to make to display surname from another model where both models have the same name? -
include_tag considers the argument as a string
I'm trying to define an inclusion_tag and pass to it a dataframe as argument. Here is the definition. @register inclusion_tag('tabla_ampliadaV2.html') def tabla_ampliadaV2(df): dataframe = df t = datetime.datetime.now() today = datetime.date.today() manana = today + datetime.timedelta(days=1) manana_weekday = calendar.weekday(manana.year, manana.month, manana.day) pasado_manana = manana + datetime.timedelta(days=1) pasado_manana_weekday = calendar.weekday(pasado_manana.year, pasado_manana.month, pasado_manana.day) return {'Dia': ['Hoy', str(t.day)+'/'+str(t.month)], 'Manana': [manana_weekday, str(manana.day)+'/'+str(manana.month)], 'Pasado': [pasado_manana_weekday, str(pasado_manana.day)+'/'+str(pasado_manana.month)], 'Nubosidad': dataframe.loc['Nubosidad'], 'Temp_aire': dataframe.loc['Temp_aire'], 'Dir_viento': dataframe.loc['Dir_viento'], 'Vel_viento': dataframe.loc['Vel_viento'], 'Temp_agua': dataframe.loc['Temp_agua'], 'Altura_ola': dataframe.loc['Altura_ola'], 'Dir_olas': dataframe.loc['Dir_olas'], 'Periodo_olas': dataframe.loc['Periodo_olas'], 'Mareas': dataframe.loc['Mareas']} Then, when I call this tag as {% tabla_ampliadaV2 my_df %} I can see that it's considering my_df as a string and thus it doesn't work. I don't know what's wrong, in the docs it is said you can pass arguments of any type. Any help please? -
Django - translate clause "WHERE identity IN (SELECT identity ... GROUP BY identity)" to django orm
I have such a schema: http://sqlfiddle.com/#!17/88c6a It is simple variation on versioning model, where all versions of single entity have the same identity. I have to find all records which used to have category = 2 in their history. How can I reproduce such query in Django? SELECT * FROM some_table a WHERE identity IN (SELECT identity FROM some_table WHERE category = 2 GROUP BY identity ) AND is_latest = true; I tried to retrieve these identities in application class SomeTableQueryset(QuerySet): def had_category_2(self): with connection.cursor() as cursor: cursor.execute(""" SELECT identity FROM some_table WHERE category = 2 GROUP BY identity; """) valid_identities = [i[0] for i in cursor.fetchall()] and filter queryset by qs = qs.filter(identity__in=valid_identities) But such approach has several cons: it's not lazy, so query will be executed as soon as had_category_2 is called it's very slow for obvious reasons So, what can I do? -
Django context not passing context well
I was trying to pass a query set using context. But on template page the context is not working. As I am implementing two queries in same view one query set is working fine but the other query is not passed well. Here is my view # Create your views here. def xray_result_view(request): q=query_holding_together.objects.filter(which_user=request.user) for x in q: all_reports=xray_result.objects.get(which_query=x) print(all_reports.sys_gen_result) return render(request,'XRay/result.html',{'reports':all_reports}) when q is passed as template it is working as it should but it is not working for all reports. here is my template {% extends "login/successful.html" %} {% block middle_window %} </div> <div class="container adjust-ment"> <div class="row"> <div class="col-12"> Previous X-ray Results </div> </div> <div class="row"> <div class="col-12"> Result </div> </div> <div class="row"> <div class="col-12"> {% for y in reports.iterator %} File Name:<br> Date and Time of Upload:<br> System Generated Result:{{ y.sys_gen_result }}<br> Doctor's Comment on Result:{{ y.doctor_comment }}<br> {% endfor %} </div> </div> </div> {%endblock middle_window %} -
Filter query between two values
I'm working on django but can't figure how to write a query , I'm trying to get value between range of values store +----+-------------+-----------+ | id | value up | value down| +----+-------------+-----------+ | 1 | 100 | 200 | +----+-------------+-----------+ | 2 | 150 | 300 | +----+-------------+-----------+ | 3 | 7000 | 7500 | +----+-------------+-----------+ How suppose I have value 290 , how do I get Id from range of 150 to 300 -
Does django save method changes require new migration?
After changing a model save method, is it required to run the makemigration command? In which case (if there are) does changes in save method involve database migrations? -
Django error: I want to update profile picture along with other account details, but its showing error
views.py def profile_edit(request): if not request.user.is_authenticated: return redirect('login') context = {} if request.POST: form = AccountUpdateForm(request.POST, request.FILES, instance=request.user) if form.is_valid(): form.initial = {'email':request.user.email, 'first_name':request.user.first_name, 'last_name':request.user.last_name, 'profile_pic':request.user.profile_pic} form.save() context['success_group'] = "Your details have been updated" else: form = AccountUpdateForm(initial={'email':request.user.email, 'first_name':request.user.first_name, 'last_name':request.user.last_name, 'profile_pic':request.user.profile_pic}) context['account_form'] = form return render(request,'accounts/accountpage_edit.html', context) forms.py class AccountUpdateForm(forms.ModelForm): class Meta: model = Account fields = ['email', 'first_name', 'last_name', 'profile_pic'] def clean_email(self): email = self.cleaned_data['email'] try: account = Account.objects.exclude(pk=self.instance.pk).get(email=email) except Account.DoesNotExist: return email raise forms.ValidationError('Email "%s" is already in use.' % account) def clean_first_name(self): if self.is_valid(): first_name = self.cleaned_data['first_name'] def clean_last_name(self): if self.is_valid(): last_name = self.cleaned_data['last_name'] def clean_profile_pic(self): if self.is_valid(): profile_pic = self.cleaned_data['profile_pic'] I am a beginner and not sure how to continue doing this. The problem before was the picture was not getting uploaded but after some tweaks its now showing this error: The view accounts.views.profile_edit didn't return an HttpResponse object. It returned None instead. Can anyone guide how to make this happen? Thanks in advance! -
What is the best way to give user interface to a python chatbot?
I made a chatbot using Python and TensorFlow. It works fine and I have the py file ready but how do I give it interface. I want to launch it as a web application. How do I do it? This is probably a very silly question for many of you. Thank you in advance Here is the code for the chatbot just in case import nltk from nltk.stem.lancaster import LancasterStemmer stemmer = LancasterStemmer() import numpy import tflearn import tensorflow import random import json import pickle with open("intents.json") as file: data = json.load(file) try: with open("data.pickle", "rb") as f: words, labels, training, output = pickle.load(f) except: words = [] labels = [] docs_x = [] docs_y = [] for intent in data["intents"]: for pattern in intent["patterns"]: wrds = nltk.word_tokenize(pattern) words.extend(wrds) docs_x.append(wrds) docs_y.append(intent["tag"]) if intent["tag"] not in labels: labels.append(intent["tag"]) words = [stemmer.stem(w.lower()) for w in words if w != "?"] words = sorted(list(set(words))) labels = sorted(labels) training = [] output =[] out_empty = [0 for _ in range(len(labels))] for x, doc in enumerate(docs_x): bag = [] wrds = [stemmer.stem(w) for w in doc] for w in words: if w in wrds: bag.append(1) else: bag.append(0) output_row = out_empty[:] output_row[labels.index(docs_y[x])] = 1 training.append(bag) output.append(output_row) … -
Cannot open file in S3 bucket
I'm trying to open a file in an S3 bucket in a view using the following filename = static('post_codes/towns.csv') contents = list(unicode_csv_reader(open(filename,encoding="utf8"))) I get a file not found, no such file or directory, but the file does exist and if I enter the url provided back by the error message it opens the file. What am I doing wrong? Note, unicode_csv_reader is just a simple function to extract the data def unicode_csv_reader(utf8_data, dialect=csv.excel, **kwargs): csv_reader = csv.reader(utf8_data, dialect=dialect, **kwargs) for row in csv_reader: yield [cell for cell in row] -
Convert string to date django template
I'm trying to convert string to date in template using template tag but it doesn't work {% load templat_tag_file %} <input name="range2" type="date" {% if request.Get.range2 %} value="{{ request.Get.range2|convert_str_date }}"{% endif %}/> my templat_tag_file.py : from datetime import datetime register = template.Library() @register.filter def convert_str_date(value): return datetime.strptime(value, '%Y-%m-%d').date()