Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Form displays error where there shouldn't be
I have a form which is actually built from 2 forms: UserForm and StudentForm which extends the User model. With the form actually there is no problem whatsoever, but when I try to handle it manually, then I get this error: "This field is required." I filled in all fields but it still appears. I think is related to the fact that I compare my student_ID field with the one from database, and if they don't match, an error like "Wrong student ID." should pop up. And indeed it pops up if values don't match but also the error from above in both cases. Here is my form: class StudentForm(forms.ModelForm): email = forms.EmailField(required=True, widget=forms.EmailInput(attrs={'placeholder': "E-mail Address", 'class': 'email'})) name = forms.CharField(max_length=50, required=True, widget=forms.TextInput(attrs={'placeholder': "Name", 'class': 'name'})) surname = forms.CharField(max_length=50, required=True, widget=forms.TextInput(attrs={'placeholder': "Surname", 'class': 'surname'})) student_ID = forms.CharField(required=True, max_length=14, min_length=14, widget=forms.PasswordInput(attrs={'placeholder': "Student ID", 'class': 'std_id'})) photo = forms.ImageField(required=True, widget=forms.FileInput(attrs={'class': 'profile_pic'})) phone = forms.CharField(max_length=15, required=True, validators=[RegexValidator(regex='^[0-9+]+$', message='Not a valid phone number.')], widget=forms.TextInput(attrs={'placeholder': "Phone Number", 'class': 'phone'})) def clean_student_ID(self): id = self.cleaned_data['student_ID'] try: StudentData.objects.get(student_ID=id) except: raise forms.ValidationError("Wrong student ID.") return id class Meta: model = Student fields = ('email', 'name', 'surname', 'phone', 'student_ID', 'photo') -
generate temporary URLs in Django 2 python 3
hi there is one same quetion in stackoverflow with this link: How to generate temporary URLs in Django but the accepted answer code is for python 2 and i converted it to python3 vertion: import hashlib, zlib import pickle as pickle import urllib.request, urllib.parse, urllib.error my_secret = "michnorts" def encode_data(data): """Turn `data` into a hash and an encoded string, suitable for use with `decode_data`.""" text = zlib.compress(pickle.dumps(data, 0)).encode('base64').replace('\n', '') m = hashlib.md5(my_secret + text).hexdigest()[:12] return m, text def decode_data(hash, enc): """The inverse of `encode_data`.""" text = urllib.parse.unquote(enc) m = hashlib.md5(my_secret + text).hexdigest()[:12] if m != hash: raise Exception("Bad hash!") data = pickle.loads(zlib.decompress(text.decode('base64'))) return data hash, enc = encode_data(['Hello', 'Goodbye']) print(hash, enc) print(decode_data(hash, enc)) but it have error : text = zlib.compress(pickle.dumps(data, 0)).encode('base64').replace('\n', '') AttributeError: 'bytes' object has no attribute 'encode' how should i fix this? -
Error while connecting to SQL server through Django
In settings file, I have given SQL SERVER Database connection values like this. DATABASES = { 'default': { 'NAME': 'AdventureWorks2014', 'ENGINE': 'sqlserver_ado', 'HOST': '127.0.0.1', 'USER': '', 'PASSWORD': '', } } Versions: Django v:1.11 Python v: 2.7 django-mssql v: 1.8 pip v:9.0 Development Platform: Visual Studio After the database connection values changes, I have used the command python manage.py makemigrations Here I got the error is , Executing manage.py makemigrations Traceback (most recent call last): File "E:\Django Projects\DjangoMSSQLDatabaseConn\DjangoMSSQLDatabaseConn\manage.py", line 17, in execute_from_command_line(sys.argv) File "E:\Django Projects\DjangoMSSQLDatabaseConn\DjangoMSSQLDatabaseConn\VirtualEnv\lib\site-packages\django\core\management__init__.py", line 364, in execute_from_command_line utility.execute() File "E:\Django Projects\DjangoMSSQLDatabaseConn\DjangoMSSQLDatabaseConn\VirtualEnv\lib\site-packages\django\core\management__init__.py", line 338, in execute django.setup() File "E:\Django Projects\DjangoMSSQLDatabaseConn\DjangoMSSQLDatabaseConn\VirtualEnv\lib\site-packages\django__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "E:\Django Projects\DjangoMSSQLDatabaseConn\DjangoMSSQLDatabaseConn\VirtualEnv\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models() File "E:\Django Projects\DjangoMSSQLDatabaseConn\DjangoMSSQLDatabaseConn\VirtualEnv\lib\site-packages\django\apps\config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "C:\Python27\Lib\importlib__init__.py", line 37, in import_module import(name) File "E:\Django Projects\DjangoMSSQLDatabaseConn\DjangoMSSQLDatabaseConn\VirtualEnv\lib\site-packages\django\contrib\auth\models.py", line 4, in from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "E:\Django Projects\DjangoMSSQLDatabaseConn\DjangoMSSQLDatabaseConn\VirtualEnv\lib\site-packages\django\contrib\auth\base_user.py", line 52, in class AbstractBaseUser(models.Model): File "E:\Django Projects\DjangoMSSQLDatabaseConn\DjangoMSSQLDatabaseConn\VirtualEnv\lib\site-packages\django\db\models\base.py", line 124, in new new_class.add_to_class('_meta', Options(meta, app_label)) File "E:\Django Projects\DjangoMSSQLDatabaseConn\DjangoMSSQLDatabaseConn\VirtualEnv\lib\site-packages\django\db\models\base.py", line 325, in add_to_class value.contribute_to_class(cls, name) File "E:\Django Projects\DjangoMSSQLDatabaseConn\DjangoMSSQLDatabaseConn\VirtualEnv\lib\site-packages\django\db\models\options.py", line 214, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "E:\Django Projects\DjangoMSSQLDatabaseConn\DjangoMSSQLDatabaseConn\VirtualEnv\lib\site-packages\django\db__init__.py", line 33, in getattr return getattr(connections[DEFAULT_DB_ALIAS], item) File "E:\Django Projects\DjangoMSSQLDatabaseConn\DjangoMSSQLDatabaseConn\VirtualEnv\lib\site-packages\django\db\utils.py", line 212, in getitem conn = backend.DatabaseWrapper(db, alias) … -
Django Image Upload - Image file not saving
I'm writing a project where you can add photos to a website from a disk or other sites. In jquery I wrote a book marklet where I can add pictures from other site. But I have problem with uploading images from the disc. I wrote model, modelform, views and html file. When I choose a img file in the form all looks OK. I'm moved to image list web page, but there is not file what I whant to upload. Image file not saving. I don't know what I did wrong. Below is my code: models.py class Image(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='images_created') title = models.CharField(max_length=200) slug = models.SlugField(max_length=200, blank=True) url = models.URLField(blank=True) image = models.ImageField(upload_to='images/%Y/%m/%d') description = models.TextField(blank=True) created = models.DateField(auto_now_add=True, db_index=True) users_like = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='images_liked', blank=True) total_likes = models.PositiveIntegerField(db_index=True, default=0) def __str__(self): return self.title def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(Image, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('images:detail', args=[self.id, self.slug]) class Meta: ordering = ["-image"] forms.py class ImageCreateForm(forms.ModelForm): class Meta: model = Image fields = ('title', 'url', 'description') widgets = { 'url': forms.HiddenInput, } def clean_url(self): url = self.cleaned_data['url'] valid_extensions = ['jpg', 'jpeg'] extension = url.rsplit('.', 1)[1].lower() if extension not in valid_extensions: raise forms.ValidationError('Podany adres URL … -
Whether Django urls.py unittest should be apart from DRF ModelViewSet?
I'm testing in my project some Django REST Framework ModelViewSet views and while I was reading Book - TDD web dev with Python, available at GitHub, I ran into a simple design question -I guess- that would be whether I should use django.urls.resolve or get the same info, for instance, calling: response = self.client.options(reverse_lazy('namespace:view_func_or_pattern_name') from DRF APITestCase and get results of resolver_match in response as I could get with django.urls.resolve. I imagine that it's just a matter of choosing to split tests of urls.py and views.py, as I have seen at this question. Or what else would it be? -
Create model instance out of Form and add it to other instance
In my models.py I have model called Bus. It contains multiple fields, including the field file below: class Bus(models.Model): file = models.OneToOneField('File', on_delete=models.PROTECT, editable=False) The File model consists of: class File(models.Model): file = models.FileField( upload_to=get_filepath, max_length=45, validators=[ FileExtensionValidator(allowed_extensions=['pdf', 'jpg', 'png']), file_size, ] ) original_name = models.CharField(max_length=45) extension = models.CharField(max_length=3) When you want to create a new Bus I need of course a form. That's defined in my forms.py: class BusForm(forms.ModelForm): upload = forms.FileField(max_length=45, required=False, validators=[ FileExtensionValidator(allowed_extensions=['pdf', 'jpg', 'png']), file_size, ],) My problem: In the save() method of BusForm I have to create a File instance and add it to the Bus instance (file field). For multiple hours I tried to achieve that. However, I don't get it. If someone could try to help me how the save() method has to look like, that would be great! -
Django autosetting user foriegnkey field to submitting user on form
What I'm trying to do is to auto set a field of a model to the user that is submitting the form. Models.py: class startcampaign(models.Model): title = models.CharField(max_length=30) description = models.TextField() user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) Forms.py: class StartCampaignsForm(forms.ModelForm): class Meta: model = startcampaign exclude =['user'] Views.py: def register(request): if request.method == 'POST': form = StartCampaignsForm(request.POST) if form.is_valid(): campaign_register = StartCampaignsForm.save(commit=False) campaign_register.user = self.objects.get(user=self.user) campaign_register.save(commit=True) return redirect('home') else: form = StartCampaignsForm() return render(request, 'Campaigns/register.html', {'form': form}) When I run this currently, I get save() is missing a positional argument 'self'. I' not dedicated to this method. I just need a working example that lets me autoset the user which is submitting the form to the foreign key field of 'user' in my model. -
Comparing DateField in Django, workd in 1.8.8 but throws error in 1.11.11
In the model... Event.date = models.DateField(default=datetime.date.today) In the view... import datetime future_events = Event.objects.filter(date__gte=datetime.date.today).order_by('date', 'start_time') The Error? expected string or buffer Request Method: GET Request URL: http://127.0.0.1:8000/event/ Django Version: 1.11.11 Exception Type: TypeError Exception Value: expected string or buffer Dont understand whats not working here worked okay before I upgraded Django but fails now. Any help is appreciated. -
Accessing list of dictionaries in template by index
I have a list of dictionaries in the django template. I wish to use its values in a form. [ { "movie_id": 1950, "title": "In the Heat of the Night (1967)" }, { "movie_id": 3741, "title": "Badlands (1973)" }, { "movie_id": 3959, "title": "Time Machine, The (1960)" }, { "movie_id": 4101, "title": "Dogs in Space (1987)" }, { "movie_id": 8572, "title": "Littlest Rebel, The (1935)" }, { "movie_id": 65230, "title": "Marley & Me (2008)" }, { "movie_id": 105954, "title": "All Is Lost (2013)" } ] In my template, I want to get values of each field by index. ie. for the list[0]['movieId'], I would like to get the value 1950. Is that possible? -
How to use external data in Django?
I have an existing Python module which encapsulate my Business Logic and itself is connected to a backend-database. import project-backend stations = project-backend.getStations() #returns a dict() stations['zurich'].getPipes() # etc. etc. As a Django-Newbie, how can I use this existing BL-module in a Django app? My Webapp does not need to store anything, because everything is handled by the existing BL. Do I need to import the existing BL-module within the representing model's definition an disable the managing (managed=False)? Or shall I implement a custom-manager which routes all queries to the BL-module? -
running django project in visual studio 2013 python exe opens but not running
I have installed VisualStudio2017 with python option enabled. I am trying to migrate my existing Django project (python 2.7) to python 3.6 . The solution build successfully in visual studio 2017 but when i am running the application (F5) , python exe opens but not executing & shows black screen and also Visual studio closes automatically. I have same issue in enter image description herevisual studio 2013 (python 2.7) , That's why i am trying to migrate to Visual Studio 2017. But the issue i had faced not solved. -
Django: save() got an unexpected keyword argument 'commit'
In my forms.py I have a custom ModelForm that contains a save() method: def save(self): bus = super().save(commit=False) datei = self.upload.name original_dateiname = datei.name extension = original_dateiname.split('.')[-1] a = Datei.objects.create(file=datei, original_dateiname=original_dateiname, extension=extension) self.datei = a bus.save() return bus However, now I get the error: save() got an unexpected keyword argument 'commit' What's wrong here? -
How to exclude some query from inline Django admin model?
Django 2.0.3, Python 3.6.1. I try to filter QuerySet of one field (ForeignKey) on inline model (Django Admin). # ./app/models.py class Product(models.Model): product_id = models.PositiveSmallIntegerField() class Price(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) price = models.PositiveSmallIntegerField() # ./app/admin.py class PriceInlineAdmin(admin.TabularInline): model = Price @admin.register(Product) class ProductAdmin(admin.ModelAdmin): list_display = ('id',) inlines = [ PriceInlineAdmin ] How to exclude from PriceInlineAdmin QuerySet products with ID start with 1? -
Django paypal ngrok
It is so strange. I integrated paypal on my django project few months before. It worked, but currently it doesn't. But I haven't changed anything. I tested an old version and it is the same. I think do what I have to do: -firstly I run my server -secondly I run ngrok python3.6 mange.py runserver 8080 ./ngrok http 8080 My payment is accepted by Paypal, I have a notification too, but I don't receive any signal and any model is created. Nothing indicates an error. It's look like if I don't use ngrok, but I do ! I do everything whith ngrok url. I have : PAYPAL_RECEIVER_EMAIL="myemail-facilitator@gmail.com" PAYPAL_TEST = True valid_ipn_received.connect(myfonction) paypal_dict = { "business": "myemail-facilitator@gmail.com",# "amount": price, "item_name":"Achat XXX", "invoice": id, "currency_code": "EUR", "custom":request.user.id, "notify_url": request.build_absolute_uri(reverse('paypal-ipn')), "return_url": request.build_absolute_uri(reverse('payment:done', kwargs={'id': id})), "cancel_return": request.build_absolute_uri(reverse('payment:canceled',kwargs={'id': id})), } I use myemail-buyer@gmail.com to buy. I think that I don't do just a little thing but what ? If somebody can help me... I become crazy Thank you ! ̀ -
Django Responsive Form using class:'form-control'
I have a from and added class':'form-control' to every field of the form to make them responsive like this : companyname=forms.CharField( widget=forms.PasswordInput(attrs={'class':'form-control' ,'style': 'width:30%'}) ) but when i add form-control class , the label is showd at the upper row of the text box i dont know what to do to bring the label beside the text box when it has no class the code below is ok but its not responsive <div class="panel-body" style="text-align:right ; margin-left:auto;margin-right:auto;width:80%;"> <div style="width:85% ;margin-left:auto;margin-right:auto;"> <form enctype="multipart/form-data" method="post" > {% csrf_token %} {{ profile_form.as_p}} <input id="savepersonalinfo" type="submit" name="" value="ثبت"> </form> </div> </div> and also how can i put the textboxes arranged exactly in same column ? in the picutre iust companyname has form-control class and is responsive and other fields are not -
GIT: Moving all content of a parent/subfolder to parent/
I am new to Github. I have uploaded my Django app to Github that I will be using on Heroku. I successfully added files and folders on the web interface of Github but realized that I incorrectly uploaded folders. I cloned my github repo on my local machine. I have a sub-folder that I want to move to it's parent folder but the git mv is not working for me or I am doing something wrong I can't figure out what. parent folder: PH_Dorms sub folder: ph_dorms 1st try: cd PH_Dorms git mv ph_dorms ../ Result: fatal: '../' is outside repository 2nd try: cd PH_Dorms git mv ph_dorms ./ Result: "fatal: can not move directory into itself, source=ph_dorms, destination=ph_dorms 3rd try: cd PH_Dorms cd ph_dorms git mv ph_dorms ./ Result: fatal: can not move directory into itself, source=ph_dorms/ph_dorms, destination=ph_dorms/ph_dorms 4th try: cd PH_Dorms cd ph_dorms git mv ph_dorms ../ Result: fatal: cannot move directory over file, source=ph_dorms/ph_dorms, destination=ph_dorms 5th try: cd PH_Dorms cd ph_dorms git mv ph_dorms/* ../ Result: fatal: bad source, source=ph_dorms/ph_dorms/, destination= 6th try: cd PH_Dorms cd ph_dorms git mv * ../ Result: fatal: bad source, source=ph_dorms/, destination= 7th try: cd PH_Dorms cd ph_dorms git mv * ./ … -
django mongoengine unable to login using correct password
I am using mongoengine with django rest framework and default User model settings.py has : AUTHENTICATION_BACKENDS = ( 'mongoengine.django.auth.MongoEngineBackend', ) SESSION_ENGINE = 'mongoengine.django.sessions' SESSION_SERIALIZER = 'mongoengine.django.sessions.BSONSerializer' MONGOENGINE_USER_DOCUMENT = 'mongoengine.django.auth.User' AUTH_USER_MODEL = 'mongo_auth.MongoUser' views.py has : from django.contrib.auth import login, logout from mongoengine.django.auth import User @csrf_exempt def log_in(request): js = json.loads(request.body) try: #user = User.objects.get(username=request.POST['username']) user = User.objects.get(username=js['username']) print user.username print user.password print js['username'] print js['password'] print user.password==js['password'] #if user.check_password(request.POST['password']): if user.check_password(js['password']): user.backend = 'mongoengine.django.auth.MongoEngineBackend' user = authenticate(username=js['username'], password=js['password']) login(request, user) request.session.set_expiry(60 * 60 * 1) # 1 hour timeout return HttpResponse(user) else: return HttpResponse('login failed') except DoesNotExist: return HttpResponse('user does not exist') except Exception: return HttpResponse('unknown error') with the correct password, I am getting login failed. What can be the reason for this? -
Issue styling the image upload button
Basically I am trying to style my image upload form field. By following guidance from another question from here I ended up doing this: document.getElementById("uploadBtn").onchange = function () { document.getElementById("uploadFile").value = this.value; }; .fileUpload { position: relative; overflow: hidden; margin: 10px; } .fileUpload input.upload { position: absolute; top: 0; right: 0; margin: 0; padding: 0; font-size: 20px; cursor: pointer; opacity: 0; filter: alpha(opacity=0); } <input id="uploadFile" placeholder="Choose File" disabled="disabled"/> <div class="fileUpload btn btn-primary"> <span>Upload</span> <input id="uploadBtn" type="file" class="upload"/> </div> This works as it should but how do I bind it to my django form field ? If I replace class attribute inside the input from "upload" to "profile_pic", the main upload button will appear, which is bad. Or am I doing it wrong ? I just need the information to be passed to my form. photo = forms.ImageField(required=True, widget=forms.FileInput(attrs={'class': 'profile_pic'})) -
How to handle django dabase migrations with captain duck duck?
machine: docker 1GB when i try manage.py migrations (after a successful makemigrations) in my already deployed captain-definition, i get this error, Probably because migrations are not synced in my git repo and django cant detect which migrations are already applied to the database without the migrations folder Captain duck duck seems to destroy any changes to the file system in my docker conatiner and hence the migrations folder is not available after a restart. System check identified some issues: WARNINGS: Users.CustomUser: (auth.W004) 'CustomUser.phone_number' is named as the 'USERNAME_FIELD', but it is not unique. HINT: Ensure that your authentication backend(s) can handle non-unique usernames. Operations to perform: Apply all migrations: Exams, Users, account, admin, auth, contenttypes, sessions, sites, socialaccount Running migrations: Applying Exams.0002_auto_20180309_1911...Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: column "owner_id" of relation "Exams_topic" already exists The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/migrate.py", … -
Passing a url variable after submitting a form
I'm working on a simple website where I can register isolated information systems in a simple database, and assign harddisks to each system using ForeignKeys. When deleting a system from the database, I use a DeleteView. In the DeleteView: To check if there are any harddisks associated with the system I use custom method. If no harddisks are found, it displays the DeleteView form. If there are any, a list of the relevant harddisks is displayed instead of the form, with a link to the UpdateView of each individual harddisk. I want to be able to click a link to one of these harddisk, make changes to it in the UpdateView, then be redirected back to the DeleteView to "check the list again". This is what I have so far (Media = harddisk/storage media) class MediaEdit(LoginRequiredMixin, SuccessMessageMixin, UpdateView): model = Media form_class = MediaForm template_name = 'dsl/media/media_create-edit.html' success_message = 'Media successfully changed!' def get_success_url(self): return reverse('dsl:media_edit', kwargs={'pk': self.get_object().id}) def get_context_data(self, **kwargs): context = super(MediaEdit, self).get_context_data(**kwargs) context['action'] = reverse('dsl:media_edit', kwargs={'pk': self.get_object().id}) next_url = self.request.GET.get('next', 'None') context['next_url'] = next_url return context I have tried using the "next_url" variable in my UpdateView form: {% if next_url %} <form class="" action="{{ next_url }}" method="post"> … -
Syntax error in "manage.py" file - django 2
I do not understand what the problem is but I keep getting a syntax error for the "from exc" line even though I did not alter the code. I have checked for un-closed parentheses and quotes and indentation look right to my beginner's eye. The issue is that this is the out-of-the-box code for the Django 2.0 virtual environment so I can only assume Sublime somehow formatted it wrong when the file was dragged into the text editor? import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings") try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) -
in my project how can i set http session tracking login time for 30 second only
In my project i want to set HTTP Session tracking for 30 second after 30 second user should be logout automatically, if user is not doing any think and also one more condition after login if user click on back button of my browser and than forward button of my browser than it must be transfer on login page for entering username and password. In my project i want to set HTTP Session tracking for 30 second after 30 second user should be logout automatically, if user is not doing any think and also one more condition after login if user click on back button of my browser and than forward button of my browser than it must be transfer on login page for entering username and password. In my project i want to set HTTP Session tracking for 30 second after 30 second user should be logout automatically, if user is not doing any think and also one more condition after login if user click on back button of my browser and than forward button of my browser than it must be transfer on login page for entering username and password. Views.py from django.shortcuts import render from django.http import … -
I need an explanation on how Django mobile apps work
So I want to create a mobile app with Django, that is basically like a sort of online store, I'm still very confused on how the process would work, but this is what I understand so far : The backend would be built with Django, which would manage users and data and all that, and then I would use MySQL to store the products and their relevant information, and Django would access that database and display the products as programmed. But then comes the matter of the interface of the app. I know that Django can display HTML pages so could those html pages act as the interface to the app, and how would I be able to achieve that on a mobile platform ? I know these kind of questions are not suitable for the stack overflow format but tbh I don't know where else to go so thanks. -
Can you help me find the error for querry in django?
So I am trying to make a search function which looks through the database to look for similar words in django database. My views.py: def result(request): # Shows the matched result request.GET.get('q') incubators = Incubators.objects.all() check = Incubators.objects.filter(incubator_name__icontains="q") return render(request, 'main/results.html', {'incubators':incubators,'check': check}) The problem is that my HTML page is not showing any result matching to the database when I know there is. Its just a black HTML page. {%extends 'main/base.html'%} {%block content%} {%for inc in check%} <p>{{inc.incubator_name}} <br> {{inc.city_location}}</p> <hr> {%endfor%} {%endblock%} I am new to Django and really confused what I am doing wrong here. -
Prevent server from interpreting uploaded files
I have a FileField where the user is meant to upload an image or video for their post: image = models.FileField(null=True, blank=True) Is there any measure I need to take to prevent users from uploading hostile files? Such as .php files? Or does Django's security already prevent that?