Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using Django-CKeditor and django_comments
couldn't use django-ckeditor with django_comments. I had used with my own apps but there is a weird error on django_comments app. I can see and use the editor but on the first time it shows an error 'This field is required'. and when I try post same comment again with submit button, I can post it but can't use editor again without page refresh cause of CKeditor locks. I use django_comments + fluent_comments + threaddedcomments it all comes from django_comments. so I should able to use it CKeditor. but I get all the time form error. I tried to debug it on fluent_comments/views.py since I use fluent_comments. request.POST.copy() ==> doesn't catch the comment on first time and app shows the error. second time catches and post it but as I said cant use CKEditor again. my django_comments form: class CommentDetailsForm(CommentSecurityForm): """ Handles the specific details of the comment (name, comment, etc.). """ name = forms.CharField(label=pgettext_lazy("Person name", "Name"), max_length=50) email = forms.EmailField(label=_("Email address")) url = forms.URLField(label=_("URL"), required=False) # Translators: 'Comment' is a noun here. comment = forms.CharField(label=_('Comment'), widget=CKEditorWidget(), max_length=COMMENT_MAX_LENGTH) I addded to my fluent_comments form.html: <script type="text/javascript" src="{% static "ckeditor/ckeditor-init.js" %}"></script> <script type="text'/javascript" src="{% static "ckeditor/ckeditor/ckeditor.js" %}"></script> -
I need to save only z values for 3D PointField in Geodjango
I have a location database for some objects using PointField with 3 dimensions. But it turns out some users only have the z coordinate (elevation) for the objects and not x and y. PointField doesn't let me define a point with only z coordinate. I really don't want to break up the PointField into two fields as it is very convenient for me this way. It would be great if there is a work-around that I could use. In []: Point(x=1,y=2,z=3).z Out[]: 3.0 In []: Point(z=3).z Out[]: -
Django Rest Framework: Test Case is not returning correct queryset
I have created an API, using DRF, for products in an inventory that can be accessed by the following endpoint url(r'products/$', views.InventoryList.as_view(), name='product-list'). When issuing a GET request via postman, I get the correct query-set back, which is a total of 11 products: [ { "id": 1, "name": "Biscuits", "description": "Papadopoulou Biscuits", "price": "2.52", "comments": [ { "id": 1, "title": "First comments for this", "comments": "Very tasty", "rating": 8, "created_by": "xx" } ] }, { "id": 2, "name": "Rice", "description": "Agrino Rice", "price": "3.45", "comments": [] }, { "id": 3, "name": "Spaghetti", "description": "Barilla", "price": "2.10", "comments": [] }, { "id": 4, "name": "Canned Tomatoes", "description": "Kyknos", "price": "3.40", "comments": [] }, { "id": 5, "name": "Bacon", "description": "Nikas Bacon", "price": "2.85", "comments": [] }, { "id": 6, "name": "Croissants", "description": "Molto", "price": "3.50", "comments": [] }, { "id": 7, "name": "Beef", "description": "Ground", "price": "12.50", "comments": [] }, { "id": 8, "name": "Flour", "description": "Traditional Flour", "price": "3.50", "comments": [] }, { "id": 9, "name": "Oregano", "description": "Traditional oregano", "price": "0.70", "comments": [] }, { "id": 10, "name": "Tortellini", "description": "Authentic tortellini", "price": "4.22", "comments": [] }, { "id": 11, "name": "Milk", "description": "Delta", "price": "1.10", "comments": [] } β¦ -
Unable to display image using django
I am new to using django. In my app, I am uploading images that is being stored to the media folder. Now, I am trying to provide the link for downloading the image which is not working. I also tried to display the image directly( using img in html) which is not working either. My code is as follows: urls.py from django.conf.urls import url from . import views from django.conf import settings from django.conf.urls.static import static app_name = 'workers' urlpatterns = [ url(r'^$', views.index, name= 'index'), url(r'^enrollment$',views.enroll, name='enroll'), url(r'^save_enrollment$',views.save_enrollment, name='save_enrollment'), ] if settings.DEBUG: urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py:- from django.db import models class Worker(models.Model): name = models.CharField(max_length=250) address = models.CharField(max_length=500) phone_number = models.CharField(max_length=100) designation = models.CharField(max_length=1000) docfile = models.ImageField(upload_to='documents/') ssn = models.CharField(max_length=200) def __str__(self): return (self.name) views.py:- from .models import Worker from .forms import Worker_enrollment from django.shortcuts import render, get_object_or_404 from django.conf import settings def index(request): workers_info = Worker.objects.all() context = { 'workers':workers_info } return render(request, 'workers/index.html', context) def enroll(request): form = Worker_enrollment(request.POST) if form.is_valid(): return render(request, 'workers/enroll.html', {'form': form}) else: form = Worker_enrollment() return render(request, 'workers/enroll.html', {'form': form}) def save_enrollment(request): worker_info = Worker() if request.method == 'POST': form = Worker_enrollment(request.POST,request.FILES) if form.is_valid(): worker_info.name = form.cleaned_data['name'] worker_info.address = β¦ -
Integration of Machine Learning with a web application
I'm pretty new to web development, I have experience in machine learning (TensorFlow) and I am looking to integrate a TensorFlow model with a web application. I have experience in Python and a bit of Java, but I would prefer if the app's back end could be written in python, using Django. So, my question; How would a go about integrating a pretrained TensorFlow model with a web app so that it can take data input from users add this to a database and then use the TensorFlow model to make predictions on that data, store those predictions, and return the predictions to the user in one form or another? I want to host all of the computing and data storage on Google Cloud Platform. My other questions: Where do I do the programming for the data processing of the web app? I understand that with Django you have several functions/programs that handle different parts of the web app: the URL, the Template, the View, and the Model. From what I understand the Model is the part that interacts, reads writes, and processes the data in the database. So, could I write the TensorFlow model in the Model? If not β¦ -
DRF Object of type 'User' is not JSON serializable
I'm trying to return the details of the current logged in user in the following way: from .serializers import UserSerializer class UserDetailsView(RetrieveAPIView): model = User queryset = User.objects.all() permission_classes = [permissions.IsAuthenticated] serializer_class = UserSerializer def get(self, request, *args, **kwargs): user = User.objects.get(id=request.user.id) print(user) return Response(user) in serializers.py I've use ModelSerializer class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) def create(self, validated_data): user = UserModel.objects.create(username=validated_data['username']) user.set_password(validated_data['password']) user.save() return user class Meta: model = UserModel fields = ('id', 'username', 'password') write_only_fields = ('password',) I get an error Object of type 'User' is not JSON serializable. What is wrong in my use case? -
ProgrammingError at / column posts_category.slug does not exist
I have a django blog project which is live in production using postgres and works fine. I'm having trouble with my local project, and when I run the server and load the page I get the following error : ProgrammingError at / column posts_category.slug does not exist LINE 1: ... "posts_category"."id", "posts_category"."title", "posts_cat... The traceback is just weird, as the location of the error was working previously and hasn't changed. When I butchered my local project trying to remove the apparent erroneous areas, the traceback just focuses on a different view and template: /Users/davidmellor/code/nomadpad/posts/views.py in getAllPosts def getAllPosts(request): latest_posts = Post.objects.all().order_by('-pub_date') comments = Comment.objects.all().order_by('-pub_date') context = { 'latest_posts':latest_posts, 'comments':comments, } return render(request, 'posts/getAllPosts.html', context) ... def getPost(request, slug): post = Post.objects.get(titleSlug=slug) comments = Comment.objects.count() context = { 'post':post, βΌ Local vars Variable Value comments Error in formatting: ProgrammingError: relation "posts_comment" does not exist LINE 1: ...thor_id", "posts_comment"."approved_comment" FROM "posts_com... ^ context Error in formatting: ProgrammingError: relation "posts_comment" does not exist LINE 1: ...thor_id", "posts_comment"."approved_comment" FROM "posts_com... ^ latest_posts Error in formatting: ProgrammingError: column posts_post.titleSlug does not exist LINE 1: ...posts_post"."pub_date", "posts_post"."author_id", "posts_pos... ^ request <WSGIRequest: GET '/'> I did git fetch --all && git reset --hard origin/master to completely reset β¦ -
Django ProgrammingError while migrations with django 1.8 and python2.7.11, mysql
I am getting following error while making migration to mysql database django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax;check the manual that corresponds to your MySQL server version for the right syntax to use near 'TABLES' at line 1") I have checked my code but didn't found anything wrong. Note: This is my first migration after creating django project -
Django deleting default form labels
While styling Authentication form i got defining labes "Username" and "Password" picture is here. How to delete these elements? Forms module class LogForm(AuthenticationForm): username = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter Login'})) password = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Enter Login'})) -
How do I read a zip(which in fact is in bytes form) without creating a temporary copy?
I am uploading a zip(which further contains pdf files to be read) as multipart/form-data . I am handling the upload as below: file = request.FILES["zipfile"].read() #gives a byte object bytes_io = io.BytesIO(file) # gives a IO stream object What I intend to do is to read the pdf files inside the zip, but I am stuck as to how to proceed from here. I am confused, what do I do with either the bytes object from the request or the IO object after conversion. -
Django queryset with for loop and pass to template
I'm trying to use multi search. I'm Splitting the search input using split function. And using Django Filter to get search query. But Filter returns queryset. I can't figure out how to send list of queryset for specific text using loop in a formatted manner like Array List. I wan something Like: 'Fish': 'Fish Queryset','Meat':'Meat Querysset'. I'm explicitly sending variable by variable for 2/3 inputs. I want to send in like an array list to template. Mt View Function: #Split Defintions change only here search_input = search_text.split('.') len_search_items = len(search_input) #Create search query for appropritated searched products if(len_search_items==1): search_split = search_input[0] #Store the split search text in Array searched_products=list(Item.objects.filter(title__contains=search_split)) args = { 'len_search_items':len_search_items,'search_split':search_split,'form':form, 'search_input':search_input,'searched_products':searched_products,'search_text':search_text} Template Code: {% extends 'base.html' %} {% block search_content %} <h2>Search Page</h2> {% include "snippets/search-form.html" %} <h2> String Separatin={{ search_input }}</h2> <h2> Searched For={{ search_text }}</h2> <h2> Searched For ={{ len_search_items }} products</h2> <h2> Search Found Result ={{ searched_products_len }} products</h2> <h2> Searched For ={{ search_split }}</h2> {% if searched_products %} <ul> <h2>Searched Product List</h2> {% for item in searched_products %} <li> <a href="{% url 'detail' item.id %}">{{ item.title }}</a></li> {% endfor %} </ul> {% else %} <h2>No Search Matched</h2> {% endif %} {% if searched_products1 β¦ -
Django - ManytoMany doesn't add values automatically to database
I have the following code in my models.py class Tags(models.Model): tag_name = models.CharField(max_length=50, primary_key=True) description = models.TextField() class Meta: ordering = ('tag_name',) def __str__(self): return self.tag_name @models.permalink def get_absolute_url(self): return "/%s/" % self.tag_name class Post(models.Model): title = models.TextField() #tags = models.ForeignKey(Tags, on_delete=models.DO_NOTHING) tags = models.ManyToManyField(Tags, through='PostTags', related_name='my_posts') class PostTags(models.Model): post = models.ForeignKey(Post, related_name='posttags', on_delete=models.DO_NOTHING) tag = models.ForeignKey(Tags, related_name='posttags', on_delete=models.DO_NOTHING) def __unicode__(self): return "%s with tag %s" % (self.post, self.tag) forms.py class postform(forms.ModelForm): class Meta: model = Post #fields = '__all__' fields = [ 'title', 'body', 'publish', 'status', 'tags'] views.py def post_create(request): print("I was called") form = postform(request.POST or None ) if form.is_valid(): article = form.save(commit= False) article.author = request.user article.save() return HttpResponseRedirect("/myblog/") return render(request, "myblog/post_form.html", {'form':form} ) Below are the main tables, blog_post blog_posttags blog_tags But after adding posts into the blog I cannot see any data in the table - blog_posttags. How to use ManyToMany field ? I know to query models.ForeigKey() - queryset = Post.published.filter(tags='football'.lower()) How to filter ManyToMany field, after getting saved? -
DJANGO queryset inconsistent result
i'm on django 2.0.2 and when i do the following statement Etudiant.objects.filter(id_etudiant = user_data)[0].id_groupe i get this result: <Groupe: Groupe object (grop0)> when i do the following statement: <QuerySet [<Groupe: Groupe object (grop0)>, <Groupe: Groupe object (grop1)>, <Groupe: Groupe object (grop2)>, <Groupe: Groupe object (grop3)>, <Groupe: Groupe object (grop4)>, <Groupe: Groupe object (grop5)>, <Groupe: Groupe object (grop6)>, <Groupe: Groupe object (grop7)>]> <Groupe: Groupe object (grop0)> is in here as you can see but when i do this: Groupe.objects.filter(id_groupe = Etudiant.objects.filter(id_etudiant = user_data)[0].id_groupe) or this: Groupe.objects.filter(id_groupe__in = [Etudiant.objects.filter(id_etudiant = user_data)[0].id_groupe]) i get an empty query set <QuerySet []> -
Django - implementing models.FileField using MEDIA_ROOT throws permission errors
I am trying to implement a models.FileField (as a side note models.ImageField complains that I do not have Pillow, but I will try to install it once this is solved). When I use MEDIA_ROOT and try to upload a file from Admin I get this error: PermissionError at /admin/resume/project/9/change/ [Errno 13] Permission denied: '/resume' Request Method: POST Request URL: http://127.0.0.1:8001/admin/resume/project/9/change/ Django Version: 2.0.3 Exception Type: PermissionError Exception Value: [Errno 13] Permission denied: '/resume' Exception Location: /home/kinkyboy/virtualenv/djangoresume/lib/python3.4/os.py in makedirs, line 237 Python Executable: /home/kinkyboy/virtualenv/djangoresume/bin/python3 Python Version: 3.4.3 .. This is the relevant part of the code. ### project/settings.py RUNNING_DEVSERVER = (len(sys.argv) > 1 and sys.argv[1] == 'runserver') DEBUG = RUNNING_DEVSERVER STATIC_ROOT = os.path.join(BASE_DIR, "static") STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, '/static') ] MEDIA_ROOT = '/resume/' MEDIA_URL = '/resume/' ### project/urls.py .. from django.conf import settings from django.conf.urls.static import static urlpatterns = [ ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) .. ### app/models.py class Project(models.Model): .. image = models.FileField(upload_to='img/',blank=True) ### app/index.html <p>Use this below: {{proj.image.url}}</p> <div class="item active" style="background-image: url('{% static '<use the image url>' %}');"> Structure of my project: Project βββ project β βββ __init__.py β βββ __init__.pyc β βββ __pycache__ β βββ settings.py β βββ urls.py β βββ wsgi.py βββ manage.py βββ β¦ -
Django 1.11 ignore TEMPLATE_DIRS
I learn Django 1.11 right now, and I have a problem. When I try to use TEMPLATE_DIRS: 'DIRS': [os.path.join(settings.BASE_DIR, 'templates'), ], or 'DIRS': [myproj/templates], it doesn't work. What can I do with it? I searched a lot, but I didn't find answer. -
Bulk create fails with 1 milion rows
For learning purposes I've created csv files with 10 000 rows and 2nd file with 1 million rows, 4 columns each. The idea is to add the data to the table most efficient. ( I am using SQL Database) First approach - @transaction.atomic @transaction.atomic def insert(request): data_reader = csv.reader(open(csv_filepathname), delimiter=',', quotechar='"') for row in data_reader: nela = Nela() # my model name nela.name = row[0] nela.last = row[1] nela.almost = row[2] nela.number = row[3] nela.save() insert(request) 1) For 10 000 rows it takes 2.1006858348846436 to insert data 2) For 1 million rows it was something around ~220.xx secs My 2nd approach is usage of bulk_create() def insert(request): data_reader = csv.reader(open(csv_filepathname), delimiter=',', quotechar='"') header = next(data_reader) Nela.objects.bulk_create([Nela(name=row[0], last=row[1], almost=row[2], number=row[3]) for row in data_reader]) insert(request) 1) for 10 000 rows it takes 0.4592757225036621 which is cool and over 4 times faster then with @transaction.atomic 2) However, for 1 million rows it fails and it outruns the limit of the SQL base. Does anyone have any idea why such bug appears ? I've been reading django docs bulk_create but besides annotation about batch_size for SQL lite I can't find anything useful. -
Django ModelForm dynamic runTIme field
How would I dynamically add fields on a ModelForm that are not defined on the model at runTime on Django 1.9.7? I'm aware I can do: class ExampleForm(forms.ModelForm): class Meta: model = Example # if you don't define the list of fields __all__ won't get the dynamic one fields = '__all__' MY_CHOICES = ( ('A', 'Choice A'), ('B', 'Choice B'), ) stuff = forms.ChoiceField(choices=MY_CHOICES) But what if I need the choices for example to be gathered at Runtime? For example: class ExampleForm(forms.ModelForm): class Meta: model = Example fields = '__all__' MY_CHOICES = ( ('A', 'Choice A'), ('B', 'Choice B'), ) def __init__(self, *args, **kwargs): super(ExampleForm, self).__init__(*args, **kwargs) self.stuff = forms.ChoiceField(choices=self.MY_CHOICES) # self.fields['stuff'] = forms.ChoiceField(choices=self.MY_CHOICES) Also does not work Returns an error of Unknown field(s) (stuff) specified for Example. How would I define a field that is not defined on the Model and that needs to gather the choises for example from a different query? Thanks -
Django template: Slicing form fields into 2 parts
I'm passing a form to my template, using django-filter and can be accessed in the template using filter.form. I'm trying to slice the filter form to only show 10 most popular tags. Why is the following now working? # template.html {% for field in filter.form.tags | slice:"0:10" %} {{ field }} {{ field.label_tag }} I get the error: 'for' statements should use the format 'for x in y': for tags in filter.form.tags | slice:":" Isn't x=field and y = filter.form.tags | slice:"0:10" -
Why does django model _meta.get_fields() returns model name?
I have this simple django model: class Member(models.Model): class Meta: db_table = 'member' last_name = models.CharField(max_length=50,blank=True,null=True) first_name = models.CharField(max_length=50,blank=True,null=True) ... I am trying to get the list of field names, but when I use get_fields(), I get a list that includes 'member' as a field name even though I don't have a field called 'member' for f in model._meta.get_fields(): print( f.name + ' : ' + f.get_internal_type() ) member : ForeignKey id : AutoField last_name : CharField first_name : CharField What is this first field 'member' that is a ForeignKey? Do I just drop it to get the true list of fields? -
Count number of events on each date , using django
I am trying to use chartist, to visualise number of events per day ,and so far i have tried the following: models.py class Event(models.Model): name = models.TextField(max_length=500) event_date = models.DateTimeField() charts.py def mychart(): events = Event.objects.annotate(start_date=Trunc('event_date', 'day', output_field=DateField())).values('event_day').annotate(myevent=Count('id')) return json.dumps({ 'labels':[p['start_day'] for p in events], 'series':[p['myevents'] for p in events]}) but i am still getting single objects, and not grouped by "day"!! as shown below: 2018-04-02 1 2018-03-31 1 2018-04-02 1 2018-04-02 1 2018-03-31 1 2018-04-02 1 2018-04-02 1 And what is that i am expecting, is something like: 2018-04-02 5 note : I am using Postgresql Database, thank you in advanced ,, -
Django: Test Models with dependencies in multiple apps
I have a model Registration which is referenced with a OneToOneField by Payment. Now I am trying to write my tests but it won't work. What should happen: When a Registration object is created, the save-method saves the Registration object and then queries the database for a Payment object. If the Payment object does not exist, it shall be created. events/models.py [...] class Registration(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) team = models.CharField(max_length=50, blank=True) date_created = models.DateTimeField(auto_now_add=True) def save(self, *args, **kwargs): "Saves the Registration and creates a new Payment." super().save(*args, **kwargs) if not Payment.objects.get(registration=self): Payment.objects.create(registration=self) if not self.category.price: payment = Payment.objects.get(registration=self) payment.paid = True payment.save() payments/models.py class Payment(models.Model): "A Payment model." uuid = models.CharField(max_length=1, default=_get_uuid) paid = models.BooleanField(default=False) registration = models.OneToOneField('events.Registration', on_delete=models.CASCADE) events/tests.py import datetime from django.test import TestCase from django.contrib.auth.models import User from .models import Sport, Event, Category, Registration class EventTest(TestCase): def setUp(self): User.objects.create(username="user") user = User.objects.get(username="user") Sport.objects.create(...) sport = Sport.objects.get(name="MMA") Event.objects.create(...) event = Event.objects.get(name="Event") Category.objects.create(...) category = Category.objects.get(event=event) reg = Registration.objects.create( category=category, user=user) def test_payment_is_created_by_registration(self): self.assertIs(1, len(Payment.objects.all())) Console (ems) C:\Users\Rubber\ems>python manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). E ====================================================================== ERROR: test_payment_is_created_by_registration (events.tests.EventTest) ---------------------------------------------------------------------- Traceback (most recent call last): β¦ -
Module not found error when uploading django app to heroku (works locally)
I'm trying to upload my updated django app to heroku - it works in my local system, but when I push my changes, it tells me it can't find a particular module (phonenumber_field). I suspect it's when I install phonenumber_field, I use the command pip install django-phonenumber-field, while in the settings file, it is phonenumber_field. I have ran pip freeze > requirements.txt, and the module in question is django-phonenumber-field==2.0.0. I have no idea where I'm going wrong, and wondering if someone could shed some light for me. I don't think this is a case of the error in the following link as I had the same problem with bootstrap 3 until I used a CDN for bootstrap (bootstrap3 in the settings page but django-bootstrap3==9.1.0 in requirements.tx). https://devcenter.heroku.com/articles/python-c-deps ERROR MESSAGE remote: -----> Python app detected remote: -----> Found python-3.6.3, removing remote: -----> Installing python-3.6.4 remote: -----> Installing pip remote: -----> Installing dependencies with Pipenv 11.8.2β¦ remote: Installing dependencies from Pipfile.lock (af8c37)β¦ remote: -----> $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "manage.py", line 15, 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 371, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 347, in execute remote: django.setup() β¦ -
urls.py for the configuration of edx ora2(openassessment.fileupload)
and I would like to ask a quesition about django configuration of ORA2 xblock in open edx : ORA2 allows learners to upload a file. Defaultly uploaded file will be store in S3 storage, and I want to change it to another storage. The document about how to configure is here: http://edx.readthedocs.io/projects/edx-installing-configuring-and-running/en/open-release-ficus.master/configuration/ora2/ora2_uploads.html?highlight=fileupload source code url: https://github.com/edx/edx-ora2 (version 1.1.13; edx version: bitnami image for azure, version FICUS). My plan is change setting to below, and I followed all 4 steps in the above url. ORA2_FILEUPLOAD_BACKEND = "filesystem" Also I did one more thing for urls.py as below: as the comments of in openassessment/fileupload/filesystem.py : """ Upload openassessment student files to a local filesystem. Note that in order to use this file storage backend, you need to include the urls from openassessment.fileupload in your urls.py file: E.g: url(r'^openassessment/storage', include(openassessment.fileupload.urls)), """ According to comments, urls.py for openassessment.fileupload should be included in the urls.py of the app (lms): content of openassessment/fileupload/urls.py: from django.conf.urls import patterns, url urlpatterns = patterns('openassessment.fileupload.views_filesystem', url(r'^(?P<key>.+)/$', 'filesystem_storage', name='openassessment-filesystem-storage'), content of edx-platform/lms/urls.py: ... urlpatterns = ( '', url(r'^$', 'branding.views.index', name="root"), # Main marketing page, or redirect to courseware url(r'', include('student.urls')), ... # URL for openassessment-fileupload --by url(r'^openassessment/storage', include(openassessment.fileupload.urls)), ) At last, β¦ -
django.db.utils.OperationalError: FATAL: password authentication failed for user
Followed this tutorial. But the password authentication was not working in django on the localhost. Here is how I am trying to do it settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'my_local_db', 'USER': 'admin', 'PASSWORD': 'mypassword', 'HOST': 'localhost', } } Created a database named my_local_db with the password mypassword and created a user named admin. Granted it all the priveleges. But it gave the authentication error. Found this so altered the user and restarted postgresql service but that didn't work either. Also found this so updated my pg_hba.conf located at /etc/postgresql/10/main/pg_hba.conf and restarted the postgresql service. This is how it looks: local all postgres peer local all all peer # IPv4 local connections: host all all 127.0.0.1/32 md5 # IPv6 local connections: host all all ::1/128 md5 Also tried adding admin as a user but that didn't work either Error: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f2b0fdd9d08> Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/django/db/backends/base/base.py", line 216, in ensure_connection self.connect() File "/usr/local/lib/python3.5/dist-packages/django/db/backends/base/base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python3.5/dist-packages/django/db/backends/postgresql/base.py", line 168, in get_new_connection connection = Database.connect(**conn_params) File "/usr/local/lib/python3.5/dist-packages/psycopg2/__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: FATAL: password authentication failed for user β¦ -
image inside another image in Django
Hi everyone! I am new to Django and I am working on a project. I need to make profile-images inside group-profile images (Image below). Lets imagine this is a school project and every student has a profile-image and there are several groups example: Bacteria, Virus etc. How do I make the student image appear inside a group image: Please see example below Please let me know if you need more info