Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF Get All Fields of OneToOne Model
I'm relatively new to DRF and currently stuck at an issue. After lot of trials I tried looking around but couldn't find something what I want. In case this question has already been answered please do direct me to the original question. Thanks in advance for the help! Problem: I've a profile model that has one to one relation with User model. When I create a new user object the profile object is auto created as expected. I would like to create an API such that when I execute it like api/profile/ in addition to returning the profile model fields it should also return all the fields from User model i.e. first_name, last_name, username, email etc... class Profile(models.Model): rater = models.OneToOneField(User, on_delete=models.CASCADE, related_name='approval') certified = models.ManyToManyField(Protocol, blank=True, default=None, related_name='trained') is_approved = models.BooleanField(default=False) My ProfileSerializer is as follows: class ProfileSerializer(serializers.ModelSerializer): approval = UserSerializer(read_only=True) class Meta: model = Profile fields = '__all__' When I run the API I get the following response: [ { "id": 1, "rater": 3, "certified": [], "is_approved": false } ] How can I get the following response: [ { "id": 1, "rater": 3, "certified": [], "is_approved": false, "first_name": xyz, "last_name": abc, "username": 123, "email": abc@gmail.com, } ] -
How Can I attach a web based cloud server to django website? Which is the best cloud database? [closed]
How Can I attach a web based cloud server to django website? Which could be the best cloud database? I run my web on google cloud and I want to attach a cloud database to it. But How?? -
Django filter based on ForeignKey model field
I am trying to eliminate a field of the Barcode model that is redundant. mostrecentscantime of Barcode is not needed because I can reference mostrecentscan.time. class Scan(models.Model): time=DateTimeField(default=timezone.now) barcode=ForeignKey('Barcode',on_delete=models.CASCADE,related_name='scans') location=ForeignKey(Location,on_delete=models.CASCADE) class Barcode(models.Model): barcode = CharField(max_length=50,unique=True) time_created = DateTimeField(default=timezone.now) mostrecentscan=ForeignKey(Scan,on_delete=models.CASCADE,related_name='+',null=True) mostrecentscantime=DateTimeField() The problem with eliminating mostrecentscantime arises with this query where I am trying to determine all Barcode objects where the time_created and the time of the mostrecentscan is greater than 7 days. Working Query: barcodematches = Barcode.objects.annotate( diff=ExpressionWrapper(F('mostrecentscantime') - F('time_created'), output_field=DurationField()) ).filter(diff__gte=timedelta(days=7)) I cannot simply reference mostrecentscan.time in this context. I have also tried adding an @property field to Barcode which doesn't work either. -
How to know the user is sign-in or not drf-social-oauth2 and reactjs
I set user login system with react-google-login and drf-social-oauth2 At first I post the message like this and check the user is signed in or not. http://localhost:8008/auth/convert-token Then how can I get to see if user is login or not in ReacJS?? I want to show welcome your@mail.com if user log-in class TestPage extends React.Component { render(){ return ( <React.Fragment> <GoogleLogin clientId={googleClientId} isSignedIn={true} buttonText="LOGIN WITH GOOGLE" onSuccess={(response) => handleGoogleLogin(response)} render={(renderProps) => ( <button onClick={renderProps.onClick} disabled={renderProps.disabled} type="button" class="login-with-google-btn" > Sign in with Google </button> )} onFailure={(err) => console.log("Google Login failed", err)} /> <GoogleLogout clientId={googleClientId} buttonText="Logout" onLogoutSuccess={logout} > </GoogleLogout> </React.Fragment> ); } -
Ldap search for extended attributes in python
When running an ldapsearch against active directory, to get the "extended attributes" of an object, we use the "+" operator. For example, ldapsearch -h localhost -p 1389 -D "cn=Directory Manager" \ -w password -b "dc=example,dc=com" "(objectclass=*)" "+" Can someone help me on how I can do the same query(getting the extended attributes) using python code. I am using ldap3 package on my current python code. -
how I add sidebar multi from in django
when I run HTML file look like enter image description here but when I using the Django framework that time it will show enter image description here please tell me what is the problem? and how to solve the problem. -
How to Integrate Web API into a ReactJS Application
I currently have a web application using ReactJS for the front-end, Django for the back-end and MariaDB for the database. Recently, I obtained a SecuGen Hamster Plus fingerprint scanner and I wish to use it for authentication in my web application. I downloaded the Web API code from the SecuGen website and managed to get it running on my localhost. However, I have no idea how to integrate the Web API with my web application so that I can use the fingerprint data for authentication. Could someone help me? -
django: VSCode not recognizing request.POST.get
And in your views.py you can get the use input using the POST method usergivenip = request.POST.get('textfield', None) i did this in my code and i got this error: "module 'django.http.request' has no attribute 'POST'. does this module not exist anymore or did it change? do i need to import something? (other than django.http.request) -
show similar users which's interest tags is similar to other users
I am using Django 3.2 and I am newbie in Django. I am building a similarity app. Like if someone's interest tags (using Tag Field) is similar to other users then show other user in the explore users list. I build a Tag Field which contains interests tags. like :- walking,etc. For Example - user_1 set to "walking, travelling". AND user_2 set to "walking", Then user_2 will be in explore users list of user_1. I am using django taggit field. BUT When i try to show similar users then similar users are not showing. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,default='',unique=True) email = models.EmailField(max_length=60,default='') interests = models.CharField(max_length=2000,default='') views.py def users_list(request,user_id): tags = Tag.objects.filter(profile__interests=user_id).distinct() users = Profile.objects.filter(interests__in=tags).distinct() context = {'users': users} return render(request, 'users_list.html', context) In view i am accessing Tag Model and I am getting all the profiles which are similar in request.user interests tags. BUT the users are not showing. I will really appreciate your Help. Thank You. -
Missing module source
I am a beginner in python, django coding. I just receive a folder that consist of a web made out of django. After i recieve it, I use powershell and go to that folder : pipenv shell pipenv install Django==3.2.5 When i open the codes in visual studio code, I got problems: How do i solve this issue? -
/auth/convert-token requires username in create_user
I have custom user model and my user manager is like this below class UserManager(BaseUserManager): """Define a model manager for User model with no username field.""" use_in_migrations = True def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): """Create and save a regular User with the given email and password.""" extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): """Create and save a SuperUser with the given email and password.""" extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) in settings.py ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_EMAIL_VERIFICATION = 'none' It doesn't require username use email instead. Now I try to set Django rest framework to use oauth (google login) My first test is post the token here to register a user http://localhost:8008/auth/convert-token However there comes error. TypeError at /auth/convert-token create_user() missing 1 required positional argument: 'username' My … -
Django, creating custom order/filter based on value from another Model
I am creating a Reddit clone and currently trying to implement the posts sort functionality. I am stuck on sorting the posts by "most upvotes." I believe I structured my models/database incorrectly and hoping I won't have to redo it because I have my voting system working perfectly. // models.py class Post(models.Model): title = models.CharField(max_length=300) content = models.TextField() date_created = models.DateTimeField(verbose_name="date_created", auto_now_add=True) date_edited = models.DateTimeField(verbose_name="date_edited", auto_now=True) author = models.ForeignKey(User, related_name="posts", on_delete=models.CASCADE) subreddit = models.ForeignKey(Subreddit, on_delete=models.CASCADE) class Meta: constraints = [ models.UniqueConstraint(fields=["title", "subreddit"], name="sameTitle_in_sameSubreddit_notAllowed") ] def __str__(self): return self.title class Vote(models.Model): original_post = models.ForeignKey(Post, related_name="post_votes", on_delete=models.CASCADE, null=True) original_comment = models.ForeignKey(Comment, related_name="comment_votes", on_delete=models.CASCADE, null=True) owner = models.ForeignKey(User, related_name="votes", on_delete=models.CASCADE) vote_choice = models.IntegerField(choices=((1, "UP"), (2, "DOWN"))) class Meta: constraints = [ models.UniqueConstraint(fields=["original_post", "owner"], name="sameOwner_samePost_notAllowed"), models.UniqueConstraint(fields=["original_comment", "owner"], name="sameOwner_sameComment_notAllowed") ] Looking at the "Votes" model, I was able to write a raw SQL query in a view (testing purposes) that sorts the 'original_post' column by the most upvotes and returns it in a list. Is it possible to take the results of this query and apply a custom sorting to the "Post" queryset. So, for example, sort the Posts by 'post_id' but sort the iDs in the same order of the 'most upvotes list.' // … -
How can i calculate the remaining amount of all customer in Django?
I want to calculate the get_remaining_amount for all customers. I am trying to retrieve the get_remaining_amount of all my customers. I don't understand how can i get that amount? models.py class Customer(models.Model): """Customer Model""" name = models.CharField(max_length=255) prop_select = models.ForeignKey(Property, on_delete=models.SET_NULL, null=True) created_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Meta: ordering = ['-created_on'] def get_remaning_amount(self): # Remaining Amount property_price = self.prop_select.price payment_done_by_customer = Payment.objects.filter(customer=self).aggregate(Sum('amount'))['amount__sum'] or Decimal('0') return property_price - payment_done_by_customer -
How do I do exponential or natural log in Django?
I have a formula, say, trustworthy = mt.exp(np.log(age) + wealth**2). I know this is written using numpy and math in Python. Nonetheless, I am not sure how to implement this in Django. What I did was from django.db.models.functions import Power,Ln,Exp trustworthy = Exp(Ln(age) + wealth*wealth) Nonetheless, there was an error and when I print out trustworthy, it became a string: Exp(Ln(Value(55))) + 16 Thanks a lot for helping ! -
Django 'str' object has no attribute 'add'
I am getting this error for below two line: subscriber.email.add(self.cleaned_data.get('email')) subscriber.address.add(self.cleaned_data.get('address')) I am using AbstractUser model and trying to add extra fields by adding new model class. Here is my code: models.py class UserManagement(AbstractUser): is_subscriber = models.BooleanField(default=False) is_blog_author = models.BooleanField(default=False) is_editor = models.BooleanField(default=False) is_customer = models.BooleanField(default=False) class Subscriber(models.Model): user = models.OneToOneField(UserManagement, on_delete=models.CASCADE, primary_key=True) email = models.EmailField(max_length=100) address = models.CharField(max_length=100) froms.py class SubscriberSignUpForm(UserCreationForm): email = forms.EmailField(max_length=100) address = forms.CharField(max_length=100) class Meta(UserCreationForm.Meta): model = UserManagement @transaction.atomic def save(self): user = super().save(commit=False) user.is_subscriber = True user.save() subscriber= Subscriber.objects.create(user=user) subscriber.email.add(self.cleaned_data.get('email')) subscriber.address.add(self.cleaned_data.get('address')) return user views.py class SubscriberSignUpView(CreateView): model = UserManagement form_class = SubscriberSignUpForm template_name = 'registration.html' def get_context_data(self, **kwargs): kwargs['user_type'] = 'subscriber' return super().get_context_data(**kwargs) def form_valid(self, form): user = form.save() login(self.request, user) return redirect('blog:my-account') console error: File "P:\django\django\farhyn\members\forms.py", line 21, in save subscriber.email.add(self.cleaned_data.get('email')) AttributeError: 'str' object has no attribute 'add' [27/Jul/2021 08:29:31] "POST /subscriber-signup/ HTTP/1.1" 500 99927 -
Python and Django - assigning fields in dict instead of overwriting?
I'm using a Python dict to map strings to Django fields. I want to update, or assign the value of the fields as so. self.sheet_headers_2_fields = { 'Index': self.index, 'Device Model': self.model, 'MAC address': self.mac_address, 'IP Address': self.ip_address, } for sheet_header, model_field in self.sheet_headers_2_fields.items(): model_field = item.get_field_value(sheet_header) I'm using the dict to make it easier to map strings to fields should more fields be added. Currently, this just overwrites model_field, instead of assigning it to the corresponding field, and thus, the model is not updated. Why does this not work? I know that Python passes by reference - my guess is that because model_field (A django field) is not the same type a item.get_field_value(sheet_header) (a str), it overwrites to a reference instead of updating the value. How can I achieve what I want, either with a dict, or some other method? -
Custom template filter and query
I'm attempting to get all active employees using a template filter, but I'm not having much luck. I was wondering if you might know why. models.py class Employee(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) active = models.BooleanField(default=False) My template filter is as follows: @register.filter def active_employees(model_instances): return model_instances.filter(active=False) template.html {% if request.user.employee.all|active_employees|length > 0 %} There is an active employee {% endif %} The error I get is as follows: Invalid filter: 'actual_employees' -
Update a Queryset in Django instead of For loop
I am trying to update a queryset, I would like to calculate a Field order class Temporal(model.Models): name=models.CharField(max_length=60) created_at = models.DateTimeField(auto_now_add=True) order = models.IntegerField(null=True, blank=True) in my app it is important to order_by created_at, and then assing a order as index, everytime a new object is created assing value cero and the rest of the objects the need to be plus +1, but I would like to do using queryset instead of using a for loop : items = Temporal.objects.all().order_by('-created_at') for index, item enumerate(items): item.order=index + 1 item.save() assuming thousands of items on the database this would be very slow... thanks in advance -
Deploy Django + React.js on Heroku
i'm currently deploying django with react in Heroku. But there is an issue when the deployment success, there is no "frontend" from react.js When i'm access the webpage in link below, It's just display an error page not found. I want to display component of React.js in the website https://mmuqiitf-react-django.herokuapp.com/ This is my folder structure : /backend /build /node_modules /public /src /staticfiles /todo .gitignore Aptfile db.slite3 manage.py package.json Procfile requirements.txt runtime.txt And this is my settings.py code : from pathlib import Path from django.conf import settings import django_heroku import os BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'secret' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'rest_framework', 'todo' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' ROOT_URLCONF = 'backend.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'build')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'backend.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { … -
Searchable Dropdown in Website - Django - Saving to data base
I am building a website and part of it involves a drop-down which is easily called in the HTML by {{ form.inspection_type }}. This is a pretty big drop-down and a pain to scroll all the way to what you need to select so I have been trying for the past few days to implement a searchable drop-down to replace it. I have tried every single library I would find on searchable drop-downs and non have worked with the specifics of my project. I have reverted to doing it through HTML and have again gone through about 40 different examples and iterations and have gotten close. The NEW code is a searchable drop-down that is populated with my Django database drop-down. However when I click submit it shows that no data was added to the list view that I have. Below is the old code that worked and didn't have a searchable drop-down and also I have added the new code that has the searchable drop-down but won't submit the data through. Let me know if I missed anything and you have any questions. Thanks! OLD - works but no searchable drop-down <form method="post" action=""> {{ form.inspection_type }} <input class="btn … -
Is it possible to control the visibility of a Featuregroup in folium with a html checkbox?
I'm working on a project in Django were I want to show layers on a map by checking or unchecking boxes which I created using bootstrap. I am aware it is possible to use LayerControl to get these boxes, but I would like to use the boxes I created. Is this possible in Folium? This is my views.py in Django. def third_view(request): m = folium.Map(width='100%', height='90%', crs='Simple', tiles=None) base_map = folium.FeatureGroup(name='Basemap', overlay=True) image= 'static/images/stitched_map.png' bounds=[[0, 0], [750, 750]] overlay = folium.raster_layers.ImageOverlay(image, bounds).add_to(base_map) base_map.add_to(m) html = 'Here lies Balin, son of Fundin' iframe = folium.IFrame(html) popup = folium.Popup(iframe, min_width=200, max_width=200) layer1 = folium.FeatureGroup(name='layer1', overlay=False) folium.Marker([350, 350], icon=icon_circle, tooltip='TA 1267', popup=popup).add_to(layer1) layer1.add_to(m) m.fit_bounds(bounds) m = m._repr_html_() context = { 'map': m, } return render(request, 'third.html', context) This is my html page/checkbox which I want to link it to: <div class="row"> <div class="col-sm-10"> {{ map|safe }} </div> <div class="col-sm-2"> <h3><span style="color: #e8c4b4;">Places</span></h3> <div class="form-check"> <input type="checkbox" class="form-check-input" id="exampleCheck1"> <label class="form-check-label" for="exampleCheck1">Cities</label> </div> <div class="form-check"> <input type="checkbox" class="form-check-input" id="exampleCheck1"> <label class="form-check-label" for="exampleCheck1">Points of Interest</label> </div> <h3><span style="color: #e8c4b4;">Travels</span></h3> <div class="form-check"> <input type="checkbox" class="form-check-input" id="exampleCheck1"> <label class="form-check-label" for="exampleCheck1">Frodo</label> </div> </div> </div> This is the not yet working webpage -
get related model set in template
I've got a a model that is related to the User model class Employee(models.Model): user = models.ForeignKey(User, related_name='actual_user', on_delete=models.CASCADE, null=True, blank=True) employee_user = models.ForeignKey(User, related_name='employee', on_delete=models.CASCADE, null=True, blank=True) Within my template, i'd like to get all instances of Employee where employee_user matches the current user who is logged in. {% for employee in request.user.employee_set.all %} This is an employee. {% endfor %} This doesn't seem to be working. I was wondering if you might know why. Thanks! -
How to build the 404 page in Django
I'm making a blog in Django, and I've to add the 404 page i need to know how to add the not found error page 404 in Django If there's any easier way just by making the 404 html page and show in views really without complications Thanks a lot -
How to render a page based on the button clicked on another page django
I have a page like that {% for product in products %} <div class="col-lg-4"> <img alt="" class="thumbnail" src="{{ product.images.all.0.image.url }}"> <div class="box-element product"> <h5><strong>{{ product.name }}</strong></h5> <hr> <button data-product="{{ product.id }}" data-action="add" class="btn btn-outline-secondary add-btn update-cart">Add to Cart</button> <a data-product="{{ product.id }}" data-action="Save" class="btn btn-outline-secondary detail" href="{% url 'detail' %}"> Detail</a> ..... and when the user click on Detail, it should go to another page to display the details of the product based on which detail button he clicked on so I made detail.js file like that var detailBtns = document.getElementsByClassName("detail") //get all add to cart button with class update-cart for (i = 0; i < detailBtns.length; i++) { detailBtns[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action console.log('productId:', productId ) console.log(current_user) GetDetail(productId, action) // this function will be called and will pass product id and action in body to your view for further processing. }) } function GetDetail(productId, action){ console.log("func") var url = '/detail/' fetch(url, { method: 'POST', headers:{ 'content-Type':'application/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({"productId": productId, "action": action}) }) .then((response) =>{ return response.json() }) .then((data) =>{ console.log('data:',data) location.reload() }) } and in the views there's a function that is connected to the URL detail/ def detail(request): data = json.loads(request.body) productId … -
allauth replace username field with custom one
I'm using allauth I want the user to login with user id instead of username field. when I try to set the setting.py for it settings.py: USERNAME_FIELD = None ACCOUNT_AUTHENTICATION_METHOD = 'user_id' ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_USERNAME_REQUIRED = False it gives me this error AssertionError at /accounts/login/ No exception message supplied Its possible to have both user id and username but I want to login with only user id forms.py: class CustomLoginForm(LoginForm): user_id = forms.IntegerField(required= True, validators=[ MinValueValidator(10_000_000_00), MaxValueValidator(99_999_999_99) ], label='User ID') class Meta: model = MyUser fields = ('user_id',) exclude = ('username',) def login(self, request, user): user.user_id = self.cleaned_data['user_id'] user.save() return user, super(CustomLoginForm, self).login