Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django allauth and custom 404 page
My question is partly two. Question 1 (allauth): I have set allauth for my project to accept facebook login which works well. However i will like the user to fill a form before he complete his signup. To do this i added the following to my profile app : class CustomSignupForm(SignupForm): first_name = forms.CharField(max_length=30, label='First Name') last_name = forms.CharField(max_length=30, label='Last Name') role = forms.CharField(max_length=30, label='Role( client or pilot )',) def signup(self, request, user): user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.role = self.cleaned_data['role'] user.save() return user seetings.py ACCOUNT_FORMS = { 'signup': 'profile.forms.CustomSignupForm', } **allauth settings:** SITE_ID = 1 After the facebook signin, it only ask for email and user name. Question 2(404): I have launched my app on digital ocean and i have set up a custome 404, 500, and 403 error page in my pages app: def handler404(request, exception, template_name="404.html"): response = render_to_response("404.html") response.status_code = 404 return response def handler403(request, exception, template_name="403.html"): response = render_to_response("403.html") response.status_code = 403 return response def handler500(request, exception, template_name="500.html"): response = render_to_response("500.html") response.status_code = 500 return response Project urls.py handler404 = 'pages.views.handler404' handler403 = 'pages.views.handler403' handler500 = 'pages.views.handler500' The 403 page works however both the 404 and 500 fails to work. -
Why .query() function not working on Django ORM query?
As I already know that using .query.__str__() , we can get sql equivalent query from Django ORM query. e.g : Employees.objects.filter(id = int(id)).query.__str__() Above code working well & I am able to get sql equivalent query but when I am using same on below query I am getting error like below. Employees.objects.filter(id = int(id)).first().query.__str__() AttributeError: 'Employees' object has no attribute 'query' Why now I am getting error, any suggestions ? -
Django - Conditional Rendering In Templates
I need some help conditionally rendering data in a modal pop up window on my site. What I want to do: When the user clicks on the "make reservation" button, I want to display this in the modal window <h3 style="margin-top:20px;">Choose dates</h3> <div style="margin-top:20px;" class="pick-dates-div"> <form method="GET" class="post-form">{% csrf_token %} {{ form.as_p }} <button type="submit" class="form-btn save btn btn-default">Make A Reservation</button> </form> <button style="margin-top: 25px;" class="btn-primary btn-block btn-lg" data-toggle="modal" data-target="#inquiryModal">More Questions ?</button> </div> Then the user can pick the dates from the date picker and press the "make a reservation" button ( which is a GET request ), the page refreshes and I want to display only this in the same modal window : <h1>Start Date: {{ date_start }}</h1> <h1>End Date: {{ date_end }}</h1> <h1>Price Per Day: ${{ price_per_day }}$</h1> <h1>Total: ${{ total_price }}$</h1> <form method="POST" class="post-form">{% csrf_token %} {{ form.as_p }} <a href=""> <button href="www.facebook.com" type="submit" class="form-btn save btn btn-default">Confirm Reservation</button></a> </form> After that the user submits the form ( POST request ) and I want to display a text : <h3> Thank you for your reservation </3> What would be the ideal way to achieve this ? Thank you stack -
How to send data in POST request where the data is not entered by the user in Django
I am trying to make a watchlist for stocks for my website. The data i.e name of the Company and the stock price is already being displayed on the webpage. I want that the user should just click on a button on the same webpage and it adds the data to the watchlist of the user. This is for a website for stock analysis. I dont know how to do this. PS- I'm new to coding Watchlist Model: class WatchList(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) watchlist = models.CharField(max_length=300, default='') price = models.IntegerField(default='') html: {% extends 'homepage/layout.html' %} {% block content %} {% load static %} <head> <title>Technical Analysis</title> <link rel="stylesheet" href="{% static 'tech_analysis/tech_analysis.css' %}"> </head> <div class="line"></div> <div class="head"> Technical Analysis </div> <div class="coname"> <ul class="ticker_table"> <li class="ticker_name">{{ ticker }}-</li> <li class="ticker_price">{{ price }}</li> <li class="diff_green">{{ diff_green }}</li> <li class="diff_red">{{ diff_red }}</li> </ul> <form action="{% url 'bsh_user:Userpage' %}" method="post"> {% csrf_token %} <input class="watchlist" type="submit" value="Add To Watchlist +"> </form> </div> the information such as {{ticker}} and {{price}} is the data that is to be posted to the model and displayed to the user on a different html. Expected outcome is to add a company and its price to the watchlist … -
Internal Server Error for User.objects.get(email=email)
I want to check if a given email exists in auth_user of django First I import from django.contrib.auth.models import User In the controller, I test like this: user_by_email = User.objects.get(email=email) # internal server error at this point. if user_by_email is not None: return HttpResponseBadRequest() But this line returns internal server error. Than I created a new row in auth_user manually, it worked as it should be. -
Compare datetime values in django models
I have an Offer model that has a datetime field and I have two records in the database >>> oldOffer.offerDate datetime.datetime(2019, 10, 29, 15, 19, 43, 755325) >>> currOffer.offerDate datetime.datetime(2019, 10, 29, 15, 20, 2, 456100) >>> Offer.objects.filter(offerDate__lt= currOffer.offerDate) <QuerySet []> >>> Offer.objects.filter(offerDate__gt= currOffer.offerDate) <QuerySet [<Offer: Offer object (5)>, <Offer: Offer object (6)>> The currOffer.offerDate is clearly greater than the oldOffer.OfferDate. Then why am I getting an empty result with the __lt clause? Also why do I get both the oldOffer (object 5) and currOffer (object 6) when I use __gt clause? What am I doing wrong? Thanks in advance -
How to confirm purchase with app using django backend
i'm thinking of having an app to check the server if it's been paid or not? if it's paid so user can use the app if not they need to pay does it work with a simple api? (i'm almost new to django) thanks -
Insert into a model with two foreign keys on a post save signal
I hope that the title of my message will be precise enough, if it is not the case I apologize in advance. I do not know how to do the following thing: I have three models: \model class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, related_name='students', on_delete=models.CASCADE, null=True) School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True,null=True) class SubjectSectionTeacher(models.Model): School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Sections = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True) Subjects = models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE, null=True) Employee_Users = models.ForeignKey(EmployeeUser, related_name='+', on_delete=models.CASCADE, null=True) class StudentsEnrolledSubject(models.Model): Students_Enrollment_Records = models.ForeignKey(StudentsEnrollmentRecord, related_name='+', on_delete=models.CASCADE, null=True) Subject_Section_Teacher = models.ForeignKey(SubjectSectionTeacher, related_name='+', on_delete=models.CASCADE, null=True,blank=True) @receiver(post_save, sender=StudentsEnrollmentRecord) def create(sender, instance, created, **kwargs): if created: StudentsEnrolledSubject.objects.create(Students_Enrollment_Records=instance.Student_Users, Subject_Section_Teacher = SubjectSectionTeacher.Employee_Users) I just want that when the admin update the student enrollment record and must be added automatically in StudentsEnrolledSubject -
Error collection and propagation in Django serializers
I am struggling with collecting exceptions when using multiple Django serializers. Here is the situation. With multiple serializers, I want the last serializer (such as Beta in the following example)to collect all errors/exceptions generated while invoking the others. However, if a serializer higher in the chain (such as Alpha)raises an exception, the server stops and reports it and the view class was even reached. What should I do to propagate these exceptions to Beta and eventually send them to the front though the view? class Alpha(Serializer): def validate(self, user_data): if something wrong: raise Exception(..) return user_data class Beta(Serializer): def validate(self, data): serializer_alpha = Alpha(data['user']) if serializer_alpha.is_valid(): [do something] else: raise Exception(serializer_alpha.errors) return data In a view, the attempt is to report all the errors/exceptions that took place along the validation chain, class ParticularAppView(APIView): def post(self, request, **kwargs): serializer = Beta(data=request) if serializer.is_valid(): try: [do something] Response(response, ...) except Exception as e: Reponse(serializer.errors, ...) -
Django Apache error: No module named 'encodings'. Windows server 2008 R2 Standard
I clone repo from git. I create venv: python -m venv myenv /myenv/scripts/activate.bat pip install -r requirements.txt pip install mod_wsgi-4.6.5+ap24vc14-cp36-cp36m-win_amd64.whl if i run from myvenv that: python manage.py runserver it's work! if I run from apache, I have a error: [Wed Oct 30 10:51:18.732028 2019] [mpm_winnt:notice] [pid 352:tid 168] AH00455: Apache/2.4.41 (Win64) mod_wsgi/4.6.5 Python/3.6 configured -- resuming normal operations [Wed Oct 30 10:51:18.732028 2019] [mpm_winnt:notice] [pid 352:tid 168] AH00456: Apache Lounge VS16 Server built: Aug 9 2019 16:46:32 [Wed Oct 30 10:51:18.732028 2019] [core:notice] [pid 352:tid 168] AH00094: Command line: 'httpd -d C:/Apache24' [Wed Oct 30 10:51:18.732028 2019] [mpm_winnt:notice] [pid 352:tid 168] AH00418: Parent: Created child process 1748 Fatal Python error: Py_Initialize: unable to load the file system codec ModuleNotFoundError: No module named 'encodings' Current thread 0x00000354 (most recent call first): [Wed Oct 30 10:51:23.677228 2019] [mpm_winnt:crit] [pid 352:tid 168] AH00419: master_main: create child process failed. Exiting. below httpd.conf: LoadFile "c:/<>/python/python36/python36.dll" LoadModule wsgi_module "c:/envs/myproject/lib/site-packages/mod_wsgi/server/mod_wsgi.cp36-win_amd64.pyd" WSGIScriptAlias / "c:/<myproject>/wsgi.py" WSGIPythonHome "c:/envs/myproject" WSGIPythonPath "c:/<myproject>" Alias /static/ "c:/<myproject>/static/" <Directory "c:/<myproject>/static"> Require all granted </Directory> <Directory c:/<myproject>> <Files wsgi.py> Require all granted </Files> </Directory> <Directory c:/<myproject>/attachments> Require all granted </Directory> I set PYTHONHOME and PYTHONPATH as "C:\Users\user\AppData\Local\Programs\Python\Python36;C:\Users\user\AppData\Local\Programs\Python\Python36\Scripts" I looked many question, example: Fatal Python error … -
Read data from external mysql database and save it into default database in django
I have 2 database connections(default and external). I want to read the data from the external database tables and save it into the default database table. settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'hello', 'USER':'root', 'PASSWORD': '', 'HOST': '127.0.0.1', }, 'external_db': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'hello_external, 'USER':'root', 'PASSWORD': '', 'HOST': '127.0.0.1', } } routers.py """ A router to control all database operations on models in the myapp2 application """ def db_for_read(self, model, **hints): return 'external_db' def db_for_write(self, model, **hints): return 'default' def allow_syncdb(self, db, model): return db == 'default' def allow_migrate(self, db, app_label, model_name=None, **hints): return (db == 'default') -
Like button in django is not working properly in django
I have added like and dislike button to Song post When like object is not created if some click on like it is showing intigrity error if like object is already there then it is not rendering that to template. models.py Codes in models.py class Song(models.Model): song_title = models.CharField(max_length=25) album = models.ForeignKey(Album, related_name='album_name', on_delete=models.CASCADE, blank=True) singer = models.ManyToManyField(Singer, blank=True) language = models.CharField(max_length=25) class VoteManager(models.Manager): def get_vote_or_unsaved_blank_vote(self,song,user): try: return Vote.objects.get(song=song,user=user) except ObjectDoesNotExist: return Vote(song=song,user=user) class Vote(models.Model): UP = 1 DOWN = -1 VALUE_CHOICE = ((UP, "👍️"),(DOWN, "👎️"),) like = models.SmallIntegerField(choices=VALUE_CHOICE) user = models.ForeignKey(User,on_delete=models.CASCADE) song = models.ForeignKey(Song, on_delete=models.CASCADE) voted_on = models.DateTimeField(auto_now=True) objects = VoteManager() class Meta: unique_together = ('user', 'song') views.py Codes in views.py class SongDetailView(DetailView): model = Song template_name = 'song/song_detail.html' def get_context_data(self,**kwargs): ctx = super().get_context_data(**kwargs) if self.request.user.is_authenticated: vote = Vote.objects.get_vote_or_unsaved_blank_vote(song=self.object, user = self.request.user) if vote.id: vote_url = reverse('music:song_vote_update', kwargs={'song_id':vote.song.id,'pk':vote.id}) else: vote_url = reverse('music:song_vote_create', kwargs={'song_id':vote.song.id}) vote_form = SongVoteForm(instance=vote) ctx['vote_form'] = vote_form ctx['vote_url'] = vote_url return ctx class SongUpdateView(UpdateView): form_class = SongVoteForm queryset = Song.objects.all() def get_object(self,queryset=None): song = super().get_object(queryset) user = self.request.user return song def get_success_url(self): song_id = self.kwargs.get('song_id') return reverse('music:song_detail', kwargs={'pk':song_id}) class SongVoteCreateView(View): form_class = SongVoteForm context = {} def post(self,request,pk=None,song_id=None): vote_obj,created = Vote.objects.get_or_create(pk=pk) song_obj = Song.objects.get(pk=song_id) vote_form = SongVoteForm(request.POST, … -
Error: pg_config executable not found. even though I have added the path to pg_config on environment variable
I am trying to setup saleor (Django based). I did a "python -m pip install -r requirements.txt" as stated on the website. Things go well until the installation Collecting psycopg2-binary==2.8.3 and then error is thrown. I have Postgre installed and I am on windows. I also have added the path to pg_config on my environment variable since it says pg_config executable not found. I am not sure how to proceed. Here is the error that is shows up: ERROR: Command errored out with exit status 1: command: 'C:\Users\ASPIRE\AppData\Local\Programs\Python\Python38-32\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\ASPIRE\\AppData\\Local\\Temp\\pip-install-d7c359c_\\psycopg2-binary\\setup.py'"'"'; __file__='"'"'C:\\Users\\ASPIRE\\AppData\\Local\\Temp\\pip-install-d7c359c_\\psycopg2-binary\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\ASPIRE\AppData\Local\Temp\pip-install-d7c359c_\psycopg2-binary\pip-egg-info' cwd: C:\Users\ASPIRE\AppData\Local\Temp\pip-install-d7c359c_\psycopg2-binary\ Complete output (23 lines): running egg_info creating C:\Users\ASPIRE\AppData\Local\Temp\pip-install-d7c359c_\psycopg2-binary\pip-egg-info\psycopg2_binary.egg-info writing C:\Users\ASPIRE\AppData\Local\Temp\pip-install-d7c359c_\psycopg2-binary\pip-egg-info\psycopg2_binary.egg-info\PKG-INFO writing dependency_links to C:\Users\ASPIRE\AppData\Local\Temp\pip-install-d7c359c_\psycopg2-binary\pip-egg-info\psycopg2_binary.egg-info\dependency_links.txt writing top-level names to C:\Users\ASPIRE\AppData\Local\Temp\pip-install-d7c359c_\psycopg2-binary\pip-egg-info\psycopg2_binary.egg-info\top_level.txt writing manifest file 'C:\Users\ASPIRE\AppData\Local\Temp\pip-install-d7c359c_\psycopg2-binary\pip-egg-info\psycopg2_binary.egg-info\SOURCES.txt' Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI 'psycopg2-binary' package instead. For further information please check the 'doc/src/install.rst' file (also … -
Choice of tech stack Django + Dojo + Dijit (Python-based) vs Express for AI-based application
Faced with a tech stack choice and appreciate any inputs. Application: user uploads files, backend processes the files, sends it to a AI-based tensor flow pipeline. Result displayed to end-user. Choice 1: Lang: python everywhere Framework: Django + Dojo + dijit DB: Postgres SQL Backend AI: Tensorflow Hosting: Google Cloud Choice 2: Lang: hybrid: javascript + python Framework: Express + modules, node.js DB: nosq mongodb Backend AI: Tensorflow Hosting: AppEngine My concerns with Choice 1 django stack - Django has power, but not a easy learning path, and deployment issues exist (e.g django + bitnami stack highly complex managed cloud instance) - Deployed a sample app, web pages seem to render twice, as the dojo, digit frameworks seem to load scripts and render so the per page load time is bad - UX Themes limitation and looks a bit arcane 2000ish - Dojo libraries are big 12K files making it hard to deploy on Appengine so u have to go the managed cloud instance route - Advantages: all in one language, and integration over command line with python and subprocess.call to call tensor flow great. Free admin with django awesome - do I have flexiblity to use a noSQL databae … -
Django signals foreignkey
model.py class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, related_name='students', on_delete=models.CASCADE, null=True) School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True, null=True) Remarks = models.TextField(max_length=500, null=True, blank=True) class SubjectSectionTeacher(models.Model): School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Sections = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True) Subjects = models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE, null=True) Employee_Users = models.ForeignKey(EmployeeUser, related_name='+', on_delete=models.CASCADE, null=True) class StudentsEnrolledSubject(models.Model): Students_Enrollment_Records = models.ForeignKey(StudentsEnrollmentRecord, related_name='+', on_delete=models.CASCADE, null=True) Subject_Section_Teacher = models.ForeignKey(SubjectSectionTeacher, related_name='+', on_delete=models.CASCADE, null=True) I code this in my model def studentenrolled(sender,instance, **kwargs): if kwargs['created']: ireceived = StudentsEnrolledSubject.objects.create(Students_Enrollment_Records=instance.Student_Users, Subject_Section_Teacher=SubjectSectionTeacher.Employee_Users) post_save.connect(studentenrolled, sender=StudentsEnrollmentRecord) this is the error I Got my error I just want that everytime the admin input/update the StudentsEnrollmentRecord.Section and StudentsEnrollmentRecord.Course, it will automatic search the Employee_Users from SubjectSectionTeacher and it will save automatically in StudentsEnrolledSubject I dont know if i am doing right in django signal, please help me! -
Django logging is empty
I'm having problem on why on earth just happen after I added a formatter on the LOGGING configuration the logging file is empty. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '{asctime} [{module}]:: {message}', 'style': '{', }, 'simple': { 'format': '{levelname} {message}', 'style': '{', }, }, 'handlers': { 'console':{ 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'verbose' }, 'file.DEBUG': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'filename': 'logs/debug.log', 'maxBytes' : 1024*1024*10, 'backupCount': 10, 'formatter':'verbose' }, 'file.INFO': { 'level': 'INFO', 'class': 'logging.handlers.RotatingFileHandler', 'filename': 'logs/info.log', 'maxBytes' : 1024*1024*10, 'formatter':'verbose' }, 'file.ERROR': { 'level': 'INFO', 'class': 'logging.handlers.RotatingFileHandler', 'filename': 'logs/error.log', 'maxBytes' : 1024*1024*10, 'backupCount': 10, 'formatter':'verbose' }, }, 'loggers': { 'django.request': { 'handlers': ['file.DEBUG'], 'level': 'DEBUG', 'propagate': True, }, 'django': { 'handlers': ['file.INFO'], 'level': 'INFO', 'propagate': True, }, 'django': { 'handlers': ['file.ERROR'], 'level': 'ERROR', 'propagate': True, }, }, } Now all the outputed debug file are empty except for the error file which I tested on the view with this code import logging logger = logging.getLogger('django') logger.info('tests') logger.error('tests') logger.debug('tests') logger.debug('tests') logger.error('tests') logger.info('tests') Only the error is being logged on the file, why is this? Im using the new version of django which is 2.2 -
Testing Django UserCreationForm - form.is_valid() always returning false
I am trying to write tests for my Django chat application to validate the UserCreationForm. I am following the Django test code here: https://github.com/django/django/blob/master/tests/auth_tests/test_forms.py I have a users app which handle registration, login, etc. users/tests.py from django.test import TestCase from django.contrib.auth.forms import UserCreationForm class UserCreationFormTest(TestCase): def test_form(self): data = { 'username': 'testuser', 'password1': 'test123', 'password2': 'test123', } form = UserCreationForm(data) self.assertTrue(form.is_valid()) I've extended the UserCreation form to include an email field (forms.py) when registering. users/forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class UserRegisterForm(UserCreationForm): email = forms.EmailField(required=True, label='Email') class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] I cannot for the life of me figure out why form.is_valid() always returns False during my testing. In my test I have self.assertTrue(form.is_valid()) To execute tests I am running python manage.py test users from the terminal. Actual registration, login, etc. works fine but my tests do not work as expected! users/views.py from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): # check if valid form.save() # save user info messages.success( request, f'Your account has been … -
How to test a django class based view with token authentication?
I am testing a REST API that requires token authentication. I am using coreapi.Client and coreapi.auth.TokenAuthentication to test the view. But it fails due to the following exception: coreapi.exceptions.NetworkError: URL missing scheme '/v0/endpoint/' My dependencies are listed here: python_version = "3.7" django = "==2.2.6" djangorestframework = "==3.9.4" Test File from rest_framework.test import APITestCase import coreapi from requests.auth import HTTPBasicAuth from django.urls import reverse from module.views import MyView class TestViews(APITestCase): def test_train_GET(self): auth = coreapi.auth.TokenAuthentication( scheme = 'Token', token = '<TOKEN>' ) client: coreapi.Client = coreapi.Client(auth=auth) response = client.get( reverse('endpoint') ) self.assertEqual(response.status_code, 200) Project Urls file: from django.urls import include, path urlpatterns = [ path('v0/', include('app.urls')), ] App Urls file: from django.conf import settings from django.contrib import admin from django.urls import include, path from .views import MyView urlpatterns = [ path('endpoint/', MyView.as_view(), name='endpoint'), ] I recieve the following error while running the test: raise exceptions.NetworkError("URL missing scheme '%s'." % url) coreapi.exceptions.NetworkError: URL missing scheme '/v0/endpoint/'. -
How to add a modal pop up on the view button?
<div class="col-md-3"> <div class="card card-profile"> <div class="card-avatar"> <a href="#pablo"> <img class="img" src="{% static 'img/faces/marc.jpg' %}"> </a> </div> <div class="card-body"> <h5 class="card-category text-gray">CEO / Co-Founder</h5> <h4 class="card-title">{{user.first_name}} {{user.last_name}}</h4> <h6 class="card-category text-gray">ILO - 001</h6> <h6 class="card-category text-gray">HOME HEALTH</h6> <p class="card-description"> Monday to Friday (9AM to 6PM) </p> <a href="#" class="btn btn-primary btn-round">View</a> </div> </div> </div> The code for an Profile Pic on my main page, and I was trying to add a modal pop to wherein when I click the View button it will show the whole profile of the employee. And i don't have an idea how to do this. Thanks for any help. -
TypeError: 'DeferredAttribute' object is not iterable for dropdown
I need to make some dropdown the list is from Instagram.username but it say object not iterable anyone can help here's my code : models.py # Create your models here. class Instagram(models.Model): nama_depan = models.CharField(max_length=100) nama_belakang = models.CharField(max_length=100) username = models.CharField(max_length=100) def __str__(self): return "{}.{}".format(self.id,self.username) class InstagramName(models.Model): Instaname = models.CharField(choices=Instagram.username) def __str__(self): return "{}.{}".format(self.id, self.Instaname) forms.py from django import forms from . models import Instagram,InstagramName class InstagramForm(forms.ModelForm): class Meta: model = Instagram fields = [ 'nama_depan', 'nama_belakang', 'username', ] class InstagramNameForm(forms.ModelForm): class Meta: model = InstagramName fields = ['Instaname'] -
django makemigrations error "no such column"
I am developing a Django project with REST Framework. It all worked well before, but all of a sudden I can't add any new model fields: If I add any new field even if the most simple one like this: def_episode = models.IntegerField(blank=True, null=True) And manage.py makemigrations, this will happen: Traceback (most recent call last): File "D:\MyProjects\Python\Django\env\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "D:\MyProjects\Python\Django\env\venv\lib\site-packages\django\db\backends\sqlite3\base.py", line 383, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such column: novelrecorder_novel.def_episode The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "D:\MyProjects\Python\Django\env\venv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "D:\MyProjects\Python\Django\env\venv\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\MyProjects\Python\Django\env\venv\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "D:\MyProjects\Python\Django\env\venv\lib\site-packages\django\core\management\base.py", line 361, in execute self.check() File "D:\MyProjects\Python\Django\env\venv\lib\site-packages\django\core\management\base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "D:\MyProjects\Python\Django\env\venv\lib\site-packages\django\core\management\base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "D:\MyProjects\Python\Django\env\venv\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "D:\MyProjects\Python\Django\env\venv\lib\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "D:\MyProjects\Python\Django\env\venv\lib\site-packages\django\core\checks\urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "D:\MyProjects\Python\Django\env\venv\lib\site-packages\django\utils\functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "D:\MyProjects\Python\Django\env\venv\lib\site-packages\django\urls\resolvers.py", line 584, in url_patterns patterns … -
Is it possible to somehow print 'i+1' in django template?
Scenario:I want to make a page for available slots for booking ,for which I want print time slot for 1 hour that is from i To i+1 and color it according to the availability. I am newbie to django and can't figure out the way to make a calendar and that is why I am printing time values in HTML template. Is there any other way to make this page and also is printing 'i+1' possible. Views.py @login_required def slots(request): k={ 'pro':range(8,17) } return render(request, 'login/slots.html',k) slots.html {% for i in pro %} <tr> <td>1</td> <td>2</td> <td>3</td> <td>4</td> <td id="demo">{{ i }} to {{ i+1 }}</td> </tr> {% endfor %} I know this might be a silly question but I am not able to figure it out, any help is appreciated. -
Django; NoReverseMatch exception - 1 Pattern Tried
Upon trying to test a model's get_absolute_url(), I'm getting the following exception. accounts happens to be the app name in this case. I'm just trying to test the path that is the result of calling that function: django.core.urlresolvers.NoReverseMatch: Reverse for 'profile' with arguments '()' and keyword arguments '{'username': 'test_user'}' not found. 1 pattern(s) tried: ['accounts/profile/<username>/'] class Profile(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) birth = models.DateField() bio = models.TextField() avatar = models.ImageField(upload_to=image_file_path) def get_absolute_url(self): profile_user = self.user.username return reverse('accounts:profile', kwargs={'username': profile_user}) class UserProfileMethods(TestCase): def setUp(self): self.test_user = User.objects.create_user('test_user') self.image = open(join(dirname(__file__), 'images/test_image.jpg'), 'rb') self.profile_data = { 'user' : self.test_user, 'birth': '2019-01-01', 'bio': 'Hello World!', 'avatar': SimpleUploadedFile( self.image.name, self.image.read(), content_type="image/jpeg" ) } self.profile = Profile.objects.create(**self.profile_data) self.profile_url = self.profile.get_absolute_url() def test_profile_url(self): self.assertEqual(self.profile_url, 'profile/test_user') from django.conf.urls import url from . import views urlpatterns = [ url(r'sign_in/$', views.sign_in, name='sign_in'), url(r'sign_up/$', views.sign_up, name='sign_up'), url(r'sign_out/$', views.sign_out, name='sign_out'), url(r'profile/<username>/', views.profile, name='profile') ] -
Django Rest Framework - return Response(serializer.data) image field get null instead of the url
I set an 'ImageField' in the model, using postman to post data. The image uploaded successfully. However, when my view returns serializers.data, the image field is null, which is supposed to be the URL of the image. Does anyone have any ideas? I appreciate it so much. This is the response { "user": 7, "category": "2018", "cover": null, "name": "Louisville" } This is my model class Journey(models.Model): def user_directory_path(self, filename): return 'media/journey_cover/{0}/{1}'.format(self.user_id, filename) user = models.ForeignKey(to=UserProfile, related_name="journeys", on_delete=models.CASCADE) category = models.CharField(null=False, max_length=50) cover = models.ImageField(upload_to=user_directory_path) created = models.DateTimeField(auto_now_add=True) name = models.CharField(null=False, max_length=50) My serializer: class JourneySerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField(queryset=UserProfile.objects.all()) cover = serializers.ImageField(use_url=True) class Meta: model = Journey fields = ['user', 'category', 'cover', 'name'] My View class JourneyList(APIView): permission_classes = [IsOwnerOrReadOnly, permissions.IsAuthenticatedOrReadOnly] parser_classes = [MultiPartParser, FormParser] def post(self, request): print(request.content_type) serializer = JourneySerializer(data=request.data) if serializer.is_valid(raise_exception=True): journey = serializer.create(serializer.validated_data) journey.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Is It Possible To Have A Theme Selector For Users Possibly In The Admin CP To Choose The Style of Their Site?
I was wondering if it's possible to have a option for users to pick from a set of themes/styles they want for there site like wordpress or forums like MyBB? I plan on releasing a script for people to use but I don't want them to all have the same theme so I would like to have a option for them to select one they like that I created or have them be able to upload/create there own. Thanks for your help!