Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use models in template django 3
I want to show the list of items in MyModel. I used to use php framework , not good for python yet. I googled around and search for best practices, but I cant find the explanation for Django 3. Does anyone help? my code is like this. in views.py mymodels = MyModel.objects.all() data = { 'mymodels' : mymodels } return render(request, 'myapp/index.html',data) in myapp/index.html {% for m in mymodels %} {{m.id}} {% endfor %} -
order creating django drf
models.py: class OrderItem(models.Model): image_number = models.CharField(max_length=20) title = models.CharField(max_length=20) image_url = models.URLField(max_length=200,null=True,blank=True) image_size = models.CharField(max_length=50) file_type = models.CharField(max_length=20) price = models.CharField(max_length=50) def __str__(self): return self.title class Order(models.Model): order_status = ( ('created','created'), ('processing','processing'), ('orderd','orderd') ) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, blank=True,null=True) items = models.ManyToManyField(OrderItem) order_status = models.CharField(choices=order_status,null=True,max_length=50) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField(auto_now_add=False,blank=True,null=True) views.py: class AddtocartView(generics.CreateAPIView): authentication_classes = [] permission_classes = [] pagination_class = None queryset = OrderItem.objects.all() serializer_class = AddtocartSerializers def perform_create(self,serializer): new_order_item = serializer.save() user=CustomUser.objects.filter(id=self.kwargs['customer_id']).first() try: orders_list = Order.objects.get(user=user) orders_list.items.add(new_order_item) except Order.DoesNotExist: order = Order.objects.create(user=user) order.items.add(new_order_item) def __str__(self): return str(self.user) urls.py: path('customer/<int:customer_id>/addtocart/',views.AddtocartView.as_view(),name='addtocart'), path('customer/<int:customer_id>/cart/',views.CartView.as_view(),name='cart'), Everything working fine. when i am run addtocart api its creating order and check if the order existed then add the orderitem to item and if not create order so my issue is when user make the payment and orderstatus changed to ordered then how i'm gonna fetch ordered item and cart item. so i was thinking i should create order for every orderitem then if order completed so changed the orderstatus to orderd otherwise created.that way i will fetch the created to cart and ordered to orderd page. any suggestion -
How to automatically fill a ModelForm field with a default value obtained from a variable?
I am using ModelForm and i want to populate my dataset_id field with an initial value that will come from the "pid" variable passed in the arguement. I ve tried something and attaching that code but its not working views.py def home(request, pid): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = DelegateForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required p = form.save() # redirect to a new URL: return HttpResponseRedirect('/') # if a GET (or any other method) we'll create a blank form else: # Here I want to pass the value of "pid" to the dataset_id field so that when it renders it is populated with the value in the pid variable form = DelegateForm(initial={'dataset_id': pid}) return render(request, 'add_delegate.html', {'dform': form, 'uid': pid}) forms.py class DelegateForm(forms.Form): dataset_id = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'}), label='Result', max_length=10) name = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'}), label='Your Name', max_length=100) phone_number = forms.CharField(label='Phone Number', max_length=12, min_length=10) template.html {% block content %} {% load static %} <form action="/success/" method="post"> {% csrf_token %} <div class="form-group"> <label>{{ dform.dataset_id.label_tag }}</label> {{ … -
Issue with oAuth in docusign in django python
The issue is while requesting for token, we are getting the "Invalid Grant" error (Response - 400). Please find attached the python code which we are using for the same. We also tried same with postman and getting the same error message. We also added callback url on docusign panel Please see below the code :- import json import requests from django.core.mail import send_mail from django.shortcuts import render, redirect from django.http import HttpResponse, HttpResponseRedirect import base64 from .utils import return_csv_values, np, get_current_day_month, return_csv_values_application from .process_docments import embedded_signing_ceremony_contract, embedded_signing_ceremony_application import pandas as pd from .models import DocumentSigned CLIENT_AUTH_ID = 'my integration id' CLIENT_SECRET_ID = 'my secret id' # Create your views here. def get_access_token(request): base_url = "https://account-d.docusign.com/oauth/auth" auth_url = "{0}?response_type=code&scope=signature click.manage organization_read permission_read dtr.documents.read&client_id={1}&redirect_uri={2}" \ .format(base_url, CLIENT_AUTH_ID, "http://127.0.0.1:8000/auth_login") # print(request.build_absolute_uri()) return HttpResponseRedirect(auth_url) #callback url def auth_login(request): access_code = request.GET['code'] # return HttpResponse(access_code) base_url = "https://account-d.docusign.com/oauth/token" auth_code_string = '{0}:{1}'.format(CLIENT_AUTH_ID, CLIENT_SECRET_ID) print(auth_code_string) auth_token = base64.b64encode(auth_code_string.encode('utf-8')) auth_token = auth_token.decode("utf-8") print(auth_token) req_headers = {"Authorization": "Basic {0}".format(auth_token), "Content-Type": "application/x-www-form-urlencoded"} post_data = {'grant_type': 'authorization_code', 'code': access_code} try: r = requests.post(base_url, data=post_data, headers=req_headers) print(r) return HttpResponse(json.dumps(r)) except Exception as e: print(str(e)) return HttpResponse(str(e)) -
Check for Uniqueness in Multiple Columns in Django
My User Models Contains columns (email and alternate_email). Note: Both are unique fields Requirement is For any user email and alternate_email should be unique, i.e. Let Say UserA registered with (email = a@b.com and alternate_email = b@c.com). Now it should not allow any other user to have (email = b@c.com and alternate_email = a@b.com). Or No other user should have either of a@b.com & b@c.com in email or alternate_email field. There are multiple ways to achieve this Check if email is already there in any of the two columns and register User only if email is not present. Try to insert and handle if it fails because of Integrity check Keep emails in some cache The above solutions does not seem to be efficient. What is the best way to achieve this ? -
APIs for selecting countries and regions
Users have to choose the country depending on the requirements. There are suggestions for "enter your location" and the locations are under this country. Mobile code is automatically selected based on that country. This is my requirement. I did the Country Codes Choice field manually and used the django-phonenumber-field package for the phone number field, but I can't reach the requirement. Are there any APIs for location, countries and mobile code? Can someone help me.? -
Django can't login with valid credentials
Django doesn't login my user. I'm using a Django REST call to do this: class UserLogin(APIView): permission_classes = [] def post(self, request, *args, **kwargs): if request.method == 'POST': user = authenticate( username=request.data.get('email'), password=request.data.get('password') ) print("User de Authenticate -> %s" % user) if user is not None: login(request, user, backend='apps.core.api.backends.EmailAuthBackend') return HttpResponse("Valid") else: return HttpResponse("Invalid") With my custom backend: class EmailAuthBackend(object): def authenticate(self, request, username=None, password=None): """ Authenticate a user based on email address as the user name. """ try: user = User.objects.get(email=username) if bcrypt.checkpw(password.encode('utf-8'), user.password.encode('utf-8')): return user except User.DoesNotExist: try: user = User.objects.get(username=username) if user.check_password(password): return user except User.DoesNotExist: return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None The point is that authenticate returns me the user if the credentials are valid, so the problem is not there. The login function its returning me None! I do a little debug of login with prints, so, here is the django login function: def login(request, user, backend=None): """ Persist a user id and a backend in the request. This way a user doesn't have to reauthenticate on every request. Note that data set during the anonymous session is retained when the user logs in. """ session_auth_hash = '' print("1") … -
Pagination not working for viewsets in django rest_framework. Why?
paginate.py class StandardResultsSetPagination(PageNumberPagination): page_size = 3 page_size_query_param = 'page_size' max_page_size = 5 Serializers.py class AreaUsersSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'first_name', 'areas') Views.py class AreaUsers(viewsets.ViewSet): queryset = User.objects.all() serializer_class = AreaUsersSerializer pagination_class = StandardResultsSetPagination # Not working def list(self, request): queryset = User.objects.all()[:10] serializer = AreaUsersSerializer(queryset, many=True) return Response(serializer.data) I just wanted to know whats wronfg with this code why the pagination is not applying.It shows all the 10 values in the api view -
Django-tables2 - self.request in render
I am trying to change the table view based on the username of requests, but it keeps returning the AttributeError for the table object has no attribute 'request.' I have directly added the request to the table (please refer below for codes), but still not able to get it done. In my table class, I have the "get_top_pinned_data" overridden to fetch the data from the database based on the username. # views.py class ListView(LoginRequiredMixin, ExportMixin, SingleTableView): ... def get_context_data(self, **kwargs): context = super(ListView, self).get_context_data(**kwargs) table = self.get_table(**self.get_table_kwargs()) table.request = self.request # ADDING REQUEST DIRECTLY TO TABLE context[self.context_filter_name] = self.filter context['firstname'] = str(self.request.user.first_name) return context def get_table(self, **kwargs): table_class = self.get_table_class() table = table_class(data=self.get_table_data(), **kwargs) return RequestConfig(self.request, paginate={'per_page':self.paginate_by}).configure( table ) # tables.py class Table(tables.Table): ... def get_top_pinned_data(self): id_list = MODEL.objects.filter(USERNAME=self.request.user.username).values_list('id', flat=True) pinned = MODEL.objects.filter(id__in=id_list) return pinned Can anyone please help me out? -
How to let the user to edit the custom user model details in the user dashboard and update it in the model in django?
I am having edit profile template and I wrote view for letting the user to edit the account but I am not getting the form even I wrote the url and view correctly can you please help me out how to let the user edit user model in the front end my views.py: def edit_profile(request): if request.method == 'POST': form = UserChangeForm(request.POST, instance=request.user) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('modsy:account')) Forms.py: class EditProfileForm(UserChangeForm): template_name='edit_profile' class Meta: model = User fields = ( 'email', 'first_name', 'last_name', 'password' ) else: form = UserChangeForm(instance=request.user) args = {'form': form} return render(request,'edit_profile.html') I am only getting the submit button in editprofile page but form is not coming can you please say what mistake I had did -
What does href="{% url 'profile' %} mean?
I tried to Google my question but ended up with 1000s of pages of Python theory and no straight answer. I have a project called Blog and in it there is a file called base.html. And it contains the line of code <a class="nav-item nav-link" href="{% url 'profile' %}">Home</a>. But in Blogs urls.py file there is no URL pattern called profile. Whereas in my project django_project3, in the urls.py file there is a URL pattern called profile. Does the percentage sign get the code to look in every urls.py file? -
Could not parse the remainder, trying to get the image url for src
Could not parse the remainder: '('latest_change_date')[0].profile_pic.docfile.url' from 'loggedinanon.profileImages.order_by('latest_change_date')[0].profile_pic.docfile.url' in the models .py i have: class Document(models.Model): docfile = models.FileField(default='settings.MEDIA_ROOT/', upload_to='documents/%y/%m/%d') class Profile_image(models.Model): profile_pic = models.OneToOneField(Document, default=None, on_delete=models.CASCADE) latest_change_date = models.DateTimeField(default=timezone.now) In the template: {{ loggedinanon.profileImages.order_by('latest_change_date')[0].profile_pic.docfile.url }} -
Django editing a model instance fails to find the instance
I'm in the process of making a Recipe Book. For some reason, whenever I try to pull up a recipe from the DB to edit it, I keep getting an error where it can't find the recipe I've specified. I'm using slugs, and my logic is that I'm going from a detailView where I've already pulled up the db information, to an updateView. I'm attempting to pass the recipe object I already pulled from the detailView to the updateView, but when I do, it keeps telling me that it can't find the recipe specified. views.py: The base views I'm calling here are only providing a default post method for handling a search so that I don't have to put it in for every view I create so I have some code reusability class RecipeDetailView(BaseDetailView): model = Recipe template_name = 'RecipeBook/recipe_detail.html' context_object_name = 'recipe_view' queryset = None slug_field = 'slug' slug_url_kwarg = 'slug' def get_context_data(self, *args, **kwargs): context = super(RecipeDetailView, self).get_context_data() recipe = self.object recipe.ingredients = recipe.ingredients_list.split('\n') context['recipe'] = recipe return context class RecipeEditView(BaseUpdateView): model = Recipe template_name = 'RecipeBook/edit_recipe.html' context_object_name = 'recipe_edit' queryset = None slug_field = 'slug' slug_url_kwarg = 'slug' form_class = RecipeForm def get_context_data(self, *args, **kwargs): context = … -
Dynamic pre processing before function call in python
I want to monkey patch all functions dynamically when they are loaded in memory in my django project. How is it to be done? -
How to get the ordering of a Django model query set?
view_set.get_queryset().query.order_by will get you the ordering tuple of a ViewSet class in Django REST Framework, but ModelName.objects.get_queryset().query.order_by is always an empty tuple. How come it's not populated? I can see from the database logs that the query is ordered when running ModelName.objects.all(). I've also tried to run the actual query, in case the ordering is populated lazily, but even that does not work: >>> all = ModelName.objects.all() >>> for instance in all: ... True >>> all.query.order_by () -
I have a question about python calculation time difference
I want to set the expiration time for my redis in the Django program, and the time is a variable, that is, the time difference between the current time and 12pm on Sunday. This is a cyclic process. After the expiration, he will query the database for new data and cache it. In redis, the data is valid for this week. Whenever I add it to the cache, I am a python beginner. I need help very much, thanks! -
Add the related objects of User and display them in User model in django admin
I am having two models projects and User in projects the User is related like shown below models.py: class project(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) room = models.ForeignKey(room,on_delete=models.CASCADE) goal = models.ManyToManyField(goal) design = models.ManyToManyField(design) furniture = models.ForeignKey(furniture,on_delete=models.CASCADE) created_at = models.DateTimeField(default=datetime.now) updated_at = models.DateTimeField(default=datetime.now) Now here I want to display the extra column as projects in user page in django admin for every user when I click on that it should take to particular project detail page of that user Screenshots: This is the user list page This is the project list page This is the project detail page admin.py: from django.contrib import admin from .models import project class ProjectAdmin(admin.ModelAdmin): readonly_fields = ('user','room','goal','design','furniture','created_at','updated_at') admin.site.register(project,ProjectAdmin) Please help me out Thanks in advance -
Django admin StackedInline in custom tab
I currently having problem trying to figure out how can i put 3 inline in a single tab on the change view. I currently have the following admin for one of the view as follow: class UserAdminCustom(admin.ModelAdmin): list_display = ('id', 'email', 'status', 'created') verbose_name = "General" exclude = ('password', 'last_login', 'is_superuser', 'is_staff', 'groups', 'user_permissions', 'username', 'first_name', 'last_name', 'is_active', 'date_joined', 'eth_private_key', 'evt_private_key', 'modified') inlines = [ UserKycInline, UserWalletInline, UserBankInline, CardBindingInline, TopUpsInline, TransfersInline, WithdrawalsInline ] def get_queryset(self, request): qs = super(UserAdminCustom, self).get_queryset(request) return qs.filter(is_staff=False) def get_readonly_fields(self, request, obj=None): return ('id', 'created', 'modified') def save_formset(self, request, form, formset, change): instances = formset.save(commit=False) if change: for instance in instances: for single_form in formset: update_fields = [] if single_form.initial['status'] != single_form.cleaned_data['status']: update_fields.append('status') instance.save(update_fields=update_fields) formset.save_m2m() admin.site.register(User, UserAdminCustom) i currently want TopUpsInline, TransfersInline, WithdrawalsInline to all be in 1 tab name transactions . I figure i would use fieldsets but it only work on the user fields and can't be apply to the Inline. Is there anyway i can show 3 inline in 1 custom tab on change view ? -
Im using Class Based View, my problem is when I submit the data It saved with 2 primary key
Im using Class Based View, my problem is when I submit the data It saved with 2 primary key or two data in 1 submit. How Can I fixed this issue in my code? Thanks class VmasterlistCreateView(CreateView): def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) model = VehicleMasterList form_class = Vmasterlist template_name = 'vehicleMasterlist/vehicleMasterlist_form.html' def post(self, request, *args, **kwargs): if request.method == 'POST': reg = '' plate = request.POST.get('PLATE_NO') endplate = int(plate[-1]) if endplate == 1 : reg = 'Jan' elif endplate == 2: reg = 'Feb' elif endplate == 3: reg = 'Mar' elif endplate == 4: reg = 'Apr' elif endplate == 5: reg = 'May' elif endplate == 6: reg = 'Jun' elif endplate == 7: reg = 'Jul' elif endplate == 8: reg = 'Aug' elif endplate == 9: reg = 'Sep' else: reg = 'Oct' saveto_end = VehicleMasterList(PLATE_ENDING=endplate, REGISTRATION_MONTH=reg) saveto_end.save() return super().post(request) -
Is date published a predefined function in Django?
class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') In the above code, how pub_date is getting the exact date? -
How manage on admin a bunch of pdf files?
i have a bunch of pdf files that need to be in different groups, for then later display each group on one template (i am using an accordion ui to separate the groups), some groups of files are like 100 or more pdf files, so any easy way to manage this? come to my mind create collections and manage from there , can i loop the files of a collection on a template? there is other way you folks with experience can recommend me? this is how looks on my design https://imgur.com/a/o6tYl0E would be nice some like a drag and drop, sometimes they send me 300 files and is not fun upload one by one Thanks you. -
Register form always give error " this field is required "
I want to make a register form , that contain user form and user profile form my table user is from django auth_user so it will contain primary column like id, user , email , password , started date etc and i have user profile form , that create from forms.py and the model from model.py here , it has FK user_id which connected to ID in auth_user the problem is ,when i insert the data, it always said this field required, even though ialready insert all the column here's the code forms.py class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control'})) username = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'})) email = forms.CharField(widget=forms.EmailInput(attrs={'class':'form-control'})) class Meta(): model = User fields = ('username','email','password') class UserProfileInfoForm(forms.ModelForm): ROLE_1 = 'Business Analyst' ROLE_2 = 'Manager' ROLE_3 = 'Segment Manager' ROLE_4 = 'Admin' ROLE_CHOICES = ( (ROLE_1, u"Business Analyst"), (ROLE_2, u"Manager"), (ROLE_3, u"Segment Manager"), (ROLE_4, u"Admin") ) role = forms.ChoiceField(choices=ROLE_CHOICES,widget=forms.Select(attrs={'class':'form-control'})) description = forms.CharField(widget=forms.Textarea(attrs={'class':'form-control'})) address = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'})) phone = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'})) cell = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'})) def __init__(self,disable_fields=True, *args, **kwargs): super().__init__(*args,**kwargs) if disable_fields == True: self.fields['role'].disabled = True models.py class UserProfileInfo(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,related_name='profile') role = models.CharField(max_length=250, blank=True) description = models.TextField(max_length=250, blank=True) address = models.CharField(max_length=250, blank=True) phone = models.CharField(max_length=250, blank=True) cell = models.CharField(max_length=250, blank=True) profile_pic = models.ImageField(upload_to='profile_pics',blank=True) def __str__(self): … -
Limiting dropdown options for a ForeignKey fireld in a ModelForm with CreateView
I have a model Port with a foreign key to Device. With my current setup, the form displayed when creating a new Port has a drop-down with all possible devices. Based on the URL, I would like to have the option to limit devices in drop down to just those with os='unix' prepopulate device with one device and disable the device field on the form I would like to keep the option of having the full drop-down list How do I do that? Below is my code: models.py: class Port(models.Model): readonly_fields = ('timestamp', 'created_by') form_fields = ('device', 'field1', 'field2', 'field3') device = ForeignKey(Device, on_delete=models.CASCADE, db_constraint=False) field1 = TextField() field2 = TextField() field3 = TextField() created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) created_at = models.DateTimeField(auto_now_add=True) timestamp = models.DateTimeField(auto_now=True, editable=False) forms.py: from django.forms import ModelForm from .models import Port class PortForm(ModelForm): class Meta: model = Port fields = Port.form_fields exclude = ['created_by'] def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') self.device = kwargs.pop('device', None) super().__init__(*args, **kwargs) views.py: class PortView(CreateView): model = Port template_name = 'port.html' form_class = PortForm def form_valid(self, form): form.instance.created_by = self.request.user return super().form_valid(form) def form_invalid(self, form): form.instance.created_by = self.request.user response = super().form_invalid(form) return response def get_form_kwargs(self, **kwargs): kwargs = super().get_form_kwargs(**kwargs) device_id = … -
Qusetion about Django. my client wants to add additional choices just by the clicking or something. Can i solve this?
In my project, there are many choice fields and I used the code like below : ——————————————————models.py—————————————————— AAA_CHOICES = ( ('choice1', 'choice1'), ('choice2', 'choice2') ) choice_att = models.Choicefield( … choices = AAA_CHOICES) ———————————————————————————————————————————————————————— but my client wants to add additional choices in AAA_CHOICES just by the clicking or something by himself (not by the hardcoding) how can i solve this problem? -
name 'latest_change_date' is not defined, how to order by datetime
in my models py I have: class Profile_image(models.Model): latest_change_date = models.DateTimeField(default=timezone.now) class Anon(models.Model): profileImages = models.ManyToManyField(Profile_image, default=None) in my views py I have images = loggedinanon.profileImages.order_by(latest_change_date) How do I order the images in a predictable way? Can I use an integer field instead?