Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django REST Framework received JPEG file as a String to ImageField
I have a model in Django like: from django.db import models from django.contrib.auth.models import User from datetime import datetime # Create your models here. class UserDetails(models.Model): def getFileName(self, filename): return 'profile_pics/'+str(self.user.id)+'/'+filename user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) profile_picture = models.ImageField(upload_to=getFileName, blank = True) country = models.CharField(max_length = 50, default='India') gender = models.CharField(max_length=10, default='NA') birthday = models.DateField(default=datetime.now()) phone = models.CharField(max_length=15) verified = models.BooleanField(default=False) def __str__(self): try: return self.user.username except: return 'Deleted User - '+str(self.phone) Then, I created a REST API that accepts Multipart requests to create a new user as well as save the user_details for the user. I am making the multipart POST request from my app in Flutter with the Image for the profile picture. The image is coming in the body of the request as a String instead of coming in as a file, where I could have read it with request.FILES['profile_picture']. The body of the request that I am getting by doing a print(request.data) is as follows: Data: <QueryDict: { 'username': ['jonsnow'], 'first_name': ['Jon'], 'last_name': ['Snow'], 'email': ['jonsnow@got.com'], 'password': ['jonsnow'], 'country': ['UK'], 'gender': ['Male'], 'birthday': ['2020-4-28'], 'phone': ['5198189849'], 'profile_picture': ['����\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00��\x00�\x00\t\x06\x07\x08\x07\x06\t\x08\x07\x08\n\n\t\x0b\r\x16\x0f\r\x0c\x0c\r\x1b\x14\x15\x10\x16 \x1d"" \x1d\x1f\x1f$(4,$&1\'\x1f\x1f-=-157:::#+?D?8C49:7\x01\n\n\n\r\x0c\r\x1a\x0f\x0f\x1a7%\x1f%77777777777777777777777777777777777777777777777777��\x00\x11\x08\x019\x01�\x03\x01"\x00\x02\x11\x01\x03\x11\x01��\x00\x1c\x00\x00\x02\x03\x01\x01\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03\x04\x02\x05\x06\x01\x07\x00\x08��\x00Q\x10\x00\x02\x01\x03\x02\x03\x05\x04\x06\x06\x07\x07\x03\x03\x01\t\x01\x02\x03\x00\x04\x11\x12!\x051A\x06\x13"Qa2q��\x14B����\x07#3Rr�\x154Sbs��\x16$C����5��%c�DtEFd����\x17��\x00\x1a\x01\x01\x01\x01\x01\x01\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06��\x00(\x11\x01\x01\x00\x02\x01\x04\x02\x02\x02\x02\x03\x01\x00\x00\x00\x00\x00\x01\x02\x11\x03\x12!1A\x04\x13\x14Q\x05"aqBR�\x15��\x00\x0c\x03\x01\x00\x02\x11\x03\x11\x00?\x00�Cl�0ɵX��¸�iB�k; ...\uebe8?��'] }> And print(request.FILES) is coming as: Files: <MultiValueDict: {}> So, I made the Multipart REST … -
Empty list inside QueryDict is actually is not empy
I have a QueryDyct object (request.data) in my method and want to do some modifications on so I have copied it: data_dict = data.copy(). On creating an empty list in it, it creates list of list: data_dict['emails'] = [] data_dict['emails'].append('foo@mail.com') data_dict['emails'].append('bar@mail.com') Instead of crating an empty list and append data into it, it creates list of list, and appends data into inner list: On PyCharm watch it is shown as: Why it behaves like this? And for the further processing it is treated (by django validator) as an email with address ['foo@mail.com', 'bar@mail.com'], but I want to have two different emails with appended addresses. How can I construct normal empty list in QueryDict ? -
Trying to send email by smtplib in django project but fatal python error occurs and compiler terminates. How can i solve this issue?
I am trying to send email using smtplib in my django 1.11 project but "Fatal Python error: Cannot recover from stack overflow." errors occurs and compiler terminates without to exception . How can i solve this issue? This same code was working before, I have not updated my python version nor updated my django version but the same code is not working now. I am using python version 3.6.8, django version 1.11 and my IDE is eclipse. def emailSendingFunctionTest(Subject, Message, EmailAddress, leadCaptureEmailStatusId, assignedToId): sender = Constants.EmailConfig_Email() MESSAGE = MIMEMultipart('alternative') MESSAGE['SUBJECT'] = Subject receivers = EmailAddress HTML_BODY = MIMEText(Message, 'html') MESSAGE.attach(HTML_BODY) try: server = smtplib.SMTP(Constants.EmailConfig_SMTP()) server.starttls() server.verify(EmailAddress) server.login(Constants.EmailConfig_Email(), Constants.EmailConfig_Password()) server.sendmail(sender, receivers, MESSAGE.as_string()) server.quit() finally: cursor.close() conn.close() except smtplib.SMTPException as e: print(str(e)) except Exception as ex: print(str(ex)) I am calling this function from an other function like this: emailSendingFunctionTest(subject, message, emailAddressAssignedTo, leadCaptureEmailStatusId, newLead["assignedToId"]) I have attached the screenshot of errors i am facing: I need help to solve this issue as soon as possible. Thanks in advance. -
Difference between staff_member_required and user_passes_test
I've a doubt about the use of this two decorators. In my project I've some view in which I will allow the access only to the staff member. These are restricted area in which a staff can create a post or modify something about the user profile. This area is the admin area of my web site but is not a default django admin. I've create a backend area that doesn't use django admin site. I've this view: MODE 1 from django.contrib.admin.views.decorators import staff_member_required @staff_member_required(login_url='login') def staff_site(request): some code here MODE 2 from django.contrib.auth.decorators import user_passes_test @user_passes_test(lambda u:u.is_staff, login_url='login') def staff_site(request): some code here What is the right way that I must use for my aim? -
Use serializer in itself Django
How can I use my serializer for an instance in the serializer. So in itself Ex: class CompanySerializer(serializers.ModelSerializer): parent = CompanySerializer class Meta: model = Company fields = ("id", "name", "parent") Django doesn't recognize it and asks to create a CompanySerializer.. -
why model attribut is necessary for update view but not create view?
here in the below code in the CreateView theres no mention of model , but since we have mentioned form_class it automatically uses the model class mentioned in the form_class which is Book.but why doesnt it do same with the Update view . in UpdateView if i remove the model attribute it gives error: UpdateBook is missing a QuerySet. Define UpdateBook.model, UpdateBook.queryset, or override UpdateBook.get_queryset(). required code: models.py: class Book(models.Model): name = models.CharField(max_length=50) picture = models.ImageField() author = models.CharField(max_length=30, default="Anonymous") email = models.EmailField(blank=True) describe = models.TextField(default="Good Book") def __str__(self): return self.name views.py: class Upload(CreateView): form_class = BookCreate template_name = "libraryapp/upload_form.html" success_url = reverse_lazy('libraryapp:index') class UpdateBook(UpdateView): model=Book form_class = BookCreate template_name = "libraryapp/upload_form.html" success_url = reverse_lazy('libraryapp:index') -
Linking enum values when used in Django choices
I'm writing a Django web app to allow doctors to manage their pending licenses, certifications, and access to scientific journals in one dashboard. I've created a model JournalEntry that represents information shown on the dashboard about a journal they are subscribed to, with information like renewal date and subscription type built into the model. It is the case that there are certain choices for journal name, so the name field on the JournalEntry model is a CharField: class JournalEntry(models.Model): name = models.CharField( null=False, choices=JOURNAL_NAME_CHOICES, max_length=256) renewal_date = models.DateField( verbose_name="Date of Renewal", auto_now=False, auto_now_add=False, blank=True, null=True, ) sub_cost = models.FloatField( blank=True, null=False, max_length=6, verbose_name='Subscription Cost', ) icon_link = models.CharField( null=True, max_length=1024, blank=True) with the choices defined in an enum at the top like this: JOURNAL_NAME_CHOICES = [ ('NEJM', 'New England Journal of Medicine'), ('JVS', 'Journal of Vascular Surgery'), ] I want to have an icon image associated with each journal we allow for (eg the logo of the New England Journal of Medicine should show up next to the name on the entry on the dashboard), but I'm not sure how I can get the logo image url (say, a google images link) to be associated with the Journal name such … -
Pytest assert django context_data
I'm trying to create pytest for a view, where I added form in get_context_data function def get_context_data(self, **kwargs): context = super(PostDetailView, self).get_context_data(**kwargs) context["form"] = CommentForm return context I made something like this def test_post_detail_view_queryset(self, client, supply_post): response = client.get(reverse('post_detail', kwargs={'slug': supply_post.slug})) assert response.context['form'] == True But i receive error TestPostDetailView::test_post_detail_view_queryset - AssertionError: assert <class 'comments.forms.CommentForm'> == True. Anyone knows how to resolve it? -
redirect to payment page is blocked by cors policy
i have an django rest api when i redirect user to payment page and i get this Access to XMLHttpRequest at 'https://<bank address>' (redirected from 'https://<my website>') from origin 'https://my origin' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. this is my settings.py INSTALLED_APPS = [ 'corsheaders', # other apps ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', # other middlewares ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_METHODS = [ # 'DELETE', 'GET', 'OPTIONS', # 'PATCH', 'POST', 'PUT', ] i have tried every solution in other related questions. -
NoReverseMatch : How to add foreign key in reverse function?
Getting "Reverse for 'detail' with keyword arguments '{'pk': }' not found. 1 pattern(s) tried: ['picture/(?P[0-9]+)/$']" #views.py class ItemDelete(DeleteView): model = Pic success_url = reverse_lazy('picture:detail', kwargs={'pk': Pic.album_id}) #urls.py urlpatterns - [ # /picture/<album_id>/ url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'), ] #models.py class Pic(models.Model): album = models.ForeignKey(Album, on_delete=models.CASCADE) file_type = models.CharField(max_length=100) caption = models.CharField(max_length=100) is_favorite = models.BooleanField(default=False) def get_absolute_url(self): return reverse('picture:item-detail', kwargs={ 'id': self.album_id , 'pk': self.pk}) def __str__(self): return self.caption -
Django two models in one view with ajax?
I have created a view that give me the possibility to fill a form using an Ajax call. This the code: # models.py class CrudUser(models.Model): name = models.CharField(max_length=30, blank=True) address = models.CharField(max_length=100, blank=True) age = models.IntegerField(blank=True, null=True) # Views.py from .models import CrudUser from django.views.generic import View from django.http import JsonResponse class CreateCrudUser(View): def get(self, request): name1 = request.GET.get('name', None) address1 = request.GET.get('address', None) age1 = request.GET.get('age', None) obj = CrudUser.objects.create( name = name1, address = address1, age = age1 ) user = {'id':obj.id,'name':obj.name,'address':obj.address,'age':obj.age} data = { 'user': user } return JsonResponse(data)' But if I want to add a new models in my CreateCrudUser how could I do it? Ad example the following one: # models.py class Dog(models.Model): name = models.CharField(max_length=30, blank=True) eyes_color= models.CharField(max_length=100, blank=True) age= models.IntegerField(blank=True, null=True) -
Django Modelform does not save TimeField to database
Hi i am creating a ModelForm where a user can enter a date and it gets saved to the database. Although the form is submitted successfully and the Charfield is saved to the database my Timefield object does not get saved. This is what the admin page looks like for me My models.py: from django.db import models # Create your models here. class GameSession(models.Model): gamechoices=[ ('seasons', 'Seasons'), ('proclubs', 'Proclubs'), ] game_choice=models.CharField(max_length=50, choices=gamechoices, default=None) time=models.TimeField() my forms.py from django import forms from .models import GameSession class CreateGameForm(forms.ModelForm): class Meta: model=GameSession fields=['game_choice', 'time'] my views.py from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from .forms import CreateGameForm # Create your views here. @login_required def create_game(request): if request.method=="POST": form=CreateGameForm(request.POST) if form.is_valid(): form.save() return redirect('create-game') else: form=CreateGameForm() context={ 'form':form } return render(request, 'games/create_game.html', context) Also, right now models.TimeField shows up in the browser as a text input. Is there a way to make it such that the user can select a time rather than input it manually and what is the default format in which time has to be input? -
Enable log entries for all users in django application
Is there a way to add/enable log entries for all crud action in all models by any user? from django.contrib.admin.models import LogEntry #this seems to exempt from logentry actions by non-admin users return LogEntry.objects.all() -
No values inserted in drop down boxes
please check my code for this problem. Nothing gets inserted in my drop down boxes as I open this page. There are no errors, but nothing is inserted in drop down boxes. Please help me solve this error. Thank you. python code : def menu(request): regular = Regular.objects.all() sicilian = Sicilian.objects.all() subs = Subs.objects.all() regplac = str(request.POST["regplace"]) sicplac = str(request.POST["sicplace"]) subplac = str(request.POST["subplace"]) return render(request,"place.html", reg=regplac, sic=sicplac, sub=subplac) html code : <html> <head> <title> logged in </title> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"> </script> </head> <body> <h1 style="font-family:verdana; font-style:italic;">Welcome to our site !!!!</h1> <ul> <li>currently logged in as {{ user.username }}</li> <li><a href="{% url 'logout' %}">logout</a></i> </ul> <hr> <form action="{% url 'menu' %}" method="post"> {% csrf_token %} <select name="regplace"> {% for r in regular %} <option>{{r}}</option> {% endfor %} </select> <select name="sicplace"> {% for s in sicilian %} <option>{{s}}</option> {% endfor %} </select> <select name="subplace"> {% for u in subs %} <option>{{u}}</option> {% endfor %}} </select> <input type="submit" value="place order"/> </form> </body> </html> -
Add model attribute to same model in Django
I have a model called Company. The Company could be the child of a bigger company. So in the model Company should be a attribute "parent" that is also a Company. I got this: class Company(models.Model): name = models.CharField(max_length=250) parent = models.ForeignKey( Company, on_delete=models.SET_NULL, related_name="notification", null=True, blank=False, ) But django is always saying I need to create a Company class. Is this the right way to do this? -
getting error Reverse for image not found in django
i want to display uploaded images in my template file, but i am getting this error Reverse for 'portfolio/steve-jobs.jpg' not found. 'portfolio/steve-jobs.jpg' is not a valid view function or pattern name., my images under mysite/uploads/portfolio/ folder can anyone please help me how to resolve this error ? here i have uploaded my whole template.html code here {% for portfolio_data in portfolio %} <div class="col-lg-4 col-6 mb-4 shuffle-item"> <div class="position-relative rounded hover-wrapper"> <img src="{% url portfolio_data.image %}" alt="portfolio-image" class="img-fluid rounded w-100"> <div class="hover-overlay"> <div class="hover-content"> <a class="btn btn-light btn-sm" href="{{ portfolio_data.url }}" target="_blank">view project</a> </div> </div> </div> </div> {% endfor %} -
Proper way of doing Geolocations using GeoIP inside a Celery task
So, I have a Django middleware calling a Celery task. This task queries the GeoIP2 database to geolocate the given IP address and perform some additional processing. In the simplified form, the celery task looks like this: @shared_task(bind=True) def dump_json_logs(self, data): g = GeoIP2() location = g.city(data["ip_address"]) # some other code... The thing is, this celery task may be called thousands of times a second, which will cause the g = GeoIP2() client to be initialized every time the task is processed. Can I move this statement outside the function so that the client is initialized only once and then passed to each task? Where should I move it to in this case? -
How do I trigger a Celery task from Django admin?
I have a model called Publication and I'd like to add a button to the list view in Django Admin which would allow triggering a Celery task. admin.py: from django.contrib import admin from .models import Publication class PublicationAdmin(admin.ModelAdmin): change_list_template = "variants/admin_publication_list.html" def update(self, request): # trigger task # redirect to admin list admin.site.register(Publication, PublicationAdmin) variants/admin_publication_list.html: {% extends 'admin/change_list.html' %} {% block object-tools %} <li> <a href="/admin/variants/publication/update/"> Update </a> </li> {{ block.super }} {% endblock %} However when I press a button I only get a notice: Publication with ID “update” doesn’t exist. Perhaps it was deleted? -
NOT NULL constraint failed: api_userlog.browser_info_id (when i want to add show me this error but update and list are working fine)
model.py from django.db import models from django.utils import timezone Create your models here. class PageOnHold(models.Model): timestamp = models.DateTimeField(max_length=None,blank=True, null=True,default=timezone.now) spent_time = models.IntegerField(max_length=None,blank=True, null=True) elapsed_time = models.DateTimeField(max_length=None,blank=True, null=True,default=timezone.now) class MouseClick(models.Model): timestamp = models.DateTimeField(blank=True, null=True,default=timezone.now) x_cord = models.IntegerField(max_length=None,blank=True, null=True) y_cord = models.IntegerField(max_length=None,blank=True, null=True) class MouseOver(models.Model): timestamp = models.DateTimeField(blank=True, null=True,default=timezone.now) x_cord = models.IntegerField(max_length=None,blank=True, null=True) y_cord = models.IntegerField(max_length=None,blank=True, null=True) class InteractionInfo(models.Model): page_in_time = models.DateTimeField(blank=True, null=True,default=timezone.now) page_on_hold = models.ForeignKey('PageOnHold',on_delete=models.CASCADE) page_out_time = models.DateTimeField(blank=True, null=True,default=timezone.now) estimated_time_spent = models.DateTimeField(max_length=None,blank=True, null=True,default=timezone.now) mouse_click = models.ForeignKey('MouseClick',on_delete= models.CASCADE) mouse_over = models.ForeignKey('MouseOver',on_delete= models.CASCADE) class NetworkInfo(models.Model): city = models.CharField(max_length=100) country = models.CharField(max_length=100) hostname = models.CharField(max_length=100) latitude = models.IntegerField(max_length=None) longitude = models.IntegerField(max_length=None) org = models.CharField(max_length=100) postal = models.IntegerField(max_length=None) region = models.CharField(max_length=100) timezone = models.DateTimeField(max_length=100,default=timezone.now) def __str__(self): return self.city class BrowserInfo(models.Model): app_code = models.CharField(max_length=100) app_name = models.CharField(max_length=100) app_version = models.CharField(max_length=100) cookie_enabled = models.BooleanField(default=False) language = models.CharField(max_length=100) online = models.BooleanField(default=False) platform = models.CharField(max_length=100) # plugins = models.ForeignKey(plugins) # another table should be implement user_agent = models.CharField(max_length=100) has_err = models.BooleanField(default=False) def __str__(self): return self.app_code class GeoLocation(models.Model): timestamp = models.DateTimeField(null=True,blank=True,default=timezone.now) coords = models.ForeignKey('Coords',on_delete=models.CASCADE) hasErr = models.BooleanField(default=False) errCode = models.CharField(max_length=100) def __str__(self): return self.errCode class Coords(models.Model): accuracy = models.IntegerField(max_length=None,blank=True, null=True,default='SOME STRING') altitude = models.IntegerField(max_length=None,blank=True, null=True,default='SOME STRING') altitudeAccuracy= models.CharField(max_length=100,blank=True, null=True,default='SOME STRING') heading = models.CharField(max_length=100,blank=True, null=True,default='SOME STRING') latitude = models.IntegerField(max_length=None,blank=True, null=True,default='SOME STRING') … -
Modify datetime value in result of F() expression
I am trying to modify datetime value while making filter. I need to make each scheduled_for value to 02:00 AM next day and compare this date to other field. So at first I add 1 day with timedelta(days=1) and then in annotation I try to replace hours and minutes: bookings = Booking.objects.filter( cancel_time__isnull=False ).annotate( invoice_date=ExpressionWrapper((F('scheduled_for') + timedelta(days=1)), output_field=models.DateTimeField()) ).annotate( invoice_time=F('invoice_date').replace(hour=2, minute=0, second=0, microsecond=0) ).filter(invoice_time__gte=F('cancel_time')) But that thing doesn't work and I got error: AttributeError: 'F' object has no attribute 'replace' Is there any way to accomplish what I am trying to do? P.S.: Also I am not sure should I use DurationField or DateTimeField as output_field in ExpressionWrapper. -
Unable to delete the data from mysql table which is fetched from a form in HTML using Django
I am want to: 1. save data from a HTML form to MySQL 2. delete data from mySQL which is entered through HTML form. The save functionality is working. While there is error in delete functionality. Model.py from django.db import models # Create your models here. class info_needed(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=200) surname = models.CharField(max_length=200) email = models.CharField(max_length=200) def __str__(self): return self.name views.py # Create your views here. from django.shortcuts import render from django.http import HttpResponse from .models import info_needed def index(request): return render(request,'userdata/index.html') def message(request): if request.method == 'POST': fname = request.POST.get("fname") lname = request.POST.get("lname") mail = request.POST.get("mail") action = request.POST.get("submit_button") action1 = request.POST.get("delete_button") p = info_needed(name = fname , surname = lname, email = mail) print("name", fname) print("action", action) print("action2", action1) if action == "Submit": p.save() elif action1 == "Delete": p.delete() else: return HttpResponse("Wrong Action Provided") return(HttpResponse("Thank you for submitting your details")) urls.py from django.urls import path from . import views urlpatterns = [ path('',views.index, name = 'index'), path('submit/', views.message, name = 'submit'), ] index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>My Page</title> </head> <body> <form action="{% url 'submit' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form }} <label for="fname">Name:</label> <input type="text" id="fname" name="fname"><br><br> <label … -
New message notifications for contacts in django channel?
I'm working to build a real-time chat app with django channels like whatsapp. Its working and I can send/receive message to active chat contact. But the main problem is how to raise notification when new message come from other contacts? consumer.py class TwilioWChatConsumer(AsyncConsumer): async def websocket_connect(self, event): other_user = self.scope['url_route']['kwargs']['contect_id'] me = self.scope['user'] self.login_contact = await self.get_contact_by_user(me) if me.is_authenticated: if me.id == other_user: await self.send({ "type": "websocket.close", }) return False self.thread_obj = await self.get_thread(me, other_user) self.chat_room = f"ChatThread_{self.thread_obj.id}" await self.channel_layer.group_add( self.chat_room, self.channel_name ) await self.send({ "type": "websocket.accept", }) else: await self.send({ "type": "websocket.close", }) async def websocket_receive(self, event): user = self.scope['user'] other_contect_id = self.scope['url_route']['kwargs']['contect_id'] if user.is_authenticated: text = json.loads(event['text']) if type(event['text']) == str else event['text'] other_contact = await self.get_contact(event['from_contect']) chatMsg = await self.create_chat_message(other_contact, text['Body']) myResponse = { 'message': event['text']['Body'], 'contact_type': 'asker', 'timestamp': str(chatMsg.timestamp.strftime("%d %b %y, %H:%M:%S")), } await self.channel_layer.group_send( self.chat_room, { 'type': 'chat_message', 'text': json.dumps(myResponse) } ) return True Check below screenshot for better understanding chat window -
moving tags inside a nav bar
How to move this 'NIHAAL NZ' to the marked position using HTML and css. To the centre of the nav-links. Please try to be elaborate as i;m just a beginner and this is for django websites. Thanks in advance :)[! I found it a bit complicated to move things around and do stuff so please do let me out, this community is so helpful in making progress.Image is given enter image description here]1 HTML CODE: {% load static %} <link rel="stylesheet" href="{% static "portofolio/css/style.css" %}"> <link href="https://fonts.googleapis.com/css2?family=Poppins&display=swap" rel="stylesheet"> {% block content %} <nav> <div class="logo"> <h4>Nihaal Nz</h4> </div> <ul class="nav-links"> <li><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a href="#">Contact</a></li> </ul> </nav> {% endblock %} CSS CODE: *{ margin: 0; padding: 0; box-sizing: content-box; } p { ; } .nav-link{ font-family: 'Poppins', sans-serif; } nav { display: flex; justify-content: center; align-items: baseline; min-height: 8vh; padding-top: 100px; height: 100px; background-color: black; } .logo { color: rgb(226,226,226); text-transform: uppercase; letter-spacing: 5px; font-size: 20px; font-family: 'Poppins', sans-serif;; } .nav-links { display: flex; justify-content: space-around; width: 30%; } .nav-links li { list-style: none; } .nav-links a { color: rgb(226,226,226); text-decoration: none; letter-spacing: 3px; font-weight: bold; font-size: 14px; font-family: 'Poppins', sans-serif; } -
Source page instead of page and wrong validation
Below is the code to write comments and reply to. I used django 2.2 and jQuery (Ajax part) here. I have a problem with reply to comment forms. When I press "Add answer" (no data in form) the source of the page appears instead of validation. If I add text and press "Add answer" (form with data), an error appears: The view spot.views.SpotDetailView didn't return an HttpResponse object. It returned None instead. Adding comments - works correctly, adds without errors (when data are in form). Validation works (empty form), but error messages also appear on other forms (forms reply to comment). I'm asking for help, thanks. detail_page.html <div class="comment-section"> {% include 'spot/comments.html' %} </div> comments.html <div class="mt-4 mb-4"> {% for comment in object.all_comments %} <div class="card mt-2"> <div class="card-body"> <div class="row"> <div class="col-md-2 col-sm-2"> <img src="https://image.ibb.co/jw55Ex/def_face.jpg" class="img img-rounded img-fluid"/> <p class="text-secondary text-center">{{ comment.date_create }}</p> </div> <div class="col-md-10"> <div class="float-right"> <i class="fas fa-ellipsis-h" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"></i> <div class="dropdown-menu"> <a class="dropdown-item" href="{% url 'spot_comment_update_url' comment.pk %}"><i class="fas fa-edit"></i> Edit</a> <a class="dropdown-item" href="{% url 'spot_comment_delete_url' comment.pk %}"><i class="fas fa-trash-alt"></i> Delete</a> </div> </div> <p><a class="float-left" href="#"><strong>{{ comment.author }}</strong></a></p> <div class="clearfix"></div> <p>{{ comment.text }}</p> </div> </div> {% for reply in comment.replies.all %} <div class="card card-inner … -
Django admin template: what is base_site.html
I am currently customizing the admin templates and this makes me wonders that what is the usage/purpose of base_site.html? I understand that base_site.html extends from base.html but from the original code itself, it only adds HTML content for branding and title blocks. Hence, if I'm overriding the whole base.html, I can just add HTML content for branding and title blocks in base.html and empty the base_site.html. Please correct me if I am wrong. Thank you