Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
invalid literal for int() with base 10: 'undefined'
I have model Employee and same table in my local database. I need to have the possibility to edit any record and save it locally. When I tried to edit record with actual id I got this error: invalid literal for int() with base 10: 'undefined'. I made a research but can't really find something helpful in my case. my edit function in views.py: def staff_edit(request, id=0): #employees = Employee.objects.all() #print(employees) if request.method == 'GET': if id == 0: form = EmployeeEditForm() else: employees = Employee.objects.get(pk=id) form = EmployeeEditForm(instance=employees) return render(request, 'staffedit.html', {'form': form}) else: if id == 0: form = EmployeeEditForm(request.POST) else: employees = Employee.objects.get(pk=id) form = EmployeeEditForm(request.POST, instance=employees) if form.is_valid(): form.save() return redirect('feedback:index_employees') context = {'form': form} #when the form is invalid return render(request, 'staffedit.html', context) this is my model.py for Employee: class Employee(models.Model): coreapiemployee_id = models.CharField(max_length=100) webflow_id_employee = models.CharField(max_length=100, default=True) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100, default=True) email = models.EmailField(max_length=100) user_type = models.CharField(max_length=100) status = models.CharField(max_length=100, default=True) roles = models.ManyToManyField('Role', through='EmployeeRole') def __str__(self): return self.coreapiemployee_id + " " + self.email + self.first_name + self.last_name this is my general html staff.html: $(document).ready(function() { var data; fetch("http://192.168.2.85:8000/displayEmployeesToFroentend/") .then(response => response.json()) .then(json => data = json) .then(() => {console.log(data); let … -
ValueError: Related model 'auth.Group' cannot be resolved when running django test
I am new to Django REST Api testing and I am running an error like this raise ValueError('Related model %r cannot be resolved' % self.remote_field.model) ValueError: Related model 'auth.Group' cannot be resolved when running an error, and im not sure this happen -
Multiple instance jquery function with bootstrap modal
I am trying to run jquery function once modal is shown, but I close modal by clicking on the side or one close button and then open I find multiple instances of the inner function running. <script type="text/javascript"> $(document).ready(function () { $(".test").click(function () { var cid = $(this).attr('cid'); $("#post-form").one('submit',function (event){ event.preventDefault(); $.ajax({ url: '{% url 'create_request' %}', type: 'POST', data: { 'cid': cid, 'req_num' : $('#request_number').val(), }, success: function (data) { console.log("success") if (data['request']=='0') { alert("Request is already there"); } else if(data['request']=='1') { alert("Not enough components:("); } $("#exampleModal").modal('hide'); } }) }) }) }) </script> -
How to fix OS error at '/' Invalid Argument?
I have a django application that converts excel to csv files. This works fine but for larger files,it shows OSError at /conversion/ [Errno 22] Invalid argument: '<django.core.files.temp.TemporaryFile object at 0x000001C4C2C21A60>' I have successfully tested with converting smaller files but when I upload large files and try to process it, it shows the above error. views.py def conversion(request): excel_form = '' if request.method == 'POST': excel_form = ConversionForm(request.POST,request.FILES) if excel_form.is_valid(): excel_file = request.FILES['excel_file'].file df = pd.read_excel(excel_file) filename1 = excel_form.cleaned_data.get('excel_file').name filename1 = filename1.replace('.xlsx','') filename1 = filename1.replace('.xls','') df.to_csv(filename1 +'.csv',encoding='ascii',index=None, header=True) context = {'excel_form': excel_form, } return render(request,'colorlib-regform-6/convert_result.html',context) else: excel_form = ConversionForm() rontext = {'excel_form' : excel_form} return render(request,'colorlib-regform-6/convert_result.html',rontext) else: return render(request,'colorlib-regform-6/convert_result.html') -
Django Utils six for Django 3.1.5
I have a token generator that uses six from django.contrib.auth.tokens import PasswordResetTokenGenerator from django.utils import six class AccountActivationTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.is_active) ) account_activation_token = AccountActivationTokenGenerator() This runs on Django 2.2 but my boss told me to run this on latest 3.1.5. However, six was already depreciated. I also checked this SO suggestion https://stackoverflow.com/a/65620383/13933721 Saying to do pip install django-six then change from django.utils import six to import six I did the installation and changes to the code but it gives error message: ModuleNotFoundError: No module named 'six' I think I did something wrong or something is missing but I don't know how to proceed. Here is my pip freeze for reference asgiref==3.3.1 Django==3.1.5 django-six==1.0.4 djangorestframework==3.12.2 Pillow==8.1.0 pytz==2020.5 sqlparse==0.4.1 -
DjangoAdmin: How to get the Add/Edit/Del buttons for an `AutocompleteSelect` form field
I'm using the AutocompleteSelect widget for a ForeignKey field. To do this, you override the ModelForm class like so: class XForm(forms.ModelForm): ... x = forms.ModelChoiceField( queryset=X.objects.all(), widget=AutocompleteSelect(x.field.remote_field, admin.site) ) However, by using this widget I lose the + ✎ ✕ buttons that are available on the Django Admin interface for a Foreign Key field by default. What will be a good way to use AutoCompleteSelect widget but also keeping these Add/Edit/Delete buttons besides the foreign key field on the Admin UI? -
Insert duplicate column value in Django
Is there any way how can I duplicate value to another column,the value should be the same whenever I upload data to column 1 for example. I have 3000 in column 1, the value of column 2 should automatically write 3000, it is possible to trick in models? or When Inserting query instead using default? Thanks in advance!. Current output Column 1 Column 2 5000 5000 3650 5000 2000 5000 Expected output Column 1 Column 2 5000 5000 3650 3650 2000 2000 models.py class Person(models.Model): amount = models.CharField(max_length=50,blank=True, null=True) amount_paid = models.CharField(max_length=60,default='5000', null=True) -
Django edit user profile with Class Based Views
I am trying to develop a profile edit page in Django 3.1. I am new to this so if something is funky just say so. I copied some of this from Django edit user profile Views.py from myapp.forms import UserForm, UserProfileInfoForm from django.views.generic import (View, TemplateView, UpdateView) from myapp.models import UserProfileInfo class UpdateProfile(UpdateView): model = UserProfileInfoForm fields = ['first_name', 'last_name', 'email', 'phone', 'title', 'password'] template_name = 'profile.html' slug_field = 'username' slug_url_kwarg = 'slug' models.py class UserProfileInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone = PhoneField(blank=True, help_text='Contact phone number') title = models.CharField(max_length=255) system_no = models.CharField(max_length=9) def __str__(self): return self.user.username forms.py #... from myapp.models import UserProfileInfo class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta(): model = User fields = ('username', 'email', 'password', 'first_name', 'last_name') class UserProfileInfoForm(forms.ModelForm): class Meta(): model = UserProfileInfo fields = ('phone', 'title', 'system_no') myapp/urls.py from django.urls import path from . import views app_name = 'myapp' urlpatterns = [ path('', views.index,name='index'), path('about/',views.AboutView.as_view(),name='about'), path('register/', views.register,name='register'), path('profile/', views.UpdateProfile.as_view(), name='profile'), ] I have a link that only show after login in: base.html (href only) <a class="nav-link active" href="{% url 'myapp:profile' %}">Profile</a> Can you tell me what to fix? After clicking on the above link I get an error message in the browser AttributeError at /profile/ type … -
How can I make the Dropdown in Django?
I'm a beginner for Django. I'm trying to make the Dropdown to change the table for searching something. I don't know how to make it.... example) when I choose the A in dropdown, It have to search A table. when I choose the B in dropdown, It have to search B table. view.py class SearchFormView(FormView, LoginRequiredMixin): form_class = SearchForm template_name = 'purchase_order/order.html' print(form_class) def form_valid(self, form): searchWord = form.cleaned_data['search_word'] print(searchWord) cat_list = Catalog_info.objects.filter(Q(CAT_ID__icontains=searchWord)|Q(CAT__icontains=searchWord)|Q(CATEGORY__icontains=searchWord)|Q(CAT_NAME__icontains=searchWord)).distinct() context={} context['form']=form context['search_term']=searchWord context['object_list']=cat_list return render(self.request, self.template_name, context) forms.py from django import forms class SearchForm(forms.Form): search_word = forms.CharField(label='Search Word') Please advise me. -
'tuple' object has no attribute 'method'
Getting this error everytime I try to send mail. This is my .view code. Any suggestions? def contact(*request): if request.method == 'POST': contact_name = request.POST.get('contact_name') contact_email = request.POST.get('contact_email') contact_content = request.POST.get('contact_content') artist_name = request.POST.get('artist_name') artist_email = request.POST.get('artist_email') county = request.POST.get('county') service = request.POST.get('service') sessiontime = request.POST.get('sessiontime') mobilenumber = request.POST.get('mobilenumber') from_email = settings.EMAIL_HOST_USER to_email = [from_email , 'otheremail@email.com'] send_mail( contact_name, contact_content, contact_email, artist_name, artist_email, county, service, sessiontime, mobilenumber, fail_silently=False, ) return render (request, 'contact.html') else: return render (request, 'contact.html') Below is the error I get AttributeError at /contact/ 'tuple' object has no attribute 'method' Request Method: POST Request URL: http://127.0.0.1:8000/contact/ Django Version: 3.1.5 Exception Type: AttributeError Exception Value: 'tuple' object has no attribute 'method' Exception Location: E:\Programming Projects\Official Website\studioapp\blog\views.py, line 14, in contact Python Executable: E:\Programming Projects\Official Website\Black_Truman\Scripts\python.exe Python Version: 3.9.1 Python Path: ['E:\Programming Projects\Official Website\studioapp', 'C:\Users\User\AppData\Local\Programs\Python\Python39\python39.zip', 'C:\Users\User\AppData\Local\Programs\Python\Python39\DLLs', 'C:\Users\User\AppData\Local\Programs\Python\Python39\lib', 'C:\Users\User\AppData\Local\Programs\Python\Python39', 'E:\Programming Projects\Official Website\Black_Truman', 'E:\Programming Projects\Official Website\Black_Truman\lib\site-packages'] Server time: Fri, 29 Jan 2021 05:36:28 +0000 -
Active nav-item highlighting based on pk passed in url
I have 4 nav-items being generating dynamically based on the Django Model entries. My template code is as below: {% for stockbroker in stockbrokers %} <li class="nav-item"> <a class="nav-link" href="{% url 'broker:display_stocks' stockbroker.id %}" id="nav">{{ stockbroker.broker_name }} </a> </li> {% endfor %} I want to highlight the currently active nav based on the id I am passing in the url section of the a tag href. Is it possible to achieve this? -
Django cut and put only the face in the picture field using opencv2
I coded FaceCropped using cv2 and it works! I want to put img through facecropped method in ProcessedImageField model. Is there anyway? What I want is to automatically cut the face and put it in the database when uploading pictures into student model. method facecropped import numpy as np import cv2 import os import glob def FaceCropped(full_path, extra='face', show=False): face_cascade = cv2.CascadeClassifier('C:../haarcascade_frontalface_default.xml') full_path = full_path path,file = os.path.split(full_path) ff = np.fromfile(full_path, np.uint8) img = cv2.imdecode(ff, cv2.IMREAD_UNCHANGED) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.3,5) for (x,y,w,h) in faces: cropped = img[y - int(h/4):y + h + int(h/4), x - int(w/4):x + w + int(w/4)] result, encoded_img = cv2.imencode(full_path, cropped) if result: with open(path + '/' + extra + file, mode='w+b') as f: encoded_img.tofile(f) if show: cv2.imshow('Image view', cropped) cv2.waitKey(0) cv2.destroyAllWindows() my model.py class Student(models.Model): picture = ProcessedImageField( verbose_name = 'picture', upload_to = 'students/%Y/', processors=[ResizeToFill(300,300)], options={'quality':80}, format='JPEG', null=True, blank=True, default='students/no-img.jpg', ) name = models.CharField(max_length=255) my views.py class StudentAdd(FormView): model = Student template_name = 'student/list_add.html' context_object_name = 'student' form_class = AddStudent def post(self, request): form = self.form_class(request.POST, request.FILES) if form.is_valid(): student = form.save(commit=False) student.created_by = request.user student.save() messages.info(request, student.name + ' addddd', extra_tags='info') if "save_add" in self.request.POST: return HttpResponseRedirect(request.META.get('HTTP_REFERER')) return redirect('student_detail', pk=student.pk, … -
Error "Object of type QuerySet is not JSON serializable" when using request.session in django
I have a trouble when using request.session in search function django It shows error "Object of type QuerySet is not JSON serializable". def list_contract_test(request): context = {} if request.method == 'GET': query1= request.GET.get('search1') query2= request.GET.get('search2') submitbutton= request.GET.get('submit') if query1 or query2 is not None: lookups_contract= Q(contract__icontains=query1) lookups_name = (Q(name__icontains=query2.upper())|Q(name__icontains=query2.lower())) contract_posts= Contracts.objects.filter(lookups_contract,lookups_name).distinct() context['contract_posts'] = contract_posts #request.session['contract_posts'] = contract_posts return render(request, "customer2.html", context) else: contract_posts= Contracts.objects.all() context['contract_posts'] = contract_posts request.session['contract_posts'] = contract_posts return render(request, 'customer2.html', context) else: return render(request, 'customer2.html') Please help me! -
What are these warning? How to fix this?
This shows me warnings when I try to install PIPENV. Click in this link for the screenshot ⬇ warnings pip3 install pipenv Collecting pipenv Downloading pipenv-2020.11.15-py2.py3-none-any.whl (3.9 MB) |████████████████████████████████| 3.9 MB 655 kB/s Requirement already satisfied: pip>=18.0 in /usr/lib/python3/dist-packages (from pipenv) (20.0.2) Requirement already satisfied: setuptools>=36.2.1 in /usr/lib/python3/dist-packages (from pipenv) (45.2.0) Requirement already satisfied: virtualenv in /usr/local/lib/python3.8/dist-packages (from pipenv) (20.4.0) Collecting virtualenv-clone>=0.2.5 Downloading virtualenv_clone-0.5.4-py2.py3-none-any.whl (6.6 kB) Requirement already satisfied: certifi in /usr/lib/python3/dist-packages (from pipenv) (2019.11.28) Requirement already satisfied: filelock<4,>=3.0.0 in /usr/local/lib/python3.8/dist-packages (from virtualenv->pipenv) (3.0.12) Requirement already satisfied: distlib<1,>=0.3.1 in /usr/local/lib/python3.8/dist-packages (from virtualenv->pipenv) (0.3.1) Requirement already satisfied: appdirs<2,>=1.4.3 in /usr/local/lib/python3.8/dist-packages (from virtualenv->pipenv) (1.4.4) Requirement already satisfied: six<2,>=1.9.0 in /usr/lib/python3/dist-packages (from virtualenv->pipenv) (1.14.0) Installing collected packages: virtualenv-clone, pipenv WARNING: The script virtualenv-clone is installed in '/home/papan/.local/bin' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. WARNING: The scripts pipenv and pipenv-resolver are installed in '/home/papan/.local/bin' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. Successfully installed pipenv-2020.11.15 virtualenv-clone-0.5.4 -
How to add link previews in django?
I'm doing a chat app in python Django and I Want to implement Link preview while typing that ink in chat box. Anybody familiar with this please help. -
Django - is_valid returns false for authentication built-in login form
Can anyone figure out why when I fill out the form it returns False for is_valid? forms.py class LoginForm(AuthenticationForm): class Meta: model = User fields = '__all__' views.py class LoginView(FormView): form_class = LoginForm template_name = 'login.html' def post(self, request, *args, **kwargs): form = LoginForm(self.request.POST) if form.is_valid(): return HttpResponse('valid') else: return HttpResponse('not valid') login.html <form action "" method = "POST"> {% csrf_token %} {{form|materializecss}} <button type = "submit">Login</button> </form> As an extra, the following change to views.py returns the username and password so I know it has been passed to the POST request: class LoginView(FormView): form_class = LoginForm template_name = 'login.html' def post(self, request, *args, **kwargs): form = LoginForm(self.request.POST) return HttpResponse (self.request.POST.get('username')+ ' ' +self.request.POST.get('password')) -
413 Error in django and nginx image on Docker Container
I'm doing on small project for web clothing flea market. My project was built with django DRF (backend) and React JS (frontend). To deploy it, I made the docker image of my project and pull it with other images like nginx, letsencrypt-nginx-proxy, and docker-gen image in cloud platform server which has centos7. (please see the figures I attached) Based on my other services, there are no problem for uploading image files regardless of the file size but, In this service, I cannot upload image files above 1mb. below one is my docker-compose.yml in /home/docker directory on cloud server. [root@flea docker]# cat docker-compose.yml version: '3' services: nginx-web: image: nginx labels: com.github.jrcs.letsencrypt_nginx_proxy_companion.nginx_proxy: "true" container_name: ${NGINX_WEB:-nginx-web} restart: always ports: - "${IP:-0.0.0.0}:${DOCKER_HTTP:-80}:80" - "${IP:-0.0.0.0}:${DOCKER_HTTPS:-443}:443" volumes: - ${NGINX_FILES_PATH:-./data}/conf.d:/etc/nginx/conf.d - ${NGINX_FILES_PATH:-./data}/vhost.d:/etc/nginx/vhost.d - ${NGINX_FILES_PATH:-./data}/html:/usr/share/nginx/html - ${NGINX_FILES_PATH:-./data}/certs:/etc/nginx/certs:ro - ${NGINX_FILES_PATH:-./data}/htpasswd:/etc/nginx/htpasswd:ro logging: driver: ${NGINX_WEB_LOG_DRIVER:-json-file} options: max-size: ${NGINX_WEB_LOG_MAX_SIZE:-4m} max-file: ${NGINX_WEB_LOG_MAX_FILE:-10} nginx-gen: image: jwilder/docker-gen command: -notify-sighup ${NGINX_WEB:-nginx-web} -watch -wait 5s:30s /etc/docker-gen/templates/nginx.tmpl /etc/nginx/conf.d/default.conf container_name: ${DOCKER_GEN:-nginx-gen} restart: always environment: SSL_POLICY: ${SSL_POLICY:-Mozilla-Intermediate} volumes: - ${NGINX_FILES_PATH:-./data}/conf.d:/etc/nginx/conf.d - ${NGINX_FILES_PATH:-./data}/vhost.d:/etc/nginx/vhost.d - ${NGINX_FILES_PATH:-./data}/html:/usr/share/nginx/html - ${NGINX_FILES_PATH:-./data}/certs:/etc/nginx/certs:ro - ${NGINX_FILES_PATH:-./data}/htpasswd:/etc/nginx/htpasswd:ro - /var/run/docker.sock:/tmp/docker.sock:ro - ./nginx.tmpl:/etc/docker-gen/templates/nginx.tmpl:ro logging: driver: ${NGINX_GEN_LOG_DRIVER:-json-file} options: max-size: ${NGINX_GEN_LOG_MAX_SIZE:-2m} max-file: ${NGINX_GEN_LOG_MAX_FILE:-10} nginx-letsencrypt: image: jrcs/letsencrypt-nginx-proxy-companion container_name: ${LETS_ENCRYPT:-nginx-letsencrypt} restart: always volumes: - ${NGINX_FILES_PATH:-./data}/conf.d:/etc/nginx/conf.d - ${NGINX_FILES_PATH:-./data}/vhost.d:/etc/nginx/vhost.d - ${NGINX_FILES_PATH:-./data}/html:/usr/share/nginx/html - ${NGINX_FILES_PATH:-./data}/certs:/etc/nginx/certs:rw - /var/run/docker.sock:/var/run/docker.sock:ro environment: NGINX_DOCKER_GEN_CONTAINER: … -
Add User Functionality at custom admin side - Django
I am working on a project in Python Djnago 3.1.2, and developing a custom admin side, where admin can perform different functionalities. At the admin site I want to add functionality to add user and I have created a function but there is some error but I could not get it. Here is My models. models.py class User(AbstractUser): GENDER = ( (True, 'Male'), (False, 'Female'), ) USER_TYPE = ( ('Admin', 'Admin'), ('Designer', 'Designer'), ('Customer', 'Customer'), ) user_id = models.AutoField("User ID", primary_key=True, auto_created=True) avatar = models.ImageField("User Avatar", null=True, blank=True) gender = models.BooleanField("Gender", choices=GENDER, default=True) role = models.CharField("User Type", max_length=10, choices=USER_TYPE, default='Customer') def __str__(self): return "{}".format(self.user_id) This is the function I have created and I think error is in my views. views.py def addUser(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('/admin1/addUser') else: addUser_show = User.objects.all() # start paginator logic paginator = Paginator(addUser_show, 3) page = request.GET.get('page') try: addUser_show = paginator.page(page) except PageNotAnInteger: addUser_show = paginator.page(1) except EmptyPage: addUser_show = paginator.page(paginator.num_pages) # end paginator logic return render(request, 'admin1/addUser.html', {'addUser_show': addUser_show, "form":form}) urls.py path('addUser/', views.addUser, name="admin-add-user"), Form I am using to get the create user form. forms.py class CreateUserForm(UserCreationForm): class Meta: model = User fields … -
Where can i execute celery commands after deploying a django application on google app engine standard environment
I am a django developer. One of my clients asked me to deploy the application on google app engine standard environment. I am new to this approach. Redis is used as a task broker for celery in my application. As i have learnt there is no cli for GAE, so where can i run commands such as celery -A project worker --loglevel=info celery -A project beat -
Django DB Design and API Guidance
This is my first Django app, and also my first time building an app, and I am seeking some DB and API guidance. I have an app that functions as an online directory and marketplace. What I aim to do is to provide the app to many different organizations such that the organizations have their own online directory's and marketplace's where they can manage it fully on their own, but that their data is still linked to my database so that I can then operate on the data for machine learning purposes. This is a pretty standard/routine practice, I realize, but I am trying to wrap my head around how best to make it work. For each organization, would there just be an instance of the app which would then be a separate app or interface that connects to the original? From my newbie understanding, that is essentially what an API is, correct? -
Python Django Graphql all possible query variant generation
Is there a tool that would generate all possible query variants based on a Django Graphql based project source code? I am evaluating a product with limited documentation and I am wondering if there is something that could help me to automate the discovery process. -
Django and modifying models to reflect a specific ERD
I have the following Django Model: from django.db import models from django.utils.text import slugify class Project(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=100, unique=True, blank=True) budget = models.IntegerField() def __str__(self): return self.name def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Project, self).save(*args, **kwargs) @property def budget_left(self): expense_list = Expense.objects.filter(project=self) total_expense_amount = 0 for expense in expense_list: total_expense_amount += expense.amount # temporary solution, because the form currently only allows integer amounts total_expense_amount = int(total_expense_amount) return self.budget - total_expense_amount @property def total_transactions(self): expense_list = Expense.objects.filter(project=self) return len(expense_list) class Category(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) name = models.CharField(max_length=50) def __str__(self): return self.name class Expense(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='expenses') title = models.CharField(max_length=100) amount = models.DecimalField(max_digits=8, decimal_places=2) category = models.ForeignKey(Category, on_delete=models.CASCADE) class Meta: ordering = ('-amount',) I don't like the current setup, it seems to unnecessarily bind and expense category to a project, instead of to a given expense. So, I want to start working towards the following ERD, starting with the category side of things: When I try to modify the models so that category is no longer a Foreign key of Project: class Category(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name but rather expense, I get the following error: category_list = Category.objects.filter(project=project) This comes out … -
Preventing Users from reaching developer tools > Sources in Chrome for a Django Project
I have deployed a Django project for production but now I am found that the media files are reachable when I select Inspect the page and go to Sources I can see all the Static Files and Media what should I do to prevent reaching them. Noting that in my project settings: if DEBUG: STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] else: STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' #STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static' )] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') My question: How to prevent reaching the static files and media files in my project for anyone from the browser? -
DatabaseError: value too long for type character varying(20)
I am not sure why i get a varying(20) error even when the max_length I've set is 200 for a CharField I looked at all the other posts and all of them had an issue with the length of the value. However, even if i enter "abc" in the name field it gives me this error. Any help is appreciated. Thanks! Django Version: 3.1.5 Python Version: 3.8.5 from django.db import models from django.contrib.gis.db import models from django.db.models import Manager as GeoManager # Create your models here. class Incidences(models.Model): name = models.CharField(max_length=200) location = models.PointField(srid=4326) objects = GeoManager() def _str_(self): return self.name Traceback (most recent call last): File "C:\Users\anuj\geo_django_tutorial\tutorial_geodjango\lifeingis\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) The above exception (value too long for type character varying(20) ) was the direct cause of the following exception: File "C:\Users\anuj\geo_django_tutorial\tutorial_geodjango\lifeingis\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\anuj\geo_django_tutorial\tutorial_geodjango\lifeingis\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\anuj\geo_django_tutorial\tutorial_geodjango\lifeingis\lib\site-packages\django\contrib\admin\options.py", line 614, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "C:\Users\anuj\geo_django_tutorial\tutorial_geodjango\lifeingis\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Users\anuj\geo_django_tutorial\tutorial_geodjango\lifeingis\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "C:\Users\anuj\geo_django_tutorial\tutorial_geodjango\lifeingis\lib\site-packages\django\contrib\admin\sites.py", line 233, in inner return view(request, *args, **kwargs) File "C:\Users\anuj\geo_django_tutorial\tutorial_geodjango\lifeingis\lib\site-packages\django\contrib\admin\options.py", line 1653, in … -
css on the relevant position of two components
I am super new to css, so apologize if the question is stupid. I have two components on a page, one is called .sub-list , which is a side bar that contains the names of all the groups available, the other main component is post-list, which has all the posts listing. I am really confused about all the positions option outhere. I've tried aboslute position for the two components and relative positions, but with screen decrease or increase, the display just completely falls apart. Here is the base.html: {% load static %} <html> <head> <meta content="width=device-width, initial-scale=1" name="viewport" /> <title>Nat's flower</title> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"> <link rel="stylesheet" href="{% static 'css/reddit.css' %}"> </head> <body> <div class="page-header"> <h1><a href="/">Nat's Flower</a></h1> {% if user.is_authenticated %} <!--<a href="{% url 'post_new' %}" class="top-menu"><span class="glyphicon glyphicon-plus"></span></a> <a href="{% url 'subreddit_new' %}" class="top-menu"><span class="glyphicon glyphicon-plus"></span></a>--> <!--<a href="{% url 'logout' %}" class="top-menu">{{ user.username }} Sign Out</a>--> <a href="{% url 'post_new' %}" class="top-menu">New Post</a> <a href="{% url 'subreddit_new' %}" class="top-menu">New Group</a> <a href="{% url 'logout' %}" class="top-menu"><span class="glyphicon glyphicon-off"></span></a> {% else %} <a href="{% url 'login' %}" class="top-menu"><span class="glyphicon glyphicon-lock"></span></a> {% endif %} </div> <div class="content-container"> <div class="row"> <div class="col-md-8"> {% block content %} {% endblock %} …