Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Multiple apps in git remote and how to specify to one app
I was working with another developer on my git repository and he pushed his work to me after forking. When I wanted to deploy the change of our work to Heroku, with git push Heroku master I get the following error. Previously it was always working when I deploy. I need to specify the app, but don't know how. I am using Django and VScode. This is the following error: Error: Multiple apps in git remotes › Usage: --remote heroku-staging › or: --app radiant-escarpment-03215 › Your local git repository has more than 1 app referenced in git remotes. › Because of this, we can't determine which app you want to run this command against. › Specify the app you want with --app or --remote. › Heroku remotes in repo: › beneluxbilal (heroku) › radiant-escarpment-03215 (heroku-staging) I already tried with --app but it seems not to work for me. -
Django set default empty url
I'm trying to learn Django and I'm following Corey Shafer's tutorials (https://www.youtube.com/watch?v=a48xeeo5Vnk), but when I try to make two different pages, I get automatically directed to the one with an "empty address": In his: /Blog /urls.py it looks like this: from django.conf.urls import path from . import views urlpatterns = [ path('', views.home, name='blog-home'), path('about/', views.about, name='blog-about'), ] and when he goes to localhost:8000/blog/about, the page displays correctly When I try to imitate his code for blog/urls.py: from django.conf.urls import url from . import views urlpatterns = [ url(r'', views.home, name='blog-home'), url(r'^about/', views.about, name='blog-about'), ] the result of the localhost:8000/blog/about is the content of views.home, and not views.about. The following works correctly, when I write a name instead of an empty string: urlpatterns = [ url(r'^home', views.home, name='blog-home'), url(r'^about/', views.about, name='blog-about'), ] But I don't understand why it worked in a previous version, why it won't work now, and what could fix it -
Can I register a setting with a default value then use that setting in a model's field?
Is there any way I can @register_setting a setting with a default value, then use that setting in the default value for a field? I'd like my users to be able to specify a global tax rate default, but change it per location as needed. I'm already using a setting in another function on the same model, but believe the issue might be that it's not within a function in this case. I tried specifying default=8.25 in the constructor for default_sales_tax_rate, but that doesn't seem to work. I am getting a NameError: name 'DefaultSalesTaxRate' is not defined error. @register_setting class DefaultSalesTaxRate(BaseSetting): default_sales_tax_rate = models.DecimalField( max_digits=4, decimal_places=2, help_text="Default Sales Tax Rate", default=8.25 ) locations.models.LocationPage(Page) location_sales_tax_rate = models.DecimalField(max_digits=4, decimal_places=2, default=DefaultSalesTaxRate.objects.first().default_sales_tax_rate) I've tried assigning a variable sales_default to 8.25 if DefaultSalesTaxRate.objects.all().count() == 0, but that didn't work either. I am thinking maybe a hook or a signal to instantiate the setting in the table if it's not present, but am not sure where to hook into or where to call the signal. -
Django Staticfiles Is Saved In An Unexpected Location
I followed the documentation at Django 2.2 Static Setup 2: https://docs.djangoproject.com/en/2.2/howto/static-files/ but to my surprise, anytime I run manage.py collectstatic it keeps storing the static files in the C:/ not inside the project static folder. The image below explains further what I am saying The settings of static file -
React Native 401 Unauthorized Error From DRF
My restful api (Django Rest API) on heroku works fine locally. It's currently deployed on heroku. I'm using react native app to interact with the API. Each time i try retrieving the details of authenticated user, first the details is returned just after that it throws 401 error.... The flow of my application is After successful authentication Save user's token Retrieve authenticated user's details Authentication passes fine (authenticated user's details is also outputted on the log) but the bit of getting user's details fails with 401 unauthorized Here is my server log on heroku 2020-12-21T22:33:45.106941+00:00 app[web.1]: 10.43.233.181 - - [21/Dec/2020:22:33:45 +0000] "POST /api/accounts/token/ HTTP/1.1" 200 441 "-" "jisee/1 CFNetwork/1206 Darwin/20.1.0" 2020-12-21T22:33:45.232882+00:00 heroku[router]: at=info method=PUT path="/api/accounts/token/device/" host=webapp.herokuapp.com request_id=4a5a06f9-ec50-4ecb-879e-20805784ba5c fwd="86.182.91.70" dyno=web.1 connect=0ms service=15ms status=200 bytes=255 protocol=https 2020-12-21T22:33:45.106757+00:00 heroku[router]: at=info method=POST path="/api/accounts/token/" host=webapp.herokuapp.com request_id=a4b7e5f6-1333-4b82-b180-12850391c382 fwd="86.182.91.70" dyno=web.1 connect=1ms service=399ms status=200 bytes=724 protocol=https 2020-12-21T22:33:45.232905+00:00 app[web.1]: 10.43.233.181 - - [21/Dec/2020:22:33:45 +0000] "PUT /api/accounts/token/device/ HTTP/1.1" 200 0 "-" "jisee/1 CFNetwork/1206 Darwin/20.1.0" 2020-12-21T22:33:45.368821+00:00 app[web.1]: Unauthorized: /api/users/details/ 2020-12-21T22:33:45.369671+00:00 app[web.1]: 10.43.233.181 - - [21/Dec/2020:22:33:45 +0000] "GET /api/users/details/ HTTP/1.1" 401 58 "-" "jisee/1 CFNetwork/1206 Darwin/20.1.0" 2020-12-21T22:33:45.369458+00:00 heroku[router]: at=info method=GET path="/api/users/details/" host=webapp.herokuapp.com request_id=1de46c11-fa6d-4ebd-984e-40191239f031 fwd="86.182.91.70" dyno=web.1 connect=0ms service=5ms status=401 bytes=393 protocol=https NOTICE THIS BIT HERE ( Which shows that the user is authorized … -
Django ajax post method dont redirect
im following a tuto on how ajax work on Django, its my first time with ajax and im facing a little problem ,the data insertion is working but the success ajax dont redirect corectly, and thank you for the help this the code views.py : class exo(View): def get(self, request): form = ExerciseForm() tasks = task.objects.all() context = { 'form': form, 'tasks': tasks } return render(request, 'coach/test.html', context=context) def post(self, request): form = ExerciseForm() if request.method == 'POST': form = ExerciseForm(request.POST) print(form) if form.is_valid(): print('adding task', form) new_exrercise = form.save() return JsonResponse({'task': model_to_dict(new_exrercise)}, status=200 ) else: print('not adding task') return redirect('exo') ajax function : $(document).ready(function(){ $("#addExercise").click(function() { var serializedData = $("#TaskForm").serialize(); $.ajax({ url: $("TaskForm").data('url'), data : serializedData, type: 'post', success: function(response) { $("#taskList").append('<div class="card"><div class="card-body">'+ response.task.name +'<button type="button" class="close float-right"> <span aria-hidden="true">&times;</span></button></div></div>'); } }) }); }); html content : <form class="submit-form" method="post" id="TaskForm" data-url="{% url 'session' %}"> {% csrf_token %} <div class="form-group"> {% for field in form %} <div style="margin-bottom: 2rem;"></div> {{field}} {% endfor %} <div style="margin-bottom: 2rem;"></div> <button type="submit" class="btn btn-success dropdown-toggle " id="addExercise">Confirm</button> </div> </form> this is what i get (i get an object and nothing else ) output image when i comeback to the page exo the … -
How to set a field equal to a related model's foreign key on save() Django
I have three models, LocationPage, Customer, and WorkOrder. LocationPage has a city_name CharField. Customer and WorkOrder both have a customer_city and service_city ForeignKey to LocationPage, respectively. On creation of a WorkOrder when service_city is left blank I want to update service_city with the same ForeignKey as belongs to Customer's customer_city. However, when I try this, I get an OperationalError at /admin/workorders/workorder/create/ table workorders_workorder has no column named service_city_id locations.models.LocationPage class LocationPage(Page): """Location page model.""" location_city = models.CharField(max_length=100, blank=False, null=False) class Meta: verbose_name = "Location Page" verbose_name_plural = "Location Pages" def get_context(self, request): context = super().get_context(request) return context workorders.models.Customer class Customer(index.Indexed, ClusterableModel, models.Model): customer_city = models.ForeignKey('locations.LocationPage', on_delete=models.PROTECT, verbose_name="City", related_name="cust_city") referred_from = models.CharField(max_length=1, choices=REFERRAL_CHOICES, default='g') created = models.DateTimeField(editable=False, default=timezone.now()) modified = models.DateTimeField(null=True) class Meta: verbose_name = "Customer" verbose_name_plural = "Customers" def get_context(self, request): context = super().get_context(request) return context def save(self, *args, **kwargs): if not self.id: self.created = timezone.now() self.modified = timezone.now() return super(Customer, self).save(*args, **kwargs) workorders.models.WorkOrder class WorkOrder(index.Indexed, ClusterableModel, models.Model): """Workorder model.""" same_as_customer_address = models.BooleanField(blank=True, default=False, verbose_name="Same as Customer") service_city = models.ForeignKey('locations.LocationPage', on_delete=models.PROTECT, help_text="Dallas", verbose_name="City", blank=True, null=False) related_customer = ParentalKey('Customer', related_name='workorders', on_delete=models.CASCADE, null=False, verbose_name="Customer") def save(self, *args, **kwargs): if self.same_as_customer_address: self.service_address = self.related_customer.customer_address self.service_city = self.related_customer.customer_city self.service_state = self.related_customer.customer_state self.service_zip = self.related_customer.customer_zip … -
How to create bitmap indexes in Django
What is the canonical way of creating bitmap indexes for in Django? Customized migration using RunSQL opeartion? How to maintain the indexes afterwards also raw queries? class Migration(migrations.Migration): dependencies = [ # Dependencies to other migrations ] operations = [ migrations.RunSQL( sql="CREATE BITMAP INDEX name ON table (column);" reverse_sql = ... ), ] -
Cloning a Django project has now meant that my CSS file isn't being found
I have been writing a project for a course I am doing but unfortunately the IDE I was using ran out of space and I had to start afresh by cloning my project to a new environment. My old environment had a CSS file that was being picked up correctly. When I cloned the project an extra base directory was created and now I have noticed that my CSS file isn't being picked up. I don't get any errors, but nothing in my CSS is being used. I assume that since it used to work it should be fairly simple to sort out but I cannot see what the problem is. If anyone has any ideas it would be greatly appreciated. This is my header in base.html: <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>IssueTracker{% block page_title %}{% endblock %}</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous"> <link rel="stylesheet" href="{% static 'css/styles.css' %}"> <script src="https://kit.fontawesome.com/c46cd61739.js" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> {% block head_js %} <script type="text/javascript" src="https://js.stripe.com/v2/"></script> <script type="text/javascript"> //<![CDATA[ Stripe.publishableKey = '{{ publishable }}'; //]]> </script> <script type="text/javascript" src="{% static 'js/stripe.js' %}"></script> {% endblock %} </head> This is the … -
Django Smart Select JQuery Conflict
I am trying to use Django smart selects as part of my website development. I first noticed that when the field, the Smart select field was working as it should in the form however it was conflicting with my jQuery templates. I tried to add a line in settings.py JQUERY_URL = False However when I added this setting the template worked correctly however the smart select field was coming blank The Jquery I'm using in my templates is: https://code.jquery.com/jquery-3.2.1.slim.min.js I am quite new to web development and therefore need help in determining what needs to be done here. Thanks -
Django Json characteristics
Tell me please how to add product characteristics via json for each category separately through the admin panel and how to display them in templates. I cannot add certain characteristics like brands. i use postgresql.thanks models.py class Product(models.Model): class Meta: verbose_name = 'Продукт' verbose_name_plural = 'Продукты' order_with_respect_to='slug' category = TreeForeignKey(Category, blank=True, null=True, related_name='category', verbose_name="Выберите категорию",on_delete=models.CASCADE) title = models.CharField(max_length=250,verbose_name='Наименоватние продукта') slug=models.SlugField(unique=True) image1 = models.ImageField(verbose_name='Главное изображение') image2 = models.ImageField(null=True,blank=True, verbose_name='Изображение 2') image3 = models.ImageField(null=True,blank=True, verbose_name='Изображение 3') image4 = models.ImageField(null=True,blank=True, verbose_name='Изображение 4') image5 = models.ImageField(null=True,blank=True, verbose_name='Изображение 5') characteristics = JSONField(blank=True,null=True) available = models.BooleanField(default=True) description = models.TextField(verbose_name='Описание товара',null=True) price = models.DecimalField(max_digits=10,decimal_places=2,verbose_name='Цена') def __str__(self): return self.title def get_model_name(self): return self.__class__.__name__.lower() def get_characteristics(self): res={} characteristics={ f.feature_key: {'feature_name':f.feature_name,'postfix':f.postfix_for_value} for f in ProductFeatures.objects.filter( feature_key__in=self.characteristics.keys() ).prefetch_related('category') } for feature_key,feature_value in self.characteristics.items(): postfix = characteristics[feature_key].get('postfix') if postfix: res[characteristics[feature_key]['feature_name']] = feature_value + ' ' + postfix else: res[characteristics[feature_key]['feature_name']] = feature_value return res def get_absolute_url(self): return reverse('product_detail',kwargs={'slug':self.slug}) def get_feature_value_by_key(self,key): return self.characteristics.get(key) ProductFeatureValidators class ProductFeatureValidators(models.Model): category = models.ForeignKey(Category,verbose_name='Категория',on_delete=models.CASCADE) feature= models.ForeignKey(ProductFeatures, verbose_name='Характеристика',null=True,blank=True,on_delete=models.CASCADE) feature_value= models.CharField(max_length=255,unique=True,null=True,blank=True,verbose_name='Значение хар-ки') def __str__(self): if not self.feature: return f'Валидатор категории "{self.category.name}"- Хар-ка не выбрана' return f'Валидатор категории"{self.category.name} | '\ f'Характеристика - "{self.feature.feature_name}"|'\ f'Значение - "{self.feature_value}"' ProductFeatures characterisrics class ProductFeatures(models.Model): RADIO='radio' CHECKBOX='checkbox' FILTER_TYPE_CHOICES=( (RADIO,'Радиокнопка'), (CHECKBOX,'Чекбокс') ) feature_key = models.CharField(max_length=100,verbose_name='Ключ характеристики') feature_name= models.CharField(max_length=255,verbose_name='Наименование … -
Error been thrown anytime i try to register my model in the admi.py using django
from django.contrib import admin from .models import UserProfile Register your models here. admin.site.register(UserProfile) the code above is in the admin.py file from django.db import models Create your models here. class UserProfile(models.Model): ''' Represents a "user profile" inside our system ''' email = models.EmailField(unique=True, max_length=255) full_name = models.CharField(max_length=255) def __str__(self): return '%s %s' %(self.full_name, self.email) the code above is in my model.py file The error I see anytime I run the files (admin.py and model.py) is this: Traceback (most recent call last): File "C:\Users\ogunw\Documents\Python Scripts\django scripts\health_web_site\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) The above exception (relation "main_userprofile" does not exist LINE 1: SELECT (1) AS "a" FROM "main_userprofile" WHERE "main_userpr... ^ ) was the direct cause of the following exception: File "C:\Users\ogunw\Documents\Python Scripts\django scripts\health_web_site\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\ogunw\Documents\Python Scripts\django scripts\health_web_site\venv\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\ogunw\Documents\Python Scripts\django scripts\health_web_site\venv\lib\site-packages\django\contrib\admin\options.py", line 614, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "C:\Users\ogunw\Documents\Python Scripts\django scripts\health_web_site\venv\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Users\ogunw\Documents\Python Scripts\django scripts\health_web_site\venv\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "C:\Users\ogunw\Documents\Python Scripts\django scripts\health_web_site\venv\lib\site-packages\django\contrib\admin\sites.py", line 233, in inner return view(request, *args, **kwargs) File "C:\Users\ogunw\Documents\Python Scripts\django scripts\health_web_site\venv\lib\site-packages\django\contrib\admin\options.py", line 1653, in … -
Django: How to order a queryset and move some items to end of the queryset
I have a queryset in my Django application: databytes_all = DataByte.objects Each item in the databytes_all queryset has many attributes but one of them is publish_date. I'd like to order the queryset by publish_date, however if publish_date is None, I'd like the item to be at the end of the queryset. This is what I'm trying but it's not working: databytes_all = DataByte.objects Make a queryset: filter out all of the publish dates that are None no_date = databytes_all.filter(publish_date=None) Make anohther queryset: exclude all of the items where publish date is none, then order the remaining items by publish date databytes_with_date = databytes_all.order_by('-publish_date').exclude(publish_date=None) Now combine the two querysets (however this doesnt work- the items with no publish date are first in the list when I want them to be last) databytes = databytes_with_date | no_date -
Hi, I have a bug in making Django models
For no reason, bugs are created in Django models and they are not made. Please help -
How do I try:except between development and production?
I'm just in a bog with this. Figured this should work fine on both development and production (having set the environment variables on both with two different methods, but I'm obv. wrong. It only works on production. On development it throws a long error ending with "django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty." try: SECRET_KEY = os.getenv("PRODUCTION_SECRET_KEY") except: SECRET_KEY = os.environ.get('DEVELOPMENT_SECRET_KEY') -
CSRF token missing or incorrect with AJAX
I have followed this tutorial and defined my form as below: <form action="" id="contactForm" method="post" role="form" class="contact-form"> {% csrf_token %} ... views.py: def contact(request): if request.is_ajax(): sender_name = request.POST.get('sender_name') sender_email = request.POST.get('sender_email') message_subject = request.POST.get('message_subject') message_text = request.POST.get('message_text') html_message = render_to_string('contact.html', {'sender_name': sender_name, 'sender_email': sender_email, 'message_subject': message_subject, 'message_text': message_text}) email_subject = 'Message Subject' email_from = 'My Name' email_to = ['me@mydomain.com',] send_mail(email_subject, '', email_from, email_to, html_message=html_message) response = {} return JsonResponse(response) AJAX code: $('#contactForm').submit(function(e){ e.preventDefault() $('#loading').css("display", "block") $.ajax({ type : "POST", url : "/contact/", data: { sender_name : $('#name').val(), sender_email : $('#email').val(), message_subject : $('#subject').val(), message_text : $('#message').val(), csrfmiddlewaretoken : '{{ csrf_token }}', datatype : "json", }, success: function(){ $('#loading').css("display", "none"), $('#sent-message').css("display", "block") }, }); }); However, I get the annoying "CSRF token missing or incorrect" error after submitting the form. Please assist. -
How to set url in Django?
I'm a newbie in web development and I'm learning to use Django. Unfortunately I have been stuck for more than 24 hours trying to figure out how to set the URL of a web page. I keep getting status 404 error displayed on the browser after running python server. I have checked python documentation and other documentations online but I still don't see anywhere I'm getting it wrong. I have the following files in the main Django follow: urls.py from django.contrib import admin from django.urls import path, include urlspatterns [ path('qbank', include ('qbank.url')), path ('admin/', admin.site.urls), ] settings.py INSTALLED APPS = [ 'qbank' ..... ] In my project folder(which I named qbank) I have the following files: urls.py from django.urls import path from . import views urlspatterns = [ path ('qbank'), views.index, name = 'index' ] view.py from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse ('Hello from Qbank') -
Cant conver sql to django queary (having dont work)
I have next sql: SELECT stock_id, consignment_id, SUM(qty), SUM(cost) FROM warehouse_regсonsignmentproduct Where product_id = '1' Group BY stock_id, consignment_id Having SUM(qty) > 0 So, I used django ORM to create this query: regСonsignmentProduct.objects .filter(product='1') .order_by('period') .values('stock', 'consignment') .annotate(total_qty=Sum('qty'), total_cost=Sum('cost')) .filter(total_qty__gt=0) But my django query return incorrect result. I think, problem in "annotate" Thanks! -
Django deleting records from database
I have a problem. When i delete record django is deleting record with latest id. I don't know why and can't find any solution. I tried to change form action, url from pk to id but it doesn't work . It always delete the lasted recored not choosed one. Thank u for the help models.py class Usterki (models.Model): id = models.AutoField(primary_key=True) dodany_przez = models.ForeignKey('auth.User', on_delete = models.CASCADE, null = True) samolot = models.CharField( max_length=3, choices = SAMOLOTY_CHOICES, default = LFA, ) usterka = models.CharField(max_length = 200, null = True) status = models.CharField( max_length=16, choices=STATUSY_CHOICES, default=UNACCEPTED, ) ograniczenia = models.CharField( max_length=22, choices = OGRANICZENIA_CHOICES, default = ONHOLD, ) data_dodania = models.DateTimeField(auto_now_add = True) aktualizacja = models.DateTimeField(auto_now = True) zdjecie = models.ImageField(upload_to='', null = True) naprawiona = models.BooleanField(default=False) def __str__(self): return self.usterka views.py class UsterkaDelete(DeleteView): #poprawić bo nie działa !!!!! model = Usterki success_url = reverse_lazy('mojeusterki') template_name = 'mojeusterki.html' urls.py urlpatterns = [ path('', views.index, name='index'), path('add',views.add, name='add'), path('usterka_edit/<int:pk>/edit/', views.usterka_edit, name='usterka_edit'), path('<int:pk>/remove/', views.UsterkaDelete.as_view(), name='usterka_remove'), path('mojeusterki', views.mojeusterki, name='mojeusterki'), path('change_password', views.change_password, name='change_password'), path('fuel', views.fuel, name='fuel'),] mojeusterki.html <form action="{% url 'usterka_remove' pk=usterka.pk %}" method="POST"> {% csrf_token %} <button type="submit" class="btn btn-gradient-danger btn-icon-text">Usuń</button> -
I want to Display the image on my template
I created a ImageFields in my Form.py class ProPic(forms.Form): image = forms.ImageField(help_text="Upload Profile Picture: ", required=False) and my views.py is def Profile(request): context = {} context['image'] = ProPic() return render( request, "profile.html", context) my template profile.html {% extends 'base.html' %} {% block content %} <!DOCTYPE html> <html lang="en"> <head> {% load crispy_forms_tags %} <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Profile</title> </head> <style> .align-middle { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } .card { width: auto; } </style> <body> <div class="card align-middle"> <!-- I want to Display the picture here --> <div class="card-body"> </div> <ul class="list-group list-group-flush"> <li class="list-group-item">Username: {{ user.username|title }}</li> <li class="list-group-item">Emai: {{ user.email }}</li> <li class="list-group-item">Vestibulum at eros</li> </ul> <div class="card-body"> <a href="{% url 'logout' %}" class="card-link">Logout</a><br> {{ image }} </div> </div> </body> </html> {% endblock content %} I just can't see my image when i upload it and i dont want to use models if it is possible and i want my image to appear where i put my comment in the code below -
How to use Django with Tornado web sockets?
I am trying to figure out a way to connect Django with Tornado web sockets. There will be a list of products rendered on an html page. As soon as new product is added through django admin panel, the html page will be updated without reload. -
Django: Form Won't Add to Database
I can add to the database from the admin page but the form in template won't save. When I try to submit the form it just refreshes the form. views: def newPost(request): if request.method == 'POST': form = NewPost(request.POST) if form.is_valid(): form.save() return redirect('myposts') else: form = NewPost() return render(request, 'create/new_post.html', {'title_page': 'New Post', 'form': form}) Template: <form method="POST" class="input_group" action="" enctype="multipart/form-data"> {% csrf_token %} {{ form }} <div class="submit_container"> <input class="submit_btn" type="submit" value="Submit"> </div> </form> Form: class NewPost(forms.ModelForm): title = forms.CharField(widget=forms.TextInput(attrs={'class': 'form_input_text'})) product = forms.ChoiceField(widget=forms.Select(attrs={'class': 'form_input_select'}), choices=PRODUCT_CHOICES) caption_description = forms.CharField(max_length=1000, widget=forms.Textarea(attrs={'class': 'form_input_text', 'style':'resize:none;', 'rows': '3'})) full_description = forms.CharField(max_length=2000, widget=forms.Textarea(attrs={'class': 'form_input_text', 'style':'resize:none;'}), required=False) links = forms.CharField(max_length=2000, widget=forms.Textarea(attrs={'class': 'form_input_text', 'style':'resize:none;'}), required=False) release_date = forms.DateField(widget=forms.SelectDateWidget(attrs={'class': 'form_input_select_date'}, years=YEARS, empty_label="---"), required=False) display_image = forms.ImageField(widget=forms.ClearableFileInput(attrs={'class': 'form_img_btn'})) -
Does Lambda API/Django API slows down if called from the same machine?
I have both Django API and Lambda API which just sleeps for 4 seconds. When I execute the API for multiple times, the response time is so slow even though the code only runs for 4 seconds. Is this happening because I'm calling it from the same website? If yes what's the technical reason for API slowness when it's called from the same machine? -
Can we install any module in cloud hosting?
It's my first app with Python and Django and I can't install all these modules in shared web hosting. So I have a query that can I install any module in cloud hosting such as: asgiref==3.2.10 atomicwrites==1.4.0 attrs==19.3.0 colorama==0.4.3 Django==3.1 iniconfig==1.0.1 install==1.3.3 more-itertools==8.4.0 olefile==0.46 packaging==20.4 Pillow==7.2.0 pluggy==0.13.1 psycopg2==2.8.5 psycopg2-binary==2.8.5 py==1.9.0 pyparsing==2.4.7 pytest==6.0.1 pytz==2020.1 six==1.15.0 sqlparse==0.3.1 toml==0.10.1 Please guide me a way to host my Django website... Thank You -
While installing Django i am getting the following things instead of version name
(modelformsave) C:\Users\nikhi\OneDrive\Consultadd training\Django\modelformsave>pip freeze asgiref @ file:///tmp/build/80754af9/asgiref_1605055780383/work certifi==2020.12.5 Django @ file:///tmp/build/80754af9/django_1606860386887/work psycopg2 @ file:///C:/ci/psycopg2_1608147681824/work pytz @ file:///tmp/build/80754af9/pytz_1606604771399/work sqlparse @ file:///tmp/build/80754af9/sqlparse_1602184451250/work wincertstore==0.2 I am getting the following error while trying to see the version Cannot find file file:///tmp/build/80754af9/asgiref_1605055780383/work