Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding fields as subset of another field in django
I am having three models and I need to access one field as the subset of another model field This is what I tried: I have a model named App class App(models.Model): name = models.CharField(max_length=255) hidden = models.BooleanField() Another model is also there with a foreign key to App Model class Build(models.Model): app = models.ForeignKey(App, on_delete=models.CASCADE) number = models.CharField(max_length=255) uploaded_date = models.DateTimeField(auto_now_add=True) The requirement is I have to add tags to both App and build with a condition 'build tags is always a subset of app tags'. Also created another model called Tags also so as to meet the above requirement but unable to implement the subset relation with that. class Tag(models.Model): name = models.CharField(max_length=255) app = models.ForeignKey(App, on_delete=models.CASCADE, null=True, related_name='tags') builds = models.ForeignKey(Build, on_delete=models.CASCADE, null=True, related_name='tags') Is there any possible way to implement that relationship in Django 2.1 ? -
Django validating client mac address with address stored in db
I am having one field in db where I can store client mac address while registering the client. Is there any possibility to fetch the mac address of the system from which, the client launching website? So that I can able to compare with mac address already available in db and if matches need to provide authentication to the client. Can anyone please help me on this? -
How to manage dictionaries inside html Django
So I'm loading a dictionary to HTML but I'm having some trouble getting the second_value from the dictionary ({'first_value': 'second_value'}). The dictionary I'm parsing is this: {1: 'Bayer', 2: 'Celgene Europe Limited', 3: 'Celgene Europe Limited'} My code inside HTML: {% for x in drugs %} <a href="{{ x }}"><li>{{ drugs.x }}</li></a> {% endfor %} And what is displaying in the HTML is: <ul style="text-decoration: none; color: black;"> <a href="1"><li></li></a> <a href="2"><li></li></a> <a href="3"><li></li></a> </ul> What is supposed to happen is the number to be displayed in the href and the drug name to be displayed inside the <li></li> tags. For example: <a href="1"><li>Bayer</li></a> -
django-private-storage configuration in nginx and Docker
I am trying to use django-private-storage package to protect a model's file from being accessed or downloaded by users who are not owners of the file. I was able to do it successfully in development (using python manage.py runserver) In development, I am using nginx configured via docker. I can create objects with both FileField and PrivateFileField. My problem is accessing the urls associated with a PrivateFileField. The mediafiles are being served as expected (e.g. when I access the url of a FileField), but I get a "404 Not Found" error from nginx when I access the url of a PrivateFileField. My hunch is that the server response is not properly configured to have a 'X-Accel-Redirect' data, thus treating the response not internal. If I remove the line "internal;" in my nginx.conf for the private-data location, the PrivateFile is served properly, although, now, it is not private. location /private-data/ { internal; #<------ the PrivateFile can be accessed if this line is removed alias /home/app/web/private-data/; } Also, I am sure that the private file was saved in /home/app/web/private-data Am I missing out something in the implementation? Thanks in advance. Additional info: nginx version: 1.17.4 django-private-storage version: 2.2.2 My production setup follows … -
how do I use detail view for users?
I have a page in my app that shows all the registered users. I want to make a detail page of their profile information. can I use DetailView? if yes, How?! if not, then what should I do? this is my function for the name list page: def all_users(request): allusers= get_user_model().objects.all() context= {'allusers': allusers} return render(request, 'users/users-info.html', context) -
Django frontend app not loading React Component
i am following tranversy Media Django-React tutorial. After the server is running ok, but the components in my App.js file are not displayed in the index.html. Kindly help on what could be wrong, all. This is my project tree: see the image Then my app.js import React, {Component} from 'react'; import ReactDOM from 'react-dom'; class App extends Component { render() { return <h1>React App</h1> } } ReactDOM.render(<App />, document.getElementById("app")); My index.html <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://bootswatch.com/4/cosmo/bootstrap.min.css"> <title>Lead Manager</title> {%load static%} </head> <body> <h1></h1> <div id="app"></div> <script>src="{%static "frontend/main.js"%}"</script> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> </body> index.js import App from './components/App'; webpack.config.js module.exports = { module: { rules: [{ test: /\.js$/, exclude: /node_modules/, use: { loader:"babel-loader" } }] } } The backend is working fine using the api. -
dataframe from view to gviz DataTable
Since I took way longer than it should have been necessary, I would like to give you a minimum working example of how to get data from a dataframe in your view to gviz in your html. Here is the view: def minimum example(request): df_fruit = {'Fruit': ['Aple', 'Cherry'], 'Amount': [1, 3]} df_fruit = DataFrame(df_fruit, columns=['Fruit', 'Amount']) fruit_list = [df_fruit.columns.values.tolist()] + df_fruit.values.tolist() fruit_json = json.dumps(fruit_list) return render(request, 'fruits.html', {'fruits': fruit_json}) and here is the html: <head> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> // Load Charts and the corechart package. google.charts.load('42', {'packages':['corechart']}); // Draw the chart for when Charts is loaded. google.charts.setOnLoadCallback(drawTestChart); function drawTestChart() { var djangodata = {{fruits|safe}}; var data = google.visualization.arrayToDataTable(djangodata); var options = { backgroundColor: '343a40', chartArea: {'width': '75%', 'height': '80%'}, hAxis: {textStyle: { color: 'white'}, title: 'Fruits', titleTextStyle: {color: 'white'}, gridlines: {color: 'white', count: 8}, baselineColor: 'white'}, vAxis: {textStyle: { color: 'white'}, minValue: 0, gridlines: {color: 'white', count: 6}, baselineColor: 'white'}, legend: { position: 'none' }, }; var chart = new google.visualization.Histogram(document.getElementById('Hist_chart_div')); chart.draw(data, options); } </script> </head> <main> <div id="Hist_chart_div" style="width: 450px; height: 400px;"></div> </main> -
how to have scroll function for mobile screen in website
i directly jump to the problem, i have 4 different screen Size and 4 of them has different scroll function .every screen scroll function is working fine excluding mobile screen which i have kept the width of var screensize = window.innerWidth; if(screensize < 767 && screensize > 200) { if (document.body.scrollTop > 90 || document.documentElement.scrollTop > 90) { } } it works fine when running same width in desktop screen but the position of element changes while scrolling, in mobile screen (only when scrolling up and down) .it reads the scrolling function of width if ( screensize > 1230) { if (document.body.scrollTop > 90 || document.documentElement.scrollTop > 90) { } } how to go through this error... thank you for the help -
How to change position of label input form django
I am using form with django, I succeeded to create the form, but I don't know how to change position of label of my input to the right, because by default label is in the center. This is an example of I have : picture code : input= forms.CharField( label="myLabel", required=True, widget=forms.TextInput(attrs={'class':'form-control','maxlength':'30'})) -
how to add current active user as foreign key to the task model in django 3?
I am creating a task to do web app using django 3, I have two models one is UserCustom and other is UserTask in which each corresponding active user can add task. I am getting the entry details through a "model form". For adding the task user need to be login. But mentioning UserCustom as foriegn key in UserTask model, creates a combo (dropdown) box on the "AddTask.html" page with all the registered users. How can i autimatically add current active user as foreign key in UserTask model ? Below are the codes models.py from django.db import models from django.contrib.auth.models import User from django.conf import settings # Create your models here. class UserCustom(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) profile_pic=models.ImageField(upload_to='profile_pics',blank=True) def __str__(self): return self.user.username #user os object defined above class UserTask(models.Model): author = models.ForeignKey(UserCustom,on_delete=models.CASCADE) label=models.CharField(max_length=264) date=models.DateField() status=models.BooleanField(default=False) def __str__(self): return str(self.label) forms.py from django import forms from django.forms.fields import DateField from django.contrib.auth.models import User from taskApp.models import UserCustom,UserTask from django.contrib.admin.widgets import AdminDateWidget class UserForm(forms.ModelForm): password=forms.CharField(widget=forms.PasswordInput()) class Meta(): model=User fields=('username','email','password') class UserCustomForm(forms.ModelForm): class Meta(): model=UserCustom fields=('profile_pic',) class UserTaskForm(forms.ModelForm): date=DateField(widget=forms.DateInput(attrs={'placeholder': 'YYYY-MM-DD', 'required': 'required'})) class Meta(): model=UserTask fields=('author','label','status','date') views.py from django.shortcuts import render from taskApp.forms import UserForm,UserCustomForm,UserTaskForm #below libraries required for login from django.contrib.auth import authenticate,login,logout from django.http … -
Saving many-to-many field with another field of that same model
I want to upload a video for a "class AND SECTION" but in the form I can only see the class but what is required is that the students from that particular 'class' and section should be able to see that video and not the entire class in general. Apology for the bad phrasing. models.py class Batch(models.Model): name = models.CharField(max_length=30) school = models.CharField(max_length=50) amount_of_fees = models.IntegerField(null=True) subjects = models.ManyToManyField(Subject) section= models.CharField(max_length=2, null= True) class LectureVideo(models.Model): user= models.ForeignKey(User, on_delete=models.CASCADE) batch= models.ManyToManyField(Batch) title= models.CharField(max_length=255) video= models.FileField(upload_to= 'video/', null=True) forms.py class LectureUploadForm(forms.ModelForm): class Meta: model= LectureVideo fields= ('title', 'video', 'batch') widgets= { 'title': forms.TextInput(), 'batch': forms.CheckboxSelectMultiple(), } views.py class LectureUploadView(CreateView): model= LectureVideo form_class= LectureUploadForm template_name= 'app/teachers/upload_lecture.html' def form_valid(self, form): form.save() return redirect('home') -
how to use django signals for creating one to many User models based on groups
I building a school management system. There are different users with respective roles. In my models.py, I am using a custom user model with the following classes. class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) date_joined = models.DateTimeField(_('date joined'), auto_now_add=True) is_active = models.BooleanField(_('active'), default=True) is_staff = models.BooleanField(_('staff'), default=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] class Meta: db_table = "User" verbose_name = _('user') verbose_name_plural = _('users') class Address(models.Model): house_number = models.CharField(max_length=20) street_number = models.CharField(max_length=20) town = models.CharField(max_length=20) city = models.CharField(max_length=20) state = models.CharField(max_length=20) def __str__(self): return self.city class Meta: db_table = 'Address' and an abstract class class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) photo = models.ImageField(upload_to='profile-photo/', null=True, blank=True) birth_date = models.DateField(null=True, blank=True) date_left = models.DateField(null=True, blank=True) salary = models.FloatField(max_length=6, null=True, blank=True) contact_number = models.CharField(max_length=11, null=True, blank=True) address = models.ForeignKey(Address, on_delete=models.CASCADE, null=True, blank=True) # groups = models.OneToOneField(Group, on_delete=models.DO_NOTHING, null=True, blank=True) # def get_absolute_url(self): # return reverse("accounts:profile", kwargs={'id':self.user}) def __str__(self): return self.user.__str__() @property def getAge(self): return int(datetime.date.today() - self.birth_date) class Meta: abstract = True and after that I am using Profile Abstract class as a base class for different users with different roles class Principal(Profile, models.Model): class HrStaff(Profile, models.Model): … -
Django: What is a database router?
I have trying to work with multi-databases in a django project and came across Database router. Going through the doc, I can't seem to understand the concept of how it works and am confused. How does the router work? Where should the routers be placed? And should we create one router class per model? -
django elasticbeanstalk deployment issue with YML config
For testing purpose I am trying to upload a django project in AWS elastic beanstalk. But environment create command eb create my-env gives me this error : ERROR: InvalidParameterValueError - The configuration file .ebextensions/django.config in application version app-8036-200522_133554 contains invalid YAML or JSON. YAML exception: Invalid Yaml: while scanning for the next token found character '\t' that cannot start any token in "<reader>", line 2, column 1: aws:elasticbeanstalk:container: ... ^ , JSON exception: Invalid JSON: Unexpected character (o) at position 0.. Update the configuration file. Here is my folder structure. . ├── db.sqlite3 ├── .ebextensions │ └── django.config ├── .elasticbeanstalk │ └── config.yml ├── .gitignore ├── manage.py ├── requirements.txt ├── static └── TaxKH_API ├── asgi.py ├── __init__.py ├── settings.py ├── urls.py └── wsgi.py and here is my .ebextensions/django.config I have validated the YML using online tool. There is no problem regarding YML formatting and validation. option_settings: aws:elasticbeanstalk:container:python: WSGIPath: TaxAPI/wsgi.py -
GetCategories ebay API call in django
i am stuck in getCateogory api call of ebay, given below is a django view which executes on a button click, i am getting desired output in backend on api call but it just returns a response as <ebaysdk.response.Response object at 0x00FC6030> on print(result), how to get data on this API call in a variable so that it can be passed as a context and can be used in frontend in desired format. Basically, i am developing an application to perform revise operation as in ebay, so want to fill all its drop down automatically as provided by ebay, for example, item condition field should automatically be filled with all valid drop down options which ebay supports and provides. So that i don't have to change it manually each time ebay adds a new item condition. If is there any way to do it please let me know. path = rootpath.detect() print(path) path = (path + "\\listing\\ebay.yaml") api = Connection(config_file=path, domain="api.sandbox.ebay.com", debug=True) GetCategoriesRequest = { "RequesterCredentials": { "eBayAuthToken": "xyz", }, "CategorySiteID": "0", "DetailLevel": "ReturnAll", "LevelLimit": "1", } result = api.execute("GetCategories", GetCategoriesRequest) print("response of getcategories function is: ") print(result) print("get Category function worked!") ctx = { 'result': result } return render(request, … -
Steps for using Next.js + Django API under same URL through NGINX
I started with a Django Backend for My React Native mobile frontend. The backend is hosted on GCP and uses Gunicorn as server and NGINX for HTTPS requests and reverse proxing. Now I am making a website, using Next.js I have only one domain name ex. www.onedomain.com How to direct traffic of API's to django backend And traffic of website viewers to Next.js The constraint is one domain name. -
Django Tutorial Part 2 Name Error ... not defined
Hopefully you can help me on my struggle in following the Part 2 Django tutorial. Here's my code import datetime from datetime import timedelta from django.utils import timezone from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date >= (timezone.now() - timedelta(days=1)) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default = 0) def __str__(self): return self.choice_text after all the code is written and typing in my command line q.was_published_recenlty() I got this result File "", line 1, in File "C:\User.... \models.py", line 12, in was_published_recently.... Name Error:name 'pub_date' is not defined -
Django - Filter objects by DateTimeField with a date range
I have a datetime field like below, class Data(models.Model): time = models.DateTimeField(default=timezone.now) I want to get the objects based on a date range from template form. I have seen ways to filter for DateField but not for DateTimeField. Can anyone help? -
Django how to use if condition inside views.py
I hope the title is enough to understand what my problem is this is my html <a href="{% url 'studentenrollment' %}?categoryID={{category.id}}" >{{category.Description}}</a> i have this code inside my views.py def studentenrollment(request): categoryID = request.GET.get('categoryID') if categoryID == 2: .... return render(request, 'Homepage/Frontpage.html') else: .... return render(request, 'Homepage/backpage.html') in my case, it always false even thought my categoryID is equal to 2. did i miss something? -
Django connecting views.py and urls.py in Hello World in Django 3.0.6
I have created a djanogo project. manage.py db.sqlite3 project/ __init__.py settings.py urls.py asgi.py wsgi.py views.py Then I have created the views.py as below. from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the polls index.") Now how do I write the code for urls.py? I donot want to create a seperate folder as polls in https://docs.djangoproject.com/en/3.0/intro/tutorial01/. The following code works but how do i use the include() function in the urlpatterns? from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('admin/', admin.site.urls) ] -
Issue with Bootstrap icon
I am having some issue with my Bootstrap setting. I am learning bootstrap. i was trying to design a buttong with bootstrap. i want to add some icon on the buttton but i couldnt get it work. i tried lots of tutorials and even with given example on the bootstrap page... Can any one help me to find my faults?? Thanks in advance. :) here is my code: {% load static %} <body> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <div class="container"> <a class="navbar-brand" href="#">Hey!!!, {{user.username}}</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav ml-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#">Registration</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'logout' %}">Log Out</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'login' %}">My Account</a> </li> </ul> </div> </div> </nav> <div class="container bordere" > <div class="mt-2"> <a href="{% url 'authuser' %}"> <button class="btn btn-primary my-2 my-sm-0" type="button">Add Items</button></a> <button class="btn btn-primary my-2 my-sm-0 " type="submit"><span class="glyphicon glyphicon-cog"></span>View Details</button> <button class="btn btn-primary my-2 my-sm-0" type="submit">Download Report</button> <button class="btn btn-primary my-2 my-sm-0" type="submit">Email Report</button> <button class="btn btn-primary my-2 my-sm-0" type="submit">Create Bill</button> <button class="btn btn-primary my-2 my-sm-0" type="submit">Modify Data</button> <button type="button" … -
Jquery AJAX not sending data to Django view
I'm trying to post some form data to django views but the problem is that ajax is not sending the data. below is my code. ajax $(document).on('click', '#lecturesave', function(e){ var token = '{{csrf_token}}'; content= $('#contenttitle').val() lecttitle= $('#lecttitle').val() console.log(content) console.log(lecttitle) e.preventDefault(); $.ajax({ headers: { "X-CSRFToken": token }, method: "POST", url: "{% url 'create_course' %}", data: { content: $('#contenttitle').val(), lecttitle: $('#lecttitle').val(), file: $('#lecturefile').prop("files")[0], action: 'post', }, //contentType: false, processData: false, success:function(data){ console.log(data) } }) }); views.py def coursecreate(request): if request.method=="POST": print(request.POST) #if 'content' in request.POST: content = CourseContent(title = request.POST.get('content')) content.save() con = CourseContent.objects.latest('id') lecture = CourseLecture(content = con, file = request.FILES.get('file'), title = request.POST.get('lecttitle')) lec = lecture.save() return JsonResponse(lec, safe = False) #course = Course(title = request.POST.get('coursetitle'), subtitle = request.POST.get('coursesubtitle'), price = request.POST.get('price'), description = request.POST.get('coursedescription')) #c = course.save() return render(request, "main/create_new_course.html", {}) and this the querydict I'm getting in django: <QueryDict: {'[object Object]': ['']}> Thanks in advance. -
stop refreshing js file in django templates
i have created countdown timer with django templates which showed on HTML templates,when page refreshed data on html page is update but it also reset countdown timer. i dont want that is there any way to stop refreshing script or update data without refreshing. app.js var count = 8 var counter = setInterval(timer , 1000) function timer(){ count = count-1 if (count <= 0) { clearInterval(counter); return window.location.href = urlFromDjango } document.getElementById("timer").innerHTML= count + " secs"; } index.html {% load static %} <head> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"> <link rel="stylesheet" href="{% static 'css/app.css' %}"> <script src="{% static 'js/app.js' %}"></script> </head> <script> var urlFromDjango = "{% url 'app:result' %}" </script> <body> <h1 id="timer"></h1> </body> <h1>{{user.username}}</h1><br> <h2>score -{{user.userextend.score}}</h2> <form action="{% url 'app:detail' quiz_id=que.quiz.id question_id=que.id %}" method="post"> {% csrf_token %} {% for choice in que.answer_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"> <label for="choice{{ forloop.counter }}">{{ choice.answer }}</label><br> {% endfor %} <button><a href="{% url 'app:detail' %}">Next</a></button> </form> -
how to set up ckfinder for ckeditor with ( React.js / django /django rest framework )?
I'm trying to create a web app for my final school project and i decided to use CKEditor5 to create rich test posts i managed to integrate Ckeditor with Django and, i can successfully create post from the admin aria and add images but when i wanted to do the same thing from the frontend (react), i faced some problems that i didn't know how to solve . so when i try to upload an image i recive a popup in the browser with the message ** can't upload the file ** this is my code for the editor (it works just fine with text ) <CKEditor editor={ClassicEditor} data="" onInit={(editor) => { // You can store the "editor" and use when it is needed. console.log("Editor is ready to use!", editor); }} onChange={(event, editor) => { const data = editor.getData(); this.setState({ content: editor.getData() }); }} onBlur={(event, editor) => {}} onFocus={(event, editor) => { console.log("Focus.", editor); }} config={{ ckfinder: { // Upload the images to the server using the CKFinder QuickUpload command. uploadUrl: "http://localhost:8000/media/uploads/", options: { resourceType: "Images", }, }, }} /> the url path that i but in the uploadUrl is the path where i put media when using the admin … -
Error message not working as expected in Django
I am trying to display a message on order creation success or failure. For messages.success(request, "My message") it is working as expected. But for messages.error(request, "My message") it is not as expected. I read the django messages framework docs, but no use. Can someone tell me why is this happening Success Message: Failed Message: This is supposed to be red alert if I am not wrong. Here's my html file. base.html <main role="main" class="container" > {% if messages %} {% for message in messages %} <div class="alert alert-{{ message.tags }}"> {{ message }} </div> {% endfor %} {% endif %} views.py if verify: if response_dict['RESPCODE'] == '01': messages.success( request, "Thank you for ordering! Your items will be delivered soon") return redirect(reverse('update-records', kwargs={'order_id': order_id})) else: messages.error( request, "Your order could not be placed, here are the details: " + response_dict['RESPMSG']) return redirect(reverse('profile-page'))