Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
JavaScript, CSS, and Image File Imports Won't Load When Running Live Server On Pycharm with Django
This might be a very basic question but I've been stuck on it a while and ended up deciding to ask on here...greatly appreciate any help! So I've just been making a basic website using pycharm and django and everything loads fine when I run the code through a browser. However, when I use runserver, it only shows the HTML code and not any of the files I have imported including javascript files, css files, and image files. All of my files are contained within the same templates folder. This is the error I receive in the terminal when opening up a live server. [13/Oct/2020 06:29:02] "GET /homepage.css HTTP/1.1" 404 2264 Not Found: /Page2.css [13/Oct/2020 06:29:02] "GET /Page2.css HTTP/1.1" 404 2255 Not Found: /Page3.css [13/Oct/2020 06:29:02] "GET /Page3.css HTTP/1.1" 404 2255 Not Found: /footer.css [13/Oct/2020 06:29:02] "GET /footer.css HTTP/1.1" 404 2258 Not Found: /login.css [13/Oct/2020 06:29:02] "GET /login.css HTTP/1.1" 404 2255 Not Found: /join.css [13/Oct/2020 06:29:02] "GET /join.css HTTP/1.1" 404 2252 Not Found: /demo.css [13/Oct/2020 06:29:02] "GET /demo.css HTTP/1.1" 404 2252 Not Found: /navbar.js [13/Oct/2020 06:29:02] "GET /navbar.js HTTP/1.1" 404 2255 Not Found: /LitChatLogo2.png [13/Oct/2020 06:29:02] "GET /LitChatLogo2.png HTTP/1.1" 404 2276 Not Found: /rectangle.png [13/Oct/2020 06:29:02] "GET /rectangle.png HTTP/1.1" 404 … -
Python Django Validation Error Message in Dictionary Form
I am working on certain validation and wants to raise human readable validation Error message in form of dictionary but I am stuck how to pass error messages and dictionary values inside dictionary here is what I have tried in other way: def _is_valid(self): boarding_points = self._location.point.all() if not set(self._data.get('point')).issubset(set(boarding_points)): for boarding_points_name in self._data.get('point'): raise ValidationError({'point', boarding_points_name, 'is not in location', self._location.name} ) above method is surely a wrong approach as it is set and secondly gives validation error message as [ "{'point', 'is not in location', 'London', <BoardingPoint: Manchester>}" ] I want error message as {'point': Boarding point: Manchester is not in Location: London} how can I do with python dictionary way to throw readable error message?TT -
Reverse for 'surveydetails' not found. 'surveydetails' is not a valid view function or pattern name
I've been stuck on this for a while, can't seem to fix the error. I've checked the code a hundred times but obviously there is something I'm missing. I have installed my app also. Can anybody see what I'm missing? views.py def survey_details(request, id=None): context = {} surveys = Survey.objects.get(id=id) context['survey'] = survey return render(request, 'surveydetails.html', context) feedback.urls.py path('details/<int:id>', views.survey_details, name="survey_details"), surveys.html {% extends 'main.html' %} {% block content%} <h1>Surveys</h1> <h2>list of {{title}} </h2> {% if surveys %} <ul> {% for survey in surveys %} <li> <a href="{% url 'feedback:surveydetails' %}">{{ survey.title }}</a> </li> {% endfor %} </ul> {% else %} <p>There are no surveys.</p> {% endif %} {% endblock %} surveydetails.html {% extends 'main.html' %} {% block content%} <h1>Surveys</h1> <h2>Detail page</h2> <h3>{{question.title}}</h3> <p>Details page of {{question.title}}</p> {% endblock %} -
how to configure Aapahe mod-wsgi for python 3.6 which is by default configured with python 2.7?
Hye everyone.. I have installed Python 3.6 and created a virtual environment and installed all required libraries including Django in that virtual environment. I want to host a django application on Linux server with wsgi but it says ImportError: No module named django.core.handlers.wsgi from what I search and think this problem is because the server is not accessing my virtual environment of python 3.6 where django is installed. My server details are: Python 3.6 [GCC 4.8.5 20150623 (Red Hat 4.8.5-39)] Django Version :3.1.1 Server version: Apache/2.4.46 (cPanel) Server Can anybody tells me how the Apache will get the djnago from my virtual environment? In other words how I can configure my server which is configured with python 2.7 to python 3.6 with libraries installed in virtual environment. Any help will be appreciated. -
How to add samesite=None in the set_cookie function django?
I want to add samesite attribute as None in the set_cookie function This is the code where I call the set_cookie function "redirect = HttpResponseRedirect( '/m/' ) redirect.set_cookie( 'access_token', access_token, max_age=60 * 60 )" This is the function where I set the cookie def set_cookie(self, key, value='', max_age=None, expires=None, path='/', domain=None, secure=False, httponly=False): self.cookies[key] = value if expires is not None: if isinstance(expires, datetime.datetime): if timezone.is_aware(expires): expires = timezone.make_naive(expires, timezone.utc) delta = expires - expires.utcnow() delta = delta + datetime.timedelta(seconds=1) expires = None max_age = max(0, delta.days * 86400 + delta.seconds) else: self.cookies[key]['expires'] = expires else: self.cookies[key]['expires'] = '' if max_age is not None: self.cookies[key]['max-age'] = max_age # IE requires expires, so set it if hasn't been already. if not expires: self.cookies[key]['expires'] = cookie_date(time.time() + max_age) if path is not None: self.cookies[key]['path'] = path if domain is not None: self.cookies[key]['domain'] = domain if secure: self.cookies[key]['secure'] = True if httponly: self.cookies[key]['httponly'] = True -
View counter (django-hitcount) - how show most vieved last week? [Django]
I use django-hitcount to make view counter in my article. Model: class Article(Created, HitCountMixin): title = models.CharField(max_length=120) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) View: class VideoDetailView(HitCountDetailView): template_name = 'video/video_detail.html' model = Video count_hit = True Template: Views: {{ hitcount.total_hits }} How Can I make Articles List View with: -most viewed last week -most viewed yesterday -etc. Shoud I make some new ListView with some queryset? -
Password not getting encrypted while registering a user in Django
serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email') class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = User(validated_data['username'], validated_data['email']) user.set_password(validated_data['password']) user.save() return user views.py class RegisterAPI(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() print("user = ",user) return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) # Create your views here. class LoginAPI(KnoxLoginView): permission_classes = (permissions.AllowAny,) def post(self, request, format=None): serializer = AuthTokenSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] login(request, user) return super(LoginAPI, self).post(request, format=None) # Get User API class UserAPI(generics.RetrieveAPIView): permission_classes = [permissions.IsAuthenticated,] serializer_class = UserSerializer def get_object(self): return self.request.user The password is not getting encrypted in specified format, and hence the login API is also not working. It shows - "non_field_errors": [ "Unable to log in with provided credentials." ] Also, in the admin panel of django, it shows this invalid password format -
How to unfollow url in django?
I created this simple code to learn about login and registration in django. My views.py is def index(request): products = Product.objects.all() return render(request,'index.html',{'products':products}) def register(request): return render(request,'register.html') def login(request): return render(request,'login.html') def logout(request): return HttpResponse('logout') urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index), path('register/', views.register), path('login/', views.login), path('logout/', views.logout), ] base.html <a href="register">Register</a> <a href="login/">Login</a> <h3>Base html </h3> {% block content %} {% endblock %} register.html {%extends 'base.html'%} <h1>Register</h1> {% block content %} {% endblock %} login.html {%extends 'base.html'%} <h1>Login</h1> {% block content %} {% endblock %} At http://127.0.0.1:8000/ when I click Register link it follows to http://127.0.0.1:8000/register page but when I click the 'Register link at that page it follows to http://127.0.0.1:8000/register/register which gives 404 error. How do I unfollow url that is instead of going to http://127.0.0.1:8000/register/register it has to go http://127.0.0.1:8000/register/? -
Django create() argument after ** must be a mapping, not list
I'm creating a writable nested serializer using DRF, I've been following the official documentation (https://www.django-rest-framework.org/api-guide/relations/#writable-nested-serializers). My use case is very similar to the one given in the documentation. models.py class TrackSerializer(serializers.ModelSerializer): class Meta: model = Track fields = ['order', 'title', 'duration'] class AlbumSerializer(serializers.ModelSerializer): tracks = TrackSerializer(many=True) class Meta: model = Album fields = ['album_name', 'artist', 'tracks'] def create(self, validated_data): tracks_data = validated_data.pop('tracks') album = Album.objects.create(**validated_data) for track_data in tracks_data: Track.objects.create(album=album, **track_data) return album My view in which I'm passing my data(I'm doing some post processing and creating this data) to the serializer looks like below NOTE: I'm creating this data in my view. data as per my understanding is a dictionary and 'tracks' has a list of dictionaries views.py @api_view(['POST']) def my_view(): .... my_data = { 'album_name': 'The Grey Album', 'artist': 'Danger Mouse', 'tracks': [ {'order': 1, 'title': 'Public Service Announcement', 'duration': 245}, {'order': 2, 'title': 'What More Can I Say', 'duration': 264}, {'order': 3, 'title': 'Encore', 'duration': 159}, ] } serializer = AlbumSerializer(data= my_data) serializer.is_valid() .... Now every time I call my_view POST API, I get the following error create() argument after ** must be a mapping, not list My primary suspect is the format of my_data I believe, … -
How to pass json data as queryset object to django template?
I have this json data in views.py [ { "id": 6, "first_name": "Star", "last_initial": "W", "phone": "+918893972142", "email": "star@gmail.com", "date_created": "2020-10-12T17:17:17.629123Z", "orders": [] }, { "id": 4, "first_name": "Sam", "last_initial": "0", "phone": "+918766897214", "email": "sam@gmail.com", "date_created": "2020-10-12T17:13:33.435065Z", "orders": [] }, { "id": 3, "first_name": "Gaara", "last_initial": "W", "phone": "+918668972789", "email": "gaara@gmail.com", "date_created": "2020-10-12T17:08:44.906809Z", "orders": [ { "order_id": "9", "customer_id": "3", "customer_name": "Gaara W", "product_id": "3", "product_name": "Jet", "date_created": "2020-10-12T17:18:18.823289Z", "status": "Delivered" } ] } ] I want to pass this data as a context object to the template from views using render function. so I can display this data using {% for %} loop in my template. -
Signal in Model of Django
I ask you this question that I cannot find a solution. I am entering records in the Django Admin, so I enter the functions in the model. In my Sample class I add several fields, but the one I have problems with is the "number" field (sample number). In this each time I add a new sample, it adds 1 to the last number, and if the year changes, it returns to zero. So I have this code for the Sample Class: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.utils import timezone class Sample(models.Model): PREST = ( ('APS', 'APS'), ('Convenio', 'Convenio'), ('Arancelado', 'Arancelado'), ) DPTO = ( ('LAB', 'LAB'), ('DB', 'DB'), ('DSB', 'DSB'), ('DSO', 'DSO'), ) dpto = models.CharField(max_length=45, choices=DPTO) number = models.PositiveIntegerField() matrix = models.ForeignKey('Matrix', models.DO_NOTHING) kindsample = models.ForeignKey('Kindsample', models.DO_NOTHING) sample = models.CharField(max_length=255) identification = models.CharField(max_length=255, blank=True, null=True) date = models.DateField(blank=True) city = models.ForeignKey('City', models.DO_NOTHING) address = models.CharField(max_length=255, blank=True, null=True) assays = models.ManyToManyField('Assay') def __str__(self): return f"{self.number} - {self.sample}" The function for the signal is this: def save_add(sender, instance, **kwargs): if Sample.objects.all().exists(): now = timezone.now() year_sample = Sample.objects.all().last().date.year last = Sample.objects.all().last().number if year_sample == now.year: next = last + 1 else: next = … -
Django Cannot resolve keyword 'AuctionListing' into field. Choices are: auctionitem, auctionitem_id, currentbid, id, usernameb, usernameb_id
This are my models: from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): pass class AuctionListing(models.Model): username = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user") title = models.CharField(max_length=64) description = models.CharField(max_length=1000) startingbid = models.DecimalField(max_digits=6, decimal_places=2) category = models.CharField(max_length=64, blank=True) imgurl = models.URLField(max_length=300, blank=True) status = models.BooleanField(default=True) class Bid(models.Model): usernameb = models.ForeignKey(User, on_delete=models.CASCADE, related_name="userb") auctionitem = models.ForeignKey(AuctionListing, on_delete=models.CASCADE, related_name="item_bided", default=1) currentbid = models.DecimalField(max_digits=6, decimal_places=2, default=0) This is my view: def login_view(request): if request.method == "POST": # Attempt to sign user in username = request.POST["username"] password = request.POST["password"] user = authenticate(request, username=username, password=password) # Check if authentication successful if user is not None: login(request, user) alfa_list = Bid.objects.filter(AuctionListing__status=True) return render(request, "auctions/index.html", { "alfa_list":alfa_list }) ... When I run login_view I get the error "Cannot resolve keyword 'AuctionListing' into field. Choices are: auctionitem, auctionitem_id, currentbid, id, usernameb, usernameb_id" Any ideas why? is it the Models? is it the code from the view to generate the alfa_list? I'm running out of ideas... This is the traceback Environment: Request Method: POST Request URL: http://127.0.0.1:8000/login Django Version: 3.1.1 Python Version: 3.8.5 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'] Traceback (most recent call last): File "C:\Users\LINA\AppData\Roaming\Python\Python38\site-packages\django\core\handlers\exception.py", line 47, in … -
curl: (7) Failed to connect to 127.0.0.1 port 8000: Connection refused
I'm trying to make a Chat application using Django and Vue.js. For this initially I started to create a Django project where I installed Django rest framework and djoser using pip and added corresponding url's in urls.py. But when I'm trying to create user using [curl -X POST http://127.0.0.1:8000/auth/users/create/ --data] I'm getting as "curl: (7) Failed to connect to 127.0.0.1 port 8000: Connection refused". Following are the required scripts. urls.py : """chatire URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('auth/', include('djoser.urls')), path('auth/', include('djoser.urls.authtoken')), ] settings.py: """ Django settings for chatire project. Generated by 'django-admin startproject' using Django 3.1.2. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ … -
Validate before creating objects and create multiple models data through one serializer
I created multiple models related to an applicant class Applicant(models.Model): app_no = models.CharField(max_length=20, unique=True) class ApplicantBasicDetails(models.Model): applicant = models.ForeignKey(Applicant, on_delete=models.CASCADE) f_name = models.CharField(max_length=255, blank=True, null=True) m_name = models.CharField(max_length=255, blank=True, null=True) l_name = models.CharField(max_length=255, blank=True, null=True) gender = models.CharField(max_length=15, blank=True, null=True) class AppplcantFamilyDetails(models.Model): applicant = models.ForeignKey(Applicant, on_delete=models.CASCADE) relation = models.CharField(max_length=255, blank=True, null=True) f_name = models.CharField(max_length=255, blank=True, null=True) m_name = models.CharField(max_length=255, blank=True, null=True) l_name = models.CharField(max_length=255, blank=True, null=True) gender = models.CharField(max_length=15, blank=True, null=True) Now developing an API where someone will POST below body { "app_no": "123456", "applicant_basic_details": { "f_name": "", "m_name": "", "l_name": "", "gender": "" }, "applicant_family_datails": [ { "relation": "", "f_name": "", "m_name": "", "l_name": "", "gender": "" }, { "relation": "", "f_name": "", "m_name": "", "l_name": "", "gender": "" } ] } I don't have much idea how to validate multiple models data first before creating objects I wrote one serializer. class AllInOneSer(serializers.Serializer): def create(self, validated_data): app_no = validated_data.pop("app_no") app_ser = ApplicantSer(data={"app_no": app_no}) if app_ser.is_valid(): pass else: return "error", app_ser.errors How can I pass these multiple models data through one serializer, to validate and create objects? -
Django | Static Files not loading in Production even after executing Collect static
I have a django app on Linode and the static files are not loading. I have executed the collectstatic command and defined STATIC_ROOT as well. I have used {%load static%} in my html file and using the following command to link the css <link rel="stylesheet" href="{% static 'mystyle.css' %}"> settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] Here is the photo of my file structure. -
Value error when trying to insert data into Django Database Table
So I've created multiple .csv files to upload data into my tables. Everything seems to be going well except for the part where I try to add data into a table which is has a foreign key attribute. I've seen a question that's similar but it's weird for my case since I've already added data for the primary key table. <QuerySet [{'ISBN': '9780815345244', 'bookName': 'Molecular Biology of the Cell', 'bookVersion': '6', 'bookAuthor': 'Bruce Alberts', 'bookPublisher': 'W. W. Norton & Company'}, i get this error: ValueError: Cannot assign "'9780815345244'": "retailer_book.ISBN" must be a "books" instance. which is weird since it is an instance. This is my models.py code: class books (models.Model): ISBN = models.CharField(max_length=255, primary_key=True) bookName = models.CharField(max_length=255) bookVersion = models.CharField(max_length=255) bookAuthor = models.CharField(max_length=255) bookPublisher = models.CharField(max_length=255, default= 'NULL') class retailer(models.Model): sellerID = models.CharField(max_length=255, primary_key=True) retailer = models.CharField(max_length=255) class retailer_book(models.Model): ISBN = models.ForeignKey(books, on_delete = models.CASCADE) sellerID = models.ForeignKey(retailer, on_delete = models.CASCADE) condition = models.CharField(max_length=255) price = models.FloatField() reviews= models.CharField(max_length=255) ID = models.CharField(max_length=255, primary_key=True) bookType = models.CharField(max_length=255) Thank You! -
use model field name for urlconf in DeleteView django
I want my DeleteView to get url with value of field name. urls.py app_name = 'myapp' urlpatterns += [ path('member/<str:number>/update/', views.member_update, name='update') # this works with function based view. I want my CBV to work as this. path('member/<str:number>/delete/', views.MemberDelete.as_view(), name='delete') ] views.py MemberDelete(LoginRequiredMixin,DeleteView): model = Employee def get_success_url(self): return reverse_lazy('myapp:member') models.py class MyModel(models.Model): myfield = models.CharField(max_length=100, unique=True) # should I change it into SlugField? I tried puttting slug_field and slug_url_kwargs in MemberDelete in no vain. Any advice would be so grateful. Thanks in advance. -
djnago-pytest not able to create test database
I am integrating django-pytest and written first test-case for it, but when running pytest it starts creating test DB and throws error 'Cannot add foreign key constraint' after creating just 5 tables. Below is the stacktrace query = b'ALTER TABLE `tracking_invoiceview` ADD CONSTRAINT `tracking_invoiceview_invoice_id_95b70617_fk_backend_invoices_id` FOREIGN KEY (`invoice_id`) REFERENCES `backend_invoices` (`id`)' def query(self, query): # Since _mysql releases GIL while querying, we need immutable buffer. if isinstance(query, bytearray): query = bytes(query) if self.waiter is not None: self.send_query(query) self.waiter(self.fileno()) self.read_query_result() else: > _mysql.connection.query(self, query) E _mysql_exceptions.IntegrityError: (1215, 'Cannot add foreign key constraint') cheetah_env/lib/python3.6/site-packages/MySQLdb/connections.py:276: IntegrityError The above exception was the direct cause of the following exception: request = <SubRequest '_django_db_marker' for <Function test_login>> @pytest.fixture(autouse=True) def _django_db_marker(request): """Implement the django_db marker, internal to pytest-django. This will dynamically request the ``db``, ``transactional_db`` or ``django_db_reset_sequences`` fixtures as required by the django_db marker. """ marker = request.node.get_closest_marker("django_db") if marker: transaction, reset_sequences = validate_django_db(marker) if reset_sequences: request.getfixturevalue("django_db_reset_sequences") elif transaction: request.getfixturevalue("transactional_db") else: > request.getfixturevalue("db") cheetah_env/lib/python3.6/site-packages/pytest_django/plugin.py:513: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ cheetah_env/lib/python3.6/site-packages/pytest_django/fixtures.py:108: in django_db_setup **setup_databases_args … -
How to get pytest-django's test database connection?
I have a Django project for Postgres with a database set up through URI: DATABASES = {"default": "postgres://user:pw@host:5432/db"} When running through tests, I was to be able to see the changes to DATABASES for the new test database that pytest-django sets up. But when I try to connect to it manually with psycopg2, it's not working: psycopg2.connect("postgres://user:pw@host:5432/test_db") It's shows a different test database? I'm not sure what's going on. When I use the regular Model.objects.get(), that works fine with the test database. It's my supplied uri that's connecting to something else... -
how can i run python management command script infinite time
here is my management command script but the problem is, every time run this script through command like python manage.py scriptname.py, how can i run this script infinite time... i'm using time schedule but its not work... from django.core.management.base import BaseCommand, CommandError from datetime import datetime, timedelta from Skoapp.models import Post class Command(BaseCommand): help = 'Delete Post older than 3 minutes' def handle(self, *args, **options): planss = 5 if Post.objects.filter(plan__exact=planss): Post.objects.filter(list_date__lte=datetime.now() - timedelta(minutes=3)).delete() self.stdout.write('Deleted objects older than 3 minutes successfully') else: self.stdout.write('Post Not Detected') -
How to format export fields with numeric values in django-import-export
Using django-import-export to export data from django admin in excel xlsx format. However, numeric fields export as text in excel. I'd like to export correctly as numeric fields. Documentation has a sample syntax for BooleanWidget, but it's not working, it replaces the value with the object __str__ value, instead of converting the value to a number. -
django except matching query does not exist
I'm trying to use try and except in django; everything work perfect if the user exist but if the user doesn't exist instead of returning NULL; my function keep returning: Userprofile matching query does not exist. I know the user is not exist in table; I just want to not return anything instead of showing error page. def userAlbumFunction(id): try: albums = Album.objects.filter(user_id = id) except Album.DoesNotExist: albums = None return {'albums' : albums} -
Is it possible to upload xlsx file to aws S3 storage on coding in django?
Here is my code (I am writing some data to existing xlsx file) wb = load_workbook(EXCEL_FILE) # it is a directory to my excel file sheets = wb.sheetnames Sheet1 = wb[sheets[0]] Sheet1.cell(row = 4, column = 5).value = user_surname Sheet1.cell(row = 5, column = 5).value = user_name Sheet1.cell(row = 6, column = 5).value = address Sheet1.cell(row = 7, column = 5).value = city_and_country Sheet1.cell(row = 8, column = 5).value = phone_number Sheet1.cell(row = 9, column = 5).value = passport length = len(products) rows = [x for x in range(1,length+1)] sum_list = [] for (row,product,count,price,attr_name,attr_value) in zip(rows,products,product_count,product_price,attr_names,attr_values): length = len(attr_name) additional_info = [] for name,value in zip(attr_name,attr_value): name_and_value = name + ': ' + value additional_info.append(name_and_value) print(additional_info) Sheet1.cell(row = 3+row, column = 7).value = product + "--" +"-".join(additional_info) Sheet1.cell(row = 3+row, column = 9).value = count Sheet1.cell(row = 3+row, column = 10).value = price real_price = price[0:-2] total_one_product = int(real_price) * count sum_list.append(total_one_product) currency = Currency.objects.last() uzs = currency.UZS if currency else 10300 total_price_usd = sum(sum_list)/uzs Sheet1.cell(row = 10, column = 14) .value = round(total_price_usd,2) wb.save("demo.xlsx") # file is being saved to the directory inside of Project and sent to courier as an attachement Now i want to save it to … -
Using iframes with bootstrap carousal
I am working on a django application. In the application, I want to display a few youtube videos in the landing page. For adding and displaying the videos, I am using django-embed-video. Right now when I add videos to the webpage, they are displayed one after the other. I would like to display these videos in the bootstrap carousal. But adding them to the bootstrap carousal does not seem to work. This is my code so far <div id="carouselVideoControls" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> <li data-target="#carouselVideoControls" data-slide-to="0" class="active"></li> <li data-target="#carouselVideoControls" data-slide-to="1"></li> <li data-target="#carouselVideoControls" data-slide-to="2"></li> </ol> <div class="carousel-inner"> {% for i in videos %} <div class="carousel-item active"> {% video i.video 'medium' %} </div> {% endfor %} </div> <a class="carousel-control-prev" href="#carouselVideoControls" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselVideoControls" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> When this code is run, the carousal breaks. The next and previous buttons in the carousal do not work and only the first video is displayed indefinitely. FYI: The carousal and the video themselves work separately. If I were to use images in the bootstrap carousals instead of videos from django-embed-videos, the carousal works. It is only when, I add the … -
Unable to redirect to new page Django
I am new to Django. I am building a multiple page website via Django. on the main page I am using an onclick event and passing the data to views.py via AJAX. the issue is that in the command prompt everything is running smoothly. the function to which Ajax call was made is being called. the data is being fetched but the URL is not changing. If we copy the URL from new URL from cmd and paste it in browser window, it is working the way it is suppose to work. Can someone tell me what might the issue.