Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Giving every submitted form a different I'd in Django
I got a problem when trying to submit the review form. Below are the two issues When l try to send the form without pk=1 it returns an error below MultipleObjectsReturned at /submit _review/7/ get() returned more than are Action Review--it returned 6! When I try to send the form when pk=1, it works and the review form is sent to the Admin. But the following below nor work It only changes the review form with an id=1 My Expectations and Needs I would like to have a form submitted and it gets the new id not being fixed like pk=1, but getting a new id everytime and every form sent or submitted #Action/views.py def submit_review(request,game_id): url = request.META.get('HTTP_REFERER') if request.method == 'POST': try: reviews = ActionReview.objects.get(user__id=request.user.id, game_name__id=game_id, pk=1) form = Game_ReviewForm(request.POST, instance=reviews) form.save() messages.success(request, 'Thank you! , Your review has been Updated Successfully.') return redirect(url) except ActionReview.DoesNotExist: form =Game_ReviewForm(request.POST) if form.is_valid(): data=ActionReview() data.subject = form.cleaned_data['subject'] data.stars = form.cleaned_data['stars'] data.content = form.cleaned_data['content'] data.game_id=game_id data.user__id=request.user.id data.save() messages.success(request, 'Thank you! , Your review has been Added Successfully.') return redirect(url) -
Django paginator does not pass second GET
My goal is to filter objects by buttons and then parse it to pages. It works but when i go to next page the filter i get from GET just disapears. it works on the first page just fine but when i move to 2.page that is where it doesn't filter. My view: def Archive(request): filte = request.GET.get("category") manga = Manga.objects.all() if filte != None: manga = manga.filter(manga_categorys=filte) cats = Categorys.objects.all() paginator = Paginator(manga, 20) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) manlen = len(manga) context = { "Category": cats, "Manga": page_obj, "MangaLen":manlen, } template = loader.get_template("Category.html") return HttpResponse(template.render(context, request)) And my template(filter): <form method="GET"> <div class="grid grid-cols-10 gap-6"> {%for x in Category%} <button class="bgl text-center p-4" type="submit" value="{{x.id}}" name="category"><h2 class="M text-xl ">{{x.category_name}}</h2></button> {%endfor%} </div> </form> Edit : I have also tried: {%for x in Category%} <a class="bgl text-center p-4" href="?category={{x.id}}"><h2 class="M text-xl ">{{x.category_name}}</h2></a> {%endfor%} My paginator(they are in the same template): <div class="pagination mx-auto p-2 flex w-max mt-4 bgl roulnded-lg"> <span class="step-links"> {% if Manga.has_previous %} <a href="?page=1"> <div class="p-3 text-lg M w-max mx-auto inline mx-2 border-r-2">&laquo;</div></a> <a href="?page={{ Manga.previous_page_number }}"><div class="p-3 text-lg M w-max mx-auto inline mx-2 border-r-2">Önceki</div></a> {% endif %} <span class="current text-lg p-3 mx-2"> {{ Manga.number }} … -
Pass order details into invoice via PayPals smart button
I have made a simple website for my father in which he sells photographic prints, They are added to the cart, order is processed and everything goes through perfectly as it should, seeing as it is not a complex ecommerce website. I am not seasoned coder and the only method I can currently get working is the PayPal smart buttons with in my check out page. Currently my orders are going through successfully and all data is been stored in the back end of my Django app/database. What I want to do is be able to pass all of the order details into the paypal invoice, such as item names, quantity etc... I cannot seem to get it working. Here is my code: Checkout.HTML / JS: <script src="https://www.paypal.com/sdk/js?client-id=MY-ID&currency=GBP"></script> <script> document.cookie = "cookie_name=value; SameSite=None; Secure"; var total = '{{order.get_cart_total}}'; var order_id = '{{ order.id }}'; // Render the PayPal button into #paypal-button-container paypal.Buttons({ style: { color: 'blue', shape: 'rect', }, // Set up the transaction createOrder: function(data, actions) { return actions.order.create({ purchase_units: [{ amount: { value:parseFloat(total).toFixed(2), }, description: order_id }] }); }, // Finalize the transaction onApprove: function(data, actions) { return actions.order.capture().then(function(details) { console.log(JSON.stringify(details)); submitFormData() }); } }).render('#paypal-button-container'); </script> <script type="text/javascript"> … -
How to draw a line graph for the django model feild In django template using google chart api
Here is sample data of my model GDP Here i want to display years (like 1961,1962,1963...) on my x-axis and prices on my y-axis Here i am also sharing my reference image to display the graph Here in above picture those point(i.e 283.75, 274.84...] are nothing but my gdp values from GDP Model i am sharing my views.py here def gdp_chart(request): gdp_values = GDP.objects.values_list('date','gdp') return render(request, 'dashboard_graph.html', {'gdp_values':gdp_values}) Please help me out write html code using google chart api to get the line graph as sample image -
Django DRF count error inside For Loop of nested serializer
I have the below block of code: class OrderSerializer(serializers.ModelSerializer): items = OrderItemSerializer(many=True) class Meta: model = Order fields = ( "id", "order_no", "items", ) def create(self, validated_data): items = validated_data.pop("items") # CREATE ORDER order = Order.objects.create(**validated_data) # ADD ITEMS for item in items: # IF QUANTITY IS NEGATIVE if item["qty"] < 0: # NEGATIVE QUANTITY, PERFORM SOME ACTION LATER order_item = OrderItem.objects.create(order=order, **item) else: order_item = OrderItem.objects.create(order=order, **item) # MANAGE INVENTORY COUNT variant = order_item.variant if variant: print("CURRENT STOCK:", variant.current_stock) print("QTY TO ADD / REDUCE:", item["qty"]) variant.current_stock -= item["qty"] # SAVE VARIANT variant.save(update_fields=["current_stock"]) print("STOCK AFTER ADD / REDUCE:", variant.current_stock) return order Have at look at the code below the comment # MANAGE INVENTORY COUNT. orderitem.variant is a ForeignKey to a model called Variant (which has 2 fields, id and current_stock). Let's say my variant.id=1 and variant.current_stock=10. If I add -5 units (item["qty"] = -5) of an order_item to an order with variant.id=1 the inventory count becomes 15 (calculation: 10 - (-5)), which is correct. But, when I add 2 order items with same variant id, example: -5 units of an order_item with variant.id=1 and +5 units of an order_item with variant.id=1 to the same order, the inventory count becomes 5, … -
Is it possible to pass data through the "redirect" function in django?
I need this so that after the user is authorized through the discord, he is redirected to the main page and "logged in" to his account. But how can I check if he is logged into the account, if, as I understand it, you can only transfer data using the "render" function? Is there any way to enable cookies? I don't know. `def outhRedirect(request): code = request.GET.get('code') user = exchange_code(code) #если нет пользователя в базе, добавляем его и входим в аккаунт if len(DiscordUser.objects.all().filter(id=user.json()['id'])) == 0: new_user = DiscordUser( id = user.json()['id'], discord_tag = user.json()['username'] + '#' + user.json()['discriminator'], avatar = user.json()['avatar'], locale = user.json()['locale'], public_flags = user.json()['public_flags'], flags = user.json()['flags'] ) new_user.save() return redirect('http://127.0.0.1:8000/') #иначе перенаправляем его на главную страницу и он "входит" в существующий аккаунт else: return redirect('http://127.0.0.1:8000/')` I just don't know how to implement it, i need help. -
Heroku app displaying "Internal Server Error" - Django App not working
I've developed an app which works fine in the local machine. But when deployed to Heroku, I only see a page displaying "Internal Server Error". I've made sure that the secret key is correct and all the database credentials (which is stored in a .env file and ignored by .gitignore) are correct. I've also migrated the database to Heroku and I do have a Heroku adds-on. Could someone please check my logs and explain what I am doing wrong? You can visit the page at: https://abbasportfolio.herokuapp.com/ and see the error. I've been struggling for about a week now. All help is appreciated! My heroku logs shows: 2023-03-29T19:30:55.007523+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.11/site-packages/django/views/debug.py", line 366, in get_traceback_data 2023-03-29T19:30:55.007523+00:00 app[web.1]: "settings": self.filter.get_safe_settings(), 2023-03-29T19:30:55.007524+00:00 app[web.1]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2023-03-29T19:30:55.007524+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.11/site-packages/django/views/debug.py", line 150, in get_safe_settings 2023-03-29T19:30:55.007524+00:00 app[web.1]: settings_dict[k] = self.cleanse_setting(k, getattr(settings, k)) 2023-03-29T19:30:55.007524+00:00 app[web.1]: ^^^^^^^^^^^^^^^^^^^^ 2023-03-29T19:30:55.007525+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.11/site-packages/django/conf/__init__.py", line 101, in __getattr__ 2023-03-29T19:30:55.007525+00:00 app[web.1]: raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") 2023-03-29T19:30:55.007525+00:00 app[web.1]: django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. 2023-03-29T19:30:55.007526+00:00 app[web.1]: 2023-03-29T19:30:55.007526+00:00 app[web.1]: During handling of the above exception, another exception occurred: 2023-03-29T19:30:55.007526+00:00 app[web.1]: 2023-03-29T19:30:55.007526+00:00 app[web.1]: Traceback (most recent call last): 2023-03-29T19:30:55.007527+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.11/site-packages/django/core/handlers/exception.py", line 56, in inner 2023-03-29T19:30:55.007527+00:00 app[web.1]: response … -
Uploading an image within Django working with a mysql database
I am trying to upload an image to a specific directory within my Django project using the upload_to='staticfiles/images' parameter within my models attribute. I have the MEDIA_URL and MEDIA_ROOT specified in settings as well as the needed addition to my urls.py page as seen below. Models.py #upload_to='staticfiles/images' image = models.ImageField(db_column='Image', upload_to='staticfiles/images', blank=True, null=True) # Field name made lowercase. Settings.py STATIC_URL = '/staticfiles/' if DEBUG: STATICFILES_DIRS = [os.path.join(BASE_DIR, 'staticfiles')] else: STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') Urls.py urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) My folder hierarchy looks like the following: -> A5 (desktop folder) -> CC (django project) -> base (django application) -> staticfiles -> images I am working with a mysql database and upon uploading the image, the image name gets successfully added to the image column within the database and everything works as it should, except for the image not being uploaded into the specific project directory folder I am specifying. Any ideas on what I am doing wrong? -
Django pip check always show the same boto and boto3 error message
Good day, After trying multiple times to deploy my django Heroku and AWS, my python pip check keeps giving me the same issue "boto3 1.16.51 has requirement botocore<1.20.0,>=1.19.51, but you have botocore 1.29.81", and i have received multiple errors on my django deployment. How should i resolve this error ? Which botocore will be suitable with my latest python 3.11.2? -
Getting int object in Django celery task after passing object PK
I am triggering a task in Django after adding an entry. The task is triggered in a post_save. # signals.py from .models import Layer from .tasks import convert @receiver(post_save, sender=Layer) def post_save_layer( sender, instance=None, created=False, **kwargs ): if created: a = convert.delay(instance.pk) In my post save, I am passing the objects primary key to query it inside the asynchronous task. In my tasks, I should get the pk. # tasks.py from .models import Layer @shared_task() def convert(obj_id): print('id', obj_id) instance = Layer.objects.get(pk=obj_id) file = instance.file.path In my function convert, I cannot print the received argument obj_id. My error is that the variable instance is an INT type. AttributeError: 'int' object has no attribute 'file' It does the get the query for the corresponding Layer object. How do I properly pass my instance primary key to a Celery task? -
Django template does not find the correct directory path even when specified in settings.py
I have a Django project that includes two React apps, and I am using Django to serve them. I have set up my settings.py file to include the directories for both React apps in the TEMPLATES and STATICFILES_DIRS sections as follows: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'clients/build/'), os.path.join(BASE_DIR, 'sephora-app/build/'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'clients/build/static'), os.path.join(BASE_DIR, 'sephora-app/build/static'), ] urls.py from . import views urlpatterns = [ path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), path('a/', views.index, name='index'), path('b/', views.index1, name='index1'), ] views.py from django.shortcuts import render def index(request): return render(request, 'index.html') def index1(request): return render(request, 'sephora-app/build/index.html') When I try to access the React app at http://localhost:8000/b/, Django gives me the following error message: TemplateDoesNotExist at /b/ sephora-app/build/index.html It looks like Django is not finding the index.html file in the correct directory even though it is specified in settings.py. I have tried changing the order of the directories in settings.py, but it only finds the first directory specified in DIRS. I have also tried setting DIRS to an empty list [], but that did not work either. Can someone please help me figure out what is … -
Django UpdateVIew is not working with form_class
I need to edit an existing form and make changes to the database. So to do this I use UpdateView based class. When I use 'fields' everything works correctly, but there are no styles applied to the form, so I'm trying to use 'form_class' instead and when I click submit button changes are not saved. Please help me with this issue. (urls) from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('register/', views.register_page, name='register'), path('login/', views.login_page, name='login'), path('logout/', views.logout_user, name='logout'), path('new_todo/', views.new_todo, name='new_todo'), path('update_todo/<int:pk>', views.UpdateTodo.as_view(), name='update_todo'), path('delete_todo/<int:pk>', views.delete_todo, name='delete_todo'), ] (views) class UpdateTodo(UpdateView): model = Todos template_name = 'todoapp/new_todo.html' # fields = ['title', 'notes', 'date', 'deadline'] form_class = TodosForm success_url = "/" (models) from django.db import models class Todos(models.Model): title = models.CharField('Title', max_length=50) notes = models.TextField('Note') date = models.DateField('Date') deadline = models.DateField('Deadline') def __str__(self): return f"Todo: {self.title}" def get_absolute_url(self): return f'/{self.id}' (forms) class TodosForm(ModelForm): class Meta: model = Todos fields = ['title', 'notes', 'date', 'deadline'] widgets = { 'title': TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Title' }), 'notes': Textarea(attrs={ 'class': 'form-control', 'placeholder': 'Notes' }), 'date': DateTimeInput(attrs={ 'class': 'form-control', 'placeholder': 'Date' }), 'deadline': DateTimeInput(attrs={ 'class': 'form-control', 'placeholder': 'Deadline' }) } (HTML template) {% extends 'base.html' %} {% block … -
How to choose clothing size on django?
sorry for my english... i wanna make choosing clothes size. I have been trying for 4 days, but i cant make views the task is: there are sizes such as S,M,L,Xl and customer chooses their and go in the cart i have models.py class Product(models.Model): ... category = models.ForeignKey('Category', related_name='products', on_delete=models.CASCADE) sizes = models.ManyToManyField('ClothingSize', through='ProductVariant') class ClothingSize(models.Model): size_choices = ( ('S', 'S'), ('M', 'M'), ('L', 'L'), ('XL', 'XL'), ) size_name = models.CharField(max_length=2, choices=size_choices, blank=True, null=True) class ProductVariant(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) product_size = models.ForeignKey(ClothingSize, on_delete=models.CASCADE) product_quantity = models.IntegerField(default=0) and then i tried to make views for choosing size and this is my fail: views.py def detail_product(request, product_slug): products = get_object_or_404(Product, slug=product_slug) get_all_photos = ProductPhotos.objects.filter(post=products) get_sizes = ProductVariant.objects.filter(product=products) if request.method == "POST": size_id = request.POST.get('size_variation') try: filter_sizes = ProductVariant.objects.filter(product_size=size_id) except: return HttpResponse('Ошибка сервера(') else: filter_sizes = None dict ={ "products": products, 'get_sizes':get_sizes, 'filter_sizes':filter_sizes, 'get_all_photos': get_all_photos } return render(request, 'shop/details.html', dict) template <form action="." method="post"> {%csrf_token%} {% for size in products.sizes.all %} <p><input name='size_variation' type="radio">{{size.size_name}}</p> {%endfor%} <input type="submit" value="Обновить"> </form> -
if statement is not working in Django HTML template
{% for feature in features %} {{feature.name}} {{feature.details}} **{% if feature.is_true == True %} Yes this is True {% endif %}** {% endfor %} I am just trying to use the if statement here. feature is the object of a class which has an attribute is_true which contains boolean values. I am trying to check if it is true then display the following paragraph else not. Eveything else seems to work fine. On runing the server Eveyrthing is dispalyed on the page except for the part in the if condition. Please help me get this right, I am new to Django. Thanks! -
(staticfiles.W004) The directory '/var/www/static/' in the STATICFILES_DIRS setting does not exist
I`ve been learning Django by yourube videos and I reached the moment when I had to create migrations I did exactly how it is in video but I got this Warning message: WARNINGS: ?: (staticfiles.W004) The directory '/var/www/static/' in the STATICFILES_DIRS setting does not exist. No changes detected and no migrations were created, I tried to google the problem but that was useless At the very start I had 2 problems: WARNINGS: ?: (staticfiles.W004) The directory '/var/www/static/' in the STATICFILES_DIRS setting does not exist. ?: (staticfiles.W004) The directory 'D:\PythonProjects\Projects\start\static' in the STATICFILES_DIRS setting does not exist. second problem I solved by creating a folder named 'static' in the project`s main folder but the second is still unsolved( -
Splitting Django application in many applications
I have a django project divided in 3 sprint. The first sprint is about importing data (20 imports about) in database A The second is about (merging) making request on database A and production of reporting in ``database B The three ... in database C The project have three differents databases. I have one app with three separate database. Do you think, I should split the app in three differents (inside the same project) and define a database router that routes to these databases. Like this: app_import with database A app_merging with database B -
Django DEBUG=False does not serve media files, thumbnails or thumbnails
I'm working on an application that when set to production mode (DEBUG=False) does not load image thumbnails, when DEBUG=True loads and displays normally, static files are also loaded normally in production when the command "python3 manage. py collectstatic" `Settings.py STATIC_URL = '/static/' MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py ... urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ...` -
Accessing Calls to Mocked Class functions
I have written a custom class to mock a general API client in a codebase so that I can centrally and easily mock all of the class methods for unit testing. This is working great so far, however I am looking for a way to track individual calls to each class method. Right now that only trackable call via Mock is the initial class instantiation. Here is the mock class: from faker import Factory faker = Factory.create() class MockAPIClass def get_some_data(self, data): return f"{data} - {faker.pyint()}" Then in my util file: def func_to_test_that_calls_client(arg): client = regular_api_client() return client.get_some_data(arg) Then in my unit tests: from unittest import mock from django.test import TransactionTestCase from .file import MockAPIClass from .util import func_to_test_that_calls_client class TestUils(TransactionTestCase): def setUp(self): self.api_call_patcher = mock.patch('path.to.mocked.class.instantiation') self.patch_api = self.api_call_patcher.start() self.mock_api = MockAPIClass() # this done so that the mocked class can be referenced below self.patch_api.return_value = self.mock_api def tearDown(self): mock.patch.stopall() def test_util_func(self): res = func_to_test_that_calls_client("test") self.assertTrue(res) self.patch_api.assert_called_once() The above functions exactly as expected and intended. However, inside of the funciton func_to_test_that_calls_client, the original client is instantiated then the class method get_some_data() is called. With this implementation, I have no visibility into the call stack of the class methods like that … -
Python (Django) createsuperuser not working with docker-compose environment
I'm currently running a project using django in docker. I have a docker-compose file that starts and runs an nginx server, an app server running alpine and a db-server running postgresql. All of these start up like they're supposed to and I can access the blank site on my localhost IP 127.0.0.1:8000. At the moment there's no models or views or anything, I just want to create the admin user for now. Dockerfile FROM python:3.10-alpine ENV PYTHONUNBUFFERED=1 ENV PYTHONDONTWRITEBYTECODE=1 RUN apk add python3-dev postgresql-client postgresql-dev musl-dev build-base COPY . /app WORKDIR /app RUN pip install -r requirements.txt ENTRYPOINT ["sh", "entrypoint.sh"] docker-compose.yml version: '3.9' services: web: image: nginx:latest ports: - 8000:8000 volumes: - ./nginx/:/etc/nginx/conf.d/ networks: - webnet depends_on: - app app: image: bankimage:latest networks: - dbnet - webnet env_file: - env depends_on: - db db: image: postgres:15.2-alpine volumes: - data:/var/lib/postgresql/data/ - ./dbscripts/:/dbscripts/ networks: - dbnet env_file: - env volumes: data: networks: dbnet: webnet: I can access the database with python manage.py exec db and I can see all the tables created for django, so I know there's a connection. Database setup: env POSTGRES_USER=pguser POSTGRES_PASSWORD=pgpassword POSTGRES_DB=bankdb TZ=Europe/Copenhagen PGTZ=Europe/Copenhagen settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ['POSTGRES_DB'], 'USER': os.environ['POSTGRES_USER'], 'PASSWORD': os.environ['POSTGRES_PASSWORD'], … -
Changing students level when session changes
I have a school management system website, i want to enable the functionality whereby the student's level will change when the school session year changes. I actually don't have an idea tackling this issue. This is my student model class Student(models.Model): student = models.OneToOneField(User, on_delete=models.CASCADE) level = models.CharField(max_length=25, choices=LEVEL, null=True) department = models.ForeignKey(Program, on_delete=models.CASCADE, null=True) def __str__(self): return self.student.get_full_name -
django.db.utils.OperationalError: connection to server at "127.0.0.1", port 5432 failed: Connection refused
psycopg2.OperationalError: connection to server at "127.0.0.1", port 5432 failed: Connection refused adh_dealmicroservice-copy-web-1 | Is the server running on that host and accepting TCP/IP connections? conn = _connect(dsn, connection_factory=connection_factory, **kwasync) adh_dealmicroservice-copy-web-1 | django.db.utils.OperationalError: connection to server at "127.0.0.1", port 5432 failed: Connection refused adh_dealmicroservice-copy-web-1 | Is the server running on that host and accepting TCP/IP connections? -
Django Web Application Mutual authentification on development server
I am working on an application that needs mutual authentication; there are needs to test it on the development server I have so far got all the keys, server and client, the server can be authenticated, what i don't know is how to request the client(browser) for the keys. Ideally this should be done once at the first request, since there is also password authentication. Anyone to show me how to go about. Note: I have searched the web for some good hours with no answer so far -
How to set the Navigation bar in the top of the html page?
I developed an index.html page in django project. The below is the template code I developed. Right now, the navigation bar is coming at the bottom index.html <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Contact Book Template</title> <link type="text/css" rel="stylesheet" href="{%static 'css/style.css' %}" /> <!-- Google Font --> <link href="https://fonts.googleapis.com/css?family=PT+Sans:400" rel="stylesheet"> </head> <body> <img class="contact_book" src="{% static 'img/contact_book.jpg' %}" alt="first" /> <div id="booking" class="section"> <div> <ul id="horizantal-style"> <li><a href="#">Home</a></li> <li><a href="#">News</a></li> <li><a href="#">Contact</a></li> <li style="float:right"><a href="#">Login</a></li> <li style="float:right"><a class="active" href="#about">Sign up</a></li> </ul> </div> </div> </body> </html> I developed the style.css file as shown below ul { list-style-type: none; margin: 0; padding: 0; overflow: hidden; background-color: #dddddd } li { display: inline-block; } li a { display: block; color: #000; text-align: center; padding: 20px 24px; text-decoration: none; } li a:hover { background-color: #555; color: white; } .active { background-color: #337ab7; } I am expecting it to set the navigation bar at the top, could anyone please help? -
Unable to display multiple locations using GraphHopper in Leaflet map
Description: I am trying to display a route on a Leaflet map that connects multiple locations using GraphHopper. I have defined an array of latitude and longitude points and passed it to the ghRouting.route() function along with the vehicle type and API key. However, I am getting an error "ghRouting.route is not a function" in the console. Code: <!-- Leaflet JavaScript --> <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script> <!-- GraphHopper Client Web JavaScript --> <script src="https://graphhopper.com/api/1/client.js?key=<your_api_key>"></script> <script> // Create a new Leaflet map centered on Kathmandu, Nepal var map = L.map('map').setView([27.7172, 85.324], 12); // Add a tile layer to the map L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors', maxZoom: 18, tileSize: 512, zoomOffset: -1 }).addTo(map); // Define an array of points (latitude and longitude) for the route var points = [ [27.7172, 85.324], // Kathmandu [27.6679, 85.3188], // Lalitpur [27.6729, 85.4286], // Bhaktapur [27.6256, 85.5154] // Banepa ]; // Define a GraphHopper routing object with the API key and profile var ghRouting = new GraphHopper.Routing({ key: '<your_api_key>', vehicle: 'car' }); // Calculate the route using the GraphHopper API ghRouting.route({ points: points, instructions: true, vehicle: 'car', elevation: false }, function (err, res) { if (err) { console.error(err); return; } // Create a new … -
How can I use the FloatingField function with an email input in Django crispy forms with Bootstrap 5?
I have a Django project where I'm using crispy forms with the Bootstrap 5 version. https://github.com/django-crispy-forms/crispy-bootstrap5 I have two floating fields for the username and password input, but I also need to add an email input. FloatingField('username', css_class='shadow-none'), FloatingField('password', css_class='shadow-none'), I tried to search for a solution in the GitHub repository, but I couldn't find anything. I was expecting to find some documentation or an example of how to add an email input to the floating field layout. I concluded that it would be best to ask here before submitting any issue to the github repository, so how can I add an email input to the floating field layout in Django crispy forms with Bootstrap 5?