Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django widget FilteredSelectMultiple
I'm trying to add the FilteredSelectMultiple widget but it is only showing the 1 half of the widget is rending. I have found some stackoverflow post but none seem to have changed it. Need guidance with FilteredSelectMultiple widget Django FilteredSelectMultiple widget rendered with bootstrap form.py class MyCustomSignupForm(SignupForm): first_name = forms.CharField(max_length=30, label='First Name') last_name = forms.CharField(max_length=30, label='Last Name') dbs_number = forms.CharField(max_length=13, label='DBS Number') hospitals = forms.ModelMultipleChoiceField(queryset=HospitalListModel.objects.all(), widget=FilteredSelectMultiple('HospitalListModel',False), required=False, ) class Media: css = { 'all': ('/admin/css/widgets.css', 'admin/css/overrides.css'), } js = ('/admin/jsi18n','/admin/jquery.js') url.py from django.urls import path from . import views from django.conf.urls import url from django import views as django_views urlpatterns = [ url(r'^jsi18n/$', django_views.i18n.JavaScriptCatalog.as_view(), name='jsi18n'), ] template {% extends '_base.html' %} {% load crispy_forms_tags %} {% block title %}Sign Up{% endblock title %} {% block content %} <h2>Sign Up</h2> <form method="post"> {% csrf_token %} {{ form|crispy }} <link href="{{ STATIC_URL }}admin/css/overrides.css" type="text/css" rel="stylesheet" /> <button class="btn btn-success" type="submit">Sign Up</button> </form> {% endblock content %} -
Relational database in django rest framework serializers
I'm working on a Rest API for a web blog, I have made the custom user class and related between custom user class and the post class, but when i try to make a post request and add a post to the database i'm stuck in serializering the post because of the the relation between the user and the post models, all i want to do is just make the author of the post is the current logged in user but i don't actually know how to do this Custom user model: class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True, blank=False, null=False) username = models.CharField(max_length=255, unique=True, blank=False, null=False) date_joined = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = CustomUserManager() def __str__(self): return self.email def has_perm(self, perm, obj=None): return self.is_superuser Post model: class Post(models.Model): title = models.CharField(max_length=255, blank=False, null=False) content = models.CharField(max_length=10000, blank=False, null=False) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return self.title Post serializer: class PostSerializer(ModelSerializer): class Meta: model = Post # I don't know if this way is right fields = ('id', 'title', 'content', 'author') extra_kwargs = {"author": {"read_only": True}} def create(self, validated_data, request): post = Post( title=validated_data['title'], content=validated_data['content'], # I … -
How to count data in Related Model in Django?
I am trying to count value of related model, but i am unable to count, Please let me know where i am Mistaking.. Here is my models.py file... class Project(models.Model): name=models.CharField(max_length= 225) slug=models.SlugField(null=True, unique=True) class Detail(models.Model): project = models.OneToOneField('Project', related_name='detailsofpro', on_delete=models.CASCADE, blank=True, null=True) possession = models.CharField(max_length=50, null=True, blank=True, choices=(('Under Construction', 'Under Construction'),('New launch', 'New Launch'),('Ready To Move', 'Ready To Move'))) here is my views.py file.. def admin_view(request): project = Project.objects.prefetch_related('project_details').annotate(Count('possession')) return render(request, 'index.html', {'project': project}) here is my index.html frile <p>{{project.project_details.possession.count}}</p> i want to count possession from details model, please let me know how i can count -
How to upload files to another APIs from django views using requests package
How to upload files to APIs from django views using requests package. -
Learning Django and Spring simultaneously
Is it possible to learn Django and spring at the same time? Is it a bad idea? I like java for object oriented programming and Django seems easy to me. So I am confused. Should I go for both? Will it be beneficial if I learn both frameworks simultaneously for web application? -
image upload in a template
My issue is if I upload from admin an image it works fine but if I want to add an image from my template, it seems that my image does not updload. It is weird as in the request.Post form, path of my image is present. I've no message of error... this is my model: class Listing(models.Model): title = models.CharField('Title',max_length=64, blank=False) description = models.TextField('Descritpion', blank=False) Creation_date = models.DateField(auto_now_add=True) enddate= models.DateField('Ending Date', blank=False) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="category") initialBid = models.DecimalField('Bid', max_digits=12, decimal_places=2, blank=False) photo = ResizedImageField(size=[300, 150], upload_to='images/', default='images/default.jpg') active = models.BooleanField('Active', default=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="author") def __str__(self): return f"{self.id} : {self.title} {self.initialBid} {self.Creation_date}" def save(self, *args, **kwargs): # Check how the current ending date is after created date, d1 = self.Creation_date d2 = self.enddate if d2 <= d1: raise ValueError("End date must be a day after today") super(Listing, self).save(*args, **kwargs) my form: class NewListingForm(forms.ModelForm): enddate = forms.DateField(label='Date of auction End', widget=forms.DateInput(format = '%d/%m/%Y'), input_formats=('%d/%m/%Y',)) def __init__(self, *args, **kwargs): self._newly_created = kwargs.get('instance') is None self.Creation_date = datetime.now() super().__init__(*args, **kwargs) class Meta: model = Listing fields = ('title','description','enddate','category','initialBid','photo','active') my template: <h2>{% if not form.instance.pk %}Create listing {% else %} Edit {% endif %}</h2> <form id="create-edit-client" class="form-horizontal" action="" method="post" accept-charset="utf-8" … -
How can I do to filter hours using Django?
Hello I am using Django and I have these variable : a = '08:00:00' b = '13:30:03' I want to do something like this : Table.objects.filter(myhour__in(a, b)) but it does not work... Could you help me please ? Thank you very much ! -
Recivieng error 500 when deploy Django rest-Vue project on Heroku
I'm been able to deploy my first project to heroku. The API is this: https://segmentacion-app.herokuapp.com/cluster/, and the front is this: https://cluster-app-wedo.herokuapp.com/, the problem appears when I try to consume the api, I receive this: Failed to load resource: the server responded with a status of 500 (Internal Server Error) Error: Request failed with status code 500 at t.exports (createError.js:16) at t.exports (settle.js:17) at XMLHttpRequest.p.onreadystatechange (xhr.js:61) Home.vue:598, can I have some feedback about what i've missed? Home.vue let datos = await axios.post('https://segmentacion-app.herokuapp.com/cluster/',json) .then(response => { ... server.js const express = require('express'); const port = process.env.PORT || 8080; const app = express(); app.use(express.static(__dirname + '/dist/')); app.get(/.*/, function(req, res) { res.sendfile(__dirname + '/dist/index.html'); }); app.listen(port); console.log("Server started..."); settings.py import os import django_heroku # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') # 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 = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['https://cluster-app-wedo.herokuapp.com/',] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'MiApp', 'import_export', 'django_extensions', 'rest_framework', 'api', 'corsheaders', ] MIDDLEWARE = [ … -
How to hide objects after deletion in Django admin?
in my Django admin interface if I delete something it leads to default Django admin deletion page. In that page under objects category can we delete any object message or make changes in it? I have provided with the image!! -
How to remotely enter email credentials in django?
My web app is deployed by the computer team but developed by me. It is essential that the emails are sent using my team's email id. Hence, I am using a form to enter credentials into a safe file only accessible to my user. This is my settings file from config parser import ConfigParser EMAIL_CREDENTIAL_CONFIG = "credentials.ini" def credential(attr): config = ConfigParser() try: config.read(EMAIL_CREDENTIAL_CONFIG) return config["DEFAULT"][attr] except KeyError: pass EMAIL_HOST_USER = credential("EMAIL_HOST_USER") EMAIL_HOST_PASSWORD = credential("EMAIL_HOST_PASSWORD") The issue is that these values are loaded only when the server starts and I cannot remotely update it without using an ssh terminal and manually entering the file location. Can you suggest alternatives to either reload the email credentials automatically or to keep the creds safe from anyone having access to the server pc? -
Cannot Assign variable to Form Field for new entry
When trying to run a form.save() on I am receiving the following error: IntegrityError at /customers/customer/1930/contacts/ ('23000', "[23000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Cannot insert the value NULL into column 'idcst_cnt', table 'app_contact_cnt'; column does not allow nulls. INSERT fails. (515) (SQLExecDirectW); [23000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]The statement has been terminated. (3621)") I cannot seem to figure out how to include the idcst_cnt value which is a variable passed in id which is a hidden field on the form/template. forms.py class ContactsForm(ModelForm): class Meta: model = AppContactCnt fields = ('idcst_cnt', 'name_cnt', 'phone_cnt', 'email_cnt', 'note_cnt', 'receives_emails_cnt') labels = {'name_cnt': 'Name', 'phone_cnt': 'Phone', 'email_cnt': 'Email', 'note_cnt': 'Note', 'receives_emails_cnt': 'Emails?', } widgets = { 'id_cnt': forms.HiddenInput(), 'idcst_cnt': forms.HiddenInput(), } ContactFormSet = modelformset_factory(AppContactCnt, exclude=()) views.py def customer_contacts(request, id): ContactFormSet = modelformset_factory(AppContactCnt, can_delete=True, fields=( 'name_cnt', 'phone_cnt', 'email_cnt', 'note_cnt', 'receives_emails_cnt'), max_num=3, extra=3) formset = ContactFormSet(queryset=AppContactCnt.objects.filter(idcst_cnt=id), prefix='contact') if request.method == 'GET': context = {'formset': formset, 'id': id} return render(request, 'customer_contacts.html', context=context) if request.method == 'POST': print(formset.errors) formset = ContactFormSet(request.POST, prefix='contact') for form in formset: if form.is_valid(): customer = get_object_or_404(AppCustomerCst, id_cst=id) form.idcst_cnt = customer form.save() print("we're updating contacts for " + str(id)) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) context = {'formset': formset, 'id': id} return render(request, 'customer_contacts.html', context=context) … -
How to be able to display any Uploaded Django File in HTML
I am making a site that can store files that means video, audio, text, and many more. But I am having a problem display those files that are in my database as in a media folder. So like I have found that iframe is best until there was a problem with the video and the audio files. When the page loads they auto start and I know that the video tag and img tag is the best of this but How am I suppose to know the file type to display. So like the website is almost like Google Drive except for the styles of course. -_- Well so like what can I do to solve my problem. Thanks in advance -
Multiple authentication for different user types
I have 3 user types (Customers, Vendors, Admins) which I have differentiated using their profiles. I want to have OTP based authentication for Customers from mobile (DRF) and Web app as well, user name and password based auth for Admins and Vendors from mobile (DRF) and Web app. How can I achieve this? If the question is not clear please comment below. -
Problems With My Project(Django Database)
I am working on an app with django I am right now still trying to create the database for it the problem is that my database is using a time field and I have never used it before what I wish to do is add a default value to it which is 0min 0sec. time_taken = models.TimeField(auto_now_add=False, default="", null=True) This is the code I have written for it. -
How to avoid duplicate data in Django Template
I have this piece of code : {% extends 'base.html' %} {% load static %} {% block page_title %}Manage Staff{% endblock page_title %} {% block content %} <section class="content"> <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <div class="card"> <div class="card-header"> <h3 class="card-title">Manage All Staff</h3> </div> <!-- /.card-header --> <div class="card-body"> <table id="example2" class="table table-bordered table-hover"> <thead> <tr> <th>SN</th> <th>Full Name</th> <th>Email</th> <th>Course</th> </tr> </thead> <tbody> {% for staff in allStaff %} <tr> <td>-</td> <td>{{staff.last_name}}, {{staff.first_name}}</td> <td>{{staff.email}}</td> <td>{{staff.course.name}}</td> </tr> {% endfor %} </tbody> </table> </div> </div> </div> </div> </div> </section> {% endblock content %} The block page_title is used to display the current page in base.html. My question is, how can I avoid repeating the text "Manage Staff" ? Is there a way to display the block page_title in this current file ? What I earlier tried was passing the value from my views.py file, so I wanna be sure I am doing the right thing -
Trying to add CSRF Token to HTML code generated in Javascript and it is not working
I am building a website using Django and React and here is my issue I want to add {% csrf_token %} to an HTML form that is produced in Javascript and it does not display when I try to add it to this: function formatPostElement(post){ var formattedPost = "<div class = 'col-12 col-md-10 mx-auto border rounded py-3 mb-4' id = 'post-" + post.id +"'><p>" + post.content + "</p><div class = 'row mb-4'><div class = 'col-md-4 mx-auto col-10'><form class = 'form' id = 'post-comment-create-form' method = 'POST' action = '/create-post-comment/" + post.id +"'><div id='post-create-form-error' class='d-none alert alert-danger'></div><input type = 'hidden' value = '/' name = 'next'/><textarea class = 'form-control' name = 'content' placeholder='Enter your comment...' required></textarea><button type = 'submit' class = 'btn btn-danger'>Comment</button></form></div></div></div>" return formattedPost } In the code above I try to add {% csrf_token %} after the form tag and before the div tag. I have another form in the same file (index.html) that has a csrf token, however that form is declared outside of javascript. What can I do to have a CSRF token running in this form? -
How to have a Payment with Google Pay in Django
So I'm making something like an online store where users can take images of a product, send it any random user they want, and the user who received the request (or the buyer) can accept it Now what I want to happen is: When the buyer clicks on to accept it will redirect him to a page where he should see "You are going to pay $ with Google pay, Continue Now when the user clicks continue the other user (The seller) Should get payed with the X amount of money This requires having a ready to pay Google Pay account i guess Any help to do so? Here is my custom user model from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): pass My trading model: import os from django.db import models from django.contrib.auth import get_user, get_user_model User = get_user_model() class Trade(models.Model): seller = models.ForeignKey( User, related_name='seller', on_delete=models.CASCADE) buyer = models.ForeignKey( User, related_name='buyer', on_delete=models.CASCADE) is_accepted = models.BooleanField(default=False) product = models.FileField(upload_to='trade/trade/products') price = models.IntegerField() date = models.DateTimeField(auto_now_add=True) def filename(self): return os.path.basename(self.product.name) and here is what happens when the user clicks (Accept trade) views.py def accept_trade(request, pk): trade = get_object_or_404(Trade, pk=pk) if request.method == 'GET': return render(request, 'trade/accept_trade.html', {'trade':trade}) else: … -
Nginx redirect to Sphinx docs for Django app in Docker
I've added Sphinx documentation to a Django project, and want to serve the generated Sphinx pages from the /docs uri, but I can't seem to get my uris and directories aligned to serve the right stuff. I've tried a number of configurations. Current one is included below. Django site serves OK (though not set up static file stuff yet - figure I'd have the same issues there!). But /docs returns a 404 from nginx. I've tried root vs. alias and different path settings. I've verified the volume is loaded OK on /docs so that index.html exists there, but no joy. All suggestions welcome! docker-compose.yml version: '3.8' services: nginx: image: nginx ports: - 443:443 - 80:80 volumes: - ./config/nginx:/etc/nginx/conf.d - ./static:/static - ./src/docs/build/html:/docs depends_on: - web web: container_name: inventory build: context: . dockerfile: Dockerfile.dev env_file: .env volumes: - ./src:/inventory - ./config/nginx/certs:/etc/certs expose: - 443 environment: - DJANGO_SETTINGS_MODULE=${DJANGO_SETTINGS_MODULE} command: > <Does stuff & runs gunicorn> nginx.conf upstream web { ip_hash; server web:443; } # Redirect all HTTP requests to HTTPS server { listen 80; server_name localhost; return 301 https://$server_name$request_uri; } server { listen 443 ssl; server_name localhost; # Serve up the Sphinx docs directly location /docs { # root /docs; try_files $uri … -
Django database api
So I'm creating a blog and I've created some posts using the django database api. With the posts I created I used myself( after creating superuser) as the author of these posts. But when I create a post using another name as the author it doesn't work. Can anyone help? models.py This is my model I haven't created views yet. So I created instances of the Post model with author as user(which is me) and now i'm trying to create a Post with another name as the author. -
relation does not exist my django in heroku
i add the column lifeexpectancydetails table and push the code in github then i go to heroku and auto deploy code from my github to heroku build run successfully and i go to heroku webconsole and run command python manage.py makemigraitons this command run successfully after this command then i run python manage.py migrate they show me i am really stuck and panic situation can any body help me pleaseenter image description here -
axios request returns 400 when sending data
Hi I have a simple Django-React app with 2 models User and Group, when trying to send put or post request on User model I'm getting a bad request error(400) Here is my code: models(User and Group) class Group(models.Model): name = models.CharField('Name', max_length=200,) description = models.CharField('Description', max_length=500) def __str__(self): return self.name class User(models.Model): username = models.CharField('Username', max_length=200) created_at = models.DateField('Created At', auto_now_add=True) is_admin = models.BooleanField('Is this user admin?', default=False) group = models.ForeignKey(Group, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return self.username serializers for both models(User serializer includes Group serializer because I need to display group name in user field( a user can only have 1 group ) so its one to many relationship. class GroupSerializer(serializers.ModelSerializer): class Meta: model = Group fields = ('pk', 'name', 'description') class UserSerializer(serializers.ModelSerializer): group = GroupSerializer() class Meta: model = User fields = ('pk', 'username', 'created_at', 'is_admin', 'group') This is my react form that handles the requests using axios module. class NewUserForm extends React.Component { constructor(props) { super(props); this.initialState = { pk: 0, username: "", is_admin: "", group: "", selectOptions: [] }; this.state = this.initialState; } async getOptions() { const res = await axios.get(GROUPS_API_URL) const data = res.data const options = data.map(d => ({ "value": d.pk, "label": d.name … -
Django AWS S3 Image error 400 "Bad Request"
I connected my Django project with heroku and amazon aws S3. I added following to my settings.py STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') AWS_ACCESS_KEY_ID = '...' AWS_SECRET_ACCESS_KEY = '...' AWS_STORAGE_BUCKET_NAME = 'name' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' As I start localhost to check if everything works, the css and static files where served perfectly but the files which can be uploaded by the user into the media folder arent shown instead it throws: HTTP/1.1 400 Bad Request Inside the src it shows a link to AWS service and if I upload an image it gets stored in the S3 Bucket! Inside the models.py I store the files in the folder media image = models.FileField(blank=True, upload_to='media'). Can someone help me or have an idea why the images get stored but can't get send? -
Is it possible to use When/Case in Django with `output_field` list (or array)?
I'm trying to use Django's conditional expressions with a output_field of type ArrayField (django.contrib.postgres.fields). Was anyone able to do something similar? An illustrative snippet below: queryset.filter(my_field__in=Case( When( status=X, then=[A LIST OF STRINGS], ), ) output_field=ArrayField(CharField(max_length=16)), ) Thanks in advance! -
Update/merge data instead of replacing it with PUT method in Django Rest Framework
In a Django app (that uses DRF), I have a user profile model. To update the profile info, I want to use PUT. However, I have a field called "meta", that is an object/dict itself. If I am missing any of its properties (gender, mobile, birthday), I will lose that data since the whole "meta" is replaced with the new one. That does not happen with any of the fields (e.g., if I do not specify the first name, the field will just stay the same). Here's an example of a PUT request body: { "id": 1, "first_name": "Jane", "last_name": "Doe", "email": "jane@example.com", "meta": { "gender": "female", "mobile": 123456789, "birthday":"01-01-1970" } } What can I do to assure that the missing properties are not lost? Is there a way to implement or force a merge/update of the previous data with the one in the request? Here's the method: def put(self, request, pk): user = User.objects.get(id=pk) serializer = UserSerializer(user, data=request.data, context={'request': request}) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) And here's the serializer: class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = [ 'id', 'url', 'first_name', 'last_name', 'email', 'meta' ] -
fields except the id field is not getting imported using Django import export
These are my codes and csv file class UserResource(ModelResource): class Meta: model = User fields = ('username', 'email', 'is_member') import_id_fields = ('username',) class UserAdmin(ImportMixin, admin.ModelAdmin): resource_class = UserResource admin.site.register(User, UserAdmin) username, email, is_member, id abc, abc@mail.com, True,