Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - setting a user to not active for 5 seconds
In my Django project, I allow users to login. If they enter the incorrect password 7 times, their account is set to not active and an error is returned to them. What I want to do is display the error message for 5 seconds, then allow them to attempt again. How can I do this ? I store a variable in the user model which is incremented each time a an unsuccessful login is performed. If it reaches 7, an error message is displayed. Here's my code: models.py: class User(AbstractUser): loginAttempts = models.IntegerField(default=0) views.py: if user.check_password(data.get("password")): user.loginAttempts = 0 user.save() auth.login(request, user) return JsonResponse({'message': 'Successfully logged in'}, status=200) else: user.loginAttempts += 1 user.save() if user.loginAttempts >= 7: user.is_active = False user.save() return JsonResponse({'message': 'Account Locked.'}, status=400) else: return JsonResponse({'message': 'Oops, username/email or password provided is invalid'}, status=400) Currently the error message ("Account Locked") is successfully displayed after 7 attempts, however what I want is the loginAttempts variable to be set back to 0 after 5 seconds has passed. How can I do this? Thank You. -
Page not found error - Writing your first Django app, part 1
I have installed Django 2.2.5 in my conda environment and I'm following the Django tutorial for Writing your first Django app, part 1 I followed the steps exactly but I'm getting a Page Not Found error when I try to access the polls/ url. My root directory structure is like this mysite/ manage.py db.sqlite3 urls.py mysite/ __init__.py settings.py urls.py wsgi.py polls/ migrations/ __init__.py admin.py apps.py models.py tests.py urls.py views.py And my view is like this D:\TEMP\djangotest\mysite\polls\views.py from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("Hello World. You're at the polls index") My two urls files are like this D:\TEMP\djangotest\mysite\polls\urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] D:\TEMP\djangotest\mysite\urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] And I run the app from the environment like this (py3.6) D:\TEMP\djangotest\mysite>python manage.py runserver But when I go to the url indicated in the tutorial it give the 404 error - page not found from the console October 21, 2019 - 16:23:13 Django version 2.2.5, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Not Found: /polls [21/Oct/2019 16:23:19] "GET /polls … -
I am not able to launch my Django app with elastic beanstalk. Receive 500 - Internal Service Error
I am attempting to deploy a simple Django project, using Amazon's guide: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html. However, I am receiving 500 errors, Internal Server Error. I have retrieved the error log, however am struggling to debug. The project runs fine locally. I've tried: Ensuring my WSGI path is correct Downgrading to Django 2.1.1 I've included the EB domain name in ALLOWED_HOSTS Here is the error log [Mon Oct 21 20:13:48.477960 2019] [:error] [pid 31600] [remote 127.0.0.1:0] apps.populate(settings.INSTALLED_APPS) [Mon Oct 21 20:13:48.477965 2019] [:error] [pid 31600] [remote 127.0.0.1:0] File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/apps/registry.py", line 114, in populate [Mon Oct 21 20:13:48.477968 2019] [:error] [pid 31600] [remote 127.0.0.1:0] app_config.import_models() [Mon Oct 21 20:13:48.477973 2019] [:error] [pid 31600] [remote 127.0.0.1:0] File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/apps/config.py", line 211, in import_models [Mon Oct 21 20:13:48.477977 2019] [:error] [pid 31600] [remote 127.0.0.1:0] self.models_module = import_module(models_module_name) [Mon Oct 21 20:13:48.477981 2019] [:error] [pid 31600] [remote 127.0.0.1:0] File "/opt/python/run/venv/lib64/python3.6/importlib/__init__.py", line 126, in import_module [Mon Oct 21 20:13:48.477985 2019] [:error] [pid 31600] [remote 127.0.0.1:0] return _bootstrap._gcd_import(name[level:], package, level) [Mon Oct 21 20:13:48.477990 2019] [:error] [pid 31600] [remote 127.0.0.1:0] File "<frozen importlib._bootstrap>", line 994, in _gcd_import [Mon Oct 21 20:13:48.477995 2019] [:error] [pid 31600] [remote 127.0.0.1:0] File "<frozen importlib._bootstrap>", line 971, in _find_and_load [Mon Oct 21 20:13:48.478000 2019] [:error] … -
How to add custom filtering fields to an Django Rest Framework APIListView
I'm using django rest framework and I have a ListAPIView that I would like to implement a complex filtering functionality that I'm using Q filters. My question is how do I generate custom fields for this filtering? url: path('', EventListView.as_view(), name='event_list_view'), serializer: class EventSerializer(serializers.ModelSerializer): class Meta: model = Event exclude = ('user', ) View: class EventListView(ListAPIView): authentication_classes = () permission_classes = () serializer_class = EventSerializer filter function: def filter_events( user: User, sort_by: int = DISTANCE, privacy_levels: [int] = [EVERYONE], categories: [Category] = None, start_date: datetime.datetime = DEFAULT_START_DATE, end_date: datetime.datetime = DEFAULT_END_DATE, distance: int = DEFAULT_DISTANCE, current_location: Point = None, unit: int = None, clubs: [UniversityClub] = None, universities: [University] = None, greeks: [GreekOrganization] = None, groups: [UserGroup] = None, users_p: [User] = None ): .... if EVERYONE in privacy_levels: everyone_q = Q(privacy_level=EVERYONE, university__in=user_universities, start_time__range=[start_date, end_date]) else: everyone_q = Q() if STUDENTS in privacy_levels: student_q = Q(privacy_level=STUDENTS, start_time__range=[start_date, end_date]) else: student_q = Q() ... -
how to ignore forward slash from django URL in a parameter
I am using django version 2.2.5. Below is my urls.py from django.urls import path, include from . import views urlpatterns = [ path('manifest/', views.home), path('manifest/<str:some_id>/', views.manifest), ] It works fine when some_id does not contain any forward slash(/). E.g. http://127.0.0.1:8000/manifest/name:19.2.4:develop:1/ In the following manifest function from views.py, I am able to get the some_id def manifest(request, some_id): print(some_id) ##prints below: ##[21/Oct/2019 19:36:55] "GET /manifest/name:19.2.4:develop:1 HTTP/1.1" 301 0 ##name:19.2.4:develop:1 However, when the some_id contains forward slash in it, I don't get the whole id. E.g., from the above URL if I would replace "develop" with "release/19.2.4" http://127.0.0.1:8000/manifest/name:19.2.4:release/19.2.4:1/ "GET /manifest/name:19.2.4:release/19.2.4:1/ HTTP/1.1" 404 3080 This is because of the forward slash being used as delimiter. Is there any way to ignore this forward slash inside of the some_id parameter? The expectation is to get name:19.2.4:release/19.2.4:1 as some_id in the views.py Note: The format of a valid some_id is it has 4 parts delimited by ":". e.g.: name:version:branch:num, where only the branch section could have one or more slash(/) in it. -
Django: single related object descriptor is deprecated, how can i replace it?
I was following this guide, when I arrived to this line: from django.db.models.fields.related import SingleRelatedObjectDescriptor I realized that SingleRelatedObjectDescriptor Class has been removed (deprecated) from the module, I searched about its deprecation in the documentation, I couldn't find anything helpful, how i can achieve its behaviour now? with what i can replace it? -
Django template 'url' tag not rendering as form field attribute value
In my Django app, I'm trying to implement an ajax request, for that, I would need a specific field in the form and setting the ajax request URL as an attribute value to the field. But the URL template tag is not rendering on the HTML. #urls.py ... path('checkdata', check_data, name='ajaxcheck') #forms.py fld_name = forms.CharField(label='Name', max_length=100, widget=forms.TextInput(attrs={'ajax-data-url': "{% 'ajaxcheck' %}"})) Output HTML: <input type="text" name="name" placeholder="Name" ajax-data-url="{% 'ajaxcheck' %}" maxlength="100" class="textinput textInput form-control" required="" id="id_name"> -
django-allauth restrict social login to registered users
What is the recommended way to restrict social login to registered users? As it is any user with a social account gets passed as authenticated after signing into a social site (google, facebook, etc) even though they aren't registered with my secure site. Lets assume I'm using the default domain/accounts/login templates. If we can sort it out with those I can make it work my forms or templates. Hopefully someone else has done this so I don't have to reinvent the wheel here.... I can post any code if you like. -
Displaying content by ID (views.py)
I've developed a university system application for practice, and get such problem: I have to display the list of specializations belonging to some chair. And here problem is: http://127.0.0.1:8000/chairs/1, http://127.0.0.1:8000/chairs/2 and etc. are showing all of the specializations like in this screenshot . But I want to display them only according to chairs id. Here are my codes: views.py: def list_of_specialties(request, chair_id): chairs = Chair.objects.all() if chair_id: chair_id = get_object_or_404(Chair, id=chair_id) bachelor_sp = Specialty.objects.filter(degree_id=1) master_sp = Specialty.objects.filter(degree_id=2) phd_sp = Specialty.objects.filter(degree_id=3) context = { 'chairs': chairs, 'chair_id': chair_id, 'bachelor_sp': bachelor_sp, 'master_sp': master_sp, 'phd_sp': phd_sp, } return render(request, 'specialties.html', context) urls.py: urlpatterns = [ path('', views.index, name='index'), path('chairs', views.chairs, name='chairs'), path('chairs/<int:chair_id>', views.list_of_specialties, name='list_of_specialties'), path('chairs/<int:chair_id>/<int:specialty_id>', views.list_of_specializations, name='list_of_specializations'), ] models.py: class Chair(models.Model): def __str__(self): return self.name name = models.CharField(max_length=100) phone = models.CharField(max_length=30) email = models.CharField(max_length=50) chairman = models.CharField(max_length=30) class Specialty(models.Model): def __str__(self): return self.name name = models.CharField(max_length=100) chair = models.ForeignKey(Chair, on_delete=models.CASCADE) degree = models.ForeignKey(Degree, on_delete=models.CASCADE) -
What is the meaning of the line 'reponse = self.client.get(reverse('polls:index'))' mean?
class QuestionIndexViewTests(TestCase): def test_no_questions(self): """ If no questions exist, an appropriate message is displayed. """ response = self.client.get(reverse('polls:index')) self.assertEqual(response.status_code, 200) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], -
Django Channels, Websocket with Parameter
I'm trying to send info back to my server when socket connects: js var id = 'testme' var endpoint = 'ws://'+ window.location.host + window.location.pathname var socket = new WebSocket(endpoint, id) consumers.py class ChatConsumer(AsyncConsumer): async def websocket_connect(self, event): info = str(self.scope['subprotocols']).replace('[', '').replace(']', '').replace("'", "") chat_room = info self.chat_room = chat_room await self.channel_layer.group_add( chat_room, self.channel_name) await self.send({"type": "websocket.accept"}) When I remove ID everything works fine; with it, the connection immediately disconnects. Anyone know why and how to fix it? (Yes, 'info' does print 'testme' as intended) -
How to render the Form (in a template tag) automatically created by CreateView
How do I render a Form automatically created by CreateView CBV? Setup views.py class CreateToJournal(LoginRequiredMixin, CreateView): model = to_journal template_name = 'to_journals/to_journal_list.html' fields = ('journal_name',) def get_success_url(self): return reverse('home') def form_valid(self, form): form.instance.journal_user = self.request.user return super(CreateToJournal, self).form_valid(form) def get_context_data(self, **kwargs): context = super(CreateToJournal, self).get_context_data(**kwargs) context['to_journals'] = to_journal.objects.filter(journal_user=self.request.user) return context urls.py urlpatterns = [ path('', CreateToJournal.as_view(), name='to-journals'), path('<slug:slug>', ToJournalEntriesList.as_view(), name='to-journal-entries'), ] As you can see I do not have a specific form mentioned, here, that is because I don't have one. CreateView creates one automatically. As you can see, this view (which does two jobs right now, help user create an object and at the same time displays all the objects) is now rendering to 'to-journals/to_journal_list.html`. I want to display the same thing (both the View and the Form) on the "home" page or any other page. Current templatetag only gets the data from the database (context) My current attempt looks like this: journal_tags.py register = template.Library() @register.inclusion_tag('template_tags/journal_list.html', takes_context=True) def get_journals(context): journals = to_journal.objects.filter(journal_user=context['request'].user) return {'journals': journals} This successfully renders all the existing journals to any page I want. Now, how do I also render the form, that CreateView created for me. Failed Approach One approach I tried is to … -
data object in Bokeh
I'm trying to generating a Bokeh chart, I have this code: x = { 'Expired': dead_247, 'Unknown': unsure_247, 'Alive': alive_247 } data = pd.Series(x).reset_index(name='value').rename(columns={'index':'status'}) data['angle'] = data['value']/data['value'].sum() * 2*pi data['color'] = ["#c0c4c1", "#009695", "#53e305"] data["value"] = data['value'].astype(str) data["value"] = data["value"].str.pad(10, side = "left") sep = [] for i in range(len(data.index)): sep.append(': ') data['legend'] = data['status'] + sep + data['value'].astype(str) I print 'data' object by print(data) and see this output. Please tell me what type of data structure the 'data' is. Is it a List, or dictionary. web_1 | status value angle color legend web_1 | 0 Expired 1422 1.553859 #c0c4c1 Expired: 1422 web_1 | 1 Unknown 3080 3.365602 #009695 Unknown: 3080 web_1 | 2 Alive 1248 1.363724 #53e305 Alive: 1248 Could you show me how to add 1 more line into data['legend'] : Total = 5750 . (This is the sum of 1422 + 3080 +1248) Thank you. -
Unable to get data of Foreign key tables in same serilizor
Order table class Orders(models.Model): restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE, blank=True, null=True) tableid=models.IntegerField() orderid=models.IntegerField() total_amount = models.DecimalField(max_digits=10, decimal_places=2) Articles table to save articles like pizza class OrderArticle(models.Model): order = models.ForeignKey(Orders, on_delete=models.CASCADE) article = models.ForeignKey(Articles, on_delete=models.CASCADE) # article_options = models.ManyToManyField(ArticlesOptions) Article options to save extra topping or any option available class OrderArticleOptions(models.Model): # order = models.ForeignKey(Orders, on_delete=models.CASCADE) article_option = models.ForeignKey(ArticlesOptions, on_delete=models.CASCADE) order_article = models.ForeignKey(OrderArticle, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) price = models.DecimalField(max_digits=10, decimal_places=2) So Now issue is When I try to get all data in one serialize I am not able to get . I am using this example to get https://www.django-rest-framework.org/api-guide/relations/ -
Celery-Progress - progress_recorder.set_progress() returns TypeError: sequence item 1: expected a bytes-like object, NoneType found
I'm inside a Django Project trying to use Celery-Progress to create a progress bar. But when I try to use progress_recorder.set_progress method inside the following function (using a celery worker): def increase_task_progress(): global progress_recorder_current, progress_recorder_total, progress_recorder progress_recorder_current += 1 progress_recorder.set_progress(progress_recorder_current, progress_recorder_total) <<< It's giving the following exception: Traceback (most recent call last): File "/usr/lib/python3.7/threading.py", line 917, in _bootstrap_inner self.run() File "/usr/lib/python3.7/threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "/projects/report/excel.py", line 193, in generate_data_sheets increase_task_progress() File "/projects/report/excel.py", line 199, in increase_task_progress progress_recorder.set_progress(progress_recorder_current, progress_recorder_total) File "/projects/report/my_venv/lib/python3.7/site-packages/celery_progress/backend.py", line 38, in set_progress 'percent': percent, File "/projects/report/my_venv/lib/python3.7/site-packages/celery/app/task.py", line 930, in update_state self.backend.store_result(task_id, meta, state, **kwargs) File "/projects/report/my_venv/lib/python3.7/site-packages/celery/backends/base.py", line 342, in store_result request=request, **kwargs) File "/projects/report/my_venv/lib/python3.7/site-packages/celery/backends/base.py", line 714, in _store_result self.set(self.get_key_for_task(task_id), self.encode(meta)) File "/projects/report/my_venv/lib/python3.7/site-packages/celery/backends/base.py", line 590, in get_key_for_task self.task_keyprefix, key_t(task_id), key_t(key), TypeError: sequence item 1: expected a bytes-like object, NoneType found These are my codes until reaching the increase_task_progress function. views.py from django.http import HttpResponse from . import tasts def myView(request): report_id = request.POST.get('report_id', 0) result = tasks.generate_report.delay(report_id) response = HttpResponse(content=task.task_id) return response tasks.py from . import excel from celery import shared_task @shared_task(bind=True) def generate_report(self, report_id): task = excel.generate_xls_report( report_id=report_id task_obj=self ) return task excel.py from celery_progress.backend import ProgressRecorder from xlsxwriter.workbook import Workbook from . import … -
[tag][Django] How to retrieve saved password in raw format
In one of my View i need UserName & Password details in raw format but Django uses PBKDF2 algorithm to store the password. I would like to know how to retrieve the saved password from Authentication Form. Using these Username and password details from my Django app , i need to use the same credentials to access another website to perform web automation on it using selenium chrome webdriver. Please let us know how to get the password in raw format once user authenticated using below LoginForm and login_view. forms.py: class LoginForm(AuthenticationForm): remember_me = forms.BooleanField(required=True, initial=False) def __init__(self, *args, **kwargs): super(LoginForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_action = '.' self.helper.layout = Layout( Field('username', placeholder="Enter Username", autofocus=""), Field('password', placeholder="Enter Password"), Field('remember_me'), Submit('sign_in', 'Log in', css_class="btn btn-lg btn-primary btn-block"), ) def apply_gsp_request_form(request, id=None): if id: action = 'edit' model = get_object_or_404(ApplyGSP, pk=id) else: action = 'submit' model = ApplyGSP() message = "" if request.method == 'POST': form = ApplyGSPForm(request.POST, instance=model) if form.is_valid(): form.save() username = request.user.username print("password:", request.user.password) # How to get password details ? If i get pwd here using request.user.password it is displaying in <SHAalgorithm>$<iterations>$<salt>$<hash> format. # but i need in raw(clear text format) applyselenium(username,password) def applyselenium(): My Views.py: views.py: … -
How to prevent Django from overriding admin URI to /admin instead of /api/admin/
Working on putting a Django API into Kubernetes. Any traffic being sent to / the ingress-nginx controller sends to the React FE. Any traffic being sent to /api is sent to the Django BE. This is the relevant part of ingress-serivce.yaml: - http: paths: - path: /?(.*) backend: serviceName: client-cluster-ip-service servicePort: 3000 - path: /api/?(.*) backend: serviceName: server-cluster-ip-service servicePort: 5000 This is the url.py: from django.contrib import admin from django.urls import include, path urlpatterns = [ path('auth/', include('authentication.urls'), name='auth'), path('admin/', admin.site.urls, name='admin'), ] The client portion works just fine. The minikube IP is 192.168.99.105. Navigating to that IP loads the react front-end. Navigating to 192.168.99.105/api/auth/test/ brings me to a `"Hello World!" response. However, when I try to go to 192.168.99.105/api/admin. It automatically redirects me to /admin/login/?next=/admin/. Is there anyway to prevent this behavior? I've also just tried this: ingress-service.yaml - http: paths: - path: /?(.*) backend: serviceName: client-cluster-ip-service servicePort: 3000 - path: /api/?(.*) backend: serviceName: server-cluster-ip-service servicePort: 5000 - path: /admin/?(.*) backend: serviceName: server-cluster-ip-service servicePort: 5000 urls.py urlpatterns = [ path('auth/', include('authentication.urls'), name='auth'), path('/', admin.site.urls), ] Which just produces "Not Found". -
Django Timezone
I have a PostgreSql database with localtime UTC: client=# SHOW TIMEZONE; TimeZone ---------- UTC (1 register) And a table with the release date that shows me 12:15 hours, according to UTC: db=# SELECT datetime_register FROM appointment; datetime_register ------------------------ 2018-08-15 12:15:00+00 (1 registro) In the Django project, I have settings.py defined: TIME_ZONE = 'America/Sao_Paulo' When I check the date on the project, it is presented in the same way as in UTC: 12:15 and should show 09:15, which is the time in Sao Paulo, as defined in settings.py. What is left to do for the Django project to display the date as TIME_ZONE set in settings.py? -
Unable to debug or use pdb in Django: bdb.BdbQuit
I'm using Django (2, 2, 4, 'final', 0) within a docker, but I'm able to bash inside to open or execute whatever is required. But I can't debug. (How to debug in Django, the good way? states some methods, none work for me) Within my views.py I'm having various functions, for instance this here. def visGraph(request): showgraph = 'Graphen' selectDB = request.GET.get('selectDB', '') __import__("pdb").set_trace() title += " <i>"+showgraph+"</i> ("+selectDB+")" It works fine until I fill in the pdb, adding the debugger makes my app crash immediately: > /code/DjangoGraphen/views.py(74)visGraph() -> title += " <i>"+showgraph+"</i> ("+selectDB+")" (Pdb) Internal Server Error: /DjangoGraphen/visGraph Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "./DjangoGraphen/views.py", line 74, in visGraph title += " <i>"+showgraph+"</i> ("+selectDB+")" File "./DjangoGraphen/views.py", line 74, in visGraph title += " <i>"+showgraph+"</i> ("+selectDB+")" File "/usr/lib64/python3.7/bdb.py", line 88, in trace_dispatch return self.dispatch_line(frame) File "/usr/lib64/python3.7/bdb.py", line 113, in dispatch_line if self.quitting: raise BdbQuit bdb.BdbQuit ERROR:django.request:Internal Server Error: /DjangoGraphen/visGraph Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response … -
How to allow '%' to pass in IIS
I have a web app developed using DJANGO. Everything works well on the DJNAGO testing server. However, I tried to host it on IIS web server and it works only one problem I am having. I have one form (user input) and I want to allow the users to input wildcard such as SCA80%. The problem is that I get 404 error and it seems that IIS blocks it because the URL contains % sign. How can I make IIS don't check for the % regardless of the security issue concerns? Is there any simple solution to fix it? That's how the URL looks like when I send my request with a wildcard: /pareto/article-description/SAC80%25/?type=failure&is_article_desc=True If I remove the %25 and I put the entire SAC80RKEU211 everything works. Even if I am on the django developing server the %25 works. But not on IIS. -
Django Performance why is there a huge time gap between the total time and SQL time
So, I have a big issue with how long it takes to load my page on the development server. Believe it or not, for one of the pages on the site, it currently takes about a minute to load according to Django's debug toolbar while the toolbar shows SQL time of roughly 1 second (still too long). So, why is there such a gap. I tried loading on other pages that loads the same overhead, e.g. static files like js, fonts, pictures, etc. and they are no where close (around 2-3 seconds). I am using a DetailView and adding some related data to the request using get_context_data. So, I have timed each method call. Here are some more detailed numbers on performance: The get request took: 9.8e-06 The get request took: 9.200000000000007e-06 The get_object call took: 0.0642546 The get_object call took: 0.0660097 The get_object call took: 0.0505043 The get_object call took: 0.048121899999999995 The entire get_context_data took: 1.6127981 The entire get_context_data took: 1.6103409999999998 Notice that each is called twice with the exception of get_object which was called four times! Comparing page to page, I cannot figure out why it takes so long for this page to load vs another page with … -
Django not syncing with sqlite3 (official polls tutorial)
So I'm following the official tutorial (creating a polls app) for django and I'm having db issues. For some reason I didn't have sqlite3 included with python (not a big issue, I just installed it). After installation, I have a connection in settings.py like this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } I ran python migrate.py migrate. The next step was to run sqlite3 and do this: .schema Nothing shows up, because no DB exists. I'm very confused as to what I may not be doing right (or what I have done to mess it up) to get a proper database connection for the app. -
Django ecommerce: does not count line total
Doing a homework, and wanted to ask, how to calculate line_total (meaning: product.price * quantity). Got no problems w/ grand_total, but cant get my head around this issue. Tried moving line_total from one model to another. Say if its in cart model - it will only calculate line total for a last item, obviously. class Cart(models.Model): grand_total = models.DecimalField(max_digits=100, decimal_places=2, default=0.00) class DestCart(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE, blank=True, null=True) destination = models.ForeignKey(Destination, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) line_total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) views.py for item in cart.destcart_set.all(): line_total = float(actual_price) * item.quantity item.line_total = line_total grand_total += line_total cart.total = grand_total cart.save() {% for item in cart.destcart_set.all %} <p>Location: {{ item.destination }}</p> <p>Quantity: {{ item.quantity }}</p> <p>Price: {{ item.destination.price }}</p> <p>Line total: {{ item.line_total }}</p> <a href="{% url 'edit_cart' item.destination.id %}?qty=0">Remove</a> {% endfor %} So, as You gather the idea is to have separate column with line total values. Cheers for a help, guys. I know it must be simple, but got stuck for good. So thanks again! -
Is there a good example to learn add, edit and delete posts and comments to posts with AJAX?
I'm wondering is there a good example to learn add, edit and delete posts and comments to posts with AJAX ? I'm using django for server side code but it example doesn't need to be with django. Thanks! -
Is there any way to makemigration on a pre-existing docker database?
I have a pre-existing docker container with a postgres database that I'm connecting to my django app, but when I try to "makemigrations" and "migrate" it doens't affect the container. Any clue how I can do it? Any help will be greatly appreciated. Thanks