Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get all related data from model and save it to the another model using django signal
I just want that if the admin insert the Course(ABM) and Education Level (Grade 11) and Section(Chronicles) in table student enrollment record it will get all related data in subjectsectionteacher(second picture) and it will automatic save to student enrolled subject(third picture) my problem is only one data save. student enrollment record subjectsectionteacher This is what the result I want Result I want This is the result I get what I got result -
How to create a dynamic form with values in a model in Django?
I am creating a kind of quiz app where i provide a quiz (say 10 question) to a user with choices for each question. I want to save the user's selected choices in a database. I dont want to check selected choices against an answer, just store user's selected choice(s). I have 3 models, one each for Questions, Choices and UserSubmission. UserSubmission model has 3 field, User, question and choice. Each entry in this database maps a user with a question and his selected choices for that question. I am having trouble creating a form with all (say 10) questions and their respective choices and storing them in the database. -
Django update data on click button
i have a classic form and a submit button that save data in model1 and i would like to update data of another model2 calling a function on the click button I try tu use an Ajax request like another mentionned in another post: Django: How to Like an Object with Ajax I try to implement an Ajax request and start with a very simple code (just want to print 'Randomize' when my method is called I have a simple form that will store data in its related model (Randomisation) But I want to update 2 others models when user click on the submit button of the form (id=randomize) I have a method in my view that should be call by Ajax but it does not work I enter in the JQuery function (alter('test') == OK) but the randomize method is not called as I have no print in my console (print('test') != OK) and the confirm is not called (confirm("You have randomize the patient") != OK) What is wrong? urls.py from django.urls import path from . import views app_name='randomization' urlpatterns = [ path('detail/<int:pk>', views.randomisation_detail, name='randomisation_detail'), path('edit/', views.randomisation_edit, name='randomisation_edit'), path('', views.index, name='index'), path('randomize/', views.randomize, name="randomize"), ] views.py @csrf_exempt def randomize(request): … -
Why is there a difference between GitHub webhook local development hashed secret vs production hashed secret?
I am validating the hashes of the signature passed with the GitHub webhook POST request to the hash of my secret. Working locally, the hashes are computed as equal (as they should be) because the secret sent from GitHub is the same as my local secret. However, when I change the URL of the webhook payload from my local development URL to my production URL, the hash of the secret sent in the webhook POST is different. The payload of the POST request is the exact same between the two environments. The only difference is the URL GitHub is POST-ing to. The secret does not change between the two environments either. My project is a Django project and is hosted on Heroku. Here is the code that compares the hashes: header_signature = request.META.get('HTTP_X_HUB_SIGNATURE') if header_signature is None: return HttpResponseForbidden('Permission denied.') sha_name, signature = header_signature.split('=') if sha_name != 'sha1': return HttpResponseServerError('Operation not supported.', status=501) mac = hmac.new(force_bytes(settings.GITHUB_WEBHOOK_KEY), msg=force_bytes(request.body), digestmod=sha1) if not hmac.compare_digest(force_bytes(mac.hexdigest()), force_bytes(signature)): return HttpResponseForbidden('Permission denied.') Any ideas why the hashes are different between local and development, even though the only thing that changes is the URL GitHub is sending the POST request to? Something to do with Heroku maybe? -
Return results from more than one database table in Django
Suppose I have 3 hypothetical models; class State(models.Model): name = models.CharField(max_length=20) class Company(models.Model): name = models.CharField(max_length=60) state = models.ForeignField(State) class Person(models.Model): name = models.CharField(max_length=60) state = models.ForeignField(State) I want to be able to return results in a Django app, where the results, if using SQL directly, would be based on a query such as this: SELECT a.name as 'personName',b.name as 'companyName', b.state as 'State' FROM Person a, Company b WHERE a.state=b.state I have tried using the select_related() method as suggested here, but I don't think this is quite what I am after, since I am trying to join two tables that have a common foreign-key, but have no key-relationships amongst themselves. Any suggestions? -
Django Doubling the path leading to a 404
I am trying to redirect the user to another page if login is successful and leading the user to the log in page if the login is unsuccessful. However, Django is leading me to the path http://127.0.0.1:8000/loginuser/loginuser in either case. Can someone point out the mistake and offer a correction? views.py def loginuser(request): if request.method == "POST": username = request.POST["username"] password = request.POST["password"] user = auth.authenticate(username=username,password=password) if user is not None: auth.login(request,user) return render(request,'getstarted.html') else: messages.info(request,"Invalid Credentials!") return render(request,'login.html') else: return render(request,"login.html") urls.py urlpatterns = [ path('admin/', admin.site.urls), path("",views.HomePage,name="home"), path("registeruser.html/",views.RegisterUser,name='registeruser'), path("registerdoctor.html/",views.RegisterDoctor,name='registerdoctor'), path("loginuser/",views.loginuser,name='login'), path("logoutuser/",views.logoutuser,name='logout'), path('aboutus/',views.about,name='about'), path('feedback/',views.feedback,name='feedback'), path('start/',views.getstarted,name='getstarted'), ] -
Read excel file in Django views using pandas module
I'm trying to read an excel file using pandas in a views method. But the server stopped with: File "/Users/ronsair/anaconda3/lib/python3.6/site-packages/py/_error.py", line 44, in __getattr__ raise AttributeError(name) AttributeError: __name__ Code: import pandas as pd def extract(request): df = pd.read_excel('update.xlsx') return render(request, "work/index.html") Can you help please? -
what is the best way to manage models in django application by separating the entities involved in project?
I started a simple contact list project and This is the current structure: project/ app/ app/ __init__.py settings.py urls.py wsgi.py core migrations/ entities/ city.py group.py town.py user.py __init__.py admin.py apps.py Dockerfile manage.py requirements.txt docker-compose.yml .env.dev I used this structure as a practice to manage the models in my django project. the entities folders are the database models and I want to come up with a good approach to keep them as separate and clean as possible. but when I run migrations with this command docker-compose run web sh -c "python manage.py makemigrations core", I get this: No changes detected in app 'core' It's probably because models.py does not exists I really need to practice the best possible approach for server programming to be able to work in a team in the future. I was wondering if anyone could help me in here and if possible please include sample codes and references. -
django forms modelchoicefield dependent to other modelchoicefield (parent child)
In django forms a have a modelchoicefield like country and a second modelchoicefield like cities. I want when I select the countries only the corrensponding cities to be available to the second modelchoicefield. A simple parent - child relationship in django forms fields. -
Wagtail: FieldError when creating instance of snippet
I'm using Wagtail v2.6.3 and Django 2.2.6. I'm trying add snippets which just consist of a plain text description and a StreamField. However, it only seems to work if I include a 'title' field. If I don't have a 'title' field I get a FieldError exception when try to create an instance of the snippet from the admin page. I've used snippets before without title fields, so I know it's something I am doing wrong, but I'm new to Django and Wagtail so it's difficult to know where to look and what to make of the debug info. Here's the snippet (uncommenting the two lines with 'title' in makes the code work), but I don't want a title field. #Content box for the sidebar @register_snippet class SidebarBox(models.Model): #title = models.CharField(max_length=100, blank=True, verbose_name="Item title"); description = models.CharField(max_length=100, blank=True, verbose_name="Optional description for this item (for ID purposes - this does not create any visuals)"); body = StreamField([ ("heading", blocks.CharBlock()), ("paragraph", blocks.RichTextBlock()), ("image", ImageChooserBlock()), ], null=True, blank=True); panels = Page.content_panels + [ FieldPanel("description"), #FieldPanel("title"), StreamFieldPanel("body"), ]; def __str__(self): return self.description; From the debug info it sounds like something is still trying to access the 'title' field of SidebarBox, but I don't know where. … -
I want to Serialize dept_name as well as it's "id" in one single model serializer. How should I do it?
I want to serialize "Department name"(dept_name) as well as Department ID(id) in the Employee Model Serializer from department Model In the Employee Serializer I want to Serialize "Department name" as well as "Dept ID" models. I mentioned Department Model in class Meta of Employee Serializer as well MODELS class Department(models.Model): dept_name = models.CharField(max_length=10) class Employee(models.Model): emp_name = models.CharField(max_length=15) email = models.EmailField(unique=True) password = models.CharField(max_length=14) designation = models.CharField(max_length=20) dept_id = models.ForeignKey(Department, on_delete=models.SET_NULL, null=True, blank=True) class Meta: ordering = ('id',) def __str__(self): return self.emp_name SERIALIZER class DepartmentSerializer(serializers.ModelSerializer): class Meta: model = Department fields = [ 'id', 'dept_name', ] class EmployeeSerializer(serializers.ModelSerializer): dept_id = serializers.SlugRelatedField(queryset=Department.objects.all(), slug_field='dept_name') deptname = DepartmentSerializer() class Meta: model = Employee,Department fields = [ 'id', 'emp_name', 'email', 'password', 'designation', 'dept_id', 'deptname', ] -
create django rest-framework request without url
I want to have a fake request object just for testing its params, a request without URL. The object that I can set its params like this: request.GET = {"offset":0, "limit":10} but when I import Request from rest-framework as below: from rest_framework.request import Request request = Request(request=None) I deal with this error: AttributeError: 'NoneType' object has no attribute 'encoding' can someone help me, to have the request object which I want? -
Django authentication error : 'str' object has no attribute 'pk'
I am having problem in Django authentication, whenever I try to login it gives 'str' object has no attribute 'pk' error. I am using MySql as my database. # views.py def user_login(request): if request.method == 'POST': form = AuthenticationForm(request,data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate( username= username,password= password) if user is not None: login(request,username) return redirect('app:home') else: return render(request,'404error.html',context={}) else: return render(request,'404error.html',context={}) form = AuthenticationForm() return render(request,'login.html',context={'form':form}) def user_logout(request): logout(request) return redirect('app:home') #urls.py # from django.contrib import admin from django.urls import path,include # from app import urls from . import views app_name = 'app' urlpatterns = [ path('',views.home,name='home'), path('register/',views.register,name='register'), path('login/',views.user_login,name='user_login'), ] -
I can't call the function merge in the file merge.py from views.py
I want to call the merge function in the file merge.py when a user has entered his input in the create_proposal.html. my merge.py file looks like: from __future__ import print_function from mailmerge import MailMerge def merge(name, refer): template = 'template.docx' document = MailMerge(template) document.merge( reference = refer ) print('merge') document.write(name) And my views.py file looks like: from django.shortcuts import render from django.http import HttpResponse from .forms import createNewFinancial from .merge import merge def inputPage(request): if request.method == 'POST': form =createNewFinancial(request.POST) if form.is_valid(): name = form.cleaned_data['name'] reference = form.cleaned_data['reference'] merge(name, reference) form = createNewFinancial() return render(request, 'create_proposal.html', {'form': form}) def resultPage(request): return render(request, 'result.html') the template create_proposal.html looks like: {% extends 'base.html' %} {% block content %} <div class="row"> <div class="col-sm-4" style="margin-left: 10vw;"> <h2>New Financial Proposal</h2> <form class="form-group" action="result/" method="post"> {% csrf_token %} {{form}}<br><br> <input type="Submit" class="btn btn-primary" value="Create"/> </form> </div> </div> {% endblock content %} I am trying to create a word document with file name from user input in create_proposal.htmland also merge the reference number from user input in the template using mailmerge -
How to control the amount of notifications sent by django signal
I have a django admin based CRM and API which updates my google spreadsheet. It is triggered by django signals. Sometimes I need to send request once with a single row change in spreadsheet. Sometimes i need to update multiple rows. The problem is that django signals trigger every time a change is registered in DB, but i can update my spreadsheet with a single request. For example, I need to remove 2 rows: Achange in DB registered for 1 row, A Request is sent to spreadsheet, A change in DB registered for 2 row, A Request is sent to spreadsheet. But I need: A change in DB registered for 1 row, A change in DB registered for 2 row, A Request is sent to spreadsheet. All the unneccessary requests pile up and take a lot of time to process. How do i register all the changes only once to send a single request? An additional question. I have 2 models: Project and ProjectImages. PI is related to P, so if i delete P, then before its removed for every related PI instance i see signals beeing triggered. Whole spreadsheet is removed and there is no neccessity to remove rows … -
Django Comment form leads to a blank page and doesn't post the comment
Right after I type the comment in the form and click the button, it gives me a white screen and it also didn't post the comment either I have a django code as shown below, I have already added the success_url but it still shows a blank screen after I click the button, and It didn't save the comment either #views.py class MessageDetailView(DetailView): model = Message template_name = "messaging/detail.html" success_url = "post/<int:pk>" #queryset = Message.objects.all() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['comments'] = Comment.objects.filter(message=self.object) context['form'] = CommentForm() return context #detail.html <div class="text-area"> <div class="comment-area"> <p>{{ comment.date_posted|date:"H:i, j-n-o" }}</p> <hr> <p> {{ comment.comment }} </p> </div> </div> #forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('comment',) #models.py class Comment(models.Model): message = models.ForeignKey(Message,on_delete=models.CASCADE) comment = models.TextField(max_length=50) date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return "Comment on {}".format(str(self.date_posted)) I am trying to show the comment and direct it to the detail page itself, help appreciated. -
get_object_or_404 don't show the value it gets from DB
I am building af blog in django. When I click to see/read details on an article and its related comments, I only see the comments, the details of the article doesn't show, but the page do not fail. I have tried just to call the model 'LifePost' and then it shows data in the template but not the related comments (only the fields for it). I have tried to call the method that use get_object_or_404 to call the model 'LifePost' and then it shows all the comments to the related article but not the article data (only the fields for it) models.py class Comment(models.Model): post = models.ForeignKey(LifePost, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=100) email = models.EmailField() body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) class Meta: ordering = ['created_on'] def __str__(self): return 'Comment {} by {}'.format(self.body, self.name) views.py def life_detail(request, slug): template_name = 'life_detail.html' post = get_object_or_404(LifePost, slug=slug) comments = post.comments.filter(active=True) new_comment = None if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.post = post new_comment.save() else: comment_form = CommentForm() return render(request, template_name, {'post': post, 'comments': comments, 'new_comment': new_comment, 'comment_form': comment_form}) urls.py path('life/<slug:slug>/', views.life_detail, name='life_detail'), (NOT IN USE, but works and show the article correctly) #path('life/<slug:slug>/', … -
CORS issue when posting (react and django)
I've connected react frontend and django rest framework backend app. I've set allow origin things in settings.py that are mentioned when solving CORS issues. and when I'm requesting axios.get in react app, it works fine, but when I'm requesting POST, it returns error "Access to XMLHttpRequest at 'http://127.0.0.1:8000/api/posts' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request." I've put these and middleware setting('corsheaders.middleware.CorsMiddleware',) and installed apps ('corsheaders') in django settings.py. CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_WHITELIST = ( 'http://localhost:3000', ) And this is added to the top of react.js component : axios.defaults.baseURL = 'http://127.0.0.1:8000/api/'; axios.defaults.baseURL = 'http://local:8000/api/'; handleSubmit = (e) => { e.preventDefault(); axios.post('posts', { memo: this.state.memo, }).then(res => { console.log(res); }) .catch(error => { console.log(error) }); It's the error message on the console: Error: Network Error at createError (createError.js:17) at XMLHttpRequest.handleError (xhr.js:80) and It's on the django terminal console: "OPTIONS /api/posts HTTP/1.1" 301 0" -
I Want To Add Permissions To User in Django?
i want to add user profile section for example superuser and simple_user so i can add permissions But When I Submit my Registration Form I Get This Error: AttributeError at /register/ 'User' object has no attribute 'register' How To Fix And Save User Profile Name? Here is my Views.py from django.shortcuts import render , get_object_or_404,redirect from django.utils import timezone from blog.models import * from blog.forms import * from django.contrib.auth.decorators import login_required from django.urls import reverse_lazy from django.contrib.auth.models import User from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import (TemplateView,ListView, DetailView,CreateView, UpdateView,DeleteView) # Create your views here. def user_register(request): if request.method == "POST": reg = register(request.POST or None) if reg.is_valid(): user = reg.save() user.profile = "simple_user" user.set_password(user.password) user.save() else: print(register.errors) else: reg = register() return render(request,"registration/register.html",{'reg':reg}) Here is my Models.py class register(models.Model): user = models.OneToOneField(User,on_delete="Cascade", related_name="profile") Here is my Forms.py class register(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput(attrs={'class':'input-field'})) class Meta(): model = User fields = ('username','email','password') Here is the Error Image: Any Help Appreciated! -
Using only Django 2.2 ORM
I want to use Django with python3 to connect to my Postgresql database. I need only ORM modules of Django. My question is that what is the best project structure to reach my goal? -
How to retrieve data from Serialized Class RestApi
In Login Function the Token is retrieving and i need to Retrieve all details of Client How to Do that ? class Client_view(generics.ListCreateAPIView, generics.RetrieveUpdateDestroyAPIView): authentication_classes = [SessionAuthentication, BasicAuthentication, TokenAuthentication] permission_classes = [IsAuthenticated] queryset = Client.objects.all() serializer_class = ClientSerializer class LoginView(APIView): def post(self, request): serializer = LoginSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data["user"] profile=ClientSerializer django_login(request, user) token, created = Token.objects.get_or_create(user=user) return Response( {"token":Token.key},{"username":user.username}, status=200) class ClientSerializer(serializers.ModelSerializer): class Meta: fields = ['id', 'Name', 'UserName', 'Email', 'Mobile', 'Address'] model = models.Client class LoginSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() def validate(self, data): username = data.get("username", "") password = data.get("password", "") if username and password: user = authenticate(username=username, password=password) if user: if user.is_active: data["user"] = user else: msg = "User is deactivated." raise exceptions.ValidationError(msg) else: msg = "Unable to login with given credentials." raise exceptions.ValidationError(msg) else: msg = "Must provide username and password both." raise exceptions.ValidationError(msg) return data -
Write data to xls and download it in python
I have successfully created .csv file and now want to create .xls for the same data. After which I want to download it as well. So after creation of csv file from python I am sending response to the ajax function and downloading it from there using jquery. def expense_export(request): print(request.POST) if request.is_ajax(): ids = request.POST.getlist('ids[]') expenses = Expense.objects.filter(id__in=ids) data = [] field = ['SLNO', 'Date of Recording', 'Category', 'Sub Category', 'Invoice Date', 'Invoice No', 'GST No. Mentioned', 'Vendor Name', 'Details', 'Gross Value', 'SGST', 'CGST', 'IGST', 'Total Invoice Value', 'TDS(if any)', 'Net Payble'] field1 = ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''] response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="Search Results.csv"' sno = 1 max = 0 for record in expenses: pay_data = [] if record.record: curr = 0 for pay_record in record.record: pay_row = [pay_record['date'], pay_record['amount'], pay_record['mode'], pay_record['ref'], pay_record['bank']] pay_data = pay_data + pay_row curr = curr + 1 if curr > max: max = curr gst_exist = 'No' if record.vendor: if record.vendor.gst_no: gst_exist = 'Yes' igst = int(record.gst) / 100 * record.amount tds = int(record.tds) / 100 * record.amount net_amount = int(record.amount) + int(igst) row = [ sno, record.timestamp.strftime('%d-%m-%Y'), record.expense_name, … -
Populating a django model with data from an external API
I am trying to pull in all the data from an external API to populate my Django Model. i found a similar question here Proper way to consume data from RESTFUL API in django I presume that what i need to do is GET request all of the data, and then POST request all the data to my model? However it doesn't fully answer my question. I would like to load all of the data from the api endpoint. What I have so far. Models.py class Bill(models.Model): STATUS = Choices('Open', 'Closed') Table_ID = models.ForeignKey(Table, default=None, on_delete=models.CASCADE) Bill_Status = models.CharField(choices=STATUS, default=STATUS.Open, max_length=20) Date_close = models.DateTimeField(default=timezone.now) class Bill_Items(models.Model): Bill_ID = models.ForeignKey(Bill, default=None, on_delete=models.CASCADE) Description = models.CharField(max_length=50) Price = models.DecimalField(max_digits=10, decimal_places=2) Payment_Made = models.BooleanField(default=False) Date = models.DateTimeField(default=timezone.now) def __str__(self): return self.Description Views.py from bill.models import Table, Bill, Bill_Items def get_bill_data(request): ##### GETTING THE DATA #### r = requests.get('http://127.0.0.1:8000/api/table1/', data=request.GET) #### POSTING THE DATA #### data = r.json() # Construct the bill attributes dictionary bill_attributes = { "PK": data["PK"], "Description": data["Description"], "Price": data["Price"] } Bill_Item = Bill_Items.objects.create(**bill_attributes) return HttpResponse(r.text) This doesnt seem to work, if anyone has some ideas please let me know. Thanks in Advance -
Django save all data
I have this code in my html <tr> <td colspan="2" style="text-align: center;"><h2 style="font-weight: bold;">Required Documents:</h2></td> </tr>{% for d in doc %} <tr> <td style="text-align: left;"> <input type="file" name="myfile" value="{{d.id}}" style="outline: none;" required/>{{d.Description}}</td> <td></td> </tr> {% endfor %} this is my code in views V_insert_data = StudentsEnrollmentRecord( Student_Users=studentname, Payment_Type=payment, Education_Levels=educationlevel,School_Year=schoolyear ) V_insert_data.save() insert_doc = StudentsSubmittedDocument( Students_Enrollment_Records = V_insert_data, Document = myfile ) insert_doc.save() \model class StudentsSubmittedDocument(models.Model): Students_Enrollment_Records = models.ForeignKey(StudentsEnrollmentRecord, related_name='+', on_delete=models.CASCADE,blank=True,null=True) Document_Requirements = models.IntegerField(null=True,blank=True) Document = models.FileField(upload_to='files/%Y/%m/%d',null=True,blank=True) Remarks = models.CharField(max_length=500,blank=True,null=True) def __str__(self): suser = '{0.Students_Enrollment_Records}' return suser.format(self) How to save all in the database all the required documents that the user input? -
Formik with Django
Hi I have to built an application of inventory and many more like receivable , payable. I am liking for a form library for front end that works well with back end django. Mist of my forms are master detail forms e.g inventory transfer note contains header information about transfer to and from with address. In detail forms have many line items. Each line has many fields that cannot be displayed fully like serial numbers or lot number. I also need auto suggest or list of values functionality on many fields like items, in stock serial numbers. What is the best tools or library to achieve this since I am a beginner in this but have lot of experience in oracle forms. Thanks in advance