Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I use django with socketio so that I can do real time communication between my arduino and my server ie on my site?
I want to read data in realtime from my arduino to my site using serial port communication. -
how can I insert input data of form in form action url
When the data is entered in the input field of form . I want it to submit that data in /wiki/that_data through form action. How do I do that?.I tried wiki/{{ title }} ,passing title as a dict in render function but it doesn't work. Can someone explain why this doesn't work? Or,guide me to good resource to learn this. layout.html <form action="/wiki/{{ title }}" method="post"> {% csrf_token %} <input class="search" type="text" name="q" placeholder="Search Encyclopedia"> </form> with this view : views.py def EntryPage(request, title): if request.method == "POST": title = request.POST return render(request, "encyclopedia/entrypage.html", { "title" : title, "getentry": util.get_entry(title) }) -
Select which fields to export in django-import-export
I'm adding the django-import-export to the admin in my app. One thing I wanted to do was to offer the possibility of selecting in the admin page of selecting which fields to export. I searched for this topic but I only came across two questions with no answers. Is it possible to add the possibility to dynamically choose which fields to export from the admin page? Thanks. -
Django: Abstract models cannot be instantiated for models for retrieving data
I am working on a project which has one abstract model and one main model for Djongo. when i try to insert a value ,it is getting inserted without errors. But when i try to retrieve the data i get " Abstract models cannot be instantiated" . Here is my model: question=models.CharField(max_length=200,null=True) options=ArrayField(models.CharField(max_length=50)) answer=models.CharField(max_length=50,null=True) types=models.CharField(max_length=50,null=True) class Meta: abstract=True class ExamDetails(models.Model): _id=ObjectIdField() exam_id=models.IntegerField(null=False,default=0) questions=models.EmbeddedField(model_container=Exam_questions) objects = models.DjongoManager() here is my code for querying: def exams_questions(request,exam_id): get_exams=ExamDetails.objects.filter(exam_id=3) print(get_exams) return HttpResponse("hello") # have given this response only for testing when i try to iterate or get values in the variable get_exams im getting "Abstract models cannot be instantiated" error. Please help! Thanks -
ModuleNotFoundError: No module named 'learning_logs.settings' in Django
For some reason i am not able to migrate file from one to another. I am working on a Django project from the book "Python crash course". CMD prompt message- (ll_env) C:\Users\visha\learning_log>python manage.py makemigrations learning_logs ModuleNotFoundError: No module named 'learning_logs.settings' this is in the command prompt. I checked the settings file and i did include the 'learning_logs' with a comma in installed apps tuple. Here is the code of the python ' settings' file INSTALLED_APPS = [ # default apps 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # my apps 'learning_logs',] I had seen solutions where they had to only include the comma but i have invcluded it and still get the error in command prompt. -
Commaseparated form field in django
Suppose I have a following fields class SomeField(forms.Charfield): def to_python(self, value): value = super().to_python(value) # some cleaning logic return value def validate(self, value): super().validate(value) #some logic class AnotherField(forms.Charfield): def to_python(self, value): value = super().to_python(value) # some cleaning logic return value def validate(self, value): super().validate(value) #some logic class CommaSeparatedSomeField(Field): base_class=SomeField class CommaSeparatedAnotherField(Field): base_class=AnotherField What is the best way to implement above CommaSeparated***Field, where comma-separated means just a text field, with comma-separated values? I tried to represent it with a CharField, splitted by commas, but now I need to validate and clean each value in a list using the base_class logic. Here I encountered a problem, since all logic is not class methods. -
Can not create a superuser in my python django project
I ran makemigration and migrate and the ran OK. When I run python manage.py createsuperuser, after keying in my info I get TypeError: save() got an unexpected keyword argument 'force_insert' -
Storing files Django
I am building an website using django in which I have to store a lot of files. I have a view, which takes file from the user and saves it. def store(request): if request.method == "POST": sender = request.POST['sender'] file = request.POST['file'] I have a model in which i save these data: class t_data(models.Model): sender = models.TextField() file = models.FileField(upload_to='files') and I have this on my settings file: MEDIA_ROOT = os.path.join(BASE_DIR,"media") MEDIA_URL = '/media/' Many files can have same name. Should I rename before saving them? How should I save them. There will be many users, So how can I distinguish files for each user? my question is : **What is the best way to store files in a django application?**Please Thank you -
Anonymous users in django many to many fields
I am trying to make a simple blog in django. I have a django ManyToManyField in my models to keep the record of likes on a blog post. It is working just fine but it only allows authenticated users to like a post but not anonymous users. I also want anonymous users to be able to like a post. Is there a way to do it? here is my models.py class Posts(models.Model): post = models.TextField(max_length=1500) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) likes = models.ManyToManyField(User, related_name="post_likes") here is my vies.py def likes(request): if request.method == "POST": post = get_object_or_404(Posts, id=request.POST.get("like_button")) post.likes.add(request.user) here like_button is a name of a input in form that has value=id of a post. -
Django admin and wagtail static files not found
I have a Django site with wagtail and puput integrated into it, as well as whitenoise handling the static files. For some reason, in production, the static files are working for the regular site, but not for the django admin or wagtail admin. Also, this may be a separate issue, but when I set debug = True, the main site throws a 500 error, while the two admin sites remain unchanged. urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('allauth.urls')), path('', views.home, name='home'), path('clubs/', include('clubs.urls', namespace="clubs")), path('members/', include('members.urls', namespace="members")), path('videos/', include('videos.urls', namespace="videos")), path('cms/', include(wagtailadmin_urls)), path('documents/', include(wagtaildocs_urls)), path('blog/', include(wagtail_urls)), path('posts/', include(puput_urls)), ] + static( settings.STATIC_URL, document_root=settings.STATIC_ROOT ) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' folder structure staticfiles/ admin/ wagtailadmin/ ... -
Django logging PermissionError with TimedRotatingFileHandler
I am trying to make django create and rotate new logs every 10 minutes using TimedRotatingFileHandler. My settings is as follows: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'DEBUG', 'class':'logging.handlers.TimedRotatingFileHandler', 'filename': 'logs/site.log', 'backupCount': 10, 'when':'m', 'interval':10, }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, }, } The first log file is created successfully. But when it is time to rotate the log file, I get the following error: PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'F:\\logs\\site.log' -> 'F:\\logs\\site.log.2021-05-22_19-18' How do I configure the logging so that the current log is copied to a timed log and new data written to the main log file? -
Using custom django model in DRF Token Authentication
I want to connect a custom User model with the Django Rest Framework TokenAuthentication module. I have tried the followings: settings.py: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'myapp.authentication.MyOwnTokenAuthentication', ), } authentication.py: class MyOwnTokenAuthentication(TokenAuthentication): model = MyOwnToken models.py: class User(models.Model): name = models.CharField(max_length=100) email = models.EmailField() birth = models.DateField() class MyOwnToken(models.Model): key = models.CharField(_("Key"), max_length=40, primary_key=True) user = models.OneToOneField( User, related_name='auth_token', on_delete=models.CASCADE, verbose_name="User" ) created = models.DateTimeField(_("Created"), auto_now_add=True) views.py: class UserApi(APIView): authentication_classes = [MyOwnTokenAuthentication] permission_classes = [IsAuthenticated] #returns all data def get(self, request): alldata=User.objects.all() alldata_serialized=UserSerializer(alldata, many=True) return Response(alldata_serialized.data) The token generates fine but when I call the UserApi get then it gives WrappedAttributeError: 'User' object has no attribute 'is_active' can anyone help?? Thanks in advance. -
How to get Django to make some files public and media files private on AWS S3 (no 403 errors)?
I'm using boto3 and django-storages to serve files from AWS S3. I'd like my static files to be public but other files to be private. I've got it kinda sorta working but not quite. My static files are being served as if they're private, with a pre-signed key. In my template file when I use: <img src="{% static 'images/3d-house-nav-gray.png' %}"> instead of what I want <img src="https://mybucket.s3.amazonaws.com/static/images/3d-house-nav-gray.png"> I'm getting <img id="home-img" src="https://mybucket.s3.amazonaws.com/static/images/3d-house-nav-gray.png?AWSAccessKeyId=AKIA1234564LQ7X4EGHK&amp;Signature=123456gIBTFlTQKCexLo3UJmoPs%3D&amp;Expires=1621693552"> This actually works when the templates are rendered from the server as part of an HTTPResponse, but not when an image like this is simply included as part of, say, a .css file. In that case I'll get: Failed to load resource: the server responded with a status of 403 (Forbidden) (I find I can copy and paste the problematic image link and replace the &amp; with an & then I have access, a further mystery.) Here is how I have AWS configured: AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID'] AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY'] AWS_STORAGE_BUCKET_NAME = 'mybucket' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_DEFAULT_ACL = None AWS_LOCATION = 'static' STATICFILES_STORAGE = 'myapp.storage_backends.StaticStorage' DEFAULT_FILE_STORAGE = 'myapp.storage_backends.MediaStorage' AWS_S3_URL = 'https://%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME STATIC_DIRECTORY = '/static/' MEDIA_DIRECTORY = '/media/' STATIC_URL = AWS_S3_URL + STATIC_DIRECTORY MEDIA_URL = … -
Django AttributeError: 'Cart' object has no attribute 'get'
I am getting this error on my django project: Request Method: GET Request URL: http://127.0.0.1:8000/cart/ Exception Type: AttributeError at /cart/ Exception Value: 'Cart' object has no attribute 'get' and here is carts.views.py: from django.shortcuts import render, redirect, get_object_or_404 from store.models import Product from .models import Cart, CartItem # Create your views here. def _cart_id(request): cart = request.session.session_key if not cart: cart = request.session.create() return cart def add_cart(request, product_id): product = Product.objects.get(id=product_id) try: cart = Cart.objects.get(cart_id=_cart_id(request)) except Cart.DoesNotExist: cart = Cart.objects.create( cart_id = _cart_id(request) ) cart.save() try: cart_item = CartItem.objects.get(product=product, cart=cart) cart_item.quantity += 1 cart_item.save() except CartItem.DoesNotExist: cart_item = CartItem.objects.create( product= product, quantity= 1, cart= cart, ) cart_item.save() return redirect('cart') def cart(request): return render(request, 'store/cart.html') I tried: rewrite the name of class 'Cart' use objectDoesnotexist instead of DoesnotExit double check the names of the classes in models.py I am not able to debug this error. I overlooked my codes many times, but cant able to understand where is the error being generated. Thanks in advance. -
Django 3.2 LookupError: Model not registered
While trying to upgrade an existing project to Django 3.2 (from 2.2), I have been getting the following error: ... from .permissionmodels import * # nopyflakes File "/home/user/miniconda3/envs/app-web-py38-test/lib/python3.8/site-packages/cms/models/ permissionmodels.py", line 19, in <module> User = apps.get_registered_model(user_app_name, user_model_name) File "/home/user/miniconda3/envs/app-web-py38-test/lib/python3.8/site-packages/django/apps /registry.py", line 273, in get_registered_model raise LookupError( LookupError: Model 'user_accounts.CustomUser' not registered. The custom model is located in apps/user_accounts/models.py and looks like this from django.db import models from django.contrib.auth.models import AbstractUser from django.db import models from .managers import CustomUserManager class CustomUser(AbstractUser, PermissionsMixin): username = None email = models.EmailField(('email address'), unique=True) # add additional fields in here profile_picture = models.ImageField(upload_to='profile/', blank=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email The installed apps are as follows INSTALLED_APPS = [ # this app is at the top because it defines a custom user model for the whole project 'apps.user_accounts', 'djangocms_admin_style', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', #'django.contrib.contenttypes.models.ContentType', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sitemaps', #after project creation# #Django CMS stuff 'django.contrib.sites', 'cms', 'menus', 'treebeard', 'sekizai', 'filer', 'easy_thumbnails', 'mptt', 'djangocms_link', 'djangocms_file', 'djangocms_picture', 'djangocms_video', 'djangocms_googlemap', 'djangocms_snippet', 'djangocms_style', 'djangocms_column', 'djangocms_text_ckeditor', 'djangocms_comments', 'bootstrap4', #Aldryn News Blog 'aldryn_apphooks_config', 'aldryn_categories', 'aldryn_common', 'aldryn_newsblog', #'aldryn_newsblog.apps.AldrynNewsBlog', 'aldryn_people', 'aldryn_translation_tools', 'absolute', 'aldryn_forms', 'aldryn_forms.contrib.email_notifications', 'captcha', 'emailit', 'parler', 'sortedm2m', 'taggit', # this AWS S3 work (boto + django-storages) … -
How can I display html using a view that displays multiple object items and after one of those items has been deleted form Django database?
I have the following models: CATEGORY_CHOICES = ( ('Hotel', 'Hotel'), ('Restaurant', 'Restaurant'), ('Attraction', 'Attraction'), ('Activity', 'Activity') ) LABEL_CHOICES = ( ('P', 'primary'), ('S', 'secondary'), ('D', 'danger') ) class Item(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=64) address = models.CharField(max_length=64) postcode = models.CharField(max_length=7) category = models.CharField(choices=CATEGORY_CHOICES, max_length=20) label = models.CharField(choices=LABEL_CHOICES, max_length=1) slug = models.SlugField() image = models.ImageField(blank=True, null=True, upload_to="images/") description = models.TextField() def __str__(self): return f"{self.id}: {self.name}" def get_absolute_url(self): return reverse("product", kwargs={ 'slug': self.slug }) def get_add_to_cart_url(self): return reverse("add-to-cart", kwargs={ 'slug': self.slug }) def get_remove_from_cart_url(self): return reverse("remove-from-cart", kwargs={ 'slug': self.slug }) class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) def __str__(self): return f"{self.quantity} of {self.item.name}" class Order1(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) step = models.CharField(max_length=1, default=0) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) step_duration = models.FloatField(default=0) def __str__(self): return self.user.username def get_total_duration(self): Pass def get_total_price(self): return F"£{self.step_duration * 20}" class Order2(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) step = models.CharField(max_length=1, default=0) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) step_duration = models.FloatField(default=0) def __str__(self): return self.user.username def get_total_duration(self): Pass def get_total_price(self): return F"£{self.step_duration * 20}" I have the following view: @login_required(login_url='login') def OrderSummaryView(request): try: order1 = Order1.objects.get(user=request.user, ordered=False) … -
django get image url from custom user creation form
i have created a custom usercreation form in django i cant figure out how to get the url from my image feild in my user creation form. i am getting error inmemoryuploadedfile has no attribute url any help would be appreciated my form: class RegisterForm(UserCreationForm): bio = forms.CharField(max_length=400, required=False) image = forms.ImageField(required=False) class Meta: model = User fields = ["username", "image", "password1", "password2", "bio"] def save(self, commit=True): user = super(RegisterForm, self).save(commit=False) user.bio = self.cleaned_data["bio"] user.image = self.cleaned_data["image"] if commit: user.save() return user views.py: class RegisterPage(FormView): template_name = "main/register.html" form_class = RegisterForm success_url = reverse_lazy('blog_list') def form_valid(self, form): user = form.save() if user is not None: login(self.request, user) return super(RegisterPage, self).form_valid(form) def post(self, request, *args, **kwargs): form = self.form_class(request.POST, request.FILES) if form.is_valid(): user = form.save() form.user = request.user login(self.request, user) print(request.user.image.url) messages.success(request, "Account Created Successully") return redirect('blog_list') return render(request, self.template_name, {'form': form}) def get(self, *args, **kwargs): if self.request.user.is_authenticated: return redirect("blog_list") return super(RegisterPage, self).get(*args, **kwargs) register.html <div class="form"> <h1>Register</h1> <form enctype='multipart/form-data' method="POST"> {% csrf_token %} <ul> {% for field in form %} {% if field.errors %}<li>{{ field.label }}: {{ field.errors|striptags }}</li>{% endif %} {% endfor %} </ul> <label>{{form.username.label}}</label> {{form.username}} <br> <label>{{form.password1.label}}</label> {{form.password1}} <br> <label>{{form.password2.label}}</label> {{form.password2}} <br> <label>{{form.image.label}}</label> {{form.image}} <br> <label>{{form.bio.label}}</label> {{form.bio}} <br> … -
Wikipedia-typed Django models relations
I need to connect some articles where mentioned some people from another fields. For example, science, cinema, music, etc. How to build models in this situation, I'm sure, it is many to many relation, but how to control this third table and which data needed to connect? I need model, where will be name of article, text of article, field (cinema), and person (50 Cent). How to deal wit that fact, that one person may be related to several fields, for example, music and cinema? -
Downloading files from a website on django
I have a website on a debian server. I fill out the template in docx format and save it. How do I download it to the user's devices? post_data = json.loads(request.body) date = post_data.get('date', False) price = post_data.get('price', False) pricesum = post_data.get('pricesum', False) startdate = post_data.get('startdate', False) enddate = post_data.get('enddate', False) doc = DocxTemplate('template.docx') dates = date prices = price tbl_contents = [{'expirationdate': expirationdate, 'price': price} for expirationdate, price in zip(dates, prices)] context = { 'tbl_contents': tbl_contents, 'finalprice': sum(prices), 'startdate': startdate, 'enddate': enddate } doc.render(context) doc.save("static.docx") -
How to query data in fields from django model?
I get values for CharField from ModelForm and i need get that data from database. I need value of variable in model from model with a certain id. -
How to set Cache-Control with django.contrib.syndication.views
I try to set the Cache-Control HTTP header in django.contrib.syndication.views with cache_control() (of django.views.decorators.cache), but in vain: from django.contrib.syndication.views import Feed from django.utils.feedgenerator import Atom1Feed import lxml.html import requests class TestFeed(Feed): feed_type = Atom1Feed language = 'zh-Hant-TW' link = 'https://www.example.com/feed' title = 'Sample feed' def items(self): s = requests.Session() r = s.get(self.link) body = lxml.html.fromstring(r.text) items = body.cssselect('.item a') return items def item_description(self, item): img = item.cssselect('img')[0] img.set('src', img.get('data-src')) content = lxml.etree.tostring(item, encoding='unicode') return content def item_link(self, item): link = item.get('href') return link def item_title(self, item): title = item.get('title') return title After tracing the source code of django.contrib.syndication.views it seems unlikely to use decorator(s) to add a HTTP header into the HTTP response object. Is there any workaround to accomplish this? -
How to exclude show filters for specific endpoint in drf-yasg
I have some ViewSet with filterset_fields and ordering_fields attributes. Also i have extra action in that ViewSet, that uses as a shortcut to get list with some filtration. I assume to use that extra action without handling any additional filter(or may be ordering) options. But in default way drf-yasg genereates parameters schema for that extra action with filterset_fields and ordering_fields. How i can ignore filterset_fields and ordering_fields attributes for specific endpoint? -
How to write test with foreign/manytomany key - Django
Please help me understand writing a test model for book model with foreign key. I am working on the local library project tutorial done by MDN. Right now it is giving me error Error is as follows ERROR: setUpClass (catalog.tests.test_models.BookModelTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/rishipalsingh/Projects/notes/mdndjango/venv/lib/python3.9/site-packages/django/test/testcases.py", line 1201, in setUpClass cls.setUpTestData() File "/Users/rishipalsingh/Projects/notes/mdndjango/mdn/catalog/tests/test_models.py", line 68, in setUpTestData Book.objects.create(title='who sold my safari', author=['first_name', 'last_name'], summary='book is about the story of person who found out that his safari is sold', genre='name', Language='name') File "/Users/rishipalsingh/Projects/notes/mdndjango/venv/lib/python3.9/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Users/rishipalsingh/Projects/notes/mdndjango/venv/lib/python3.9/site-packages/django/db/models/query.py", line 451, in create obj = self.model(**kwargs) File "/Users/rishipalsingh/Projects/notes/mdndjango/venv/lib/python3.9/site-packages/django/db/models/base.py", line 485, in __init__ _setattr(self, field.name, rel_obj) File "/Users/rishipalsingh/Projects/notes/mdndjango/venv/lib/python3.9/site-packages/django/db/models/fields/related_descriptors.py", line 215, in __set__ raise ValueError( ValueError: Cannot assign "['first_name', 'last_name']": "Book.author" must be a "Author" instance. Book code for your reference is as follows class Book(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True) summary = models.TextField(max_length=1000, help_text='Enter a brief description of the book') isbn = models.CharField('ISBN', max_length=13, unique=True, help_text='13 Character <a href="https://www.isbn-international.org/content/what-isbn">ISBN number</a>') genre = models.ManyToManyField( Genre, help_text='Select a genre for this book') language = models.ManyToManyField( Language, help_text='Select Language for this book') def get_language(self): return ', '.join(language.name for language in self.language.all()) get_language.short_description = 'Language' class Meta: … -
Random NoneType Exception when running Django + Guardian with PGPOOL-II
I have kinda complex topic today I would like to share with you. We are running a "massive" Django Backend with high focus on High Availability. For legal reasons we had to change our infrastructure provider and started hosting main database internally (on our kubernetes cluster) instead of using one of the popular Database as a Service offerings. Long story short, with bringing pgpool-II into the game we suffer from random NoneType errors that nobody can explain. Actually the plan was to write a guide how to setup a scalable, ha & production-rdy deployment on k8s.However,for now it seems that there are issues to solve/understand, beforehand. Consider the following setup: We are deploying Django-Applications with Guardian as Docker-Containers to k8s Django 3.2.3 Gunicorn 20.1.0 with uvicorn Workers (0.13.4) ASGI 3 Protocol (asgref 3.3.4) Django-Guardian 2.3.0 Our PostgreSQL Cluster is based on the latest bitnami/postgresql-ha image Pgpool-II (2.2) and PostgreSQL (11.12) Follow best practices we use django's signal logic to execute permission assignment as part of the post_save for various models. What we see now that maybe 1 out 50 requests fails with an NoneType exception. If you check the error trace I linked then u will see the "real" problem … -
submitted data through form but not stored in database
I have created models.py as well as views.py, wanted to submit data through the front page and those need to store in the database but failed to sent data. when I click to submit after fillup the form it goes to the else block which is mentioned in views.py but not checking if statement. help appricated. models.py from django.db import models # Create your models here. # creating modeles here and storing in database acts as mysql class Contact(models.Model): usn = models.CharField(max_length=50, primary_key=True) name = models.CharField(max_length=50, default="") sem = models.CharField(max_length=50, default="") phone = models.CharField(max_length=50, default="") email = models.CharField(max_length=50, default="") def __str__(self): return self.name views.py from django.shortcuts import render, redirect, HttpResponse from django.conf import settings from .models import Contact # Create your views here. def index(request): if request.method=="POST": usn = request.POST.get('usn','') name = request.POST.get('name','') sem = request.POST.get('sem','') phone = request.POST.get('phone','') email = request.POST.get('email', '') if usn and name and sem and phone and email: contact = Contact(usn = usn, name = name, sem = sem, phone = phone, email = email) contact.save() else: return HttpResponse("Enter all details") return render (request, 'index.html')