Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I do to test the method save from a Model?
I have this model : class Team(models.Model): user = models.CharField(max_length=250, default="default", null=True) def __str__(self): return self.user And I would like to do a unittest for the save. I have that : class TeamModelTest(TestCase): @classmethod def setUpTestData(cls): Team.objects.create(user='Peter') def test_save(self): team = Team() team.user = 'Bruce' team.save() But the problem is how can I do to test a function which return nothing ? Could you help me please ? Thank you very much ! -
Static folder django
I just created a django application, and I have a problem that I cannot resolve. I have 1 css file 'root.css' that I would like to link with my html database but it's like this /static/root.css was completely ignored. I arrive mostly at link /static/home/home.css on my home app. This is not work (/templates/base.html) : {% load static %} <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr-FR" lang="fr-FR"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover"> <link rel="stylesheet" type="text/css" ref="{% static 'root.css' %}"> **// Not work** {% block css %} {% endblock %} <title>Learned</title> </head> <body> {% block content %} {% endblock %} </body> </html> This is work (/home/templates.home.html) : {% block css %} {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'home/home.css' %}"> {% endblock %} In my settings.py : STATIC_URL = 'static/' STATICFILES_DIRS = [ BASE_DIR / "static" ] -
My uploaded files are not saved to the Database
my model class FactuurBestanden(models.Model): file = models.FileField(upload_to='profile_pics') my form class FactuurBestandenForm(forms.ModelForm): class Meta: model = FactuurBestanden fields = '__all__' my view def createFacturenAdmin(request): if request.user.is_superuser: if request.method == "POST": form = FactuurBestandenForm(request.POST) if form.is_valid(): form.save() else: print("form not valid") return redirect("facturatie_admin") form = FactuurBestandenForm() return render(request, 'users/admin_facturatie.html', {'form':form}) and my template <form method="post"> {% csrf_token %} {{ form.as_p }} <button style="margin-left: 40px" class="Button1" type="submit">Click here</button> </form> The uploaded files are not saved to the DB ? what am i doing wrong here. -
Unable to POST the data using rest Django - NOT NULL constraint failed: author_id
I have the following error, and I guess the problem with how can I add the author id to the post automatically. And also I tried to add null=True author = models.ForeignKey(User, null=True, blank=True) The error disappeared! but unfortunately, the author id is still null!!! Please I'm a new developer in Django. IntegrityError at /auctions/api/addAuction/ NOT NULL constraint failed: auctions_auction.author_id Request Method: POST Request URL: http://127.0.0.1:8000/auctions/api/addAuction/ Django Version: 3.1.5 Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: auctions_auction.author_id /auctions/api/serializers.py class AddAuctionsSerializer(serializers.ModelSerializer): print("AddA uctionsSerializer Function call") class Meta: model = Auction # Get the current user from request context def validate_author(self, value): return self.context['request'].user author_id = serializers.Field(source='author.id') fields = ["title", "desc", "image","location","min_value","date_added","author_id"] read_only_fields = ('author','id','author_id','author.id') /auctions/api/view.py class addAuction(APIView): #permission_classes = [permissions.IsAuthenticated] #authentication_classes = [SessionAuthentication, BasicAuthentication] def pre_save(self, obj): obj.owner = self.request.user def post(self, request, format=None): auction = Auction() auction.author = request.user serializer = AddAuctionsSerializer(data=request.data) print(serializer) 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) /auctions/api/url.py``` path('addAuction/', addAuction.as_view()), /auctions/model.py class Auction(models.Model): location = LocationField() author = models.ForeignKey(User, on_delete=models.CASCADE,null=False) # author = models.ForeignKey(User, null=True, blank=True) title = models.CharField(max_length=300) desc = models.CharField(max_length=2000, blank=True) image = models.ImageField(upload_to='auction_images/', blank=True, default = 'auction_images/default/default.svg') min_value = models.IntegerField() #date_added = models.DateTimeField() date_added = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) winner … -
Django runserver is working but website isn't loading on other port than 8080: CPANEL
I have two projects of Django, I am using the Cpanel terminal to host this at 8080(WORKING),8083(NOT WORKING) I am using the Cpanel terminal to host the Django website at port 8083 Now I tried this python manage.py runserver 0.0.0.0:8083 It is working and the server started at 0.0.0.0:8083 Now this should be visible to us in the browser using our websiteIP:8083 But this isn't working. The port 8083 website isn't loading but port 8080 I have checked ALLOWED HOST =["my.IP.241.0","my_website_url.com"] in settings.py -
Django Template - Unable To Modify Jekyll Carousel Script
I'm using the Jekyll framework and using the official Carousel script from their website (https://jekyllcodex.org/without-plugin/slider/) and I'm struggling to figure out how to make it possible to pass a name to the carousel.html script so that I can setup multiple carousels using the same script. My goal is to be able to just use: {% include carousel.html name="CatImages" height="20" unit="%" duration="7" %} and it should be able to simply receive the images from a carousel.yml file that looks similar to: ` CatImages: - /assets/img/cat1.png - /assets/img/cat2.png I've tried to append the string to the variable name, which works but gives me a slightly different output - one that I can't figure out the type of. The resulting variable coming from {{site.data.carousel.{{ include.name }}}} returns {"CatImages"=>["/assets/img/cat1.png", "/assets/img/cat2.png"]} and when running through the for loops it returns the image paths as one whole string. For example, this: {% for item in images %} {{item}} {% endfor %} returns: images/assets/img/cat1.png/assets/img/cat2.png But overall, I don't understand what the variable is and I can't figure it out from googling. I'm new to Django templates, but for the life of me I can't figure out what the {""=>["",""]} notation is. Any pointers or tips would be … -
CONSOLE ERROR: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
I am trying to receive a data from form in HTML, I added javascript to add EventListener and convert the data into json format var form = document.getElementById('form') csrftoken = form.getElementsByTagName("input")[0].value console.log("Newtoken:", form.getElementsByTagName("input")[0].value) form.addEventListener('submit', function(e){ e.preventDefault() console.log('Form submitted') submitFormData() }) function submitFormData(){ console.log('Add button clicked') var itemInfo = { 'item_name':form.item_name.value, 'item_quantity':form.item_quantity.value, 'item_status':form.item_status.value, 'date':form.date.value, } console.log('Item Info:', itemInfo) var url = '/add_item/' fetch(url,{ method:'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({'item':itemInfo}) }) .then((response) => response.json()) .then((data) => { console.log('Success:', data); window.location.href = "{% url 'listview' %}" }) } But I keep getting this console error: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 Promise.then (async) submitFormData @ (index):75 (anonymous) @ (index):51 -
how can i pre set author by user with helper crispy inlineformset_factory django?
guys. First fo all, thanks for any helpers. I have started learning Django a few months. So, I am trying to set author with the logged user. I have spent long hours looking up for... But up to now I didn't have successful. models.py class Painel(models.Model): created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) hashtag = models.CharField(max_length=255, unique=True, blank=False, null=True) painel_date_posted = models.DateTimeField(auto_now_add= True, null=True) painel_date_updated = models.DateTimeField(auto_now= True, null=True) def __str__(self): return self.hashtag def get_absolute_url(self): return reverse('painel-detail', kwargs={'hashtag': self.hashtag}) class Post(models.Model): #=============================================================================== author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) painel = models.ForeignKey(Painel, on_delete=models.CASCADE, blank=True, null=True) title = models.CharField(max_length=100, blank=False) slug = models.SlugField(max_length=100 ,null=True) #=============================================================================== content = models.TextField(null=True, help_text='Write your Post', blank=False) url = models.URLField(help_text='Paste here the link, witch you saw that news?', blank=False) contact_number = models.CharField(max_length=20,blank=True, help_text='If you have another way to comunicate.') def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) form.py class PainelForm(ModelForm): class Meta: model = Painel fields = ('hashtag', 'created_by', ) @property def helper(self, *args, **kwargs): helper = FormHelper() helper.form_tag = False # This is crucial. helper.layout = Layout( Fieldset('Create new Painel - {{ user|capfirst }}', PrependedText('hashtag','#', placeholder="hashtag"), ), ) return helper class PostFormHelper(FormHelper): def __init__(self, *args, **kwargs): super(PostFormHelper, self).__init__(*args, **kwargs) self.form_tag = False # This is … -
Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? in Django
I'm getting this error while trying to run: docker-compose run app python manage.py migrate with Django. this is the docker-compose.yml: version: '3' volumes: database: { } services: app: build: context: . dockerfile: ./docker/app/dev/Dockerfile depends_on: - postgres volumes: - ./app:/app:z env_file: - ./.envs/.dev/.app - ./.envs/.dev/.postgres ports: - "8000:8000" command: "python manage.py runserver 0.0.0.0:8000" postgres: image: "postgres:13.1" volumes: - database:/var/lib/postgresql/data:Z env_file: - ./.envs/.dev/.postgres environment: - POSTGRES_HOST_AUTH_METHOD=trust ports: - "5432:5432" I don't know why I'm getting this error. PostgreSQL is running correctly and all the settings are appropiately configured. This is the full traceback error:. Traceback (most recent call last): File "/app/manage.py", line 7, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 92, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/usr/local/lib/python3.9/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/usr/local/lib/python3.9/site-packages/django/db/migrations/loader.py", line 53, in __init__ self.build_graph() File "/usr/local/lib/python3.9/site-packages/django/db/migrations/loader.py", line 216, in build_graph self.applied_migrations = recorder.applied_migrations() File "/usr/local/lib/python3.9/site-packages/django/db/migrations/recorder.py", line 77, in applied_migrations if self.has_table(): File "/usr/local/lib/python3.9/site-packages/django/db/migrations/recorder.py", line 55, in has_table with self.connection.cursor() as cursor: File … -
how to get a string parametr in drf modelviewset
i need to use a path with an optional paramentr, to specify a user via a srting a request would look like 'api/users/specific_username' or 'api/users' for all users urls: router = DefaultRouter() router.register(r'users', MyUserViewSet, basename='user-me') views: `class UserViewSet(viewsets.ModelViewSet): serializer_class = UserSerializer def get_queryset(self): queryset = User.objects.all() if self.kwargs['username']: username=self.request.GET.get('username') queryset = User.objects.filter(username=username) return queryset` username=self.kwargs['username'] returns KeyError username=self.request.GET.get('username') returns None -
How to make this serializer (python django) to convert comments under a post to Json data
from .models import User, Post, Project, Comment, Version, Tag from rest_framework import serializers import bcrypt from .models import Stock class PostSerializer(serializers.ModelSerializer) class Meta: model = posts fields = 'all' def create(self, validated_data): I cant figure out how to make it convert the data -
Django CSRF Token not validated despite inheriting Generic View and CSRF middleware
I have a POST request on a DRF view that inherits generics.CreateAPIView and CSRF enabled in middleware, but despite that it doesn't validate my CSRF token, I am not sure why not ? Here's my View: class SchemeView(generics.CreateAPIView): queryset = SchemeModel.objects.get_queryset() serializer_class = SchemeModelGraphSerializer def post(self, request, *args, **kwargs): try: ----Business Logic Code ----- return Response(result, status=status.HTTP_200_OK) except Exception as e: return Response("Error: %s" % (e), status=status.HTTP_400_BAD_REQUEST) Middleware: MIDDLEWARE = { 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'corsheaders.middleware.CorsMiddleware', 'RMS.middleware.AuthTokenMiddleware' } REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'RMS.authentication.JWTAuthentication', 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } CSRF Settings: CSRF_COOKIE_SECURE = False CSRF_COOKIE_HTTPONLY = True Using React for FE, Django for BE, CSRF Cookies does get sent along with request to Django server. I tried changing CSRF cookie value, but Django silently ignores it. Note: Some had suggested that along with Token auth, CSRF isn't needed. But I don't understand the reason why ? Also, not using CSRF with Token Auth, doesn't provide a solution to Django ignoring CSRF validation. I am more curious as why doesn't it get validated ? -
How to fetch a query/mutation to graphene-django API from JavaScript?
I am trying to make a mutation when the user submits a form, but I always get a 400 err. The weird thing is that I used the GraphiQL interface to check how do they do the fetch function, and in the end, they use the exact same headers, method, body, and credentials. So I really don't know how to do it. This is the mutation: const mutation = ` mutation { createCompetitors(comp1: ${comp_1}, comp2: ${comp_2}) { comp1 { id name } comp2 { id name } } } `; fetch('/graphql/#', { method: 'POST', headers: { "Accept": 'application/json', "Content-Type": 'application/json', "X-CSRFToken": getCookie('csrftoken') }, body: JSON.stringify({ query: mutation }), credentials: 'include', }) .then(response => { if (!response.ok) { throw Error(`${response.statusText} - ${response.url}`); } return response.json(); }) .then(result => { console.log(result) }) .catch(err => { if (err.stack === 'TypeError: Failed to fetch') { err = 'Hubo un error en el proceso, intenta más tarde.' } useModal('Error', err); }) I get a 400 error that just says: Failed to load resource: the server responded with a status of 400 (Bad Request), and the Django output says: Bad Request: /graphql/ [07/Feb/2021 12:51:44] "POST /graphql/ HTTP/1.1" 400 294 But that is not it. After this, … -
Django: How to create a abstract field?
I would like to start using an abstract model for my application (based on a django-accounting app). How should I create my field on the views.py. I guess I will also need to change my view file when creating a new field...Can I still create the same way I used to if it was not an abstract model? views.py @login_required(login_url="/login/") def create_bill(request): form = BillForm(request.POST or None, request.FILES or None) if form.is_valid(): bill = form.save(commit=False) bill.save() return render(request, 'accounting/bills/detail.html', {'bill': bill}) context = { "form": form, } return render(request, 'accounting/bills/create_bill.html', context) @login_required(login_url="/login/") def detail_bill(request, bill_id): user = request.user bill = get_object_or_404(Bill, pk=bill_id) return render(request, 'accounting/bills/detail.html', {'bill': bill, 'user': user}) @login_required(login_url="/login/") def bill_update(request, bill_id): bill = get_object_or_404(Bill, pk=bill_id) form = BillForm(request.POST or None, instance=bill) if form.is_valid(): form.save() return render(request, 'accounting/bills/index_table.html', {'bill': bill}) else: form = BillForm(instance=bill) return render(request, 'accounting/bills/edit.html', {'form': form}) models.py class AbstractSale(CheckingModelMixin, models.Model): number = models.IntegerField(default=1,db_index=True) # Total price needs to be stored with and wihtout taxes # because the tax percentage can vary depending on the associated lines total_incl_tax = models.DecimalField("Total (inc. tax)",decimal_places=2,max_digits=12,default=D('0')) total_excl_tax = models.DecimalField("Total (excl. tax)",decimal_places=2,max_digits=12,default=D('0')) # tracking date_issued = models.DateField(default=date.today) date_dued = models.DateField("Due date",blank=True, null=True,help_text="The date when the total amount ""should have been collected") date_paid … -
Django Ajax Like Section not working in Docker
I am trying to create dynamic like functionality in Django. But it shows following error: Not Found: /blogs/why-do-we-use-it/{% url "like_post" %} Here is my urls.py: urlpatterns = [ path('', PostListView.as_view(), name='post-list'), path('like/', like_post, name='like_post'), path('<slug:slug>/', post_detail, name='post-detail'), ] models.py: likes = models.ManyToManyField(get_user_model(), blank=True, related_name='likes') views.py: def like_post(request): post = get_object_or_404(Post, id=request.POST.get('post_id')) is_liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) is_liked = False else: post.likes.add(request.user) is_liked = True context = { 'post': post, 'is_liked': is_liked, 'total_likes': post.total_likes(), } if request.is_ajax(): html = render_to_string('blogs/like_section.html', context, request=request) return JsonResponse({'form': html}) post_detail.html: <div id="like-section"> {% include 'blogs/like_section.html' %} </div> like_section.html: {{ total_likes }} Like{{ total_likes|pluralize }} {% if request.user.is_authenticated %} <form action="{% url 'like_post' %}" method="post"> {% csrf_token %} {% if is_liked %} <button type="submit" id="like" name="post_id" value="{{ post.id }}" class="btn btn-danger">Dislike</button> {% else %} <button type="submit" id="like" name="post_id" value="{{ post.id }}" class="btn btn-primary">Like</button> {% endif %} </form> {% endif %} In console logs: The current path, <code>blogs/why-do-we-use-it/{% url &quot;like_post&quot; %}</code>, didn't match any of these. I couldn't find a way how it done. Thanks in advance. -
Background workers and overriding save method on Django models
I have a long-running process that depends on model fields. Let's say I have a model that looks like this class Client(models.Model): input_data = models.CharField(max_length=100) # The field that will be computed in the background task computed_data = models.CharField(max_length=100, null=True, blank=True) I want to trigger a background task every time this model is updated, but the problem is I also need to call the save method after the background task updates the instance. It's roughly looking something like this. def a_long_running_background_task(instance): input_data = instance.input_data # Reading the model input data # Updating the output_data field using the input data from the model instance instance.output_data = input_data.title() # To make sure the changes apply to the database we need to call the save method instance.save() The problem with this code is that it would cause an infinite loop, because I'm calling the background task on the save method, and I'm calling the save method in the background task. And I kept getting this error RecursionError: maximum recursion depth exceeded while calling a Python object After I researched this problem, I found a solution which suggests using the post_save signal, with the created attribute, and then would check if the instance is … -
How to raise error for email field if user is trying to pass just few letters
How can I rise the error and information, if user is puting only "dummy date" without "@"? Email model is email = models.EmailField(max_length=254) but is only preventing passsing empty field, and nothing else. Can someone advice ? def addContact(request): form = ContactForm if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): form.save() return redirect('/contact') context = {'form': form} return render(request, 'contact/new.html', context) -
Django how to control format of input html content
When I copy some content for example a news, from other website into my django website.I copy the whole html which contains the content into my django admin,not only the text content. And in my template I use: {% autoescape off %} {{news.content}} {% endautoescape %} So that it will display text and image content not html code in the final template. But I find some of the content is too wide, makes a scroll bar in the bottom of my django page. I tried to use css like: overflow: hidden !important; But it is still not work.So I need go to admin to use ckeditor to manually editor the format of the article.For example ,add a line break if the line is too long. My question is ,is that any way that django can automatically editor the format of input content?So that I don't need to edit each article's format manually. Best! -
Insert JS value to Django template
As I am exploring Web Development, I require small assistance here. In my case, I have a folder with static images. To display an image I need to get data from API, let's say, some pointer on which particular image should be displayed. <img class="some_img" src="{% static 'image_PIONTER.png' %}"> I'm getting that pointer using JS in a separate file script.js. To achieve what I want I need to replace POINTER in the src attribute of html with some actual word (lets say 'Captain') to get an image 'image_Captain.png' from static files. How could I get this POINTER from a JS to django template? As I already know, Django renders its templates before any client side (JS code) executed. So I cant just pass this attribute or even a part of html as $().html or $().append. It won't work. Picture should be displayed on a button click, preferably without refreshing the whole page. Thanks in advance -
The current path, {% didn't match any of these django responsive images
I keep getting this error when the browser width size is below 640px and above 990px. I am trying to display different resolution images depending on the browser width size. The current path, about/{%, didn't match any of these. In other words the only image that displays properly is footer-city-medium.jpg {% extends "base.html" %} {% block content %} {% load static %} <picture> <source media="(min-width:990px)" srcset={% static '/images/footer-city-large.jpg' %}> <source media="(min-width:640px)" srcset={% static '/images/footer-city-medium.jpg' %}> <img src={% static '/images/footer-city-small.jpg' %}> </picture> {% endblock %} The page renders properly except for the image. Only the footer-city-medium.jpg renders in properly. Does the source attribute not work with django? -
Django Selenium test onclik not calling function
In a Selenium test of my homepage I ran into the following problem: I have a number of buttons on the page. When clicking one of them a selections list is populated with a number of options via a javascript function. After clicking one of the buttons the selection list can look like this: <select id="selectionList" name="List1" size="10" style="width:100%;"> <option style="color:#0275d8">Item Type 1</option> <option onclick="onSelection()" id="Item_1">Item 1</option> <option onclick="onSelection()" id="Item_2">Item 2</option> <option onclick="onSelection()" id="Item_3">Item 3</option> <option onclick="onSelection()" id="Item_4">Item 4</option> <option onclick="onSelection()" id="Item_5">Item 5</option> <option onclick="onSelection()" id="Item_6">Item 6</option> <option style="color:#0275d8">Item Type 2</option> <option onclick="onSelection()" id="Item_7">Item 7</option> <option onclick="onSelection()" id="Item_8">Item 8</option> <option onclick="onSelection()" id="Item_9">Item 9</option> <option onclick="onSelection()" id="Item_10">Item 10</option> </select> In my test I used the following to click on one of the items. WebDriverWait(self.browser, 60).until(EC.element_to_be_clickable((By.XPATH, "//*[@id='Item_1']"))).click() I do see that item 1 gets highlighted but the onSelection() function is not called. I also tried this time.sleep(10) self.browser.find_element_by_id("Item_1").click() Again item 1 gets highlighted but the function onSelection() is not called. Any idea of how to solved this issue? -
How to make time slots(for a particular date and time) not appear after a person has booked it in Django?
I am creating a website in which there is a form where you can book appointments(for doctors)..The issue I am facing is that, if a particular timeslot(for the particular date and time) has been selected it should not appear anymore on the form, but I have no clue on how to do it The form looks like this(This is returned from the index function in views.py) <section id="appointment" data-stellar-background-ratio="3"> <div class="container"> <div class="row"> <div class="col-md-6 col-sm-6"> <img src="{% static 'images/appointment-image.jpg' %}" class="img-responsive" alt=""> </div> <div class="col-md-6 col-sm-6"> <!-- CONTACT FORM HERE --> <form id="appointment-form" role="form" method="post" action="{% url 'test' %}"> {% csrf_token %} <!-- SECTION TITLE --> <div class="section-title wow fadeInUp" data-wow-delay="0.4s"> <h2>Make an appointment</h2> </div> <div class="wow fadeInUp" data-wow-delay="0.8s"> <div class="col-md-6 col-sm-6"> <label for="name">Name</label> <input type="text" class="form-control" id="name" name="name" placeholder="Full Name"> </div> <div class="col-md-6 col-sm-6"> <label for="email">Email</label> <input type="email" class="form-control" id="email" name="email" placeholder="Your Email"> </div> <div class="col-md-6 col-sm-6"> <label for="date">Select Date</label> <input type="date" name="date" value="" class="form-control"> </div> <div class="col-md-6 col-sm-6"> <label for="select">Select Department</label> <select class="form-control" name="drop"> {% for entry in items %} <option>{{ entry.category }}</option> {% endfor %} </select> </div> <div class="col-md-6 col-sm-6"> <label for="select">Select Time</label> <select class="form-control" name="drop1"> {% for entry in times %} <option>{{ entry.time }}</option> {% … -
Django wait for session variable to be written
is it actually possible to wait for a session variable to be written in a django view befor I return the actual response? For example: views: def post_detail(request, pk): .... if post.file: if 'download' in request.session: del request.session['download'] request.session['download'] = post.file.url else: request.session['download'] = post.file.url I just want to wait until the variable has been written sucsessfully to the db/cache. Can smb help? Thanks in advance -
Django GraphQL UI - not working in Heroku
I am trying to deploy a Django-graphql api server to Heroku. The app is successfully deployed to Heroku. However, when I try to launch https://jeba-blogapi.herokuapp.com/graphql/, I am facing the issue The graphql.js is not found, but I have it in my settings.py files STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR,'staticfiles') I am also facing same error when I try to launch admin page(css is not getting loaded) -
Integrating Collapse functionality of Bootstrap with Django Backend. How to use for loops?
I'm struggling with a task in Django. I have my database up and running with information on resellers. (name, address, region etc...) and I want to implement Bootstrap collapse functionality where each card is a region. I was able to do that hardcoding the handling of the region. So in my base.html file I have: <div class="card"> <div class="card-header" id="headingOne"> <h2 class="mb-0"> <button class="btn btn-link btn-block text-left" type="button" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne"> Region1 </button> </h2> </div> <div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#accordionExample"> <div class="card-body"> {% block content_Region1 %} {% endblock %} </div> </div> </div> and in the block content of Region1 I use the home.html template as follow: {% extends "base.html" %} {% load static %} {% block content_Veneto %} <div class = "container"> {% for reseller in resellers %} {% if reseller.region == "Veneto" %} <div class="reseller_name"> <a href="{% url 'reseller_detail' reseller.id %}"> <p>{{reseller.name}} - {{reseller.cityname}}</p> </a> </div> {% endif %} {% endfor %} </div> What I would like to have is a list containing all the regions that are present in by database and then, in the base.html file I would like to do something like: {% for region in list_regions %} <div class="card"> <div class="card-header" id="headingOne"> <h2 …