Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How i Display form errors with django and ajax
When i console these are my errors: [error] for username: Please fill the username field usersignup:179 [error] for first_name: Please fill the first name field usersignup:179 [error] for last_name: Please fill the last name field usersignup:179 [error] for email: Please fill the email field usersignup:179 [error] for password: Please fill the password field usersignup:179 [error] for password2: Please fill the confirm password field How i display my response errors in span tag according to all keys in html file. Please help and why these are repeated when i submit request again and again. How i display my response errors in span tag according to all keys in html file. Please help and why these are repeated when i submit request again and again. How i display my response errors in span tag according to all keys in html file. Please help and why these are repeated when i submit request again and again. My script: This is my script resukt will be ok when i console but how i display i don't know jquery and ajax. $(document).ready(function () { var $myForm = $('#myform') $myForm.submit(function (event) { event.preventDefault() var $formData = $(this).serialize() var $thisURL = $myForm.attr('data-url') || window.location.href // or set … -
Loading Django static files into css styles
This is the part I am referring to in the question: <div class="my-class" style="background: url({% static 'no_profile_pic/no-profile-pic.png' %}) center / cover no-repeat;"></div> It is finding it: [20/Aug/2020 12:54:30] "GET /static/no_profile_pic/no-profile-pic.png HTTP/1.1" 200 41235 However, it is not loading on my webpage. I have {% load static %} in my html file. Here is my settings file: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] Any ideas anyone? -
Deploying Django with channels and asgi to heroku
I'm trying to update my Django Heroku server to run asgi as well and consume a WebSocket. I updated the settings, Procfile, asgi file But I can't seem to be able to consume the WebSocket, I get an error: 2020-08-20T12:55:16.708582+00:00 app[web.1]: 2020-08-20 12:55:16,708 INFO "10.11.225.205" - - [18/Jan/1970:07:49:50 +0000] "GET /ws/camera_online/connect/ HTTP/1.1" 404 179 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36" 2020-08-20T12:55:16.708835+00:00 app[web.1]: 2020-08-20 12:55:16,708 DEBUG HTTP response complete for ['10.11.225.205', 15753] 2020-08-20T12:55:16.708954+00:00 app[web.1]: 10.11.225.205:15753 - - [20/Aug/2020:12:55:16] "GET /ws/camera_online/connect/" 404 179 2020-08-20T12:55:16.710071+00:00 heroku[router]: at=info method=GET path="/ws/camera_online/connect/" host=scr-rivendell.herokuapp.com request_id=faa1ffe7-1bbc-4906-a37c-c468a15b4131 fwd="5.102.193.183" dyno=web.1 connect=0ms service=8ms status=404 bytes=326 protocol=https 2020-08-20T12:56:16.356480+00:00 app[web.1]: 10.63.224.151:18254 - - [20/Aug/2020:12:56:16] "WSCONNECTING /ws/camera_online/connect/" - - 2020-08-20T12:56:16.356714+00:00 app[web.1]: 2020-08-20 12:56:16,356 DEBUG Upgraded connection ['10.63.224.151', 18254] to WebSocket 2020-08-20T12:56:16.533805+00:00 app[web.1]: 2020-08-20 12:56:16,533 ERROR Exception inside application: Django can only handle ASGI/HTTP connections, not websocket. 2020-08-20T12:56:16.533809+00:00 app[web.1]: Traceback (most recent call last): 2020-08-20T12:56:16.533809+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/daphne/cli.py", line 30, in asgi 2020-08-20T12:56:16.533810+00:00 app[web.1]: await self.app(scope, receive, send) 2020-08-20T12:56:16.533811+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/django/core/handlers/asgi.py", line 144, in __call__ 2020-08-20T12:56:16.533812+00:00 app[web.1]: raise ValueError( 2020-08-20T12:56:16.533813+00:00 app[web.1]: ValueError: Django can only handle ASGI/HTTP connections, not websocket. 2020-08-20T12:56:16.534169+00:00 app[web.1]: 2020-08-20 12:56:16,533 INFO failing WebSocket opening handshake ('Internal server error') 2020-08-20T12:56:16.534659+00:00 app[web.1]: 2020-08-20 12:56:16,534 … -
Django First Aplication
After starting python manage.py run server throws such an error, before creating the directory, the server page started correctly. M:\Project_Django\mysite>python manage.py runserver Performing system checks... Unhandled exception in thread started by <function wrapper at 0x043E18F0> Traceback (most recent call last): File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Python27\lib\site-packages\django\core\management\commands\runserver.py", line 124, in inner_run self.check(display_num_errors=True) File "C:\Python27\lib\site-packages\django\core\management\base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "C:\Python27\lib\site-packages\django\core\management\base.py", line 346, in run_checks return checks.run_checks(**kwargs) File "C:\Python27\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Python27\lib\site-packages\django\core\checks\urls.py", line 16, in check_url_config return check_resolver(resolver) File "C:\Python27\lib\site-packages\django\core\checks\urls.py", line 26, in check_resolver return check_method() File "C:\Python27\lib\site-packages\django\urls\resolvers.py", line 256, in check for pattern in self.url_patterns: File "C:\Python27\lib\site-packages\django\utils\functional.py", line 35, in get res = instance.dict[self.name] = self.func(instance) File "C:\Python27\lib\site-packages\django\urls\resolvers.py", line 407, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Python27\lib\site-packages\django\utils\functional.py", line 35, in get res = instance.dict[self.name] = self.func(instance) File "C:\Python27\lib\site-packages\django\urls\resolvers.py", line 400, in urlconf_module return import_module(self.urlconf_name) File "C:\Python27\lib\importlib_init.py", line 37, in import_module import(name) File "M:\Project_Django\mysite\mysite\urls.py", line 17, in from django.urls import path, include,strona ImportError: cannot import name path -
Testing the HomeTests class in tests.py has an error in line 29
I am continuing the Inspections/Defects project that I am doing for fun. On line 29, the error says that HomeTests has no attribute Inspection, and I am trying to find out why. Here is the tests.py file. class HomeTests(TestCase): def setUp(self): Inspection.objects.create(workOrderNum='123DER', partNumber='sd', customerName="RYANTRONICS", qtyInspected=10,qtyRejected=3) url = reverse('home') self.response = self.client.get(url) def test_home_view_status_code(self): self.assertEquals(self.response.status_code, 200) def test_home_url_resolves_home_view(self): view = resolve('/') self.assertEquals(view.func, home) def test_home_url_resolves_home_view(self): view = resolve('/') self.assertEquals(view.func, home) def test_home_view_contains_link_to_topics_page(self): inspection_topics_url = reverse(inspection_topics, kwargs={'pk': self.inspection.pk}) -> error occurs at this line self.assertContains(self.response, 'href="{0}"'.format(inspection_topics_url)) I also have been looking in my views.py file to see if it was the source of the problem. I followed the guide at Django URLs Advanced but I had missed something. Here is the views.py file in case you wanted to look at it. from django.shortcuts import render,get_object_or_404 from .models import Inspection # Create your views here. def home(request): inspections = Inspection.objects.all() return render(request, 'home.html', {'inspections': inspections}) def inspection_topics(request, pk): inspection = get_object_or_404(Inspection, pk=pk) return render(request, 'topics.html', {'inspection': inspection}) The views.py has two files, home.html and topics.html. Here they are. {% load static %}<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Final Inspection Report</title> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> </head> <body> <div class="container"> <ol class="breadcrumb my-4"> … -
Django inconsistent queries on oracle DB
i'm having really hard times debugging some queries in my project. They look like this: hosts = Hosts.objects.filter(...) query = reduce( operator.or_, ( Q(packages_set__name=name, packages__version__in=versions) for name, versions in some_versions_dict ) ) hosts = dc_hosts.filter(query).annotate( num_packages=Count('packages_set') ).filter( num_packages=len(some_versions_dict) ) and they run really inconsistently, sometimes they finish just fine and sometimes they stay stucked and does not finish. I expect it has something to od with this because I don't really know how to fix that so I just use queries later in a way which does not trigger it (.values_list(...)). Is there some other way how to solve my previous question or is there any way how could I fix it for my db? Thanks for you help this is work related and its driving me crazy currently. -
Ingesting json dump in AWS RDS
I made a django application and want to use an sqlite3 db for local development and a Amazon MySql RDS DB for production. My webserver is running on an EC2 Instance. I have exported the data from the sqlite3 db to a json object using python manage.py dumpdata > datadump.json Is there a way to import this JSON into a MySql DB in RDS or should I tackle this problem in a different manner? Thanks in advance :) -
Python Script integration in a Website (Django)
I have 2 python scripts that I want to implement into a website using Django. They are both based around emails. The first is to check the MX of multiple emails with different variations, and the second is to send out emails to all of the emails provided. How do I implement these scripts below into a Django website? I have a friend who wants to use them, and I want to give him a website rather than have to run it locally. Script #1 from validate_email import validate_email # inputs for verification first_name_input = input(" Enter first name") last_name_input = input(" Enter last name") name = first_name_input + last_name_input domain_input = input(" Enter an email domain(ex. ‘gmail.com’): ") # email variations list email1 = name + "@" + domain_input email2 = first_name_input + "@" + domain_input email3 = first_name_input + last_name_input[0] + "@" + domain_input email4 = first_name_input[0] + last_name_input + "@" + domain_input email5 = first_name_input + "." + last_name_input + "@" + domain_input email6 = first_name_input + "-" + last_name_input + "@" + domain_input email7 = last_name_input + "." + first_name_input + "@" + domain_input email8 = last_name_input + first_name_input + "@" + domain_input email9 = first_name_input … -
django show user information in regroup only to user
Making a web app that lets a user log workouts. I have a page that groups all the logged workouts together by date, using regroup and a for 2 loops. How do I only show the user that is logged in information their own information. When I try to use a 3rd for loop (ex. {% for workout in workouts%}, {% if workout.person == user %})I just get 2 tables with the same information. Heres the code in my template. {% regroup workouts by date_of as dateof %} {%for date_of in dateof %} <table class="table table-striped table-dark mt-3"> <thead> <th scope="col">{{date_of.grouper}}</th> </thead> <thead> <tr> <th scope="col">Body Part</th> <th scope="col">Exercise</th> <th scope="col">Weight(lbs)</th> <th scope="col">Sets</th> <th scope="col">Reps</th> </tr> </thead> <tbody> {% for workout in date_of.list %} <tr> <td>{{workout.body_part}}</td> <td>{{workout.exercise}}</td> <td>{{workout.weight}}</td> <td>{{workout.sets}}</td> <td>{{workout.reps}}</td> </tr> {% endfor %} </tbody> </table> {% endfor %} -
Group multiple rows by multiple fields and replace one field with it total sum Django
Let's assume that I have such model in Django represented with below table: Name Year Month Project Name City Total Joe Doe 2020 7 Project_A SomeCity 10 Joe Doe 2020 7 Project_A SomeCity 30 Joe Doe 2020 7 Project_A SomeCity 30 Joe Doe 2020 8 Project_A SomeCity 10 Joe Doe 2020 8 Project_A SomeCity 30 Joe Doe 2020 8 Project_A SomeCity 30 The result which I'm expecting is: Name Year Month Project Name City Total Joe Doe 2020 7 Project_A SomeCity 70 Joe Doe 2020 8 Project_A SomeCity 70 I've tried to achieve this using: Model.objects.values().order_by('Project Name', 'Month').annotate(percentage=Sum('percentage')) Unfortunately result of this operation is slightly different from expected one: Name Year Month Project Name City Total Joe Doe 2020 7 Project_A SomeCity 60 Joe Doe 2020 7 Project_A SomeCity 10 Joe Doe 2020 8 Project_A SomeCity 60 Joe Doe 2020 8 Project_A SomeCity 10 At first look I thought that those records are just different and that's why it's not grouped together, but after looking thoroughly I see group_by should work on those. So, what could be problem here? -
Cannot activate my virtualenv in project folder, I get the error arguments required dest. (windows 10, Powershell)
Going through FreeCodeCamp Django: https://www.youtube.com/watch?v=F5mRW0jo-U4&t I have installed my virtual Environment on Windows 10 using Powershell, but when trying to activate my virtualenv I get the error arguments required dest. Interestingly when I type virtualenv --version, in my project folder it will return the version. However when I type just virtualenv, I receive the error in the title. I am using powershell. Having trouble activating / deactivating.. -
DRF, Djongo and log4mongo
I have setup log4mogo to capture django logs and this is working and putting all the logs into the database correctly. I would like to expose these as part of the drf api and have tried to setup djongo as the orm for this access to the mongo db, but for some reason I get nothing back, I would like to know if someone has any ideas on this. In terms of error, I don't get one I get back an empty dict. So it would seem as the query is coming back with nothing, but there is entries in the db. I am lost as to a direction to go in so any thoughts would be welcome. Model: import djongo.models class Logs(djongo.models.Model): _id = djongo.models.CharField(max_length=400) thread = djongo.models.CharField(max_length=400) level = djongo.models.CharField(max_length=400) timestamp = djongo.models.CharField(max_length=400) threadName = djongo.models.CharField(max_length=400) module = djongo.models.CharField(max_length=400) loggerName = djongo.models.CharField(max_length=400) lineNumber = djongo.models.CharField(max_length=400) message = djongo.models.CharField(max_length=4000) fileName = djongo.models.CharField(max_length=400) method = djongo.models.CharField(max_length=400) View: class UserViewSet(rest_framework.viewsets.ReadOnlyModelViewSet): queryset = logger_api.models.Logs.objects.using('logging_api').all() serializer_class = logger_api.serializers.LogSerializer settings: DATABASES = { 'logging_api': { 'ENGINE': 'djongo', 'NAME': 'logging', 'ENFORCE_SCHEMA': False, 'CLIENT': { 'host': ********************, 'port': ********************, 'username': ***********, 'password': ***********, 'authSource': *********, 'ssl': True } } } -
django rest framework using action decorator to add path to view financial statement in url
I need the following URLs to work where ticker would stand for a stock ticker such as AAPL or AMZN, and is stands for income_statement. localhost:8000/stocks/ localhost:8000/stocks/<TICKER>/ localhost:8000/stocks/<TICKER>/is/ in the views.py file below I am using a viewset which and router which automatically configures the first two urls above, and for the third url I am using the action decorator with methods=['get'] and url_path="is" to achieve the localhost:8000/stocks/<TICKER>/is/ path. the third URL is configured, but I get a key error for ticker when entering the following url in the browser: localhost:8000/stocks/AAPL/is/ what am I doing wrong here ? models.py class Stock(models.Model): id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) ticker = models.CharField(max_length=10, unique=True, primary_key=True) slug = models.SlugField(default="", editable=False) def save(self, *args, **kwargs): value = self.ticker self.slug = slugify(value, allow_unicode=True) super().save(*args, **kwargs) def __str__(self): return self.ticker class Meta: verbose_name = "stock" verbose_name_plural = "stocks" ordering = ["ticker"] class IncomeStatement(models.Model): ticker = models.ForeignKey( Stock, on_delete=models.CASCADE, related_name="income_statements" ) date = models.DateField(default=datetime.date.today) PERIODICITY_CHOICES = [("ANNUAL", "ANNUAL"), ("QUARTERLY", "QUARTERLY")] periodicity = models.CharField( max_length=10, choices=PERIODICITY_CHOICES, default="annually" ) net_income_continuous_operations = models.DecimalField( max_digits=20, decimal_places=2 views.py class StockViewSet(viewsets.ModelViewSet): queryset = Stock.objects.all() serializer_class = StockSerializer # lookup_field = "slug" @action(detail=True, methods=["get"], url_path="is", url_name="is") def get_income_statement(self, request, *args, **kwargs): income_statement = self.queryset.get(ticker=kwargs["ticker"]).select_related( "income_statements" ) … -
Python3.8 Django 3 Method Not Allowed: /delete/DPDC-001 , when I confirm delete, these error appear. Help me, please
[Confirm_delete.html] <form action="{{ object.ref }}" method="post"> {% csrf_token %} <p>Are you sure you want to delete "{{ object }}"?</p> <input type="submit" value="Confirm"> </form> [urls.py] urlpatterns = [ path('delete/<pk>', login_required(DeleteView.as_view()), name='s_Delete'), ] [View.py] class DeleteView(DetailView): model = Warehouse template_name = "Slot_Confirm_Delete.html" def get_object(self, queryset=None): obj = super(DeleteView, self).get_object() if not obj.op_user == self.request.user.id: raise Http404 return obj def get_success_url(self): return reverse('success') -
Django Static Files(CSS) don't link with template
Just as the title says, static files somehow are not loading up in my template. I've tried working on it and looking at similar StackOverflow questions but I can't find a solution. I tried debugging it using browser's dev tools. I tried opening the CSS file from there but it just leads me to this error. This leads me to the conclusion that Django doesn't seem to find base.css inside the static folder. I've already done manage.py collectstatic so there shouldn't be a problem. Thanks! Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/static/static/base.css 'static\base.css' could not be found You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. settings.py # Static files (CSS, JavaScript, Images) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') template {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'static/base.css' %}"> -
Unable to Fetch particular product for each category
I am always getting all the food items in all Categories. I want to display each Category with each food item. Need to display Category with item belonging to that Category. Please someone help me on this issue to resolve. I have tried looking over internet but couldn't find the solution to it #Models.py class Category(models.Model): category_name = models.CharField(max_length=50) def __str__(self): return self.category_name class Menu(models.Model): dish_name = models.CharField(max_length=200, verbose_name='Name of Dish') Desc = models.TextField(verbose_name='Dish Description') Amount = models.IntegerField(null=False, blank=False, verbose_name='Amount of Dish') date_posted = models.DateTimeField(default=timezone.now, verbose_name='Dish Date Posted') category = models.ForeignKey(Category, on_delete=models.CASCADE, default=1) def __str__(self): return self.dish_name #Views.py def menu(request): products = Menu.objects.all() categories = Category.objects.all() data = {} data['products'] = products data['categories'] = categories template = 'food/menu.html' return render(request, template, data) #html {% for category in categories %} {% if categories %} <div class="col-xs-12 col-sm-6"> <div class="menu-section"> <h2 class="menu-section-title">{{ category.category_name }}</h2> <hr> {% endif %} {% for i in products %} <div class="menu-item"> <div class="menu-item-name">{{ i.dish_name}}</div> <div class="menu-item-price">Rs {{ i.Amount}}</div> <div class="menu-item-description">{{ i.Desc}}</div> </div> {% endfor %} </div> </div> {% endfor %} ` -
How to pass the listview of another model and detailview of another model in same template
i want to pass the listview of post model and detailview of movies model in the same template using class based views class MoviesDetailListView(ListView): model = Movies template_name = 'blog/post_list.html' context_object_name = 'posts' paginate_by = 10 def get_queryset(self): user = get_object_or_404(Movies, name=self.kwargs.get('name')) return Post.objects.filter(name=user).order_by('-date_posted') want to print detailview of model Movies from pk of movies passed in urls i passed the movies name and pk from url but cant get other detail like in detailview we get from pk urls.py urlpatterns = [ path('about/', AboutView.as_view(), name='blog-about'), path('user/<str:username>/', UserPostListView.as_view(), name='user-post'), path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'), path('post/new/<str:name>/<int:id>/', PostCreateView.as_view(), name='post-create'), path('', MoviesListView.as_view(), name='blog-home'), path('<str:name>/<int:pk>/',MoviesDetailListView.as_view(), name='movies-detail'), path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'), path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'), -
Can I use edit django cms PlaceholderField before saving (publishing) my page outside of django cms?
I use the placeholder fields outside of the regular django cms. I wish to edit placeholder fields before publishing something. The documentation states: However, any PlaceholderFields in it will only be available for editing from the frontend. And: If you add a PlaceholderField to an existing model, you’ll be able to see the placeholder in the frontend editor only after saving the relevant instance. The only solution I can think of to edit the placeholder is adding a stage of published/unpublished and make unpublished only visible to some with the right access. Or is there a way to "hack" placeholder editing in the admin field? Or some other solution? -
why static files and images are not working on my django s3 bucket project?
while trying to use s3 bucket on my local django project it does not work, after moving the static files and images to the s3 bucket it is not rendering any of them. my project structure goes like this Project |-> app-name |-> static | |-> img "folder of png images" | |-> app-name | |-> css "folder contain all css files" | |-> js "folder contains all js files" | |-> img "contains images used for styling" |-> project name |-> manage.py in settings.py "media, static and s3 bucket settings are set like this" STATIC_URL = '/static/' MEDIA_URL = '/img/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] MEDIA_ROOT = os.path.join(BASE_DIR, 'static/img') AWS_ACCESS_KEY_ID = '***************' AWS_SECRET_ACCESS_KEY = '***************' AWS_STORAGE_BUCKET_NAME = 'bucket-name' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None AWS_S3_HOST = 's3.us-east-2.amazonaws.com' AWS_S3_REGION_NAME = 'us-east-2' AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' when I try to inspect element to see the src in images or links for css I can see them like this "https://bucket-name.s3.amazonaws.com/gallery/css/bootstrap.min.css" or for image "https://bucket-name.s3.amazonaws.com/stockholm_Samit.jpg" could you please help me with this? -
I am getting a response error in my tests.py file
I am getting an error in my tests.py file when testing my Inspection class. It is located in tests.py and it says that the syntax is invalid on line 30. class HomeTests(TestCase): def setUp(self): Inspection.objects.create(workOrderNum='123DER', partNumber='sd', customerName="RYANTRONICS", qtyInspected=10,qtyRejected=3) url = reverse('home') self.response = self.client.get(url) def test_home_view_status_code(self): self.assertEquals(self.response.status_code, 200) def test_home_url_resolves_home_view(self): view = resolve('/') self.assertEquals(view.func, home) def test_home_url_resolves_home_view(self): view = resolve('/') self.assertEquals(view.func, home) def test_home_view_contains_link_to_topics_page(self): inspection_topics_url = reverse(inspection_topics, kwargs={'pk': self.inspection.pk} self.assertContains(self.response, 'href="{0}"'.format(inspection_topics_url)) -> this line is the problem, invalid syntax. Can someone show me what this error means, and how to fix it? I never got this error before when I made the Board class on a tutorial site. -
Issue with deploying Django on Heroku
Hi Guys I tried deploying my first django on heroku and i am frequently facing issues with the deployment. I think this is something to do with my settings.py file. I am clearly unaware with this issue python manage.py collectstatic--noinput , but i have written everything . Thanks in Advance for help and ideas. $ python manage.py collectstatic--noinput 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 "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 187, in handle collected = self.collect() File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 104, in collect for path, storage in finder.list(self.ignore_patterns): File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/finders.py", line 130, in list for path in utils.get_files(storage, ignore_patterns): File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/utils.py", line 23, in get_files directories, files = storage.listdir(location) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/files/storage.py", line 316, in listdir for entry in os.scandir(path): FileNotFoundError: [Errno 2] No such file or directory: '/tmp/build_6613795b_/static' ! Error while running '$ python manage.py collectstatic --noinput'. See traceback above for details. You may need to update application code to resolve this error. Or, you can disable collectstatic for this … -
Fetch data from Server using Jquery AJAX and then trying to make a url using Jinja 2 format
Hello Everyone i am Trying to Get Data Using Api from the Server and Then Render it in Jinja2 Template Page but i dont know how to pass the item.id in it. the Code is bellow kindly help me with this $.get("http://127.0.0.1:8000/api/product",function(data){ $.each(data,function(index,item){ var obj="<div class='col-lg-3'>"+ "<div class='card shop-hover'>"+ "<img src="+item.image[0]+" style='height:250px;' alt='wrapkit' class='img-fluid' />"+ "<div class='card-img-overlay align-items-center'>"+ "<a href='{% url 'Checkout' item.id %}' class='btn btn-md btn-info-gradiant'>Buy Now</a>"+ "</div>"+ "<span class='label label-rounded label-success'>Sale</span>"+"</div>"+ "<div class='card'>"+ "<h6><a href='#' class='link'>"+item.Name+"</a></h6>"+ "<h6 class='subtitle'>"+item.BottomHeading+"</h6>"+ "<h5 class='font-medium m-b-30'>"+item.UnitPrice+" / <del class='text-muted line-through'>$225</del></h5>"+ "</div>"+ "</div>"; $(".shop-listing").append(obj); }); }); And this is the line of Code Where i am getting Trouble "<a href='{% url 'Checkout' item.id %}' class='btn btn-md btn-info-gradiant'>Buy Now</a>" Thanks in Advance! -
resolve the metaclass conflict
Actually I got the following error and honestly, I'm a newbie with the metaclass errors if anyone could help me to solve the following error. view.py class EditView(CustomizedRequiredMixin(account_type=Account.SELLER_ACCOUNT), UpdateView): pass decorators.py class CustomizedRequiredMixin(AccessMixin): def __init__(self, account_type=None): self.account_type = account_type def dispatch(self, request, *args, **kwargs): if not request.user.is_authenticated: return self.handle_no_permission() if self.user_has_permissions(request, self.account_type): return super().dispatch(request, *args, **kwargs) raise Http404 def user_has_permissions(self, request, account_type): account = request.user.account if account_type == Account.SELLER_ACCOUNT: return account and account.account_type == Account.SELLER_ACCOUNT if account_type == Account.BUYER_ACCOUNT: return account and account.account_type == Account.SELLER_ACCOUNT got the following error: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases -
How to create superuser in django using Unix Environment
when I'm using Visual Studio Code for the Django project in windows Environment, for creating a superuser I'm using the below command. (test) C:\Users\SAHEB\projects\project>python manage.py runserver this same Django project is deployed in Unix server, below is the path where whole project is deployed. /apps/sample/python but python manage.py runserver this command is not working in Unix server from this path, what's the solution -
For Update operation how can you only update some data Django and not all?
I want to update only some of the data in a model. Suppose a Django model is as such: class Test(model.models): name = models.CharField(max_length=10) desc = models.CharField(max_length=100) When I want to update the data using a view in Django Rest Framework, how can I update only name and not description. Right now if I send a PUT request it throws an error that desc is a required field. Here is my view? class Test_ListView(APIView): def get(self, request, format=None): db_data = Test.objects.all() serializer = Test_Serializer(db_data, many=True) return Response(serializer.data) def post(self, request, format=None): serializer = Test_Serializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class Test_DetailView(APIView): def get_object(self, pk): db_data = Test.objects.get(pk=pk) try: return db_data except Test.DoesNotExist: raise Http404 def get(self, request, pk, format=None): db_data = self.get_object(pk) serializer = Test_Serializer(db_data) return Response(serializer.data) def put(self, request, pk, format=None): db_data = self.get_object(pk) serializer = Test_Serializer(db_data, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, pk, format=None): db_data = self.get_object(pk) db_data.delete() return Response(status=status.HTTP_204_NO_CONTENT)