Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django+React rest-auth
I am using the rest-auth module to enable user authentication on my web app. Though I am facing some difficulties in fetching details about the user. The Django-rest-framework return a key when I post my username and password, while that's enough for logging in I also want to fetch additional details like user.is_staff, user.username and user.email. I tried to use Token serializer, but I am not sure if I am doing it right. ** settings.py ** REST_AUTH_SERIALIZERS = { 'TOKEN_SERIALIZER': '## How to define the path to my serializer ##', } ** serializers.py ** from rest_framework import serializers from lms.models.post_models import Post from django.contrib.auth.models import User from rest_auth.models import TokenModel class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'email') class TokenSerializer(serializers.ModelSerializer): user = UserSerializer() class Meta: model = TokenModel fields = ('key', 'user') Please tell what piece is missing or if any piece is incorrect. Also, please help me figure out the part between ## ##. Thank you! -
How to restart a port 8080 in port 8080, 8081, 8082 in apache on Centos 7?
i want restart one port in multiple port of apache in Centos 7, how i can do this? thank you. -
Django - set a model CharField value to the name of a field from another model
I have a model when I want to field_name to be the name of any field from another model. I wrote this code: from providers.models import Organisation FIELD_CHOICES = [(x.name,x.verbose_name) for x in Organisation._meta.get_fields() ] class Score (models.Model): field_name = models.CharField(max_length=101, choices=FIELD_CHOICES) When I run makemigrations I get django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. This is the complete traceback: Traceback (most recent call last): File "./src/manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/henry/Documents/Sites/Development/autumna-dev/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/henry/Documents/Sites/Development/autumna-dev/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/home/henry/Documents/Sites/Development/autumna-dev/env/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/henry/Documents/Sites/Development/autumna-dev/env/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/home/henry/Documents/Sites/Development/autumna-dev/env/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/home/henry/Documents/Sites/Development/autumna-dev/env/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/henry/Documents/Sites/Development/autumna-dev/autumna/src/scoring/models.py", line 7, in <module> FIELD_CHOICES = [(x.name,x.verbose_name) for x in Organisation._meta.get_fields() ] File "/home/henry/Documents/Sites/Development/autumna-dev/env/lib/python3.6/site-packages/django/db/models/options.py", line 733, in get_fields return self._get_fields(include_parents=include_parents, include_hidden=include_hidden) File "/home/henry/Documents/Sites/Development/autumna-dev/env/lib/python3.6/site-packages/django/db/models/options.py", line 793, in _get_fields all_fields = self._relation_tree File "/home/henry/Documents/Sites/Development/autumna-dev/env/lib/python3.6/site-packages/django/utils/functional.py", line 37, in __get__ res = instance.__dict__[self.name] … -
How to add an element without changing the height of the card or disturbing position of other elements
How do I add an element(image) at the end without changing the height of the card, with card height set to auto is there any way to solve this? any help is appreciated, Thanks! .card { width: 540px; height: auto; border: 1px solid #707070; } .field2 { font-family: inherit; padding-top: 20px; padding-bottom: 25px; display: flex; justify-content: space-between; } .log_in_instead { padding-left: 60px; } .create { padding-right: 70px; } #img101 { position: relative; left: 490px; top: -150px; } <div class="card"> <div class="field2"> <span class="log_in_instead"> <a href="#">Log in instead</a> </span> <span class="create"><button id="create_button" type="submit">Create</button</span> </div> <span><img src="{% static 'main/images/img101.svg' %}" id="img101"></span> </div> This is what it should look like: [1]: https://i.stack.imgur.com/jkPg2.png This is what it looks like: [2]: https://i.stack.imgur.com/w1ROu.png -
How to put an if statement outside the functions in Django Views, Python
I have 3 functions. Each of them has the same line of code: if request.method == "POST" and 'url' in request.POST: Here are the functions: def checkurl(request): if request.method == "POST" and 'url' in request.POST: url = request.POST.get('url', '') url_response = "" if not url.startswith('http://') and not url.startswith('https://'): url_get = "http://" + url url_response = requests.get(url_get, headers=headers, allow_redirects=False) url_status_code = url_response.status_code if url_status_code == 200: url = url_get return url else: url = "https://" + url return url return url def netloc(request): url = checkurl(request) global url_scheme global url_port global url_netloc global url_path if request.method == "POST" and 'url' in request.POST: url_parsed = urlparse(url) url_scheme = url_parsed.scheme url_port = url_parsed.port url_netloc = url_parsed.netloc if url_netloc.startswith('www.'): url_netloc = url_netloc.replace('www.', '') if url_netloc.endswith('/'): url_netloc = url_netloc.replace('/', '') return url_scheme, url_port, url_netloc def tests(request): if request.method == "POST" and 'url' in request.POST: url = checkurl(request) netloc(request) var = { 'url':url, 'url_scheme':url_scheme, 'url_port':url_port, 'url_netloc':url_netloc, } return render(request, 'apptests/shots.html', var) else: return render(request, 'apptests/shots.html') I do not want to repeat the same line of code in each function and want to remove it and put it aside before these 3 functions. But I cannot do it Please help -
adding html links to different fields: Django
I have a question if i have 3-4 different post/section in html which i uploaded through admin panel but all this posts/sections have different html pages so how can i link each post/section with their specific html page and is there a field in django model which helps in uploading videos?? posts.Html <div class="blog_list"> <h1 class="blog_heading"> Top 10 Family Holiday Destination</h1><br><br> {% for postv in postv %} <h2 class="blog_location">{{ postv.locationv }}</h2><br> <img class="blog_img" src="{{ postv.imgv.url }}"><br> <p class="blog_details article-content">{{ postv.detailv }}</p><br><br> {% endfor %} </div> models.py class vacation(models.Model): locationv = models.CharField(max_length=100) imgv = models.ImageField(upload_to='locations') detailv = models.TextField() def __str__(self): return self.locationv views.py class top10_vacation(ListView): model = vacation template_name = 'shop/vacation.html' context_object_name = 'postv' -
How do I submit a form without page reload using Ajax
I'm learning Ajax on how I can submit a comment form without page reload. I'm using Django, I have list of posts in homepage each with comment form. When I submit a comment it is not saving in database and also it doesn't display in browser. When I check on Chrome console, I got an error 2 elements with non-unique id. from django.http import JsonResponse from django.template.loader import render_to_string def home(request): all_images = Post.objects.filter(poster_profile=request.user) if request.method == 'POST': post_id = request.POST.get("post_comment") post_obj = Post.objects.get(pk=post_id) form = CommentForm(request.POST) if form.is_valid(): comment=form.save(commit=False) comment.user=request.user comment.commented_image=post_obj comment.save() else: form=CommentForm() context = {'all_images':all_images, 'form':form} if request.is_ajax(): html=render_to_string('ajax_feeds_comment.html', context, request=request) return render(request, 'home.html', context) #home.html {% for post in all_images %} <img src="{{ post.image.url }}"> {% for comment in post.comments.all %} <p>{{ comment.comment_post }}</p> {% endfor %} <div class="reload-form"> {% include "ajax_feeds_comments.html" %} </div> {% endfor %} #ajax_feeds_comments.html <form method="POST" class="feeds-comment" action="."> {% csrf_token %} <input type="hidden" value="{{post.id}}" name="post_comment"> <textarea name="comment_post" class="form-control" id="id_comment_post{{post.id}}"></textarea> <button type="submit" class="btn btn-primary">submit</button> </form> <script> $(document).on('submit', 'feeds-comment', function(event){ event.preventDefault(); console.log($(this).serialize()); $.ajax({ type: 'POST', url: $(this).attr('action'), data: $(this).serialize(), dataType: 'json', success: function(response){ $('.reload-form').html(response['form']); }, error: function(rs, e) { console.log(rs,responseText); }, }); }); </script> -
Django: dropdown toggle javascript does not work well
I have the following sidebar in my django: <a class="sidebar-heading d-flex justify-content-between align-items-center px-3 mt-4 mb-1" href="#firstSubmenu" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle">Performance Monitoring<span data-feather="plus-circle"></span></a> <ul class="collapse list-unstyled" id="firstSubmenu"> <li> <a class="nav-link" href="#"> <span data-feather="monitor"></span> Dashboard</a> </li> <a class="sidebar-heading d-flex justify-content-between align-items-center px-3 mt-4 mb-1" href="#secondSubmenu" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle">Performance Monitoring<span data-feather="plus-circle"></span></a> <ul class="collapse list-unstyled" id="secondSubmenu"> <li> <a class="nav-link" href="#"> <span data-feather="monitor"></span> Dashboard</a> </li> And the following script to allow me to keep open the dropdown button when change url $("#firstSubmenu").on('shown.bs.collapse', function(){ // Save in sessionStorage here }); $("#secondSubmenu").on('shown.bs.collapse', function(){ // Save in sessionStorage here }); $("#firstSubmenu").on('hidden.bs.collapse', function(){ // Save in sessionStorage here }); $("#secondSubmenu").on('hidden.bs.collapse', function(){ // Save in sessionStorage here }); $("#firstSubmenu").collapse("show"); $("#secondSubmenu").collapse("show"); But, for example, If I keep close the first submenu and open the second one, if I update the url both submenu are opened. Whre is the error/s? -
Django Admin Classes that Override formfield_for_dbfield - Error
I have a bunch of FlatPages on my django website and would like to translate their content in different languages from the Admin using the django-modeltranslations pacakge. Here is my code: class TinyMCEFlatPageAdmin(FlatPageAdmin): def formfield_for_dbfield(self, db_field, **kwargs): if db_field.name.startswith('content'): return db_field.formfield(widget=TinyMCE(attrs={'cols': 80, 'rows': 30},)) return super().formfield_for_dbfield(db_field, **kwargs) Basically, I created a TinyMCEFlatPageAdmin class from the default one FlatPageAdmin to display the Flatpage content in HTML on the admin site. As far as the translation is concerned, i added the following code: class MyTranslatedFlatPageAdmin(TinyMCEFlatPageAdmin, TabbedTranslationAdmin): def formfield_for_dbfield(self, db_field, **kwargs): field = super().formfield_for_dbfield(db_field, **kwargs) self.patch_translation_field(db_field, field, **kwargs) return field I have then registered the new MyTranslatedFlatPageAdmin class: admin.site.unregister(FlatPage) admin.site.register(FlatPage, MyTranslatedFlatPageAdmin) When i log in to the flatpage content page i receive the following error: formfield_for_dbfield() takes 2 positional arguments but 3 were given I am struggling to find out why as everything seems to be correct to me. Thanks in advance for your help -
How to select for update postgresql in node js
I'm generally using django, and for operations with ordered concurrency I use next code with transaction.atomic(): try: player = Player.objects.select_for_update().get( id=player.id, player_online=False) except: return bad_response("Unknown error") player.player_socket = socket_id player.save() # Even here it will wait until "with" finished if player.extra_security: print("Ask for password action") else: pass So in this code I get player by criteria and while code inside "with transaction.atomic():" All other queries will WAIT, not returned with error. How can I reproduce such flow in node_js + postgresql (or MongoDb) I have found some solutions but, they not fit, because if object is locked they'll return an error (for mongo db) -
Is there a way to hide autodoc of exceptions and save methods?
I'm documenting a huge Django project and would like to have an option to hide autogenerated Django stuff like below. Is it something I have to "deal with" or is there a setting I haven't found yet? I document with: .. automodule:: module.models :members: and get things like below, which would be good if I had those overriden, but they're not: exception DoesNotExist exception MultipleObjectsReturned save(*args, **kwargs):... -
request.post redirecting to get in django development server
from rest_framework.authentication import BasicAuthentication from rest_framework.permissions import IsAuthenticated class TestApiView(APIView): authentication_classes = [BasicAuthentication] permission_classes = [IsAuthenticated] def post(self, *args, **kwargs): return Response({'method': 'post'}) def get(self, *args, **kwargs): return Response({'method': 'get'}) The view is accessable in the url http://127.0.0.1:8000/test/ and working as expected in browser I am calling the api from python shell import requests from requests.auth import HTTPBasicAuth url = 'http://127.0.0.1:8000/test/' my_auth = HTTPBasicAuth('<my-user-name>', '<password>') r=requests.post(url, auth=my_auth) print(r.json()) {'method': 'get'} The get method is called instead of post in the django development server. I want to make it work in django development server. Its working perfect in my nginx-gunicorn-django server Any help appreciated. -
Django TypeError objects is not iterable in Templates
I have two models one is club details and the other is player structure. so my plan is to based on the club iteration which has values like'test', 'odi', 'listA' i need to represent its respective player structure in my Django template. models.py class Clubstate(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class PlayerStructure(models.Model): clubstate = models.ForeignKey('Clubstate', on_delete=models.CASCADE, related_name='clubstate') country = models.ForeignKey('TeamStructure', on_delete=models.CASCADE, null=True, related_name='identifier1') firstname = models.CharField(max_length=255) lastname = models.CharField(max_length=255) imageUri = models.ImageField(upload_to='images/', verbose_name='image') JerseyNumber = models.IntegerField() def __str__(self): return self.firstname + self.lastname In views.py I'm using DetailView to represent the data. class PlayerStatistics(DetailView): context_object_name = 'Clubstate_details' model = models.Clubstate template_name = 'CricketDetails/playerstatistics_details.html' Template html <div class="jumbotron"> <div class="container"> <div class="row"> {% for club in Clubstate_details %} <h1>{{club.name</h1> {% endfor %} </div> </div> </div> My thought, logic is like {% for club in clubs %} {{club.name}} {{club.player_structure.firstname}} {{club.player_structure.lastname}} {% endfor%} So that for indivdual club i get its respective player structure. I get TypeError: 'Clubstate' object is not iterable error. Hope that makes sense... -
Error Unknown command: 'mycommand' in django management command
I am a beginner and I want Multiple arguments with values to custom management command, I am using following code def add_arguments(self, parser): parser.add_argument('--str_arg1', nargs='+') parser.add_argument('--int_arg2', nargs='+', type=int) when I run manage.py mycommand but I am getting an error F:\tb\sun>manage.py mycommand Unknown command: 'mycommand' Type 'manage.py help' for usage. My path is management/ commands/ __init__.py mucommand.py __init__.py -
trying to create a second forms.py on my Django app to post on the same page
I have one forms.py set up to post onto my Django application successfully. I would like to set up a second forms.py which posts onto the same page but i cannot get it to work. The form comes up but it does not post. Here is my forms.py, the first one is the successful one: ''' from django import forms from . import models class CreatePost(forms.ModelForm): class Meta: model = models.Post fields = ['title', 'body','reverse_around_the_corner','speed_limit','watching_mirrors','centre_of_the_road','slug'] class CreateLearnerPost(forms.ModelForm): class Meta: model = models.LearnerPost fields = ['title', 'body', 'author', 'slug'] ''' Here is my views py, the LearnerPost view is the one i'm trying to create: ''' rom django.shortcuts import render, redirect from .models import Post, LearnerPost from django.contrib.auth.decorators import login_required from . import forms def PostList(request): posts = Post.objects.all().order_by('date') learner_posts = LearnerPost.objects.all().order_by('date') return render(request, 'logbook_index.html', {'posts':posts}, {'learner_posts':learner_posts}) def PostDetail(request, slug): post = Post.objects.get(slug=slug) return render(request, 'post_detail.html', {'post':post}) def LearnerPostDetail(request, slug): learner_post = LearnerPost.objects.get(slug=slug) return render(request, 'learner_post_detail.html', {'learner_post':learner_post}) def PostCreate(request): if request.method == 'POST': form = forms.CreatePost(request.POST, request.FILES) if form.is_valid(): instance = form.save(commit=False) instance.author = request.user instance.save() return redirect('/logbook/') else: form = forms.CreatePost() return render(request, 'post_create.html', {'form':form}) def LearnerPostCreate(request): if request.method == 'POST': form = forms.CreateLearnerPost(request.POST, request.FILES) if form.is_valid(): instance = form.save(commit=False) … -
Django REST Framework - paginate_queryset() takes 2 positional arguments but 3 were given
Really not sure what I have done wrong here, minus a few details, it's very similar to both examples on the REST framework website and almost a carbon copy of another Viewset I have. class ArtistViewSet( mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet, ArtistSetPagination ): queryset = Profile.objects.all() permission_classes = [permissions.AllowAny,] pagination_class = ArtistSetPagination serializer_class = ProfileSerializer def get_queryset(self, *args, **kwargs): return Profile.objects.all().prefetch_related( 'user' ) # Artwork List & List Filtering API View: def list(self, request, *args, **kwargs): parameters = {key: request.GET.get(key) for key in dict(request.GET).keys()} queryset = self.get_queryset().annotate( first_name_len=Length('user__first_name'), last_name_len=Length('user__last_name') ).filter( first_name_len__gt=0, last_name_len__gt=0, ).filter( **parameters ).order_by( '-created' ) page = self.paginate_queryset(queryset, self.request) if page is not None: serializer = ProfileSerializer(page, context={'request': request}, many=True) data = paginated.data paginated = self.get_paginated_response(data) else: serializer = ProfileSerializer(queryset, context={'request': request}, many=True) data = serializer.data response = standardized_json_response( message='Artist Objects Has Been Successfully Listed', timestamp=datetime.datetime.now(), data=data ) return Response(data=response, status=status.HTTP_200_OK) All I can see that is different is the use of the annotation for Length()... If anyone has any pointers I would gladly accept. N.B. The standardised_json_response() is just a wrapper which takes a few variables and returns a dict() object, just injecting some extra meta such as the timestamp of the request and the success status (True/False) -
How i display specific page for specidfic logged in user in django
i want to display specific tasks for specific people....like if raj is logged in then tasks of raj should display not others. so please give me some solution... views.py(home fn) def home(request): username=request.session['username'] for username in username: todo_items=TODO.objects.all().order_by("-created_date") return render(request,'main/index.html', {'todo_items':todo_items,'username':username}) models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class TODO(models.Model): user=models.ForeignKey(User,on_delete=models.SET_NULL, null=True) created_date=models.DateTimeField() text=models.CharField(max_length=200) -
How to send an error to user that already add book to favorite
I'm trying to make a user stop adding a book into favorite when they already added and show the message into template. Here's my class django python: class User(models.Model): fname = models.CharField(max_length=255) lname = models.CharField(max_length=255) email = models.EmailField() password = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = UserManager() class Book(models.Model): title = models.CharField(max_length=255) description = models.TextField() uploaded_by = models.ForeignKey(User, related_name="book_uploaded", on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = BookManager() class Like(models.Model): u_like = models.ForeignKey( User, related_name="user_like", on_delete=models.CASCADE) b_like = models.ForeignKey( Book, related_name="book_like", on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) And here's my views.py: def book_info(request, id): user_who_like = Book.objects.get(id=id).book_like.all() context = { 'book': Book.objects.get(id=id), 'user': User.objects.get(id=request.session["user_id"]), 'user_who_like': Book.objects.get(id=id).book_like.all(), 'user_uploaded': Book.objects.first().uploaded_by, } return render(request, 'book_info.html', context) def like(request, id): book = Book.objects.get(id=id) user = User.objects.get(id=request.session["user_id"]) like = Like.objects.create(u_like=user, b_like=book) return redirect(f"/books/{book.id}") Appreciate all your help! Thank you -
How to setup Google Cloud Storage as a media backend for Django?
I am using Django Storages [google] https://django-storages.readthedocs.io/en/latest/backends/gcloud.html I deployed my app to App engine using no-promote so that I test it out but everytime i upload an image, I get this error Cannot determine path without bucket name.'. Please note am using Django admin to make the upload and my service account key is at the root of my project. My bucket name is 'kyimages' and in models.py, image = models.ImageField(upload_to='kyimages/', blank=True, null=True) -
Creating a progress bar by using django-background-tasks
How can I create a progress bar with django-background-tasks library? I have researched many things but i could not find anything about that. All of the examples are about Celery. Can anyone help me? -
specify list of certain allowed values in char field
i want to specify list of values in CharField and make my serializer to accept the incoming json only if the value of this field is exactly like one of the values in the list. this is an example of what i have in mind. class UserSerializer(serializers.Serializer): username = serializers.CharField() first_name = serializers.CharField() last_name = serializers.CharField() gender = serializers.CharField(allowed=["male", "female", "other"]) is there a way to that? -
Best practices for extending Custom User Model in django
I have a Custom User model in my app class User(AbstractBaseUser, PermissionsMixin): uuid = models.UUIDField(default=uuid.uuid4, unique=True) email = models.EmailField(_('email address'), db_index=True, unique=True) and this AUTH_USER_MODEL = 'users.User' in my settings file. Now I want to create a model on the top of this custom user model(User), lets call it Agent, this model will have three columns: user_uuid #Foreign Key Refernce(OnetoOne) to the Custom User Model uuid # unique identifier for Agent model scope # CharField specific to Agent model What is the best way to do that? -
soup.find_all() returns empty dictionary
i have a code up here in my django and it is supposed to return all the resultRows class and it does not. It is not a problem with the module cause it returns 'a' tags, when asked alone. Here is the website im trying to access : https://ras-al-khaimah.locanto.ae/q/?query=computer . . Please someone help :) def new_search(request): search = request.POST.get('search') models.Search.objects.create(search=search) final_url = BASE_CRAIGSLIST_URL.format(quote_plus(search)) print(final_url) response = requests.get(final_url) data = response.text soup = BeautifulSoup(data,features='html.parser') post_titles = soup.find_all('a',{'class':'result-row'}) print(post_titles) stuff_for_frontend = { 'search':search, } return render(request,'my_app/new_search.html', stuff_for_frontend) -
Dynamically create Django settings variables
I have two settings files: settings_commons.py which holds the variables that are common for all instances settings_prod.py prod instance-specific vars settings_dev.py dev instance-specific vars I have multiple variables that set paths for logs, uploads and etc. These paths depend on MNT_DATA_DIR which is different for every instance (dev, prod, etc). I don't want to have these paths duplicated in every instance settings file. What I do in settings_commons.py MNT_DATA_DIR_DEPENDENT_VARS = ( ('FILE_DIR', os.path.join('{MNT_DATA_DIR}', "file_root")), ('LOG_DIR', os.path.join('{MNT_DATA_DIR}', "logs", "lab")), ... ) FILE_DIR_DEPENDENT_VARS = ( ('IMPORT_DATA_DIR', os.path.join('{FILE_DIR}', "Import")), ('REMOTE_DATA_DIR', '{FILE_DIR}'), ... ) And then in the instance-specific file from .settings_commons import * MNT_DATA_DIR = '/mnt/dir' for item in MNT_DATA_DIR_DEPENDENT_VARS: globals()[item[0]] = item[1].format(MNT_DATA_DIR=MNT_DATA_DIR) for item in FILE_DIR_DEPENDENT_VARS: globals()[item[0]] = item[1].format(FILE_DIR=FILE_DIR) Could this approach cause any problems? What about using setattr() instead of globals()? Is this the right approach? -
Django update database using edit form
I am a newbie to Django, and this is my first Django web-app. I have created a student management system where admin can add students. I have created a form at index page where student can enter their enrollment id and date of birth and will be redirected to a edit form page. Now I want to know that how to update the record with new values provided by user, I have no idea where to write the SQLite queries ( I have not changed any db setting and I red that Django uses SQLite db by default ) or how to handle the request. Any help would be appreciated. models.py class Student(models.Model): gender_choices = [('M', 'Male'), ('F', 'Female')] enrollment_no = models.CharField(max_length=10, primary_key=True, unique=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) father_name = models.CharField(max_length=50) mother_name = models.CharField(max_length=50) address = models.CharField(max_length=200) dob = models.DateField('date of birth') gender = models.CharField(choices=gender_choices,max_length=1,default=None) def __str__(self): return (self.first_name +" "+ self.last_name) STUDENT LOGIN FORM (index.html page) <form action="{% url 'students:detail' %}" method="get"> <div class="form-group"> <label for="enrollmentid">Enrollment ID: </label> <input type="text" class="form-control" name="enrollmentid" id="enrollmentid" placeholder="Enter enrollment id" required> </div> <div class="form-group"> <label for="dob">Date of Birth: </label> <input type="text" class="form-control" name="dob" id="dob" placeholder="Enter dob (YYYY-MM-DD)" required> </div> <button class="btn …