Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django FileNotFoundError when trying to add an item to a model
I am trying to create some models using Django and python. All my models are working and I can add items to the models, except for my User model. Can anyone suggest what could be wrong about it? models.py from django.db import models # Create your models here. class Item(models.Model): ID = models.IntegerField(auto_created=True, primary_key=True, unique=True) Name = models.CharField(max_length=30) Price = models.IntegerField() class User(models.Model): ID = models.IntegerField(auto_created=True, primary_key=True) Nickname = models.CharField(max_length=50) Password = models.CharField(max_length=200) Mail = models.EmailField() Points = models.IntegerField() SaleItem = models.ForeignKey(Item, on_delete=models.CASCADE) ProfilePic = models.FilePathField() BannerPic = models.FilePathField() ZodiacSign = models.CharField(max_length=50) class Friendship(models.Model): ID = models.IntegerField(auto_created=True, primary_key=True, unique=True) UserID = models.ManyToManyField(User, related_name="user") FriendID = models.ManyToManyField(User, related_name="befriended_user") class ThreadPrivate(models.Model): ID = models.IntegerField(auto_created=True, primary_key=True, unique=True) Text = models.TextField() Sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Sender") Receiver = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Receiver") Time = models.DateTimeField(auto_now_add=True) class Side(models.Model): ID = models.IntegerField(auto_created=True, primary_key=True, unique=True) Creator = models.ForeignKey(User, on_delete=models.CASCADE, related_name="creator_of_page") Time = models.DateTimeField(auto_now_add=True) class ThreadPublic(models.Model): ID = models.IntegerField(auto_created=True, primary_key=True, unique=True) Text = models.TextField() Time = models.DateTimeField(auto_now_add=True) Sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name="thread_sender") SideID = models.ForeignKey(Side, on_delete=models.CASCADE, related_name="side_for_thread") and admin.py from django.contrib import admin from .models import * # Register your models here. admin.site.register(Item) admin.site.register(User) admin.site.register(Friendship) admin.site.register(ThreadPrivate) admin.site.register(Side) admin.site.register(ThreadPublic) I have remembered to add to APPS in settings.py and such. … -
How can I redirect user twice - Django?
This is my files: urls.py path('add/<str:slug>/', views.addBookmark, name='addBookmark') views.py @login_required def addBookmark(request, slug): book = Book.objects.get(slug=slug) if BookMark.objects.filter(user=request.user, book=book).exists(): bookMark = BookMark.objects.get(user=request.user, book=book) bookMark.delete() return HttpResponseRedirect(request.META.get("HTTP_REFERER")) newBookMark = BookMark.objects.create(user=request.user, book=book) newBookMark.save() return HttpResponseRedirect(request.META.get("HTTP_REFERER")) Notice: my view just refresh the page Button <a class="addInBookmarks" href="{% url 'addBookmark' book.slug %}">In bookmarks</a> What do I have: When a non-authenticated user tries to add a book in bookmarks I have the next URL pattern: .../login/?next=/cart/add/harry-potter It does add an object to the database. However, after the action, it reloads the page and the page is the login page. I need to redirect back to the book page. My problem: For authenticated users, everything works well. However, If a user isn't authenticated, then I wanna have the next scheme: a non-authenticated user clicks on the button -> redirect on the login page -> log in -> add an object in the database(Bookmark model)(using the view above) -> redirect back to the book page. -
django admin return value.utcoffset() is None
I get this error when I try to enter the Django admin panel: Traceback (most recent call last): File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python38-32\lib\wsgiref\handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "D:\workspace\web\djangoProject\lib\site-packages\django\contrib\staticfiles\handlers.py", line 76, in __call__ return self.application(environ, start_response) File "D:\workspace\web\djangoProject\lib\site-packages\django\core\handlers\wsgi.py", line 133, in __call__ response = self.get_response(request) File "D:\workspace\web\djangoProject\lib\site-packages\django\core\handlers\base.py", line 130, in get_response response = self._middleware_chain(request) File "D:\workspace\web\djangoProject\lib\site-packages\django\core\handlers\exception.py", line 49, in inner response = response_for_exception(request, exc) File "D:\workspace\web\djangoProject\lib\site-packages\django\core\handlers\exception.py", line 103, in response_for_exception response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) File "D:\workspace\web\djangoProject\lib\site-packages\django\core\handlers\exception.py", line 138, in handle_uncaught_exception return debug.technical_500_response(request, *exc_info) File "D:\workspace\web\djangoProject\lib\site-packages\django\views\debug.py", line 52, in technical_500_response html = reporter.get_traceback_html() File "D:\workspace\web\djangoProject\lib\site-packages\django\views\debug.py", line 331, in get_traceback_html return t.render(c) File "D:\workspace\web\djangoProject\lib\site-packages\django\template\base.py", line 170, in render return self._render(context) File "D:\workspace\web\djangoProject\lib\site-packages\django\template\base.py", line 162, in _render return self.nodelist.render(context) File "D:\workspace\web\djangoProject\lib\site-packages\django\template\base.py", line 938, in render bit = node.render_annotated(context) File "D:\workspace\web\djangoProject\lib\site-packages\django\template\base.py", line 905, in render_annotated return self.render(context) File "D:\workspace\web\djangoProject\lib\site-packages\django\template\base.py", line 988, in render output = self.filter_expression.resolve(context) File "D:\workspace\web\djangoProject\lib\site-packages\django\template\base.py", line 698, in resolve new_obj = func(obj, *arg_vals) File "D:\workspace\web\djangoProject\lib\site-packages\django\template\defaultfilters.py", line 702, in date return formats.date_format(value, arg) File "D:\workspace\web\djangoProject\lib\site-packages\django\utils\formats.py", line 152, in date_format return dateformat.format(value, get_format(format or 'DATE_FORMAT', use_l10n=use_l10n)) File "D:\workspace\web\djangoProject\lib\site-packages\django\utils\dateformat.py", line 342, in format df = DateFormat(value) File "D:\workspace\web\djangoProject\lib\site-packages\django\utils\dateformat.py", line 57, in __init__ if is_naive(obj): File "D:\workspace\web\djangoProject\lib\site-packages\django\utils\timezone.py", line 225, in is_naive return value.utcoffset() … -
Change the function based views to class based generic views(update view)
I need to change the function based views to class based generic view i have the html page which displays the ticket status and info along with the button ticket image with accept button if i click on accept button it goes into below function based view(accept_ticket_view()) i need that function based view to be written in cbv(updateview). model.py class Ticket(models.Model): ticket_title = models.CharField(unique=True,max_length=200) ticket_description = models.TextField() created_by = models.ForeignKey(User,related_name = 'created_by',blank=True,null=True,on_delete=models.CASCADE) STATUS_CHOICES = ( ('Opened','Opened'), ('Accepted','Accepted'), ('Completed','Completed'), ('Closed','Closed') ) status = models.CharField('Status',choices=STATUS_CHOICES,max_length = 100,blank=True,null=True) closed_date = models.DateTimeField(blank=True,null=True) completed_date = models.DateTimeField(blank=True,null=True) accepted_date = models.DateTimeField(blank=True,null=True) opened_date = models.DateTimeField(blank=True,null=True) accepted_by = models.ForeignKey(User,related_name='assigned_to',on_delete=models.CASCADE,blank=True,null=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) openticket.html <thead> <tr> <th>ID</th> <th>Status</th> <th>Created</th> <th>Title</th> <th>Description</th> </tr> </thead> <tbody> {% for ticket in tickets %} <tr> <td><a href="">{{ ticket.id }}</a></td> <td>{{ ticket.status }}</td> <td>{{ ticket.created_by }}</td> <td>{{ ticket.ticket_title }}</td> <td>{{ ticket.ticket_description }}</td> <td><a href="{% url 'accept_tickets' pk=ticket.id %}"> Accept</a> views.py @login_required def open_tickets_view(request): tickets_open = Ticket.objects.filter(status = 'Opened') return render(request,'app/open_tickets.html',{"tickets": tickets_open}) @login_required def accept_tickets_view(request,pk): ticket = get_object_or_404(Ticket,id=pk) if ticket.status == 'Opened': ticket.status = 'Accepted' ticket.accepted_date = datetime.datetime.now() ticket.accepted_by = request.user ticket.save() return redirect(reverse('open_tickets')) @login_required def dev_accepted_ticket(request): ticket_complete = Ticket.objects.filter(status = 'Accepted',accepted_by = request.user) return render(request,'app/dev_accepted_ticket.html',{"tickets": ticket_complete}) @login_required def mark_complete_tickets_view(request,pk): ticket = get_object_or_404(Ticket,id=pk) … -
How to add a custom view to django admin similar to /change and /add?
How can I create an extended view to a instance of an object in Django. For example, in the changelist_view of a model's object, I would like to have a link to a custom view that will display some information. I would like to have that page sitting in something like: admin/my_app/my_model/<id>/custom-view urls.py urlpatterns = [ path('admin/', admin.site.urls), path('admin/my_app/my_model/<id>/customers-in-use', views.custom_view), admin.py class MyModelAdmin(VersionAdmin) list_display = [... custom_view, ...] def custom_view(self, obj): url = f"/admin/my_app/my_model/{obj.id}/custom-view/" return format_html(f"<a href='{url}'>{obj.id}</a>") And in views.py I have the method that just collects the data. But when I click on the link, it redirects me to admin's home page with a message my_model with ID <id>/custom-view" doesn't exist. Perhaps it was deleted? What is the proper way (if any) to do this? -
Django: use select_related / prefetch_related for 3 models in one query
I have few Django models: Domains, Kpis, Tests, TestsAndKpis TestsAndKpis is many-to-many model with test_id and kpi_id as keys. Kpis model has a ForiegnKey of domain_id. I want to efficiently get data from my DB (i use MySQL), meaning to have as less DB queries as possible. Currently, to get what i need i run this items = [{'kpi_type': t_k.type, 'kpi_name': t_k.kpi_id.name, 'kpi_display_name': t_k.kpi_id.display_name, 'domain_display_name':t_k.kpi_id.domain_id.display_name} for t_k in TestsAndKpis.objects.filter(test_id=test_id).select_related('kpi_id')] Which results my application to run LOTS of redundant queries [like SELECT ... FROM domains WHERE domains.id = 6 [total of 25 queries] When i remove the 'domain_display_name' key that extract from domains table: items = [{'kpi_type': t_k.type, 'kpi_name': t_k.kpi_id.name, 'kpi_display_name': t_k.kpi_id.display_name for t_k in TestsAndKpis.objects.filter(test_id=test_id).select_related('kpi_id')] The application runs only 15 queries in total and returns MUCH faster. My question: How can i extract the data efficiently, and avoid the redundant 10 queries? I tried to use chained select_related/prefetch_related but it did not work out for me. -
Django Server Side set-up for pagination with Datatable
I am using Django for backend, and I am using Datatable library to display a large number of records ( approx 1 million records ). I am trying to set up datatable in such a way that every time 25 records are being fetched from the backend and when the user clicks on the next page button, another ajax call gets the next 25 records and so on. But I am having a trouble setting these up. My DataTable initialisation : $("#company-table").DataTable({ "processing": true, "serverSide": true, "bDestroy": true, ajax: { type: "POST", url: "/get_results/", headers: { "X-CSRFToken": getCookie("csrftoken"), }, data: { ...other data params... page:$("#company-table").DataTable().page() }, }, columns: [ ...populating columns... ], }); And my views.py looks like this ( It is completely wrong as far as I know ) : #filtered_queryset contains all the records. paginator = Paginator(filtered_queryset, 25) # Show 25 contacts per page. page_number = request.POST.get('page') start = request.POST.get('start') length = request.POST.get('length') page_obj = paginator.get_page(page_number) data = list(page_obj.object_list.values()) return_data = {"data": data} json_data = json.dumps(return_data,indent=4, sort_keys=True, default=str) return HttpResponse (json_data, content_type = "application/json") Can anyone help me? Or just nudge me in the right direction? -
FileNotFoundError: [Errno 2] No such file or directory: 'auto-restart'
Tried use watchdog to auto-restart celery worker/beat in docker container when code changed, and get error: # watchmedo auto-restart -d . -R -- celery -A main_app_name beat -l info Traceback (most recent call last): File "/usr/local/bin/watchmedo", line 8, in <module> sys.exit(main()) File "/usr/local/lib/python3.9/site-packages/watchdog/watchmedo.py", line 641, in main args.func(args) File "/usr/local/lib/python3.9/site-packages/watchdog/watchmedo.py", line 625, in auto_restart handler.start() File "/usr/local/lib/python3.9/site-packages/watchdog/tricks/__init__.py", line 174, in start self.process = subprocess.Popen(self.command, preexec_fn=getattr(os, 'setsid', None)) File "/usr/local/lib/python3.9/subprocess.py", line 951, in __init__ self._execute_child(args, executable, preexec_fn, close_fds, File "/usr/local/lib/python3.9/subprocess.py", line 1821, in _execute_child raise child_exception_type(errno_num, err_msg, err_filename) FileNotFoundError: [Errno 2] No such file or directory: 'auto-restart' # all dependencies installed from requirements.txt: *** pyyaml~=6.0 watchdog~=2.1.6 auto-restart~=2.2 *** When search 'auro-restart' file in container, got: # find / -type f -name '*auto*restart*' /root/.cache/pip/wheels/40/11/c1/9e570f5aac7910cf701243cda8b5fc58e56b329a3d73b4840b/auto_restart-2.2-py3-none-any.whl /usr/local/bin/auto_restart /usr/local/bin/auto_restart_tool /usr/local/lib/python3.9/site-packages/auto_restart/auto_restart_when_git_changed.py /usr/local/lib/python3.9/site-packages/auto_restart/__pycache__/auto_restart_when_git_changed.cpython-39.pyc # Anybody knows the reason of this issue? -
why 'bool' object is not callable
here is my middleware file in django import re from django.conf import settings from django.shortcuts import redirect EXEMPT_URL = [re.compile(settings.LOGIN_URL.lstrip('/'))] if hasattr(settings, 'LOGIN_EXEMPT_URLS'): EXEMPT_URL += [re.compile(url)for url in settings.LOGIN_EXEMPT_URLS] class LoginRequiredMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self,request): response = self.get_response(request) return response def process_view(self,request, view_func, view_args, view_kwargs): assert hasattr(request,'user') path = request.path_info print(path) if not request.user.is_authenticated(): if not any (url.match(path) for url in EXEMPT_URL): return redirect(settings.LOGIN_URL) url_is_exempt = any (url.match(path) for url in EXEMPT_URL) if request.user.is_authenticated() and url_is_exempt: return redirect(settings.LOGIN_REDIRECT_URL) elif request.user.is_authenticated() or url_is_exempt: return None else: return redirect(settings.LOGIN_URL) here is my error : if not request.user.is_authenticated(): TypeError: 'bool' object is not callable please somebody help me with that -
How can generator a url link of text code
I want to make a project that we paste a code on a text field and after submit button, they generate a URL link for accessing this code it is similar to git gists. Can anyone tell me that how can I approach -
How to call a task asynchronously from react to django rest framework using celery
Here is the react frontend code: getStatus = (obj) => { axios.get(`/api/test_calc/${obj.data.task_id}/`, { headers: { 'accept': 'application/json', } }, ).then(resp => { (obj.data.task_status === 'PENDING') ? this.getStatus(obj) : this.getImageClass(resp) console.log("PENDING") }) .catch(err => { console.log(err.response) }) this.deactivateSpinner() Here is the view of the Django API @api_view(('GET',)) def get_status(request, task_id): task = current_app.AsyncResult(task_id) context = {'task_status': task.status, 'task_id': task.id} if task.status == 'SUCCESS': response_data = TestSerializer(Test.objects.get(pk=task.get())) return Response({**context, **response_data.data}, status=status.HTTP_201_CREATED) else: time.sleep(1) return Response({**context}, status=status.HTTP_201_CREATED) Here are my URLS: router = routers.DefaultRouter() router.register(r'test_calc', ImageViewSet) urlpatterns = [ path('', include(router.urls)), path('task/<task_id>/', get_status, name="get_status"), ] All it shows is pending, although when I check Flower (Celery UI), it shows the task is successful. Can someone tell me how to get and send the success to the react frontend? -
when I create super user for custom user model, its dont provide me username, firstname, lastname filed then its show error
when I create super user for custom user model, its dont provide me username, firstname, lastname filed then its show this error: MyAccountManager.create_superuser() missing 3 required positional arguments: 'first_name', 'last_name', and 'username' Here My Code: class MyAccountManager(BaseUserManager): def create_user(self,first_name,last_name, username, email, password=None): email = self.normalize_email(email) if email is None: raise ValueError('User Must have a email') first_name = first_name.title() last_name = last_name.title() username = username.title() user = self.model( email=email, first_name= first_name, last_name=last_name, username=username ) user.set_password(password) user.save(using = self._db) return user def create_superuser(self, email,first_name,last_name, username, password=None): user = self.create_user(email=email, password=password,first_name= first_name, last_name=last_name, username=username), user.is_staff = True user.save(using = self._db) class Account(AbstractBaseUser): first_name = models.CharField(max_length=50, blank=True, null=True) last_name = models.CharField(max_length=50, blank=True, null=True) username = models.CharField( max_length=50, default='test', unique=True, blank=True, null=True) email = models.EmailField(max_length=100, unique=True) phone_number = models.CharField(max_length=50) # required date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now_add=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) objects = MyAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELD = ['username', 'first_name','last_name'] -
How to prefix a foreign key object to a model field in Wagtail admin?
In this case, each feature has one Epic (models.Model) epic = models.ForeignKey(Epic, on_delete=models.CASCADE, default='') In the admin drop-down (and only there) I would like to show each item as: epic.name - feature.name Because some of my features have a similar name but different epics. I can't change the __ str __ function of the Feature model or it will affect the whole app. How can I achieve that? -
Error when deploy Django Project on Heroku
I tried to deploy django app on heroku but got this error.I followed every steps from heroku and this website: https://studygyaan.com/django/django-everywhere-host-your-django-app-for-free-on-heroku.This is my error: error: command '/usr/bin/gcc' failed with exit code 1 ERROR: Command errored out with exit status 1: /app/.heroku/python/bin/python -u -c 'import io, os, sys, setuptools, tokenize; Please help me with this problems. -
How to enforce validation in django forms
I have a form that takes in start_time and end_time, both of which are DateTimeFields in my model.py. However, I want to make sure that the start_time is less than the end_time. I have created a function in my forms.py but it does not seem to be taking any effect. How I can enforce this validation? my forms.py class EventForm(ModelForm): class Meta: model = Event # datetime-local is a HTML5 input type, format to make date time show on fields widgets = { "start_time": DateInput( attrs={"type": "datetime-local"}, format="%Y-%m-%dT%H:%M" ), "end_time": DateInput( attrs={"type": "datetime-local"}, format="%Y-%m-%dT%H:%M" ), "title": TextInput(attrs={"placeholder": "Title"}), "description": TextInput(attrs={"placeholder": "Description"}), "author": forms.HiddenInput(), } fields = ["title", "description", "start_time", "end_time", "author"] def clean_time(self): start_time = self.cleaned_data.get('start_time') end_time = self.cleaned_data.get('end_time') if start_time > end_time: raise forms.ValidationError("Start time cannot be greater than end time") return self.cleaned_data def __init__(self, *args, **kwargs): super(EventForm, self).__init__(*args, **kwargs) # input_formats parses HTML5 datetime-local input to datetime field self.fields["start_time"].input_formats = ("%Y-%m-%dT%H:%M",) self.fields["end_time"].input_formats = ("%Y-%m-%dT%H:%M",) my views.py for creating event: def event_create(request): instance = Event() data = request.POST.copy() data["author"] = request.user form = EventForm(data or None, instance=instance) if request.POST and form.is_valid(): form.save() return HttpResponseRedirect(reverse("cal:calendar")) return render(request, "cal/create_event.html", {"event": form}) -
django.db.utils.ProgrammingError: multiple default values specified for column "id" of table "products_customer"
After make migrations , i tried to do migrate, but i am getting the django.db.utils.ProgrammingError: multiple default values specified for column "id" of table "products_customer" But iam remove this customer table from models.py how i solve this ? models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class product(models.Model): product_id = models.IntegerField(primary_key=True) product_name = models.CharField(max_length=255) product_price = models.FloatField() product_stock = models.IntegerField() product_image = models.CharField(max_length=2500) class order(models.Model): order_id = models.IntegerField(primary_key=True) product_id = models.ForeignKey(product,on_delete=models.CASCADE) user = models.ForeignKey(User,on_delete=models.CASCADE) order_quantity = models.IntegerField() order_total = models.IntegerField() order_shipped = models.BooleanField() class address(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) house_name = models.CharField(max_length=255, blank=True) town = models.CharField(max_length=255, blank=True) post_office = models.CharField(max_length=255, blank=True) pincode = models.CharField(max_length=255) district = models.CharField(max_length=255, blank=True) land_mark = models.CharField(max_length=255, blank=True) phone = models.CharField(max_length=15, blank=True) @receiver(post_save, sender=User) def create_user_address(sender, instance, created, **kwargs): if created: address.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_address(sender, instance, **kwargs): instance.address.save() -
Why does django show me existing rows error?
You are trying to add the field 'created' with 'auto_now_add=True' to user without a default; the database needs something to populate existing rows. Provide a one-off default now (will be set on all existing rows) Quit, and let me add a default in models.py -
how use super in django tables2 render_*
i create new Column and add customize render as below class PriceColumn(django_tables2.Column): def render(self, value): if isinstance(value, int) or isinstance(value, float): self.attrs['td']['title'] = f'{round(value, 2):,}' return number_convertor_to_milion(value) return '--- then i used it for field weekly_returns = PriceColumn(verbose_name=_('Weekly Returns')) def render_weekly_returns(self, value,**kwargs): final_result = value*100 // i want to call super().render() like below return super().render(final_result,**kwargs) i want to call super as in code writed but gives error how can do this? -
How to get access token and refresh token ( rest_framework_jwt ) in a single API in Django
I need to get access token and refresh token in a single API, Currently I have 2 API's for both access and refresh tokens url(r'^token-auth', view.ObtainJWTView.as_view(), name='token-auth'), url(r'^token-refresh', refresh_jwt_token), I need one more API for both -
How to remove first brackets from list in django?
I write a query to get the list like this: tStartEnd = APIHistory.objects.values('status_start','status_end') codereview = list(tStartEnd) expected output is: ['start', 'end'] but I'm getting : [('START', 'END')] using django query how get the output like this ['start', 'end'] -
serving media files in django with a small size
I'm building a Django app (call it Drive) to upload photos (2MB or higher) and use its links in another project. the problem is when uploading all photos on the drive and adding their links in the other project the photos take a lot of time to load, I found a solution to server these photos on the drive itself and compress them when uploading, but still takes a long time to load. this is the serve function: def serve(request, path, document_root=None): file_link = path file = File.objects.get(privacy__link=file_link) rendered_file = FileResponse(file.file) return rendered_file it returns the file as a FileResponse and then it will be returned in its full size and I think that is the problem, and I don't want something like this to happen, I just want to preview the photos with small sizes to load faster on the site. any help? -
Django : GET / HTTP/1.1" 404 2029
I'm a beginner Django. I get his 404 error, couldn't find why. Followed all the instructions step by step. Using Django version 3.1.1. Trying to find solution on google, no help. When I execute python manage.py runserver - I get the following message Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). November 16, 2021 - 06:17:59 Django version 3.1.1, using settings 'lecture3.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Not Found: / [16/Nov/2021 06:18:02] "GET / HTTP/1.1" 404 2029 Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). November 16, 2021 - 06:25:43 Django version 3.1.1, using settings 'lecture3.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Not Found: / [16/Nov/2021 06:25:46] "GET / HTTP/1.1" 404 2029 Error on the page is : Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in lecture3.urls, Django tried these URL patterns, in this order: admin/ hello/ The empty path didn't match any of these. Hello/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name="index") ] hello/views.py from django.http import HttpResponse from django.shortcuts … -
'OperationalError ' when I insert : owner = models.ForeignKey(User,on_delete=models.CASCADE)
I'm very new in django, when I put this code : ''' owner = models.ForeignKey(User,on_delete=models.CASCADE) ''' the page gives ' OperationalError ' in a position . Is this code wrong, or it needs something ? I need a good new book in django to free download . -
django-admin start project returns command not found on mac with django version 3.10
I just started learning django and to start my first project, I have installed Python version 3.10.0 on mac. created a virtual environment and installed django but when trying to run django-admin startproject myproject in virtual environment, it returns command not found. could this be a bug on the latest version of python or there is something else I should try ? -
How to display rest api using AJAX in Django?
I want to be able to use the REST API below and display data on a single HTML page. This is the API (response) from a database connection function in my Django project. URL: http://127.0.0.1:8000/api/v1/test/ API output: { "message": "Success !", "server": "Connection established from ('PostgreSQL 12.7, compiled by Visual C++ build 1914, 64-bit',)" } I tried to display the data using AJAX. However, the data does not appear on the page. This is my attempt: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>API Calls Demo</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> </head> <body> <div class="container-fluid"> <h3>Test Output</h3> <br></br> <table class="table table-sm"> <tr> <th>Output</th> </tr> <tbody id="divBody"></tbody> </table> </div> </body> <script> $(document).ready(function () { BindConnection(); }); function BindConnection(){ $.ajax({ type:"GET", dataType: "JSON", url: "http://127.0.0.1:8000/api/v1/test", success: function(data){ console.log(data); var str = ""; var totalLength = data.length; for (let i=0; i < totalLength; i++){ str += "<tr>" + "<td>" + data[i].server + "</td>" "</tr>" } $("#divBody").append(str) } }); } </script> Note: The result can be displayed on the console and there is no error. Sorry for my poor attempt, cause I am still new with Django, REST API, and Javascript (AJAX). I have tried several attempts …