Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
How to generate the json which looks like this using Django Rest Framework
I need to generate this below JSON Using Django. I need help in designing Models, Serializers and Views for generating this below JSON. I have no idea in doing this as this looks like nested JSON. { "ok": true, "members": [{ "id": "01FC991", "real_name": "John Anderson", "tz": "America/Los_Angeles", "activity_periods": [{ "start_time": "Feb 2 2020 1:33PM", "end_time": "Feb 2 2020 1:54PM" }, { "start_time": "Mar 2 2020 11:11AM", "end_time": "Mar 2 2020 2:00PM" }, { "start_time": "Mar 17 2020 5:33PM", "end_time": "Mar 17 2020 8:02PM" } ] }, { "id": "01FC992", "real_name": "James Anderson", "tz": "Asia/Kolkata", "activity_periods": [{ "start_time": "Feb 2 2020 1:33PM", "end_time": "Feb 2 2020 1:54PM" }, { "start_time": "Mar 2 2020 11:11AM", "end_time": "Mar 2 2020 2:00PM" }, { "start_time": "Mar 17 2020 5:33PM", "end_time": "Mar 17 2020 8:02PM" } ] } ] } -
Django filter related field using through model's custom manager
I have 2 models and a custom manager to filter out on active items: class List(models.Model): items = models.ManyToManyField("Item", through="ListItem") class ListItemManager(models.Manager): def get_queryset(self): return super(ListItemManager, self).get_queryset().filter(item__is_active=True) class ListItem(OrderedModel): item = models.ForeignKey("Item") objects = ListItemManager() Why does this not work as I would expect? active_list_items = List.objects.first().items # Contains items with `is_active=False` :( What is the correct way to filter out non active items through my through model? -
NoReverseMatch at / Reverse for 'create_order' not found. 'create_order' is not a valid view function or pattern name. Django question
**Dashboard file** <div class="col-md-7"> <h5>LAST 5 ORDERS</h5> <hr> <div class="card card-body"> <a class="btn btn-primary btn-sm btn-block" href="{% url 'create_order' %}">Create Order</a> <table class="table table-sm"> <tr> <th>Product</th> <th>Date Orderd</th> <th>Status</th> <th>Update</th> <th>Remove</th> order_form.html...I need an extra pair of eyes for this problem, cant find for hours what syntax mistake have I made this time or if django syntax rules changed after some update I dont konw about, from some reason, it just cannot find the create_order. Hope you guys can help and find it easily, it would help a ton {% extends 'accounts/main.html' %} {% load static %} {% block content %} <form action="" method="POST"> <input type="submit" name="Submit"> </form> {%endblock%} urls.py file from django.urls import path from . import views urlpatterns = [ path('', views.home, name="home"), path('customer/<str:pk>/', views.customer, name="customer"), path('products/', views.products, name="products"), path('create_order/', views.createOrder, name="create_order"), ] views.py file from django.shortcuts import render from django.http import HttpResponse from.models import * def home(request): customers=Customer.objects.all() orders=Order.objects.all() total_customers=customers.count() total_orders=orders.count() delivered=orders.filter(status="Delivered").count() pending=orders.filter(status="Pending").count() context={'orders':orders,'customers':customers, 'pending':pending, 'delivered':delivered,'total_orders':total_orders} return render(request, 'accounts/dashboard.html',context) def products(request): products = Product.objects.all() return render(request, 'accounts/products.html',{'products' :products}) def customer(request, pk): customer=Customer.objects.get(id=pk) orders=customer.order_set.all() order_count=orders.count() context={'customer': customer, 'orders': orders,'order_count':order_count} return render(request, 'accounts/customer.html', context) def createOrder(request): context={} return render(request, 'accounts/order_form.html',context) error by django NoReverseMatch at / Reverse for 'create_order' … -
why this problem appear when run this code to locate the position by use geoip2 in django?
I am working on a project to determine the location of the person using the IP using the 'geoip2' and 'geopy'. I have finished that and when I run this message appeared to him. The address 127.0.0.1 is not in the database. This is the code: