Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Making sports website, question on the django models
Im new at Django, at the moment I have 2 models in my sports website project: Question and Option (to do some voting). I'd like advice on more models I should add to my project. I'm thinking of article to have as a model, but I dont know if that's correct -
How to automatically built 3 column cards inside of a row html with django
i am new at django and i am learning html too. So, i want to do a simple question (maybe). I am developing a little project in django, and i have a problem with a frontend part. Especifically in a HTML part. as you can see in the picture, i am developing a kind of a ecommerce. But i have a mistake in my HTML part. I don´t want to show the cards of the articles like a list of rows, like the image. I want want to show 3 cards articles by columns, automatically done when i add a new article. Just like this another picture (made from paint :P): This is my HTML, to that part: <div class="row"> <div class="col-lg-7"> <h5>Tipo de vista:<button class="btn btn-lg" type="reset""><a href="{% url 'adminview:article' %}"><h6>Lista</h6></button></a>/<button class="btn btn-lg" type="reset""><a href="{% url 'adminview:cuadricula' %}"><h6>Cuadrícula</h6></button></a></button></button></h5> <div class="card mb-8"> <div class="card-header"> <i class="fas fa-chart-bar"></i> Productos disponibles</div> <div class="card-body"> <div class="table-responsive"> <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0"> {% if articulo %} {% for articulo in articulo %} <div class="col-lg-4 col-md-6 mb-4"> <div class="card h-100 w-100"> <a href="article/id/{{ articulo.id }}"><img class="card-img-top" src="{% url 'home:preload_image' pk=articulo.pk %}" alt=""></a> <div class="card-body"> <h4 class="card-title"> <hr class="sidebar-divider"> <a href="article/id/{{articulo.id}}">{{articulo.nombre_producto}}</a> </h4> <h5>{{articulo.precio}} bsS</h5> <p … -
Django+PostgreSQL Not Able to Fin Object From DB Right After Create It
I was testing User creation by creating a TestCase, and it couldn't be found right after created it. I've tried to flush cache by calling .refresh_from_db(), but it doesn't work. Here is my TestCase: class SuperStrangeTest(TestCase): def test_super_strange(self): john = User.objects.create() john.refresh_from_db() print('!=====START' * 10) print(User.objects.count()) print(User.objects.all()) self.assertIsNotNone(User.objects.filter().first()) # None of assertions below would be right self.assertIsNotNone(User.objects.filter(id=john.id).first()) self.assertTrue(User.objects.filter(id=john.id).exists()) My command to run this test is: ./manage.py test --noinput --failfast --keepdb links.tests.SuperStrangeTest.test_super_strange The result sometimes went right, but most times it just broken. Using existing test database for alias 'default'... /Users/oldcai/.virtualenvs/web/lib/python3.7/site-packages/grequests.py:21: MonkeyPatchWarning: Patching more than once will result in the union of all True parameters being patched curious_george.patch_all(thread=False, select=False) System check identified no issues (0 silenced). !=====START!=====START!=====START!=====START!=====START!=====START!=====START!=====START!=====START!=====START 1 <QuerySet [<User: >]> F ====================================================================== FAIL: test_super_strange (links.tests.SuperStrangeTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/oldcai/programs/python/webproject/zine/links/tests.py", line 41, in test_super_strange self.assertIsNotNone(User.objects.filter().first()) AssertionError: unexpectedly None ---------------------------------------------------------------------- Ran 1 test in 0.130s FAILED (failures=1) Preserving test database for alias 'default'... Errors of other lines: ====================================================================== FAIL: test_super_strange (links.tests.SuperStrangeTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/oldcai/programs/python/webproject/links/tests.py", line 35, in test_super_strange self.assertTrue(User.objects.filter(id=john.id).exists()) AssertionError: False is not true ---------------------------------------------------------------------- ====================================================================== FAIL: test_super_strange (links.tests.SuperStrangeTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/oldcai/programs/python/webproject/links/tests.py", line 35, in test_super_strange self.assertTrue(User.objects.filter(id=john.id).exists()) AssertionError: … -
homepage link sends to about/about page unable to get home
I am trying to go back to my home page which is local host. however when trying to link to home using some python script it sends me to my forum page. Even stranger my forum page is at forum/forum/. while using an html href srcipt though it goes back to home. also loads in home. whats going on? im using django 2.2 and pyhton 3.6 #tcghome/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('hometemplate.urls')), path('forum/', include('hometemplate.urls')), path('admin/', admin.site.urls), ] #hometemplate/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name ='tcg-home'), path('forum/', views.forum, name ='tcg-forum'), ] #hometemplate/views.py from django.shortcuts import render from django.http import HttpResponse posts = [ { 'author': 'Pyralis', 'title': 'Test 1', 'content': 'test content', 'date_posted': 'April 19, 2019' }, { 'author': 'Pyro', 'title': 'Test 2', 'content': 'test content how are you', 'date_posted': 'April 13, 2019' }, ] def home(request): context = { 'posts': posts } return render(request, 'hometemplate/home.html', context) def forum(request): return render(request, 'hometemplate/forum.html', {'title': 'About'}) #base.html <a class="navbar-brand mr-4" href="{% url 'tcg-home' %}">The Coddiwomple Ginger</a> <a class="nav-item nav-link" href="/">Home</a> <a class="nav-item nav-link" href="{% url 'tcg-forum' %}">Forum</a> #web source <a class="navbar-brand mr-4" href="/forum/">The Coddiwomple Ginger</a> <a … -
Django should I manage users in a separate startapp?
In Django 2.2, if I plan to make authentication its own service in the future and serve requests through DRF, should I put my User model in a separate app from my regular "functional apps"? There's no way each app should contain its own implementation of auth, right? Project_Root |--app_auth |--app_shipper |--app_cleaner -
Why my Django app server-send events endpoint close immediately?
I am making endpoints for stream data with Django and django-eventstream from Fanout. But whenever I connect to the endpoint, it return data then close. For example: http --stream http://127.0.0.1:8000/stream-api/projects/22/feeds/ Response: HTTP/1.1 200 OK Cache-Control: no-cache Content-Length: 2077 Content-Type: text/event-stream Date: Fri, 19 Apr 2019 23:57:20 GMT Grip-Channel: events-project-22; filter=skip-users, user-anonymous; filter=require-sub Grip-Hold: stream Grip-Keep-Alive: event: keep-alive\ndata:\n\n; format=cstring; timeout=20 Grip-Link: </stream-api/projects/22/feeds/?link=next&recover=true&es-meta=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJlcyIsImV4cCI6MTU1NTcyMTg0MCwiY2hhbm5lbHMiOlsicHJvamVjdC0yMiJdLCJ1c2VyIjoiYW5vbnltb3VzIn0.-30HrkebKMBxw7RWf_QoNnmE1baWIdID3DrHSL58Et4>; rel=next Grip-Set-Meta: user="anonymous" Server: WSGIServer/0.2 CPython/3.6.7 Vary: Cookie X-Frame-Options: SAMEORIGIN : event: stream-open data: I am using Django 2.2 and Django-eventstream for server send events. My configuration. routing.py from django.conf.urls import url from channels.routing import URLRouter from channels.http import AsgiHandler from channels.auth import AuthMiddlewareStack import django_eventstream urlpatterns = [ #url(r'^events/', AuthMiddlewareStack( # URLRouter(django_eventstream.routing.urlpatterns) #), {'channels': ['test']}), url(r'^projects/(?P<room_id>[^/]+)/feeds/', AuthMiddlewareStack( URLRouter(django_eventstream.routing.urlpatterns) ), {'format-channels': ['project-{room_id}']}), url(r'', AsgiHandler), ] urls.py from django.urls import path, include import django_eventstream urlpatterns = [ #path('events/', include(django_eventstream.urls), {'channels': ['test']}), path('projects/<project_id>/feeds/', include(django_eventstream.urls), {'format-channels': ['project-{project_id}']}), ] -
Django.contrib.auth.login is not working after i redirect to a different url
The login function is not working , after i call auth_login(request, message) request.user.is_authenticated is set 'true' but after i redirect to main request.user.is_authenticated is set 'false'. class LoginForm(forms.Form): user = forms.CharField() password = forms.CharField() def login(self): try: cred = users.objects.get(username = user) if password==cred.password): return (True, cred) return (False, 'Invalid Password.') except: return (False, 'Not exist') def login(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): valid, message = form.login() if valid: auth_login(request, message) print(request.user.is_authenticated) # this is not working return redirect(main) else: return redirect(login) form = LoginForm() args = {'form': form} return render(request, 'accounts/login.html', args) def main(request): print(request.user.is_authenticated) -
How to create a foreign key set for each file in a list of files with django
I am trying to upload multiple images to my database with django. I would like each file to be stored separately as a foreignkey to the main product.So basically what I mean is that there will be products and then each product will have multiple foreign keys that are images. Django isn't storing the images to the database at all. Here's my code: class product(models.Model): title = models.CharField('', max_length=100, db_index=True) price = models.CharField('', max_length=100, db_index=True) description = models.CharField('', max_length=100, db_index=True) class productimage(models.Model): product = models.ForeignKey(product, on_delete=models.CASCADE) product_images = models.FileField(blank=True) if request.method == "POST": title = request.POST.get("title") price = request.POST.get("price") description = request.POST.get("description") products = product(title=title,description=description,price=price) products.save() for image in request.FILES.getlist("images"): product_images = image products.productimage_set.create(product_images = product_images) return render(request,'selling/addproduct.html') So basically I would like each product to have a list of images stored as a foreign key to the main product. -
Django Default Password Reset
I am trying to reset the password, everything works but not sending email, what am i doing wrong here. urls.py from django.contrib import admin from django.contrib.auth import views as auth_views from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from users import views as user_views urlpatterns = [ path('', include('home.urls')), path('user/', include('users.urls')), path('admin/', admin.site.urls), path('password-reset/', auth_views.PasswordResetView.as_view(template_name='users/password_reset.html'), name='password_reset'), path('password-reset/done', auth_views.PasswordResetDoneView.as_view(template_name='users/password_reset_done.html'), name='password_reset_done'), path('password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name='users/password_reset_confirm.html'), name='password_reset_confirm'), path('password-reset-complete/', auth_views.PasswordResetCompleteView.as_view(template_name='users/password_reset_complete.html'), name='password_reset_complete'), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'EMAIL_USER' EMAIL_HOST_PASSWORD = 'EMAIL_PASS' I am trying to reset the password, everything works but not sending email, what am i doing wrong here. -
Django json loads fails
I have ajax call posted to /cart/total where I am dumping JSON string stored in local storage using post when I run json loads it shows me the error. TypeError(f'the JSON object must be str, bytes or bytearray, ' TypeError: the JSON object must be str, bytes or bytearray, not QueryDict and my JSON string before parsing looks like having an empty feild, which I am not aware of in Django <QueryDict: {'{"32":1,"33":1,"34":2}': ['']}> <script> function addtocart(mitem, mprice) { if(localStorage.getItem('cart')==null){ // var mobj = {} // var countQ ={} var price = String(mprice) var mobj = { [String(mitem)]: 1 } var countQ = {'Quantity':1} var storeobj = JSON.stringify(mobj) var storeCountq = JSON.stringify(countQ) localStorage.setItem('cart', storeobj) localStorage.setItem('quantity',storeCountq) console.log(localStorage.getItem('cart')) }else{ var data = localStorage.getItem('cart') var quant = localStorage.getItem('quantity') var obj = JSON.parse(data) var parsequant = JSON.parse(quant) if(obj.hasOwnProperty(String(mitem))){ obj['%s',mitem]++ parsequant['Quantity']++ var storeobj = JSON.stringify(obj) console.log(localStorage.getItem('cart')) var storeCountq = JSON.stringify(parsequant) localStorage.setItem('cart', storeobj) localStorage.setItem('quantity', storeCountq) } else{ obj[String(mitem)] = 1 parsequant['Quantity']++ var storeobj = JSON.stringify(obj) console.log(localStorage.getItem('cart')) var storeCountq = JSON.stringify(parsequant) localStorage.setItem('cart', storeobj) localStorage.setItem('quantity', storeCountq) } } } function ajaxcall(){ $.ajax( { type: "POST", url: "/cart/total", data: localStorage.getItem('cart'), success: function () { console.log("sent tdata") } }) } ajaxcall() </script> <p style="position: absolute; bottom: 0px"><button class="button" style="width: 200px" … -
update_session_auth_hash Will Not Keep User Logged In Without Seemingly Irrelevant Line of Code
I'm trying to reset a password using SetPasswordForm in Django. However, an authenticated user will not remained logged in after I save the form unless I have an irrelevant line of code in there which I've titled, "NONSENE". This is in the form_valid method. Any ideas why? Thanks! class PasswordResetView(FormView): """ Reset user password. Either with provided uid/token get parameters or if the user is logged in. """ template_name = 'users/password_reset.html' form_class = SetPasswordForm success_url = '/' def corrupt_link_redirect(self, request): messages.error( self.request, user_strings.PASSWORD_RESET_INVALID_LINK ) return redirect('forgot_password') def get_form(self): try: user = User.objects.get(pk=self.request.session.get('pw_pk')) except User.DoesNotExist: return Http404() ## Refine this return self.form_class(user, **self.get_form_kwargs()) def post(self, request, *args, **kwargs): if not request.session.get('pw_pk') and request.user.is_authenticated: request.session['pw_pk'] = request.user.pk return super(PasswordResetView, self).post(request, *args, **kwargs) def get(self, request, *args, **kwargs): if request.user.is_authenticated: ## User is logged in so present them with the password reset form request.session['pw_pk'] = request.user.pk return super(PasswordResetView, self).get(request, *args, **kwargs) try: uidb64 = request.GET.get('uid') token = request.GET.get('token') if uidb64 is None or token is None: return self.corrupt_link_redirect(request) ## Failure redirect uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): return self.corrupt_link_redirect(request) ## Failure redirect if user is not None and PasswordResetTokenGenerator().check_token(user, token): request.session['pw_pk'] = user.pk return super(PasswordResetView, self).get(request, *args, **kwargs) … -
GeoDjango: How to perform a query of spatially close records
I have two Django models (A and B) which are not related by any foreign key, but both have a geometry field. class A(Model): position = PointField(geography=True) class B(Model): position = PointField(geography=True) I would like to relate them spatially, i.e. given a queryset of A, being able to obtain a queryset of B containing those records that are at less than a given distance to A. I haven't found a way using pure Django's ORM to do such a thing. Of course, I could write a property in A such as this one: @property def nearby(self): return B.objects.filter(position__dwithin=(self.position, 0.1)) But this only allows me to fetch the nearby records on each instance and not in a single query, which is far from efficient. I have also tried to do this: nearby = B.objects.filter(position__dwithin=(OuterRef('position'), 0.1)) query = A.objects.annotate(nearby=Subquery(nearby.values('pk'))) list(query) # error here However, I get this error for the last line: ValueError: This queryset contains a reference to an outer query and may only be used in a subquery Does anybody know a better way (more efficient) of performing such a query or maybe the reason why my code is failing? I very much appreciate. -
conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError
I'm getting this error when running: 'python manage.py makemigrations' to setup my new Postgresql database located on a remote server (Ubuntu 18.04) for my Django project. How can I solve this? Here's the error output I'm getting: $ python manage.py makemigrations Traceback (most recent call last): File "C:\Users\loicq\desktop\coding\uvergo\venv\lib\site-packages\django\db\backends\base\base.py", line 217, in ensure_connection self.connect() File "C:\Users\loicq\desktop\coding\uvergo\venv\lib\site-packages\django\db\backends\base\base.py", line 195, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\loicq\desktop\coding\uvergo\venv\lib\site-packages\django\db\backends\postgresql\base.py", line 178, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\loicq\desktop\coding\uvergo\venv\lib\site-packages\psycopg2\__init__.py", line 126, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError 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 "C:\Users\loicq\desktop\coding\uvergo\venv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\loicq\desktop\coding\uvergo\venv\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\loicq\desktop\coding\uvergo\venv\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\loicq\desktop\coding\uvergo\venv\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Users\loicq\desktop\coding\uvergo\venv\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\loicq\desktop\coding\uvergo\venv\lib\site-packages\django\core\management\commands\makemigrations.py", line 101, in handle loader.check_consistent_history(connection) File "C:\Users\loicq\desktop\coding\uvergo\venv\lib\site-packages\django\db\migrations\loader.py", line 283, in check_consistent_history applied = recorder.applied_migrations() File "C:\Users\loicq\desktop\coding\uvergo\venv\lib\site-packages\django\db\migrations\recorder.py", line 73, in applied_migrations if self.has_table(): File "C:\Users\loicq\desktop\coding\uvergo\venv\lib\site-packages\django\db\migrations\recorder.py", line 56, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "C:\Users\loicq\desktop\coding\uvergo\venv\lib\site-packages\django\db\backends\base\base.py", line 256, in cursor return self._cursor() File "C:\Users\loicq\desktop\coding\uvergo\venv\lib\site-packages\django\db\backends\base\base.py", line … -
How to make urls in django middleware more dynamic when using get.path
I wrote a custom middleware in my django application. Basically I added a counter which increments whenever a site is viewed. To filter out the admin site and condition my views, I use basic conditionals like so: My middleware.py class GetUrlMiddleware(): def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. response = self.get_response(request) if request.path.startswith('/admin/'): pass elif request.path == ('/jobs'): Counter.objects.update(total_views=F('total_views')+1) Counter.objects.update(job_list_site_views=F('job_list_site_views')+1) elif request.path == ('/'): Counter.objects.update(home_site_views=F('home_site_views')+1) Counter.objects.update(total_views=F('total_views')+1) elif request.path.startswith('/jobs/'): Counter.objects.update(total_views=F('total_views')+1) # Code to be executed for each request/response after # the view is called. return response Here are my urls: urlpatterns = [ path('jobs', ListJobView.as_view(), name="list_jobs"), path('jobs/<int:id>/', DetailJobView.as_view(), name="detail_jobs"), path('jobs/new', CreateJobView.as_view(), name="create_job"), path('jobs/update/<int:id>/', UpdateJobView.as_view(), name="update_job"), path('jobs/delete/<int:id>/', DeleteJobView.as_view(), name="delete_job"), ] Now that works. But I would like to make it a bit more dynamic, so I was thinking about using the url-namespaces instead of hardcoding the path. But what I tried so far doesn't work. Also I don't know how I can condition my detail view in which I pass ids. Is there any way to do that? Any help is appreciated, thanks in advance. -
Why do Django apps required `manage.py` for everything instead of using `__init__py`?
If copy over some manage.py lines to my __init__.py all my views.py and models.py files can be imported from anywhere without requiring python manage.py shell: import os import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings') django.setup() That way I can import my submodules in __init__.py (further down): import glob modules = glob.glob(os.path.join(os.path.dirname(__file__), '*.py')) __all__ = [os.path.basename(f)[:-3] for f in modules if os.path.isfile(f) and not f.endswith('__init__.py')] from . import * That way I can do this from any directory: import myproject as mp mp.models.MyModel.objects.get(field_name='value') This is handy when importing data or doing data migrations away from the project fixtures directory. Is there anything wrong with this? If not, why doesn't Django do it this way by default when you python manage.py startproject? -
Problems with customizing django password_reset template?
I am trying to customize the password_reset_form.html and render my own customized form for password reset. But for some reason, it keeps redirecting me to the default django password_reset form. what could i be doing wrong. root/urls.py url('accounts/', include('django.contrib.auth.urls')), accounts/urls.py from django.conf.urls import url from .views import * from django.contrib.auth import views as auth_views urlpatterns = [ url(r'^password/change/$', auth_views.PasswordChangeView.as_view(), name='password_change'), url(r'^password/change/done/$', auth_views.PasswordChangeDoneView.as_view(), name='password_change_done'), url(r'^password/reset/$', auth_views.PasswordResetView.as_view(), name='password_reset'), url(r'^password/reset/done/$', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), url(r'^password/reset/\ (?P<uidb64>[0-9A-Za-z_\-]+)/\ (?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), url(r'^password/reset/complete/$', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), ] template folder -
Django Development Server
Just to give you some general context of what I am doing, I am currently in the process of making a mobile app for university students to notify them when a seat becomes available in a previously full course. For my project architecture, my web service stack is setup very similar to a LAMP stack: Linode cloud ubuntu instance for linux OS, Apache2 for my HTTP Server, MySQL for my relational database management system, and Python for my programming language. Also, to gather the data needed for my project, I am going to web-scrape via a python script with beautiful soup and selenium (for timed delays when loading the webpages), and plan on implementing cron jobs for minutely scrapes to continuously update my database on my LAMP Stack (specifically the number of seats available in a particular course) which will then send any updates of newly open seats to the mobile app (which I will code in the future, but have not gotten to yet). I am having a LOT of trouble installing Django on my server. Thus far, I am able to starting up the Django development server in terminal, but when I try to access the project / … -
Django: How can I send an email with a description that includes all inputs from a contact form?
I have a Django-built website which sends an email to a certain employee after a contact form is submitted. The relevant code in my views.py file that does this is as follows: def quote_req(request): submitted = False if request.method == 'POST': form = QuoteForm(request.POST, request.FILES) description = request.POST['company'] if form.is_valid(): form.save() # assert false send_mail('Contact Form', description, settings.EMAIL_HOST_USER, ['sample@gmail.com'], fail_silently=False) return HttpResponseRedirect('/quote/?submitted=True') else: form = QuoteForm() if 'submitted' in request.GET: submitted = True return render(request, 'quotes/quote.html', {'form': form, 'page_list': Page.objects.all(), 'submitted': submitted}) The website successfully sends the email; however, at the moment I am limited to sending only one input from the contact form (in this case, 'company') for the email description (which is utilized in the send_mail command). Does anyone know if I can modify the request.POST command or use another type of method to send more than one contact form input for the email description (i.e., 'company', 'phone', 'address', etc.)? -
Creating a web app that uses machine learning model with Django
i have been trying to convert my machine learning model to a web application. Even though my code works on its own. It doesn't work when i call the functions in django's files. Here is my directory : ├───app │ │ admin.py │ │ apps.py │ │ classify_images.py │ │ forms.py │ │ model.ann │ │ modelnn.py │ │ models.py │ │ tests.py │ │ Untitled.ipynb │ │ urls.py │ │ views.py │ │ __init__.py │ │ │ ├───.ipynb_checkpoints │ │ Untitled-checkpoint.ipynb │ │ │ ├───image_vectors │ ├───img │ │ heat.PNG │ │ pp.jpg │ │ tosbik.jpg │ │ │ ├───migrations │ │ │ 0001_initial.py │ │ │ __init__.py │ │ │ │ │ └───__pycache__ │ │ 0001_initial.cpython-36.pyc │ │ __init__.cpython-36.pyc │ │ │ ├───static │ │ └───app │ │ │ main.css │ │ │ │ │ └───img │ │ logo.png │ │ logo2.png │ │ removed_noise.png │ │ xx_23242A72_xx.jpg.npz │ │ xx_23256H6_xx.jpg.npz │ │ xx_23476B26_xx.jpg.npz │ │ xx_23617A13_xx.jpg.npz │ │ xx_23666A46_xx.jpg.npz │ │ xx_24211O6_xx.jpg.npz │ │ │ ├───templates │ │ └───app │ │ complete.html │ │ index.html │ │ upload.html │ │ upload2.html │ │ │ ├───tmp │ │ └───imagenet │ │ classify_image_graph_def.pb │ │ cropped_panda.jpg │ │ imagenet_2012_challenge_label_map_proto.pbtxt … -
TypeError: login() got an unexpected keyword argument 'template_name'
I upgraded my project from Django 1.11 to 2.2, made all the changes but came with new error that says login() got an unexpected keyword argument 'template_name'.It worked fine with the previous version of Django 1.11 (All the other urls are working, only the landing page gives the error). I couldn't find any references to this issue. Below is the error and urls and views for the issue. Internal Server Error: / Traceback (most recent call last): File "C:\Users\User\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\User\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\User\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\User\PycharmProjects\MyWebsite\landing\views.py", line 43, in landing_validation login_response = login(request, template_name='landing.html') TypeError: login() got an unexpected keyword argument 'template_name' [19/Apr/2019 16:20:00] "GET / HTTP/1.1" 500 71948 Landing\urls.py from django.conf.urls import url from landing.views import landing_validation app_name='landing' urlpatterns = [ url(r'^$', landing_validation, name='landing') ] Landing\views.py from django.contrib.auth import login def landing_validation(request): login_response = login(request, template_name='landing.html') return login_response C:\Users\User\venv\Lib\site-packages\django\contrib\auth__init__.py def login(request, user, backend=None): """ Persist a user id and a backend in the request. This way a user doesn't have to reauthenticate on every request. Note that data set during the anonymous session is retained when … -
Possible to use get_absolute_url in {% url %} tags without the model object?
I have a navbar where user can log in and after logging in, the user will have a dropdown menu with a link to his/her profile. Here are my codes: navbar.html: {% url 'students:student_profile_view' as student_profile_url %} {% if request.user.is_authenticated %} <!-- User Dropdown Menu --> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <i class="far fa fa-user"></i> {{request.user.first_name}}</a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="{{ student_profile_url }}">Profile</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="{{ logout_url }}">Logout</a> </div> </li> students/urls.py: path('profile/<slug:slug>/', views.student_profile_view, name='student_profile_view'), students/model.py: from django.contrib.auth.models import User from django.utils.text import slugify class StudentProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) slug = models.SlugField(blank=True, unique=True) avatar = models.ImageField(upload_to='student_profile/', null=True, blank=True) description = models.CharField(max_length=120, null=True, blank=True) objects = models.Manager() def save(self, *args, **kwargs): self.slug = slugify(self.user) super(StudentProfile, self).save(*args, **kwargs) def __str__(self): return self.user.username def get_absolute_url(self): # return 'students:student_profile_view', (), {'slug': self.slug} return reverse("students:student_profile_view", kwargs={"slug": self.slug}) Navbar.html is a base template, it's not being rendered through a view where I could've passed an object and then called object.get_absolute_url Right now the profile button in my navbar dropdown menu is not working as it's not finding a reverse match for the user. Also, after logging in I tried entering the link to profile manually in … -
Upgrade from Django 2.1 to 2.2: problem with prepopulated field
Today I've updated my Django version from 2.1 to 2.2 and I've noticed that the prepopulated field don't work. Based your experience which are the things to see before do the update? In my site there are this plugins: - django-tinymce4-lite - django-filebrowser - django-grappelli I can exclude compatibility problems between Django 2.2 and one of this plugins because I've made a test with a new empty project and the prepopulated field work fine. -
JS: function not defined
I have JS script function that holds cart items to order food. This function is passed with 2 parameters ID and price. My script file looks like <script> function addtocart(mitem, mprice) { var price = String(mprice) var mobj = { String(mitem): price } var storeobj = JSON.stringify(mobj) localStorage.setItem('cart', storeobj) } </script> My button looks like this <p style="position: absolute; bottom: 0px"><button class="button" style="width: 200px" onclick="addtocart( '{{M.Menu_Item}}', '{{M.Menu_ItemPrice}}' )" >Add to Cart</button> When I click on the button in developer console in chrome says that addtocart function not defined. I did read about on click listens but I have to pass the parameter for each button click, which is different. What might I be doing wrong? -
Why am I getting an AssertionError durin unittesting?
i am testing some test in django and i got an error How can i solve those error!! This is django 2.1.7 (venv) C:\Users\hp\myblog\myblog>python manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). ..F...F........F................. FAIL: test_form_errors (accounts.tests.test_view_signup.InvalidSignUpTests) Traceback (most recent call last): File "C:\Users\hp\myblog\myblog\accounts\tests\test_view_signup.py", line 86, in test_form_errors self.assertTrue(form.errors) AssertionError: {} is not true ====================================================================== FAIL: test_form_inputs (accounts.tests.test_view_signup.SignUpTests) Traceback (most recent call last): File "C:\Users\hp\myblog\myblog\accounts\tests\test_view_signup.py", line 36, in test_form_inputs self.assertContains(self.response, ' File "C:\Users\hp\myblog\venv\lib\site-packages\django\test\testcases.py", line 366, in assertContains msg_prefix + "Found %d instances of %s in response (expected %d)" % (real_count, text_repr, count) AssertionError: 9 != 5 : Found 9 instances of ' ====================================================================== FAIL: test_valid_bound_field (boards.tests.test_templatetags.InputClassTests) Traceback (most recent call last): File "C:\Users\hp\myblog\myblog\boards\tests\test_templatetags.py", line 25, in test_valid_bound_field self.assertEquals('form-control', input_class(form['password'])) AssertionError: 'form-control' != 'form-control ' - form-control + form-control ? + My test_view_signup.py file is!! from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django.urls import reverse from django.urls import resolve from django.test import TestCase from ..views import signup from ..forms import SignUpForm Create your tests here. class SignUpTests(TestCase): def setUp(self): url = reverse('signup') self.response = self.client.get(url) def test_signup_status_code(self): self.assertEquals(self.response.status_code, 200) def test_signup_url_resolves_signup_view(self): view = resolve('/signup/') self.assertEquals(view.func, signup) def test_csrf(self): self.assertContains(self.response, 'csrfmiddlewaretoken') def test_contains_form(self): form … -
Updating Front-End (HTML CSS etc) without Redeployment of Elastic Beanstalk
I am new to amazon Elastic Beanstalk and I have a Django app that is been deployed successfully to AWS. My question which I couldn’t find an answer for, can I make an immediate changes for html or css on the Django application without redeploying? or is there a workaround of this? I tried to make the changes on html and css but my site isn’t affected by the changes I make unless I redeploy the eb environment? Thank you in advance for your help and guidance!