Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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, -
My CSS does not appear when I use "extend" and "block" in Django
I have spent half a day trying to figure this out. I ended up passing the CSS through the HTML style attribute. What do I have and tried: In settings.py I have included: django.contrib.staticfiles, `STATIC_URL = '/static/' In layout.html: {% load static %}, <link href="{% static 'auctions/styles.css' %}" rel="stylesheet"> The static files folders are orginized the following: MY_APP/static/auctions/styles.css And extending the layout and filling the body block, I have tried adding {% load static %} on top; I have put <link href="{% static 'auctions/styles.css' %}" rel="stylesheet"> afterwards and restarted the server, yet all this to no avail; -
Creating web card game for 4 players
I would like to make a web card game. Game should be for 4 players and it should wait for all players to connect and then start the game. Each player should see only his hand (not others hand), but all of them should see the same stack in the middle. My idea is that each player (when is on move) clicks on some card and that card will come to the middle where others will see it. There is specific order of players who is on a move. I would like to write this game in python and then use some JavaScript probably. I want to ask you what do you think is the easiest way to write this web app. I am struggling with the idea where should I write game's engine. Friend of mine has suggested me to use Django but I don't think this will solve my problem. As you probably noticed I am not very experienced in this stuff and that's why I am asking for an advice. Could you please give me an short advice how this all should be connected together and how should I continue? Thank you for your answers. -
How to add a plugin in a plugin Django CMS
I have create a plugin like http://docs.django-cms.org/en/latest/how_to/custom_plugins.html But i dont know how to add another plugin in this plugin . -
How do I add multiple authentications for a single user model in Django?
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? Before downvoting, if the question is not clear, please comment below. -
How to get specific fields from a django model serializer which return all field(fields = '__all__' in serializer's meta)?
I have a serializer: class UsrSerializer(serializers.ModelSerializer): class Meta: model = Usr fields = '__all__' I don't want all fields but id, first_name, last_name and email here and don't want to modify serializer because I need all fields somewhere else: org = Organization.objects.get(pk=org_id) members = org.user_set.all() serializer = UsrSerializer(members, many=True) -
Live video stream problems with Django
I'm trying to stream live feed from my webcam into django. My code is very very similar to the code on this github page https://github.com/log0/video_streaming_with_flask_example (just using a StreamingHttpResponse instead of a response). I only added some keystroke features with pynput to control a cursor on the stream. The problem is my mac starts getting really slow after about 30-40 seconds or so to the point where I have to restart it. My main plan is to later transfer this system into a raspberry pi web server but my worry is that if it makes my mac freeze, whats its gonna do to the Pi? A solution I thought of was to maybe pause the stream or stop it but every time I try calling the VideoCamera.del() method the whole localhost server closes instead of the just the stream stopping. Some people were saying that it may be a memory problem but I mainly code in Python and I dont have much knowledge in terms of memory so if someone can help me out with that it would be great. I'm not sure if this is a problem with my computer or wifi or what. The raspberry pi is pretty … -
How to Keep Django Project Running After Putty Close?
i am new in django and i am uploading Django Project on digitalocean server first Time. My Upload is Successfull. i have Connected my digitalocean server Using Putty. when i run my Server ,it works Fine, but when i close Putty my Project Stopped Working .I have aplied following steps: sudo apt-get install screen Hit Ctrl + A and then Ctrl + D in immediate succession. You will see the message [detached] screen -r screen -D -r Howevver its not working. How to Keep running Djnago Project after closing Putty. i Can't find any valid Solution.How to do that? i Will be Thankful if any one can help me with this Issue. -
Using two submit buttons to save django inlineformset as draft
I have an inlineformset that works. I have attempted to add a second submit button, that when clicked will check that a particular field in each inline form has been filled out i.e. this field becomes a required filed only when the second submit button is clicked. The problem is that when I click this second submit button the validation errors don't appear and the form just seems to submit anyway. I think the issue is within my view, within form_valid. I'm not sure what I need to return when if form.is_valid() fails. I'm teaching myself to code, so any help or direction is much appreciated. Forms.py class response_form_draft(forms.ModelForm): class Meta: name = response exclude = ['id_question','order'] def __init__(self, *args, **kwargs): super(response_form_draft, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_show_labels = False class response_form_final(forms.ModelForm): class Meta: name = response exclude = ['id_question','order'] def __init__(self, *args, **kwargs): super(response_form_final, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_show_labels = False def clean(self): data = self.cleaned_data resp = data['response'] if resp == "": raise forms.ValidationError(('must not be blank')) checklist_formset_draft = inlineformset_factory(checklist, response, form = response_form_draft, extra=0, can_delete=False, widgets={'comments': forms.Textarea(attrs={'cols': 7, 'rows': 3, 'style':'resize:none'}) }) checklist_formset_final = inlineformset_factory(checklist, response, form = response_form_final, extra=0, can_delete=False, widgets={'comments': forms.Textarea(attrs={'cols': 7, 'rows': 3, … -
How to sort the list of query sets based on first name and last name using lambda in python?
Now I have the results based on the first name of the user using the below code : users.sort( key=lambda user:user.first_name) Here users is a list Ex: [<User: itnotify@awggases.com>, <User: aaron.debord@awggases.com>, <User: amy.sexton@awggases.com>, <User: andrew.funk@awggases.com>, <User: anthony.dieterle@amwelding.com>, <User: bill.neeley@amwelding.com>] I want a code which will sort users first name and last name using the same logic above -
Can not Upload Image from Form to Django Admin Model
I am trying to upload a Image from my Form (signup.html) and then i want that uploaded image name/url to be shown at Django admin models panel too. so i can access the image that user uploaded from the django admin panel. image upload feature is working in Django panel but when i upload it from my Form . my django admin is not saving it . it is also not saving any information like(email, bio,image). i already tried some solutions from stackoverflow but it didn't work. this is my views.py from django.shortcuts import render, redirect from .forms import CustomerForm from django.contrib import messages from django.contrib.auth.decorators import login_required from .models import Profile def register(request): if request.method == 'POST': form = CustomerForm(request.POST, request.FILES or None) if form.is_valid(): username = form.cleaned_data.get('username') email = form.cleaned_data.get('email') bio = form.cleaned_data.get('bio') image = request.FILES.get('image') form.save() messages.success(request, f'Account is created. ') return redirect('signin') else: form = CustomerForm() return render(request, 'Authentication/signup.html', {'form': form}) @login_required def UserAuth(request): return render(request, 'Authentication/profile.html') This is my forms.py below from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import * class CustomerForm(UserCreationForm): first_name = forms.CharField(max_length=100, help_text='Preferred first Name') last_name = forms.CharField(max_length=100, help_text='Preferred Last Name') email = forms.EmailField() image … -
After creating virtual environment for installing Django
After creating virtual environment for installing Django, I have a non stopping blinking underscore with no feedback what I have is (my Environment)C:\Users\Smith\Desktop\djangoEnv>pip install Django blinking underscore "_ " on windows cmd -
AssertionError: Relational field must provide a `queryset` in Django Rest API even though one is provided
I'm trying to send my User -> Group foreign key to rest api to get the Group.name for display but when i use the serializer RelationalField(any of them) i get the following error: AssertionError: Relational field must provide a `queryset` argument, override `get_queryset`, or set read_only=`True`. even though I provided the queryset argument in my serializer class UserSerializer(serializers.ModelSerializer): group = serializers.SlugRelatedField(many=True, slug_field='name', queryset=Group.objects.all()) class Meta: model = User fields = ('pk', 'username', 'created_at', 'is_admin', 'group') I still get the error. Setting read_only='True' displayed the value but after that it wont let me change it. this is my GroupSerializer: class GroupSerializer(serializers.ModelSerializer): class Meta: model = Group fields = ('pk', 'name', 'description') these are the models I use: 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) def __str__(self): return self.username