Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
- 
        ModelForm is creating a new record inspite of providing an instanceI am creating a ToDo list where I can create a ToDo item and provide a button against each item to update it. I am using ModelForm to save my data to DB. The update button takes me to 'update.html' with the instance of selected task. But when I update the task information and click on 'Submit', it creates a new task with the updated information and does not update the same task. Please helo me, I am stuck. views.py from django.shortcuts import render, redirect from .models import Task from .forms import * def index(request): tasks = Task.objects.all() form = TaskForm() if request.method == 'POST': form = TaskForm(request.POST) if form.is_valid(): form.save() return redirect('/') else: context = {'tasks':tasks,'form':form} return render(request,'TaskList/list.html',context) def update(request, pk): task = Task.objects.get(id = pk) if request.method == 'POST': form = TaskForm(request.POST, instance=task) if form.is_valid(): form.save() return redirect('/') else: form = TaskForm(instance = task) context = {'task':task, 'form':form} return render(request,'TaskList/update.html', context) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name = 'list'), path('update/<str:pk>/', views.update, name = 'update') ] update.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form method = 'POST' action = ''> {% csrf_token …
- 
        Python Django views .home dividing into sub classesI'm trying to do a platform which is querying some data from different social media channels. My "Home" Class is now full of these queries and it takes up to 10 seconds to load the page. My question would be how I can divide the Home class into sub classes like this. Currently my code looks like this: def Home(Request): function1() function2() function3() function4() context{ query1: "query1", query2: "query2", query3: "query3", } return render(request, 'base.html', context) But I want to do like this: def Home(Request): function1() context{ query: "query" } return render(request, 'base.html', context) def Home-query2(Request): function2() context{ query2: "query2", } return render(request, 'base.html', context) def Home-query3(Request): function3() context{ query3: "query3", } return render(request, 'base.html', context) Other question would be, how can I first load the home class and then load each query all at the same time. So that I that load time totally is decreased.
- 
        django.db.utils.OperationalError: no such table: Homepage_generalsettingsI am setting up git project to my local server. when I try to makemigrations, migrate, run. i get the following error: django.db.utils.OperationalError: no such table: Homepage_generalsettings i have installed sqlite as well. I am using django version 3. please help me to solve this problemscreenshot of error message
- 
        How can i set my position at the first page in fiverr market place to get more orders?I want to rank my fiver gig so that it appear in the first page and I get more orders. How can I rank this gig Python Programmer and Developer?
- 
        Django:How to prevent non authorize users to access reset url to reset password?reset url pattern url(r'^reset/$', auth_views.PasswordResetView.as_view( template_name='password_reset.html', email_template_name='password_reset_email.html', subject_template_name='password_reset_subject.txt', ) this url is basically if user want to reset his password but i want that only login users can access this page.I know i can prevent non-authorize user to access this url with @login_required decorator but i'm using PasswordResetView which is written by django and i'm unable to use this decorator on it. Can anyone tell me how i can added this functionality that only login user can access this page and how i can Modify PasswordResetView class-view according to me.
- 
        ModuleNotFoundError: No module named 'django' while running server in virtual environmenti am new in python learning.after learning python basics i have moved to learn python web framework Django. for this i followed these steps for installing django on my windows after installing python 3.7 first i opens cmd command prompt (C:\users\mypcname) then i created virtual environment wrapper with command pip install virtualenvironmentwrapper-win then i created virtual environment with command mkvirtualenv test then i entered command workon test to enable virtual environment then tried to install django with command pip install django and its successfully installed then i created projects directory with command mkdir djangoprojects then i created app directory in djangoprojects(which i created in last step) with command django-admin startproject firstproject then i moved to firstproject with command cd.. there i tried to run server with command python manage.py runserver and got error Traceback (most recent call last): File "manage.py", line 10, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in main() File "manage.py", line 12, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did …
- 
        django clean data if create but not clean when updateIm new in django so this is very confusing I have this clean method to raise error when the input data has the same year with existing data def clean_date_year(self): clean_year = self.cleaned_data.get('effective_date') year = clean_year.strftime("%Y") check = model.objects.filter(effective_date__year=tahun).exists() if check: raise forms.ValidationError("The Year Input already here") return clean_year but i also use the same page and the same form to make update, how can i not clean it when i update it ? im using date field so it was a date picker <fieldset> <div class="row"> <div class="col-lg-3"> <label >Effective Date</label> </div> <div class="col-lg-9"> {{ form.effective_date.errors}} {{ form.effective_date }} </div> </div> </fieldset>
- 
        How can i get current status or http code in django via requestI check status code in request.META but there is not available Like request.status or request.status_code
- 
        Django Ajax formI want to use Ajax in Django to handle the view of my checkout form after it has been submitted. After the form is submitted, I want it to go to : return HttpResponseRedirect(reverse(str(next_page))+"?address_added=True") , i.e http://127.0.0.1:8000/checkout/?address_added=True But for some reason, it is not going there. Rather it's being going to http://127.0.0.1:8000/checkout/?csrfmiddlewaretoken=W4iXFaxwpdtbZLyVI0ov8Uw7KWOM8Ix5GcOQ4k3Ve65KPkJwPUKyBVcE1IjL3GHa&address=123+Main+Street&address2=&state=MA&country=USA&zipcode=55525&phone=%28877%29+314-0742&billing=on As a result, the form data is also not getting saved. I was thinking if it were because of the new version of Django. What I want to do is that after they submit the place order button, the form is going to be None, i.e disapper and then I would add a credit card form there for payment. But it is not happening. What is wrong here? Can anyone please help me out of this or is there a better way to do this? My forms.py: class UserAddressForm(forms.ModelForm): class Meta: model = UserAddress fields = ["address", "address", "address2", "state", "country", "zipcode", "phone", "billing"] My accounts.views.py: def add_user_address(request): try: next_page = request.GET.get("next") except: next_page = None if request.method == "POST": form = UserAddressForm(request.POST) if form.is_valid(): new_address = form.save(commit=False) new_address.user = request.user new_address.save() if next_page is not None: return HttpResponseRedirect(reverse(str(next_page))+"?address_added=True") else: raise Http404 My orders.views.py: try: address_added = request.GET.get("address_added") …
- 
        How to implement ownership roles for specific models through DRFHave two types of models, User and Object. Each User can have different ownership level of Object which will come attached with different permissions when accessing DRF endpoints (ownership=ManyToManyField(Object, through='UserObject')). e.g. A User with ownership.permission='Owner' for Object would have CRUD permissions while a User with ownership.permission='Manager' would only have RU permissions while a User with no ownership would have only C permissions. I'm currently storing the relationship with two tables OwnershipLevel with M2M to Permissions which states which of the CRUD permissions the role has but every API transaction is DB heavy as I have to retrieve the user permissions at the beginning. Looking for a way to lessen the load on the DB if possible, by caching role permissions on load or something. Thank you!
- 
        Django render a DynamoDB JSON into a HTML tableI'm try to use a Django page as front-end using some AWS DynamoDB tables as back-end. To do so, I use boto3 library and it gets the data from the table correctly but I'm not able to parse the data into a HTML table. I have the following in views.py def history(request): itemsid = list() agents = list() dates = list() source = list() dynamodb_resource('dynamodb') history_table = dynamodb_resource.Table('name_of_the_table') all_items = history_table.scan() for p in all_items['Items']: itemsid.append((p['id'])), agents.append((p['agent'])), dates.append((p['date'])), source.append((p['source'])) return render(request, 'history.html', {'itemsid':itemsid, 'agents':agents, 'dates':dates, 'source':source} The issue is that I don't know how to write the html code to show a table with the rows: id, agent, date and source. I have the following in history.html <table> {% for i in itemsid %} <tr> <td>{{ i }}</td> ... but I don't know how to code it (how to loop it) to show the table with the lists as source. Any idea please about how to parse a Json with the following format into a HTML with Django and Python please?. JSON from DynamoDB: { 'Items: [ {'id' : '94f' 'agent' : 'aws' 'date' : '04/05 'source' 'case1' }, { 'id' :'lk42' ..... Thank you so much. I'm new in …
- 
        How do I lowercase the first letter of part of my urls address?I created a for-loop in the template.html to have several buttons direct to different URLs with the product names specified: <a href=http://127.0.0.1:8000/products/{{product.name}} class="btn btn-primary">Click Here</a> For example, if you click the button for pizza, you will be directed to http://127.0.0.1:8000/products/Pizza However, the product names I assigned are all capitalized; how I can address the URLs to be http://127.0.0.1:8000/products/pizza instead of http://127.0.0.1:8000/products/Pizza?
- 
        Django - How to Insert Multiple Form Data using JQuery AjaxI want to perform a similar task like what described in the following video, https://youtu.be/NoAdMtqtrTA?t=2156 To add multiple rows in the table and then insert it all in a batch to the database. Any reference or any sample code will be really appreciable. Thank you.
- 
        Why do I get an unexpected keyword argument?I have created a model in my Djano project and the name of the model is Questions in which I have created a primary key called questionid. I am able to get all listings as summaries on one page however when I try to get a detailed listing of one query (say question number 4 out of the several in the table) by going to the http://127.0.0.1:8000/qanda/4 (here 4 is the question number), I get an error that says TypeError at /qanda/4 question() got an unexpected keyword argument 'question_questionid' Please see the code below In my model's views file def question(request): questionsm = Questions.objects.order_by('-published_date').filter(is_published=True) context = { 'questionid': questionsm } return render(request,'qanda/question.html', context) In my model url file path('<int:question_questionid>', views.question, name='question'), I will appreciate any help. thanks
- 
        Django Model with python-docx-templateI have two Models - ReportData and Report: class ReportData(models.Model): reportname = models.CharField(max_length=25) itemname = models.CharField(max_length=50) address = models.TextField() img1 = models.ImageField(default="default.jpg" ,upload_to="report_images") img2 = models.ImageField(default="default.jpg" ,upload_to="report_images") img3 = models.ImageField(default="default.jpg" ,upload_to="report_images") date_created = models.DateTimeField(default=timezone.now) preparedby = models.ForeignKey(User, on_delete=models.CASCADE) class Report(models.Model): report = models.OnetoOneField(ReportData, on_delete=models.CASCADE,primary_key=True) document = models.FileField(upload_to='reports/') I want to perform a function using all the fields of ReportData (except preparedby,date_created) which will return a file and store in document field of Report class. The function is here: doc = DocxTemplate('--default path of template file--') context = { 'rname' : ReportData.reportname,'iname':ReportData.itemname , 'addr': ReportData.address, 'img1': InlineImage(doc, ReportData.img1.url , width=Inches(7.1)), 'img2':InlineImage(doc, ReportData.img2.url, width=Inches(4.79)), 'img3':InlineImage(doc, ReportData.img3.url, width=Inches(1.91))} doc.render(context) doc.save('destination path') I dont know what will go in destination path as I want to store it in document field of Report class. Also have no idea how to get ReportData fields in context.
- 
        how to arrange the template tags in django templates for Default user registration page with extra fieldsI am beginner for django. When i am registering the details by using registration form which is not saving into database. Basically for this i am using the default User model for that with three extra fields such as firstname, lastname and confirm password. for that in registration template where can i use the template tags. Here is my forms.py: class UserRegisterForm(forms.ModelForm): email = forms.EmailField(label='Email Field') password = forms.CharField(widget=forms.PasswordInput) password1 = forms.CharField(widget=forms.PasswordInput) firstname = forms.CharField() lastname = forms.CharField() class Meta: model = User fields = [ 'firstname', 'lastname', 'email', 'password', 'password1', ] def clean_password(self): password = self.cleaned_data.get('password') password2 = self.cleaned_data.get('password1') if password != password2: raise forms.ValidationError('passwords must match') return password view.py file for registration code snippet def register_view(request): next = request.GET.get('next') form = UserRegisterForm(request.POST or None) if form.is_valid(): user = form.save() password = form.cleaned_data.get('password') user.set_password(password) user.save() new_user = authenticate(username=user.username, password=password) login(request, new_user) if next: return redirect(next) return redirect('/') context = { 'form': form, } return render(request, 'auth-register.html', context) template for auth-register.html <form method="POST">{% csrf_token %} <div class="row"> <div class="form-group col-6"> <label for="{{frist_name}}">First Name</label> <input id="{{frist_name}}" type="text" class="form-control" name="frist_name" autofocus=""> </div> <div class="form-group col-6"> <label for="{{last_name}}">Last Name</label> <input id="{{last_name}}" type="text" class="form-control" name="last_name"> </div> </div> <div class="form-group"> <label for="{{email}}">Email</label> <input id="{{email}}" type="email" …
- 
        How to remove unnecessary characters from stdout in python?I have this script: lec_name = request.POST['selected_name'] out = run([sys.executable,'//Projects//altg//algorithm.py',lec_name], shell=False, stdout=PIPE) print(out.stdout) This script works fine. But I'm not getting the output properly. OUTPUT: b"Hello World\r\n" EXPECTED OUTPUT: Hello World How can I solve this? I found lot of answers about this, but none helped. I'm using Python 3.7.4, Django 3.0.1
- 
        how can i use my other app oauth authentication to authenticate my other app django rest frame work?how can i use my other app oauth authentication to authenticate my other app Django rest frame work? i want to make several apps to use my authentication server to authenticate. is my thoughts in correct way?
- 
        When I click to submit the registration form. Form submitted successfully but user data not added in dbI am trying to save the user registration form in django but when I clicked to save the user details in db. Form get submitted but data should not save in db and apart from this I am also not getting any error. But I can't get my submit to work. Anytime I submit, the page just reloads and nothing happens. I check my admin page to see if user is added but nothing seems to happens there too in django from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from webapp import models class RegistrationForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2' ) def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] if commit: user.save() return user
- 
        Django_elasticsearch_dsl_drf not returning expected resultI was applying elastic search in one my django app, Below is my code snippets documents.py ads_index = Index("ads_index") ads_index.settings( number_of_shards=1, number_of_replicas=0 ) html_strip = analyzer( 'html_strip', tokenizer="standard", filter=["standard", "lowercase", "stop", "snowball"], char_filter=["html_strip"] ) @ads_index.doc_type class AdDocument(Document): id = fields.IntegerField(attr='id') title = fields.TextField( analyzer=html_strip, fields={ 'title': fields.TextField(analyzer='keyword'), } ) description = fields.TextField( analyzer=html_strip, fields={ 'description': fields.TextField(analyzer='keyword'), } ) category = fields.ObjectField( properties={ 'title': fields.TextField(), } ) class Django: model = Ad # The model associated with this Document # The fields of the model you want to be indexed in Elasticsearch fields = [ 'price', 'created_at', ] related_models = [Category] def get_queryset(self): return super().get_queryset().select_related('category') def get_instances_from_related(self, related_instance): if isinstance(related_instance, Category): return related_instance.ad_set.all() serializer class AdDocumentSerializer(DocumentSerializer): class Meta: document = AdDocument fields = ( "id", "title", "description", "price", "created_at", ) viewset class AdViewSet(DocumentViewSet): document = AdDocument serializer_class = AdDocumentSerializer ordering = ('id',) lookup_field = 'id' filter_backends = [ DefaultOrderingFilterBackend, FilteringFilterBackend, CompoundSearchFilterBackend, SuggesterFilterBackend, ] search_fields = ( 'title', 'description', ) filter_fields = { 'id': { 'field': 'id', 'lookups': [ LOOKUP_FILTER_RANGE, LOOKUP_QUERY_IN, LOOKUP_QUERY_GT, LOOKUP_QUERY_GTE, LOOKUP_QUERY_LT, LOOKUP_QUERY_LTE, ], }, 'title': 'title.raw', 'description': 'description.raw', } ordering_fields = { 'id': 'id', } Below is my data I have When I hit http://127.0.0.1:8000/ads/search/?search=Tit it's not returning anything …
- 
        Register several DRF views in urls.pyPlease how to register 2 DRF views in urls.py? For now I do something like this below: class AcyVcsViewSet(viewsets.ModelViewSet): queryset = vcs_acymailing_subscriber.objects.all().order_by('subid') serializer_class = AcyVcsSerializer class AcyVcsEmail(viewsets.ModelViewSet): queryset = vcs_acymailing_subscriber.objects.all().order_by('subid') serializer_class = AcyVcsSerializer def get_queryset(self): email = self.request.query_params.get('email', None) return vcs_acymailing_subscriber.objects.filter(email=email) Then I register these views in urls.py: router = routers.DefaultRouter() router.register(r'first_view', views.AcyVcsViewSet) router.register(r'second_view', views.AcyVcsEmail) urlpatterns = [ path('', include(router.urls)), ] It works if I manually change the URLs in my browser. But "URLs" mentioned in my API are corrupted, maybe because I do not know this right syntax in urls.py. I searched for and tried a lot of syntax but ... No success Thanks
- 
        Initialize a formsetI have two models connected by manytomany relationship and I am trying to use formset to create a dynamic form. I am able to save the form but the problem arise when I am trying to edit the saved instance, I don't know hoe to properly pass the instance to the formset such that it shows the instance data in form for editing Here are the details: Models.py class Player(models.Model): pname = models.CharField(max_length=50) hscore = models.IntegerField() age = models.IntegerField() def __str__(self): return self.pname class Team(models.Model): tname = models.CharField(max_length=100) player= models.ManyToManyField(Player) def __str__(self): return self.tname Forms.py class PlayerForm(forms.ModelForm): class Meta: model = Player fields = '__all__' PlayerFormset= formset_factory(PlayerForm) class TeamForm(forms.ModelForm): player= PlayerFormset() class Meta: model = Team fields = '__all__' exclude = ["player"] Views.py def team(request): if request.POST: form = TeamForm(request.POST) form.player_instances = PlayerFormset(request.POST) if form.is_valid(): team= Team() team.tname= form.cleaned_data['tname'] team.save() if form.player_instances.cleaned_data is not None: for item in form.player_instances.cleaned_data: player = Player() player.pname= item['pname'] player.hscore= item['hscore'] player.age= item['age'] player.save() team.player.add(player) team.save() else: form = TeamForm() return render(request, 'packsapp/employee/new.html', {'form':form}) def updateTeam(request,pk): team = Team.objects.get(id=pk) form = TeamForm(instance=team) // something here to initialize the formset ?? if request.method == "POST": form = TeamForm(request.POST, instance=team) if form.is_valid(): form.save() context = {'form': form} …
- 
        Facebook Webhook for DjangoHow can I post on the Facebook page from my Django website? I've created Facebook developer account but don't know to the public it as it is in developer mode
- 
        Integrating Whatsapp in DjangoHow can integrate and send whatsapp messaged in django rest framework ? Basically i want to send messages to users to the whatsapp numbers they enter in the field. If any code references are available, i would request for sharing it. Thanks in Advance
- 
        Not able see the image after uploading on admin panelI am learning django but i am stuck at Imagefield. I am trying to rename the file and save the image to my media directory where exactly i am going wrong i am not able to understand. It was working fine till worked with filefield. after changing the filefield to imagefield i am getting an page not found. Not Found: /media/products/926045120/926045120.jpg above is the error from django.db import models import random import os def get_filename_ext(filepath): base_name = os.path.basename(filepath) name, ext = os.path.splitext(base_name) return name, ext def upload_image_path(instance, filename): # print(instance) #print(filename) new_filename = random.randint(1,3910209312) name, ext = get_filename_ext(filename) final_filename = '{new_filename}{ext}'.format(new_filename=new_filename, ext=ext) return "products/{new_filename}/{final_filename}".format( new_filename=new_filename, final_filename=final_filename ) # Create your models here. class Product(models.Model): title = models.CharField(max_length=120) description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=20, default=39.99) image = models.ImageField(upload_to=upload_image_path, null=True, blank=True) def __str__(self): return self.title def __unicode__(self): return self.title model.py of product import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'z45+z23#cgk-fem6x&6i9_n@tz8p3)f^l+f1#8$e^n7(hv&dgz' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application …