Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i take object values from another apps in Django
I have 4 different apps in my Django application. I would like to take a object values in another app. For example while i select an one object,i would like to see the detail values about this object as read-only. -
Duplicate columns issue when applying migrations files by another team member in django
I have been facing a huge issue. We are working on a large project with a small team of developers. Now, issue is that when I push the code and in that commit there are some migration files. when other team member pull and merge the code and try to apply the migration files at his side. It gives out duplicate columns issue at his side. Migration files are unapplied but the tables or columns created in those files are in the db at his side. It is very strange that without applying the migrations how can db sense them. By applying python manage.py showmigrations, the files are unapplied. Please help me out, things are working at my side but issue at other teammates side and also on beta as well. I know about the solutions of changing db or deleting migration files but I don't need those. Looking forward for an immediate help. Thanks -
How to add cookies for ecommerce cart?
im really confused about how can i apply and manage cookies which adds product into cart for my ecommerce website. I am using django and mysql for development. If someone knows, kindly share your valuable experience. -
Django Commenting Errors
I am new to Django and was working on my blog site to include a comment feature by using django-comments-xtd package. I was following the tutorials specified on "https://django-comments-xtd.readthedocs.io/en/latest/tutorial.html", but it kept giving me an error saying "DoesNotExist at /comments/post/" whenever I tried to submit any comment. I think the following line was the place where it kept giving me an error, "comment = form.get_comment_object(site_id=get_current_site(request).id)", which is in lib\site-packages\django_comments\views\comments.py Does anybody had this kind of issue before? Thank you very much for your help! -
Django Cronjob issue With multiple Environments
I am having some issues setting up Django-crontab in my project (With Multiple enviournments). Here we have base.py contains all common settings and we have multiple environments like local.py, production.py, etc inside the settings folder. settings <-- folder __init__.py base.py local.py production.py Multiple enviournments I have defined my generate_data.py under an app named cron_jobs. So its location is project/cron_jobs(which is the app)/generate_data.py. Inside generate_data.py, is a function named data_detail(). I have defined 'django_crontab' under my base.py in INSTALLED_APPS. Declare Cron Job - in local.py file CRONTAB_COMMAND_SUFFIX = '2>&1' CRONJOBS = [ ('* * * * *', 'cron_jobs.generate_data.data_detail' , '>>'+os.path.join(BASE_DIR,'log', 'debug7.log')) ] Add Cron - python manage.py crontab add --settings=project_dir.settings.local Check Cron is added or not - crontab -l * * * * * /home/pradeep/Desktop/phase4/convo-ocr/convo_ocr/venv/bin/python /home/pradeep/Desktop/phase4/convo-ocr/convo_ocr/manage.py crontab run 8d0abd75f775830eb29cddc63eeb30ea >>/home/pradeep/Desktop/phase4/convo-ocr/convo_ocr/log/debug7.log 2>&1 # django-cronjobs for convo_ocr ERROR Traceback (most recent call last): File "/home/pradeep/Desktop/phase4/convo-ocr/convo_ocr/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 224, in fetch_command **app_name = commands[subcommand] KeyError: 'crontab'** During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/pradeep/Desktop/phase4/convo-ocr/convo_ocr/manage.py", line 34, in <module> main() File "/home/pradeep/Desktop/phase4/convo-ocr/convo_ocr/manage.py", line 29, in main **execute_from_command_line(sys.argv)** File "/home/pradeep/Desktop/phase4/convo-ocr/convo_ocr/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/pradeep/Desktop/phase4/convo-ocr/convo_ocr/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/pradeep/Desktop/phase4/convo-ocr/convo_ocr/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 231, in fetch_command settings.INSTALLED_APPS … -
Django, getting 500 error when debug=False
The app works when debug = True, when debug = False I am getting 500 errors on both my computer and Heroku. The http://127.0.0.1:8000/admin/ part is working. http://127.0.0.1:8000/ is the one giving 500 errors, so I am guessing the mistake is in the static file. I ran python manage.py collectstatic and create staticfiles, still same issue. Any suggestions: This is what I see on Terminal: [25/May/2021 00:37:43] "GET / HTTP/1.1" 500 145 This is my settings.py: from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ import os # using django-environ to read from .env # https://github.com/joke2k/django-environ import environ env = environ.Env( # set casting, default value # DEBUG=(bool, False) ) # reading .env file environ.Env.read_env() # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', '%)4ja40!mqevxsrj%2^o+2&a=8&t4oy$*^d-e5t^p^-^crpyy#') # SECURITY WARNING: don't run with debug turned on in production! # DEBUG = True DEBUG = os.environ.get('DJANGO_DEBUG', '') != 'False' ALLOWED_HOSTS = [ '127.0.0.1', '.localhost', '.herokuapp.com' ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'attendance.apps.AttendanceConfig', 'pgtrigger', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', … -
I cannot access reverse ManyToMany field from django ModelForm
I have two entities with a ManyToMany relation between them. ProcessModel has a ManyToManyField of RouteModel and a reverse relalion 'processes' is created. I have define two ModelForms, but I cannot access the reverse ManyToMany relation 'processes' from the routes form. The view holding the route form don't display the processes field. How can I show that reverse ManyToMany field and save the information using the form. Here is my code class ProcessModel(models.Model): name = models.CharField(verbose_name="nombre", max_length=50, blank=False, null=False) code = models.CharField(verbose_name="Código", max_length=50, blank=True, null=True, unique=True) routes = models.ManyToManyField("RouteModel", verbose_name="lista de rutas", related_name="processes", blank=True) class RouteModel(models.Model): name = models.CharField(verbose_name="Nombre", max_length=50, blank=False, null=False) route_type_id = models.ForeignKey("RouteTypeModel", verbose_name="Tipo", blank=True, null=True, on_delete=models.SET_NULL, related_name="routes") start_date = models.DateField(verbose_name="Fecha inicio") end_date = models.DateField(verbose_name="Fecha inicio") from django_select2.forms import ModelSelect2Widget, ModelSelect2MultipleWidget class ProcessForm(forms.ModelForm): class Meta: model = ProcessModel exclude = ('id',) widgets = { 'name':forms.TextInput(attrs={'class': 'form-control'}), 'code':forms.TextInput(attrs={'class': 'form-control'}), 'routes': ModelSelect2MultipleWidget(model=RouteModel, queryset=RouteModel.objects.filter(), search_fields=['name__icontains'], attrs={'style': 'width: 100%;'}), } class RouteForm(forms.ModelForm): class Meta: model = RouteModel exclude = ("id",) widgets = { 'name':forms.TextInput(attrs={'class': 'form-control'}), 'route_type_id': forms.Select(attrs={'class': 'form-control'}), 'start_date' :forms.DateInput(attrs={'class': 'form-control datepicker', 'autocomplete': 'off'}), 'end_date' :forms.DateInput(attrs={'class': 'form-control datepicker', 'autocomplete': 'off'}), 'processes': ModelSelect2MultipleWidget(model=ProcessModel, queryset=ProcessModel.objects.filter(), search_fields=['name__icontains'], attrs={'style': 'width: 100%;'}), } -
django.templatetags.static not working in models.py?
I've used in my views, to import my static files: from django.templatetags.static import static ... static('myapp/img/icn/chain.png') and it's working great. I've tried to do the same in models.py (since I needed a fixture when using one of my model) static('myapp/fixtures/fixt.json') But the file isn't found. In the error, it says that the file path is converted apparently to : /static/myapp/fixtures/fixt.json. If I go manually to this path (http://127.0.0.1:8000/static/myapp/fixtures/fixt.json), I can get this file so the location is good (I've collected the static files before). -
Is there a way to standardize the amount of time a third party API request takes? (Javascript - Spotify API)
I have a function that calls the Spotify API to play a particular song through the following code: //app_apis.js socket.onmessage = async() function(e){ let data = { 'context_uri' : album, 'offset': { 'position': track_num - 1 }, 'position_ms': track_pos }; await fetch("https://api.spotify.com/v1/me/player/play" + "?device_id=" + active_device, { method: "PUT", headers: { 'Content-Type' : 'application/json', 'Authorization' : 'Bearer ' + token }, body: JSON.stringify(data) }); } Where "socket" is a webSocket created through Django channels, such that when the .onmessage event is triggered, an asynchronous API call is made for all connections, setting their playback to a certain song. The purpose of this project is to function like a "silent disco" where the playback of one user is made to be the playback for all users. The issue I'm having is that an API call to "https://api.spotify.com/v1/me/player/play" takes a non-standard amount of time to complete. As an example, if there are three connections, the code is working properly in that the .onmessage event will occur and send a request to start playback at 0:00 for all three connections nearly simultaneously. However, the first call might finish in 600 milliseconds, the second might finish in 400 milliseconds, and the third might finish … -
upload multiple images to a single model django viewsets
I'm working on this app with frontend in react and backend in django Here is the model for a component: class Card(models.Model): title = models.CharField(max_length=30) description = models.CharField(max_length=200) rating = models.IntegerField() ratingCount = models.IntegerField() location = models.CharField(max_length=30) rate = models.IntegerField() I want this model to have multiple images, so that when the card component in react requests data from it gets json data and all images that were uploaded for this model I'm using viewsets, I have tried searching for this but I haven't found a tutorial or doc where they're doing this with viewsets. Here is the serializer: class CardSerializer(serializers.ModelSerializer): class Meta: model = Card fields = '__all__' Here is the api: class CardViewSet(viewsets.ModelViewSet): queryset = Card.objects.all() permission_classes = [ permissions.AllowAny ] serializer_class = CardSerializer admin.py : admin.site.register(Card) tldr: in short I want a option to upload 0 to n number of images when inserting data with the model with viewsets What changes would I have to make in models, serializer, api, admin files How would I go on about implementing this with these viewsets, any help would be appreciated -
PostGis importance with geodjango
So at first i tried to create a model using model from django.contrib.gis.db which threw an error regarding GDAL (there are many posts regarding that and how to solve that and i already did that). After installing the required files for GDAL, i also added a postgres database to my django project. As the model used by me is used in case if we are dealing with geoDjango (or simply location) but geoDjango can be used even without that. What i mean is there is no connection b/w our database and geoDjango as we can simply apply the functions like geodesic, geocoders etc without any error(please correct me if i am wrong). So after doing that, i ran the migrations and everything was fine. Now my question is; If everything ran without any error, then what is the use of PostGis in it. Though i didn't used it yet but everybody is adding it to the project where geoDjango has to be used. Why to add django.contrib.gis to installed apps and why to add PostGis extension to the postgresql database. -
Error while running anything with manage.py in django
I created a Django project the previous month and I deleted it. But now whenever I create a Django project and run any command with manage.py, it gives me an error regarding the previously deleted project. E.g: When I ran python manage.py makemigrations, it gave me this error: Traceback (most recent call last): File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 393, in execute self.check() File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 423, in check databases=databases, File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\checks\translation.py", line 43, in check_setting_languages for tag, _ in settings.LANGUAGES if not isinstance(tag, str) or not language_code_re.match(tag) File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python37\lib\site-packages\django\conf\__init__.py", line 82, in __getattr__ self._setup(name) File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python37\lib\site-packages\django\conf\__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python37\lib\site-packages\django\conf\__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'C:\\Users\\Lenovo\\Desktop\\django\\car_service\\car_service\\settings' During handling of the above exception, another exception … -
I want to deploy the DB, API, and FRONT containers in the above repository to AWS ECS so that they can be operated
https://github.com/hodanov/react-django-postgres-sample-app I want to deploy the DB, API, and FRONT containers in the above repository to AWS ECS so that they can be operated. Therefore, in order to operate the containers separately, the docker-compose.yaml file was divided into containers. I pushed the container to ECR and operated it with ECS, but it stopped by all means. Where should I review it? -
Django global login required middleware error
I'm using Django to make a website In the website, users can have access to all pages only after they log in the website other than login page. So, I did pip install django-glrm and added 'global_login_required.GlobalLoginRequiredMiddleware' in MIDDLEWARE in settings.py Here is the reference https://django-glrm.readthedocs.io/en/latest/readme.html After installing, I just added @login_not_required to login function and it worked for several days. However, today I ran into an error. Not Found http://127.0.0.1:8000/accounts/login/?next=/ What is the problem? After erasing 'global_login_required.GlobalLoginRequiredMiddleware' in settings.py, it does not show the error but login required does not work of course. Please let me know it you have an idea -
NoReverseMatch at / Reverse for 'product_detail' with arguments '(8, '')' not found. 1 pattern(s) tried: ['(?P<id>[0-9]+)/(?P<product_slug>[^/]+)/$']
I am a student currently learning Django. The following error occurs in the project I'm making. We are implementing a function related to product registration, but we can't do anything because of an error. Actually, I don't know much about slugs or Django. What should I do to solve it? Great developers, please help me. I have attached the files for our project. Help would be appreciated. error content : NoReverseMatch at / Reverse for 'product_detail' with arguments '(8, '')' not found. 1 pattern(s) tried: ['(?P[0-9]+)/(?P<product_slug>[^/]+)/$'] Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.1.5 Exception Type: NoReverseMatch Exception Value: Reverse for 'product_detail' with arguments '(8, '')' not found. 1 pattern(s) tried: ['(?P[0-9]+)/(?P<product_slug>[^/]+)/$'] Exception Location: D:\anaconda3\envs\vnv_zn\lib\site-packages\django\urls\resolvers.py, line 685, in _reverse_with_prefix Python Executable: D:\anaconda3\envs\vnv_zn\python.exe Python Version: 3.7.6 Python Path: ['C:\zeronine_project (1)', 'D:\anaconda3\envs\vnv_zn\python37.zip', 'D:\anaconda3\envs\vnv_zn\DLLs', 'D:\anaconda3\envs\vnv_zn\lib', 'D:\anaconda3\envs\vnv_zn', 'D:\anaconda3\envs\vnv_zn\lib\site-packages'] Server time: Tue, 25 May 2021 12:19:01 +0900 model.py from django.db import models from django.contrib.auth.models import AbstractUser from django.urls import reverse # member class Member(AbstractUser): username = models.CharField(primary_key=True, max_length=20, verbose_name='아이디') name = models.CharField(max_length=20, verbose_name='이름', default='') password = models.CharField(max_length=64, verbose_name='비밀번호') phone = models.CharField(max_length=64, verbose_name='전화번호') def __str__(self): return self.username class Meta: verbose_name = ('Member') verbose_name_plural = ('Members') # category class Category(models.Model): category_code = models.AutoField(primary_key=True) name = models.CharField(max_length=200, … -
Getting attribute error while joining 2 tables
There are 2 tables category, sub_category that i want to join through common column id, category. While doing so I'm getting attribute error. I want category's data first then sub_category's data. Models.py: class Category(models.Model): category = models.CharField(max_length=50) image = models.CharField(max_length=500) store_image = models.CharField(max_length=1000) is_active = models.IntegerField() parent_id = models.IntegerField() class Meta: managed = False db_table = 'category' class SubCategory(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, db_column='category') sub_category = models.CharField(max_length=50) is_active = models.IntegerField() class Meta: managed = False db_table = 'sub_category' Views.py: class CategoryView(generics.GenericAPIView): def post(self, request): queryset = Category.objects.all().exclude(parent_id=0) serializer = CategorySerializer(queryset, many=True) return Response(serializer.data) Serialzer.py: class SubCategorySerializer(serializers.ModelSerializer): class Meta: fields = ["id", "category", "sub_category", "is_active"] model = SubCategory class CategorySerializer(serializers.ModelSerializer): sub_category_data = SubCategorySerializer(read_only=True, source='id') class Meta: fields = ["id", "category", "image", "is_active", "parent_id","sub_category_data"] model = Category Error: AttributeError: Got AttributeError when attempting to get a value for field `category` on serializer `SubCategorySerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `int` instance. Original exception text was: 'int' object has no attribute 'category'. -
how to convert a variable passed into HTML from python into HTML?
I'm learning Django. I have a views.py file that converts markdown into html. Then this is passed as a variable, called body into the following html. When I view the page, rather than converting the variable body into html, it just displays: <h1>CSS</h1> <p>Cats can run fast or slow <a href="/animals/HTML">HTML</a> page.</p> Below is my html file. I'm wondering, in order for the html to be read by the web-browser not as a string but as html, do I do something different then {{body}}? {% extends "mapper/layout.html" %} {% block title %} mapper {% endblock %} {% block body %} <h1>{{ title }}</h1> <div> {{ body }} </div> {% endblock %} -
Django static jpg file gets 404
I have been confused for a while and have no idea what is wrong. What i got error is GET /static/jpgfile/connect.jpg HTTP/1.1" 404 ,connect.jpg can be viewed when open http://127.0.0.1:8000/runoob/ Can anyone help to point out what should be modified .Your help will be gratefully appreciated. Here is my directory: Demo |--Demo | |--__init__.py | |--asgi.py | |--search.py | |--settings.py | |--urls.py | |--wsgi.py |--demoapp |--static | |--jpgfile | | |--connect.jpg |--templates | |--runoob.html relevant code is : in Demon>settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] Demon>search.py: def search_form(request): return render(request,'runoob.html') Demon>urls.py: urlpatterns = [path('runoob/',search.search_form),] templates>runoob.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>test</title> {% load static %} </head> <body> <img src="/static/jpgfile/connect.jpg" alt="test"> </body> </html> -
Django how to carry url parameters over into new URL
My site has a list of car manufactures. User clicks on a manufacture it displays the models from that manufacture. What I want is when they click on the model it displays data but I am having issues setting up my url structure. path('browse/', BrowseListView.as_view(), name='blog-browse'), path('browse/models/<int:pk_test>/', views.modelsView, name='db-manufactures'), path('browse/models/<int:pk_test>/<int:new_stuff>', views.modelPosts, name='model-post') #this is the new url When i run this i get the error that modelPosts() got an unexpected keyword argument 'pk_test' i believe i am getting this error because pk_test is not being carried over into the new url How do i go about carrying over the pk_test value into the new url. I have been reading through the docs but im still unsure -
Django Boolean Checkbox Input Field printing value='False'
I have a number of Boolean Field checkbox inputs within a form and I have noticed the following Boolean Fields (avaialble, bfbw, asp and tours) are printing a default value of 'False' whilst the remainder of the Boolean Fields (para_athlete, working_with_children) do not. When the value of False is there I cannot toggle the checkbox between on/off (True/False) Is there something obvious that I am missing as I am struggling to see any difference between the fields? Thanks in advance for any help I can get on this. Below is the code. Model athlete_ref = models.CharField(max_length=10, default=1) athlete_name = models.CharField(max_length=80) email = models.EmailField() phone_number = models.CharField(max_length=120) home = models.CharField(max_length=120) education = models.CharField(max_length=120) sport = models.CharField(max_length=120, choices=sports, default='Shooting') notes = models.TextField() gender = models.CharField(max_length=120, choices=genders, default='Not Specified') para_athlete = models.BooleanField(blank=True) working_with_children = models.BooleanField(blank=True) expiry_date = models.DateField(blank=True, null=True) available = models.BooleanField(blank=True) available_from = models.DateField(blank=True, null=True) bfbw = models.BooleanField(blank=True) latest_bfbw_session = models.DateField(blank=True, null=True) number_bfbw_sessions = models.CharField(blank=True, null=True, max_length=10) asp = models.BooleanField(blank=True) latest_asp_session = models.DateField(blank=True, null=True) number_asp_sessions = models.CharField(blank=True, null=True, max_length=10) tours = models.BooleanField(blank=True) latest_tours_session = models.DateField(blank=True, null=True) number_tours_sessions = models.CharField(blank=True, null=True, max_length=10) Form class EditAthleteForm(forms.ModelForm): class Meta(): model = Athlete fields = ('__all__') widgets = { 'athlete_ref': TextInput(attrs={'id':'athlete_ref', 'name': 'athlete_ref', 'hidden': 'hidden'}), 'athlete_name': … -
is it possible to use regular Django+templates and Django restframework+a javascript framework in the same project?
I'm just wondering since Jquery is used less and less and instead of classic use with Ajax, if it is possible to let for example React or Vue handle all of the functionality where Javascript would be needed with DRF in one hand , and consider all of it as statics. And in the other hand, keep working with Django and regular templates. i'm just asking about the possiblity to do so. -
image path is not identifiable on index.html of django3
i am following a tutorial based on django 2 and currently running version 3 of django, the problem i am facing is the identifying path of the tag on the front end of index.html, i'll post the code bellow , kindly tell me where i went wrong and any other mistakes my settings.py STATIC_URL = '/static/' STATICFILES_DIRS= (os.path.join(BASE_DIR, 'static'),) #static root added (A2) MEDIA_ROOT=os.path.join(BASE_DIR, 'media') MEDIA_URL='/media/' my urls.py of main project from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('',include('posts.urls')), path('user/',include('user.urls')), path('admin/', admin.site.urls), ]+ static(settings.STATIC_URL, document_root=settings.MEDIA_ROOT) my models.py of app class Posts(models.Model): #created this model field def min_len(val): #this is the custom validator working if len(val)<=9: raise validators.ValidationError("%(val)s Must be more than 10", params={'val':val}) title=models.CharField(validators=[min_len],max_length=255) #validation list provided content=models.TextField(validators=[min_len]) thumb_nail=models.FileField(upload_to="posts/",null=True) #file field added class Posts_Form(forms.ModelForm): #to build a form using django and not html class Meta: #will get data of the fields=[] only model=Posts fields=['title','content','thumb_nail','user','category'] views.py def index(request): form=Posts_Form() #created form object data=Posts.objects.all() #retrive data from the model to display category=Category.objects.all() #we get all data of category if request.method=='POST': form=Posts_Form(request.POST,request.FILES) #request.FILES for file data if form.is_valid(): # data=Posts( # title=request.POST['title'], # content=request.POST['content'], # ) form.save() return redirect('/') return … -
Django forms : 'NoneType' object has no attribute 'is_valid'
Like a lot of people here, i have to deal with a form problem, but even with other posts I can't see the solution, here are my files : testeuh/models.py : from django.db import models from django.contrib import admin # Create your models here. class diapo(models.Model): title = models.CharField(max_length=30) corpus = models.TextField(max_length=300) image = models.ImageField(upload_to="DossierImages") class diapoAdmin(admin.ModelAdmin): search_fields = ['title'] list_display = ['title'] testeuh/forms.py : from django.forms import ModelForm from .models import diapo def DiapoForm(ModelForm): class Meta: model = diapo fields = [ 'title', 'corpus', 'image', ] testeuh/views.py : from django.shortcuts import render from .forms import DiapoForm from .models import diapo # Create your views here. def diapo_create_view(request): form = DiapoForm(request.POST or None) if form.is_valid(): form.save() context = { 'form': form } return render(request, "diapo/create.html", context) def diapo_detail_view(request): obj = diapo.objects.get(id=1) context = { "object" : obj } return render(request, "diapo/detail.html", context) urls.py : """SiteEcran URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including … -
How to configure fields in Django forms.Form?
I'm learning Django and web dev and having difficulty configuring the fields in Django forms.Form so that they come out correctly. Below is my code: Even if I adjust my attrs rows and cols in forms.Textarea it doesn't make any difference. Also, it doesn't seem to matter what I put in CSS the output is still the same. class NewPageForm(forms.Form): title = forms.CharField(label="Title", max_length=100, widget=forms.TextInput) content = forms.CharField(label="Content", widget=forms.Textarea(attrs{"rows":3,"cols":10})) My html: {% block body %} <div class="form"> <form action="{% url 'create' %}" method="post"> {% csrf_token %} {{ form.as_p }} <input type = submit> </form> </div> {% endblock %} What it looks like: Please advise. -
Error: relation "django_admin_log" does not exist
When I try to log in to admin section I get the error page: http://localhost:8000/admin/ ProgrammingError at /admin/ ERROR: relation "django_admin_log" does not exist Then I noticed that 'django_admin_log' table does not exist. captured from psql I can not remember whether I accidentally removed it or not. In order to recover it I checked "django.contrib.admin" is in INSTALLED_APPS in settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'db.apps.DbConfig', 'django.contrib.postgres', 'accounts.apps.AccountsConfig', 'django.contrib.sites', 'allauth', 'allauth.account', ] and execute "python manage.py migrate admin" But still, I can not create django_admin_log table. PostgreSQL version is 12.6 I just mentioned the above settings in this question but still if more code is required then tell me I'll update my question with that information. Thank you