Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In the Django project,how to rebuild the model classes by migrations file?
In the Django project, if the model folder files are deleted, is it possible to use the migrations folder files to rebuild the model classes? -
Deploying django rest and react app on aws (elastic bean / S3)
I'm trying to deploy my django rest + react app on AWS, but I have a hard time collecting info how to achieve this. Following this tutorial: https://www.newline.co/fullstack-react/articles/deploying-a-react-app-to-s3/ seems lika a good option for deploying react front. What is left for me is django and postresql DB. I've read about deplying copuled django and react on EC2 (as the simpler option), but I would like to use S3. This How to Deploy Django Rest Framework and React on AWS answer provide some info, but I'm not able to go any further. Should I separate them to different buckets, or use other AWS tools for django and database ? Any artcles, tutorials will be very much appreciated! -
What is equivalent of *Laravel Model's Global Scope* in Python or Django?
In general when data is queried using App\Models in laravel, we have a luxury to apply filters using Model Level Global scope and Local Scope. Is there any equivalent in "Python"? May be in "Django"? Or may be in models.Model ? -
Django debug_toolbar not working if DEBUG=False
I followed the installation process from the django_toolbar doc and at no point it's indicated that DEBUG must be set to True. When I have DEBUG set to True the debug_toolbar works but when it's set to False it doesn't. I'm working with Docker and I found a piece of code to make it work in the first place with DEBUG=True but not in this configuration: DEBUG = False ALLOWED_HOSTS = ["localhost", "127.0.0.1"] [...] INSTALLED_APPS.append("debug_toolbar") MIDDLEWARE.append("debug_toolbar.middleware.DebugToolbarMiddleware") INTERNAL_IPS = ["127.0.0.1"] import socket ip = socket.gethostbyname(socket.gethostname()) INTERNAL_IPS += [ip[:-1] + '1'] -
Django form DateTimeField : select a valid date and a valid time
I have a form with datetimefield format : class DateTimeInput(forms.DateTimeInput): input_type = "datetime-local" class myform(forms.ModelForm): myfield= forms.DateTimeField(input_formats = ["%d/%m/%Y %H:%M"], widget=DateTimeInput(attrs={ 'class':'form-control'})) but I have still the error "select a valid date and a valid time". My input look like : 14/02/2021 15:59 -
Error: ModuleNotFoundError: No module named 'members.urls'
I tried to start a app so that I can create a Login for my blog but I came by this error. So I thought to post a question in stack over flow. I hope yu can take some time to answer my question. It says there is no module named members.urls. This is the trace back error, Traceback (most recent call last): File "C:\Users\Selvi\AppData\Local\Programs\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Users\Selvi\AppData\Local\Programs\Python\Python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "C:\simpleblog\virt\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\simpleblog\virt\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\simpleblog\virt\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = checks.run_checks( File "C:\simpleblog\virt\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\simpleblog\virt\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\simpleblog\virt\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\simpleblog\virt\lib\site-packages\django\urls\resolvers.py", line 408, in check for pattern in self.url_patterns: File "C:\simpleblog\virt\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\simpleblog\virt\lib\site-packages\django\urls\resolvers.py", line 589, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\simpleblog\virt\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\simpleblog\virt\lib\site-packages\django\urls\resolvers.py", line 582, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\Selvi\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line … -
How to get books of the the same author in Django
I am developing an online Book Store. Here is the models: class Author(models.Model): name = models.CharField(max_length=250, unique=True) class Publisher(models.Model): name = models.CharField(max_length=250, unique=True) class Book(models.Model): author = models.ManyToManyField(Author, related_name='authors') publisher = models.ForeignKey(Publisher, on_delete=models.PROTECT, blank=True, null=True) isbn13 = models.BigIntegerField(unique=True) name = models.CharField(max_length=500) ... Here is the View: class AuthorsListView(ListView): model = Author context_object_name = 'authors_list' template_name = 'authors_list.html' paginate_by = 500 class AuthorBooksListView(ListView): model = Book context_object_name = 'author_books' template_name = 'author_books.html' def get_queryset(self, **kwargs): author_id = Author.objects.get(pk = self.kwargs['pk']) qs = super().get_queryset(**kwargs) return qs.filter(author = author_id) def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) # Add in a QuerySet context['author'] = Author.objects.get(pk = self.kwargs['pk']) return context class PublishersListView(ListView): model = Publisher context_object_name = 'publishers_list' template_name = 'publishers_list.html' paginate_by = 500 class PublisherBooksListView(ListView): model = Book context_object_name = 'publisher_books' template_name = 'publisher_books.html' paginate_by = 20 def get_queryset(self, **kwargs): publisher_id = Publisher.objects.get(pk = self.kwargs['pk']) qs = super().get_queryset(**kwargs) return qs.filter(publisher = publisher_id) def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) # Add in a QuerySet context['publisher'] = Publisher.objects.get(pk = self.kwargs['pk']) return context class BooksListView(ListView): model = Book context_object_name = 'books_list' template_name = 'books_list.html' paginate_by = 100 class … -
trying to use username in urlpattern to give every user a unique link
this my approach if you know how to do it please help my views.py def profile(request, username): return render(request, 'profile.html') my urls.py from django.conf.urls import url from django.urls import path from django.contrib.auth import views as auth_views from . import views # Template Urls! app_name = 'accounts' urlpatterns = [ path('Skolar/',views.base, name= 'base'), path('Register/',views.register,name='register'), path('login/', views.my_login_view, name='login'), path('logout/',views.user_logout,name='logout'), path('<slug:username>',views.profile, name='profile'), path('EditProfile/',views.update_profile,name='editprofile'), ] error showing Reverse for 'profile' with no arguments not found. 1 pattern(s) tried: ['(?P<username>[-a-zA-Z0-9_]+)$'] in my html i use <a class="dropdown-item" href="{% url 'accounts:profile' %}">My Account</a> -
How to get absolute url of a Cloudinary Obejct
I am using Cloudinary in my django app. But, I get an output like this: { "post": "Test", "image_field": "image/upload/v1613308988/cizqjtpk59j5orvl2l5e.jpg" } My MODEL: class Image(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="image_field", default=None) image_field = CloudinaryField('image') def __str__(self): return self.post.title My SERIALIZER: class ImageSerializer(serializers.ModelSerializer): post = serializers.StringRelatedField() class Meta: model = Image fields = ["post", "image_field"] MY VIEWS: class ImageViewSet(viewsets.ModelViewSet): serializer_class = ImageSerializer queryset = Image.objects.all() filter_backends = [DjangoFilterBackend] filter_fields = ['post', 'image_type'] def get_permissions(self): if self.request.method in permissions.SAFE_METHODS: return [permissions.IsAuthenticatedOrReadOnly()] return [permissions.IsAdminUser()] Thanks for any help. :) -
TypeError at /products/ object of type 'ModelBase' has no len()
So I'm trying to use pagination, When I visit the page I get TypeError at /products/ object of type 'ModelBase' has no len(). The traceback shows this line has the error books = haha.page(page) views.py def showproducts(request): oof = CartItem.objects.filter(user=request.user).values_list('book', flat=True) lmao = OrderItem.objects.filter(user=request.user).values_list('book', flat=True) hehe = CartItem.objects.filter(user=request.user) category = Category.objects.all() haha = Paginator(Book, 2) page = request.GET.get('page') if page is None: page = 1 fianlprice = 0 for item in hehe: fianlprice += item.book.price # books = Book.objects.all() books = haha.page(page) return render(request, 'main/products.html', {'books':books, 'price':fianlprice, 'cart':oof, 'order':lmao, 'category':category}) products.html <h1>Products</h1> <h1>{{ error }}</h1> {% if user.is_authenticated %} <h1>Your cart currently costs ${{ price }}</h1> {% else %} <h1>Please login to view your cart</h1> {% endif %} <form method="GET" action="/search/"> <label>Choose a category</label> <select name="category" id="category"> <option value="All" selected>All</option> {% for name in category %} <option value="{{ name.name }}">{{ name.name }}</option> {% endfor %} </select> <input type="text" placeholder="Search here" name="search" id="search"> <button type="submit">Search</button> </form> {% for book in books %} <a href="{% url 'detailview' book.id %}"><h3>{{ book.name }}</h3></a> <img src= "/media/{{ book.image }}" alt=""> <p>{{ book.description }}</p> {% if not user.is_authenticated %} <p>Please login</p> {% else %} {% if book.id in cart %} <form method="POST" action="/removefromcartforhome/"> {% csrf_token %} … -
How can handle UpdateView on same page
am new to django , i want to make updateview shows the edit form in same page rather than opening an new page class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Post fields = ['title', 'slug', 'content', 'category', 'post_image'] template_name = 'update.html' def get_context_data(self, **kwargs): data = super(PostUpdateView, self).get_context_data(**kwargs) data['update_form'] = data.get('form') return data def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): post = self.get_object() if self.request.user == post.author: return True else: return False -
accepting and saving the data entered into input field (email) using django
I'm a newbie currently learning how to work with django. I rendered a static homepage with an email input field for a project. The field is supposed to get inputs from folks that would want to be on my waitlist for the project when it's ready. enter image description here I'm confused about how to capture this data and store it in my database and now i'm stuck. I tried creating an app within my project called Waitlist with a model class(Waitlist). This class has just one attribute "email".enter image description here. would really appreciate some kind assistance. thanks -
why my wsgi module is not found and why the process has failed
I'm not sure why my wsgi module is not found and why the process has failed despite following the steps. Can someone advise which file is causing the problem? Please let me know if more code is required. This is the tutorial i am following: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-20-04 (myprojectenv):~# sudo systemctl status gunicorn ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; disabled; vendor preset: enabled) Active: failed (Result: exit-code) since 9min ago Main PID: 12810 (code=exited, status=3) Feb 14 13:44:02 ubuntu-s-1vcpu-1gb-nyc1-01 gunicorn[12810]: return _bootstrap._gcd_import(name[level:], package, level) gunicorn[12810]: File "<frozen importlib._bootstrap>", line 994, in _gcd_import gunicorn[12810]: File "<frozen importlib._bootstrap>", line 971, in _find_and_load gunicorn[12810]: File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked gunicorn[12810]: ModuleNotFoundError: No module named 'hello.wsgi' gunicorn[12810]: [2021-02-14 13:44:02 +0000] [12829] [INFO] Worker exiting (pid: 12829) gunicorn[12810]: [2021-02-14 13:44:02 +0000] [12810] [INFO] Shutting down: Master gunicorn[12810]: [2021-02-14 13:44:02 +0000] [12810] [INFO] Reason: Worker failed to boot. systemd[1]: gunicorn.service: Main process exited, code=exited, status=3/NOTIMPLEMENTED systemd[1]: gunicorn.service: Failed with result 'exit-code'. My gunicorn service code: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=root Group=www-data WorkingDirectory=/root/myprojectdir ExecStart=/root/myprojectdir/myprojectenv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ hello.wsgi:application [Install] WantedBy=multi-user.target -
How to create a URL that links directly to open a Modal with data
When i click td(title) on the table, the data is retrieved via api and displayed in a pop-up modal window using ajax. is there any chance to create url so that I can get the data I want by launching pop-up right away without click on the table page? What i want to is When you click on an url, redirect to the page(the table page ) and the corresponding data modal is opened immediately. plz help me up my ajax and jquery to open modal and get data $(".title_txt").click(function (e) { e.preventDefault(); var currentNum = $(this).closest('tr').prevAll().length + 1; var td = get_td(currentNum); get_consul(td,currentNum); }) function get_consul(td,currentNum) { var pk = td.eq(8).text(); var lastNum = $("#orders__table tbody tr").length; if (lastNum == currentNum) { $(".next_consul").hide(); $(".prev_consul").show(); } else if (currentNum == 1){ $(".prev_consul").hide(); $(".next_consul").show(); } else{ $(".next_consul").show(); $(".prev_consul").show(); } $.ajax({ type: 'GET', url: "{% url 'get_consul' %}", data: {"pk": pk}, dataType: "json", success: function (response) { /* modal value changed */ var student_url = "{% url 'student_detail' 1 2 %}" $(".title_con").text(response[0].fields.title) $(".con_con").html(response[0].fields.content) $(".con_txt_created_by").text(response[0].fields.created_by) $(".con_txt_created_at").text(response[0].fields.created_at) $(".con_txt_classification").text(response[0].fields.classification) $(".con_txt_status").text(response[0].fields.status) $(".con_txt_status").removeClass('imp_01 imp_02 imp_03') $(".con_txt_status").addClass(response[0].fields.status_css) $(".con_txt_name").text(response[0].fields.created_to) $(".con_txt_name").attr("href", student_url .replace('2',response[0].fields.student_pk) .replace('1',response[0].fields.school_year)) $(".con_txt_school_year").text(response[0].fields.get_school_year_display) $(".con_txt_type").text(response[0].fields.get_type_display) $(".con_txt_admission_date").text(response[0].fields.admission_date) $(".con_txt_picture").attr("src", '/media/' + response[0].fields.picture) $(".currentNum").text(currentNum) /* list css changed to read */ td.removeClass('on') … -
How to connect postgresql to django
hello everyone hense i connect my separeted django settings to databse it start making problem, i make migration to new postgress and everything looks good succesfully connected and create new tables on postgress but cannt start service what should be a problem? Feb 14 13:27:45 ip-88-99-22-33 gunicorn[49315]: self.stop() Feb 14 13:27:45 ip-88-99-22-33 gunicorn[49315]: File "/var/www/html/web/venv/lib/python3.8/site-packages/gunicorn/arbiter.py", line 393, in stop Feb 14 13:27:45 ip-88-99-22-33 gunicorn[49315]: time.sleep(0.1) Feb 14 13:27:45 ip-88-99-22-33 gunicorn[49315]: File "/var/www/html/web/venv/lib/python3.8/site-packages/gunicorn/arbiter.py", line 242, in handle_chld Feb 14 13:27:45 ip-88-99-22-33 gunicorn[49315]: self.reap_workers() Feb 14 13:27:45 ip-88-99-22-33 gunicorn[49315]: File "/var/www/html/web/venv/lib/python3.8/site-packages/gunicorn/arbiter.py", line 525, in reap_workers Feb 14 13:27:45 ip-88-99-22-33 gunicorn[49315]: raise HaltServer(reason, self.WORKER_BOOT_ERROR) Feb 14 13:27:45 ip-88-99-22-33 gunicorn[49315]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> Feb 14 13:27:45 ip-88-99-22-33 systemd[1]: gunicorn.service: Main process exited, code=exited, status=1/FAILURE Feb 14 13:27:45 ip-88-99-22-33 systemd[1]: gunicorn.service: Failed with result 'exit-code'. but when i run manage.py runserver it works base.py base settings DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get('DB_NAME'), 'USER': os.environ.get('DB_USER'), 'PASSWORD': os.environ.get('DB_PASS'), 'HOST': os.environ.get('DB_HOST'), 'PORT': os.environ.get('DB_PORT'), } } -
Per-record classifying dates by another table's names for those date ranges
Bit of a long-winded title, but essentially I've got Models for projects, with various foreign key sub-models for aspects of it. One related table is a Model where specifically named Date periods are defined, ie. a start and end date are provided and that date is then named by the user, and linked to a set project. It's easiest to think of it as maybe quarters based off that specific project's start date, but it's not always strictly quarters so I can't use conventional 'built-in' date tools. The user has to be able to define assymetrical reporting periods. Every project also has an Events model linked to it for specific occasions/happenings on the project, each with a date that I then need to stratify into these Project_Periods. Since it falls in a range of dates I can't just call up the usual foreign-key relations. The absolute easiest would be just to force the user to select a Project_Period for each Project_Event they add - but there's a lot of events and I want it to be set automatically without a user being able to mismatch it. I've thought of saving a date/calendar table for every project once the Project_Period is … -
Url in django template contains domain
Trying to insert {{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %} in an email as a link, but the result is something as http://domain//domain.localhost:8000/... which is an invalid link. When only outputting the {% url ... %} block, it begins with //domain.localhost:8000/reset..., which also occurs when trying with different url endpoints. -
TemplateSyntaxError at / 'xxx' is not a registered tag library. Must be one of:
... admin_list, admin_modify, admin_urls, cache, i18n, l10n, log, static, tz I have problems with creating a custom tag. I followed the instructions on the official Django documentation. I also copied the code but still get this error. The file it contains the tag is xxx.py that is in the templatetags dir. Is in app's root directory: app/ migrations static template templatetags __init.py__ admin.py apps.py models.py ....etc The tag in xxx.py: from django import template import datetime register = template.Library() @register.simple_tag def current_time(format_string): return datetime.datetime.now().strftime(format_string) The code in template index.html {% load xxx %} {% current_time "%d/%m/%Y %H:%M:%S %p" %} The traceback: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.1.5 Python Version: 3.9.0 Installed Applications: ['auctions', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template C:\Users\paren\OneDrive\Documenti\Programmazione\copia progetti corso harvard\CS50\project2\commerce\commerce\auctions\templates\auctions\index.html, error at line 1 'xxx' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls cache i18n l10n log static tz 1 : {% load xxx %} 2 : 3 : 4 : {% block body %} 5 : {% if message %} 6 : <div class="alert">{{message}}</div> 7 : {% endif %} 8 : <div class="main"> 9 … -
Deploying flask app as url in django site
I am using Apache2 I have my main app (django) in /opt/site and a docs app (flask) in /opt/docs I use a shared virtualenv in /opt/env I tried the following WSGIScriptAlias /docs/ /opt/docs/docs.wsgi WSGIScriptAlias / /opt/site/site/wsgi.py WSGIDaemonProcess my-wsgi user=www-data group=www-data python-path=/opt/env/lib/python3.8/site-packages:/opt/site:/opt/docs WSGIProcessGroup my-wsgi WSGIScriptReloading On I want site.com/docs/. I do not want docs.site.com. Unsurprisingly, the above does not work in routing /docs/ to my flask app. How do I do that? How to Use Django with Apache and mod_wsgi is not much help in this instance. Merging docs into the site codebase is not an option currently. Note: I know that my usage of WSGIDaemonProcess may also be outdated and can be replaced with WSGIPythonHome and WSGIPythonPath -
Doing a filter of Python string list against a Django model JsonField
I have the following Django JSONField data structure: searchtermlist = {'terms': ['test', 'cache', 'hello', 'as'], 'subscribed': ['product', 'test']} Given a searh string as such: searchterm = 'hello test' What I am doing now to match if JsonField subscribed field has a matching string to searchterm is: for user in CustomUser.objects.all() if user.searchtermlist and any(s in (searchterm).lower() for s in user.searchtermlist['subscribed']): # Has a match proceed pass My fear is that when the number of users gets large, I can't afford to be doing the objects.all() routine. Except that shouldn't be a problem? My question; is there any more efficient way to achieve the above using tools like Django QuerySet filter? -
ModuleNotFoundError: No module named 'members.urls'
I tried to start a app so that I can create a Login for my blog but I came by this error. So I thought to post a question in stack over flow. I hope yu can take some time to answer my question. This is the trace back error, Traceback (most recent call last): File "C:\Users\Selvi\AppData\Local\Programs\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Users\Selvi\AppData\Local\Programs\Python\Python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "C:\simpleblog\virt\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\simpleblog\virt\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\simpleblog\virt\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = checks.run_checks( File "C:\simpleblog\virt\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\simpleblog\virt\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\simpleblog\virt\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\simpleblog\virt\lib\site-packages\django\urls\resolvers.py", line 408, in check for pattern in self.url_patterns: File "C:\simpleblog\virt\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\simpleblog\virt\lib\site-packages\django\urls\resolvers.py", line 589, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\simpleblog\virt\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\simpleblog\virt\lib\site-packages\django\urls\resolvers.py", line 582, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\Selvi\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, … -
Get response in Django testing?
I have a problem with getting response in django testing this is the problem appear in terminal self.assertEquals(self.response.status_code, 200) AttributeError: 'StoreCreateTest' object has no attribute 'response' This is the command py manage.py test This is my def def test_store_create_view_status_code(self): self.assertEquals(self.response.status_code, 200) and this is my import from django.test import TestCase from configuration.models import Stores please help me getting this. -
MultiValueDictKeyError at /products/ 'page'
So I'm trying to use pagination, When I visit the page I get MultiValueDictKeyError at /products/ 'page', and when I go to localhost:8000/thatpage/?page=1 then I get TypeError at /products/ 'Paginator' object is not callable. This error occurs when i visit the page and i don't know what i'm doing wrong, Any help would be great. views.py def showproducts(request): oof = CartItem.objects.filter(user=request.user).values_list('book', flat=True) lmao = OrderItem.objects.filter(user=request.user).values_list('book', flat=True) hehe = CartItem.objects.filter(user=request.user) category = Category.objects.all() haha = Paginator(Book, 2) page = request.GET['page'] fianlprice = 0 for item in hehe: fianlprice += item.book.price # books = Book.objects.all() books = haha(page) return render(request, 'main/products.html', {'books':books, 'price':fianlprice, 'cart':oof, 'order':lmao, 'category':category}) products.html <h1>Products</h1> <h1>{{ error }}</h1> {% if user.is_authenticated %} <h1>Your cart currently costs ${{ price }}</h1> {% else %} <h1>Please login to view your cart</h1> {% endif %} <form method="GET" action="/search/"> <label>Choose a category</label> <select name="category" id="category"> <option value="All" selected>All</option> {% for name in category %} <option value="{{ name.name }}">{{ name.name }}</option> {% endfor %} </select> <input type="text" placeholder="Search here" name="search" id="search"> <button type="submit">Search</button> </form> {% for book in books %} <a href="{% url 'detailview' book.id %}"><h3>{{ book.name }}</h3></a> <img src= "/media/{{ book.image }}" alt=""> <p>{{ book.description }}</p> {% if not user.is_authenticated %} <p>Please login</p> {% … -
Django/channels chat api calls interfering with other backend api calls
For my application, I have set up a real-time chat messaging system implemented using django-channels. As per their official tutorial, I have my ASGI deployment server listening on localhost:8000 with a Websocket URL defined as follows: ws://127.0.0.1:8000/ws/chat/. I call my other backend endpoints from my frontend React application through axios. The issue I'm currently facing is that my websocket endpoints are interfering with my other backend endpoints. Here is quick summary of how I have things set up: The chat component is set it to render on all routes. My 'Dashboard' component is being served through a specific route. In my 'Dashboard' component, I utilise my useEffect hook to fetch data whenever a particular state variable changes. This data fetches information from my backend endpoint. Here is a description of the problem: Whenever my state variable updates, the fetch logic executes. While these requests go through, if I send a message through my chat component (which in turns triggers the websocket endpoint) the messages do not come through instantaneously. Upon close inspection, I've noticed that the chat messages wait for the backend endpoint requests to go through and then only do the websocket messages come through. How can I resolve … -
Proper way of making an external API call based on given data - DRF
I am trying to save location data based on given IP address using Django REST Framework. So, I have a few questions about the sturcture of this process. The program should call external API based on given data and after that it will create a new object in the database. The question is - How I can pass the given IP address to the call function? I tried to use serializers.CharField and take the value from there with validated_data but it throws an attribute error after creating a new object. And where I must use the create() function in order to save response data? I just need to know what is the proper way of passing data(given IP address) to the create() function? serializers.py from rest_framework import serializers from core.models import GeoLocation from .services import get_location class GeoLocationSerializer(serializers.Serializer): url = serializers.CharField(max_length=255) def create(self, validated_data): url = validated_data.get("url", None) validated_data.pop('url') geo_data = get_location(url) return GeoLocation.objects.create( ip=geo_data['ip'], country_name=geo_data['country_name'], region_code=geo_data['region_code'], city=geo_data['city'], latitude=geo_data['latitude'], longitude=geo_data['longitude'], zip_code=geo_data['zip'] ) views.py from rest_framework import viewsets, mixins, generics from geolocation import serializers from core.models import GeoLocation from geolocation.services import get_location class GeoLocationViewSet(viewsets.GenericViewSet, mixins.ListModelMixin, mixins.CreateModelMixin): queryset = GeoLocation.objects.all() serializer_class = serializers.GeoLocationSerializer def get_queryset(self): return self.queryset.order_by('-id') def perform_create(self, serializer): serializer.save()