Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do i add custom fields to UserManager in Django
I am trying to create a user profile, i followed through a tutorial which has registration for only username, email and password but i want to be able to add other custom fields. What i did: Models.py: class UserManager(BaseUserManager): def create_user(self, username, email, password=None,): if username is None: raise TypeError('User should have a userame') if email is None: raise TypeError('Users should have a Email') user = self.model(username=username , email = self.normalize_email(email)) user.set_password(password) user.save() return user def create_superuser(self, username, email, password=None): if password is None: raise TypeError('User should have a password') user=self.create_user(username,email,password) user.is_superuser = True user.is_staff = True user.save() return user class User(models.Model): dso = models.ForeignKey(Dso,related_name='dso',default=NULL,blank=False,on_delete=models.CASCADE) name = models.CharField(max_length=70, blank=False, default='') email = models.EmailField(max_length=70, blank=False, default='') password = models.CharField(max_length=70, blank=False, default='') address = models.CharField(max_length=70, blank=False, default='') roleId = models.IntegerField(blank=False, default='1') isActive = models.BooleanField(blank=False, default=True) customerId = models.CharField(max_length=70, blank=False, default='') dateJoined = models.DateTimeField(auto_now_add=False, blank=False, default=NULL) @property def energy_data(self): energydata = EnergyData.objects.filter(customerId=self.customerId).first() return energydata Serializers.py: class RegisterSerializer(serializers.ModelSerializer): password = serializers.CharField(max_length = 68, min_length=6, write_only = True) class Meta: model=User fields=['email','username','password','name','address','customerId', 'dso', 'roleId'] def validate(self, attrs): email = attrs.get('email', '') username = attrs.get('username', '') if not len(username) >= 4: raise serializers.ValidationError('Username must be morethan 4 letters or characters') return attrs def create(self, validated_data): return … -
How to access token after signin with google dj_rest_auth
When I visit this url https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=<CALLBACK_URL_YOU_SET_ON_GOOGLE>&prompt=consent&response_type=token&client_id=&scope=openid%20email%20profile it redirect to me http://127.0.0.1:8000/accounts/google/login/callback/#access_token=tokonkey&token_type=Bearer&expires_in=3599&scope=email%20profile%20https://www.googleapis.com/auth/userinfo.profile%20openid%20https://www.googleapis.com/auth/userinfo.email&authuser=0&prompt=consent in response I got "success" But I want to get access_token that shown in url,just like { "token":tokenkey } can someone tell me how to do that? And my code look likes In urls.py from users.views import GoogleLogin,GoogleRedirect path('auth/google/', GoogleLogin.as_view(), name='google_login'), path('accounts/google/login/callback/', GoogleRedirect.as_view()) in views.y class GoogleLogin(SocialLoginView): adapter_class = GoogleOAuth2Adapter client_class = OAuth2Client class GoogleRedirect(APIView): def get(self, request): return Response("success") ''' -
Expo React native fetch requests twice
import React, { useState } from 'react'; import { Text, View, StyleSheet, Image } from 'react-native'; import Constants from 'expo-constants'; // You can import from local files import AssetExample from './components/AssetExample'; // or any pure javascript modules available in npm import { Card } from 'react-native-paper'; import * as FileSystem from 'expo-file-system'; export default function App() { let data = new FormData(); let url="https://uploadfilesserver.eugenevolkov.repl.co/upload" data.append("content",{type:'image/jpeg', uri:'https://snack-code-uploads.s3.us-west-1.amazonaws.com/~asset/201a148e3d40baa81d8ef06e316b5ca2', name:'ball.jpg'} ) function upload(){ fetch(url, { method: "post", headers: { "Content-Type": "multipart/form-data", }, body: data, }) .then(res => {res.json() // console.log('res',res) } ) .then(final => { console.log( "Success")} ) // .catch(err => { // console.error("error uploading images: ", err); // }); } upload() return ( Image to upload <Image source={require('./ball_1.jpg')}/> ); } i am new to react native. The fecth always results in two uploads (two POST reqests). There is no OPTIONS request. In the backend (Django) upload folder there are always 2 'ball.jpg' files. The same issue happens after building app. -
Django pre-save function not removing group and users permissions from user model in django signal
I am trying to write a signal function as below: def on_user_deactivation(sender, instance, **kwargs): if not instance.is_active: instance.team_set.clear() instance.groups.clear() instance.user_permissions.clear() ``` -
Can I use Django to make non-web python apps as a data scientist?
I'm a data scientist, and I make apps using python. Where I make a lot of connections with databases, build and deploy my code on the cloud and I use models training and visualization. My question is: Is Django useful for making non-web apps? if not are they any other frameworks? (similar to spring-boot for java) Best regards -
UnicodeDecodeError - Django Upload file
I'm using Django Rest Framework, and with a simple form on the frontend I upload some data, and attachments to a model in Django. I store the files at AWS S3, and I'm using Django S3 Storage. When I upload a file I get an UnicodeDecodeError as follows. (See bottom for trace) My file model class JourAttachment(models.Model): jourreport = models.ForeignKey(JourReport,related_name="jourattachments", on_delete=models.CASCADE) file = models.FileField(null=False) View class JourReportListView(APIView): serializer_class = JourReportListSerializer permission_classes = (IsAuthenticated, ) parser_classes = (MultiPartParser,) def post(self,request,*args, **kwargs): user_making_request = request.user if not user_is_admin(user_making_request): return UserNotAdminResponse() attachments = request.FILES.getlist('attachment', None) serializer = JourReportCreateUpdateSerializer(data=request.data,partial=True,context={'attachments': attachments}) valid = serializer.is_valid(raise_exception=True) if valid: report = serializer.save() status_code = status.HTTP_201_CREATED #send_mail_with_jourreport(report) return SuccessfulResponse(data=request.data, message="Jour report successfully registered!" ,status_code=status_code) return ErrorResponse() Serializer class JourReportCreateUpdateSerializer(serializers.ModelSerializer): class Meta: model = JourReport fields = ('apartment_number', 'address', 'tenant_name','tenant_phone', 'debit_tenant','worker','total_hours', 'additional_workers','defect_description','actions_made','actions_to_be_made') def create(self, validated_data): users = [] attachments = self.context['attachments'] if "additional_workers" in validated_data: users = [w.id for w in validated_data["additional_workers"]] del validated_data["additional_workers"] report = JourReport.objects.create(**validated_data) for a in attachments: JourAttachment.objects.create(file=a,jourreport=report) # Add attachments to instance if(len(users) > 0): report.additional_workers.add(*users) return report The model is correctly added and all files are stored, but either way I get an 500 response with UnicodeDecodeError Trace Traceback (most recent call last): File … -
Django sterilizer update method validated_data convertion
I am trying to update an instance of my model via the serializer update method. This modal have many to many connection to another model. my models: class GPX(models.Model): name = models.CharField(max_length=255) created_date = models.DateField(auto_now_add=True) updated_date = models.DateField(auto_now=True) trail_types = models.ManyToManyField(TrailTypes, blank=True) class TrailTypes(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name I want to get has input a list contain trail_types names instead of their ids. The problem is that Django converts the data objects of trail_types and then pass it as validate_data to the update method under the seralizer. How can I do the conversion before? or is there another way to specify to Django to create trail_type objects by its name. @transaction.atomic def update(self, instance, validated_data): gpx: GPX = super().update(instance, validated_data) return gpx thanks in advanced -
How can I customize drf-yasg endpoints's example response?
on my Django project, I'm using DRF and drf-yasg. At some endpoint, the example response body shows the incorrect example. like the following example: But some of them don't show the correct example response body. This endpoint actually returns access_token and refresh_token, doesn't return the email and password. It's wrong information for the front-end devs. Is there any way to change this? -
Django registration & authentication via def
Pls help me with my problem. I need register user with some additional fields (phone, adress). Form without username field. Auth throut email. Prefer using def. I add model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone = models.IntegerField('phone ', null=True, blank=True) country = models.CharField('country ', max_length=100, null=True, blank=True) city = models.CharField('city ', max_length=100, null=True, blank=True) adress = models.CharField('adress', max_length=300, null=True, blank=True) zip_code = models.IntegerField('zip_code', null=True, blank=True) birth_day = models.DateField('birth_day', null=True, blank=True) avatar = models.ImageField('avatar', upload_to='avatar', null=True, blank=True) agreement = models.BooleanField('agreement', default=True) comment = models.TextField('comment', max_length=3000, null=True, blank=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() def admin_display(self): return self.user.last_name + ' ' + self.user.first_name And add two forms: class ProfileForm(forms.ModelForm): class Meta: model = Profile exclude = ('comment', 'register_date', 'avatar', 'password', ) widgets = { 'phone': forms.NumberInput(attrs={'placeholder': '9XXXXXXXXX', 'class': 'form-control', 'id': 'phone'}), 'country': forms.TextInput(attrs={'placeholder': 'Россия', 'class': 'form-control', 'id': 'country'}), 'city': forms.TextInput(attrs={'placeholder': 'Москва', 'class': 'form-control', 'id': 'city'}), 'adress': forms.TextInput(attrs={'placeholder': 'Ленина 25', 'class': 'form-control', 'id': 'adress'}), 'zip_code': forms.TextInput(attrs={'placeholder': '101000', 'class': 'form-control', 'id': 'zip_code'}), 'agreement': forms.CheckboxInput(attrs={'class': 'form-check-input', 'id': 'flexSwitchCheckChecked'}), 'birth_day': DateInput(attrs={'class': 'form-control', 'id': 'birth_day'}), } class UserForm(forms.ModelForm): class Meta: model = User fields = '__all__' widgets = { 'first_name': forms.TextInput(attrs={'placeholder': 'Иван', 'class': 'form-control', 'id': … -
Django model validation in clean or in separate validators?
I am pretty new to Django and I was wondering what is the best method to validate your models in Django? Are there any advantages to using clean vs adding validators to your models? By validators I mean when you do declare the field, populating the validator=[] list. I find the models to be easier to read with the validators in another package, and declared in the field list. Also, I try to validate the data before in services, before initializing the models. What do you think / prefer? Thanks a lot. -
Can't render django template to pdf: UnsupportedMediaPathException
I have a Django template rendered by a DetailView, I want to turn that template to PDF using a different view and this library: django-easy-pdf My view: class ServizioPDFView(PDFTemplateView): template_name = 'hub/anteprima.html' base_url = 'file://' + settings.MEDIA_ROOT download_filename = 'anteprima.pdf' def get_context_data(self, **kwargs): ctx = super(ServizioPDFView, self).get_context_data( pagesize='A4', title='Anteprima Offerta', **kwargs ) r = self.request.user.referente ctx['referente'] = r ctx['hub'] = r.hub ctx['servizio'] = Servizio.objects.get(pk=self.kwargs.get('pk')) return ctx My Urls path('servizi_offerti-pdf/<int:pk>', ServizioPDFView.as_view(), name='servizio-detail-pdf'), I get the error: UnsupportedMediaPathException at /servizi_offerti-pdf/7 media urls must start with media_root/ or /static/ I followed the usage tutorial of the library and tinkered with static and media root in my settings.py but without success. Any help is greatly appreciated. -
module 'django.http.request' has no attribute 'session'
I created a class to generate a token when the user logs in. I would like to create a session when the user logs in. Here is the error I am getting: "module 'django.http.request' has no attribute 'session'" Thank you for helping me. Voici l'extrait de mon code. class TokenObtainLifetimeSerializer(TokenObtainPairSerializer): permission_classes = (permissions.AllowAny,) authentication_class = [CsrfExemptSessionAuthentication] def validate(self, attrs): loginInfo = [] # loginInfo[0] -> identifiant ||| loginInfo[1] -> password data = super().validate(attrs) for values in attrs.values(): loginInfo.append(values) if data : user = auth.authenticate(request, identifiant=loginInfo[0], password=loginInfo[1]) auth.login(request, user) refresh = self.get_token(self.user) data['lifetime'] = int(refresh.access_token.lifetime.total_seconds()) return data class CustomTokenObtainPairView(TokenViewBase): serializer_class = TokenObtainLifetimeSerializer -
Duration matching query does not exist
Traceback (most recent call last): File "/home/ahmed/SavannahX/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/ahmed/SavannahX/venv/lib/python3.9/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ahmed/SavannahX/venv/lib/python3.9/site-packages/django/contrib/auth/decorators.py", line 23, in _wrapped_view return view_func(request, *args, **kwargs) File "/home/ahmed/SavannahX/app/views.py", line 1352, in yearly_subscription_plans duration = Duration.objects.get(name="yearly") File "/home/ahmed/SavannahX/venv/lib/python3.9/site-packages/``` django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/ahmed/SavannahX/venv/lib/python3.9/site-packages/django/db/models/query.py", line 496, in get raise self.model.DoesNotExist( Exception Type: DoesNotExist at /yearly/subscriptions/ Exception Value: Duration matching query does not exist. -
Dynamic data not getting extended
I making a shopping website and I am using extend tag of html to extend a table into another page. Below is the table in shoppingpage.html enter image description here When I click on any of the categories(blue in color in the image above), only 'Our Products' comes and without the remaining table enter image description here Below are the codes that I have tried shoppingpage.html <body> <h1>Hello, welcome to shopping page!</h1> <ul> <a class="lynessa-menu-item-title" title="Our Products" href="/allproducts">Our Products</a> <div class="submenu megamenu megamenu-shop"> <div class="row"> {% for result in category %} <div class="col-md-3"> <div class="lynessa-listitem style-01"> <div class="listitem-inner"> <a href="{% url 'polls:category' result.id %}" target="_self"> <h4 class="title">{{result.category_name}}</h4> </a> {% for ans in result.subcategories_set.all %} <ul class="listitem-list"> <li> <a href="{% url 'polls:subcategory' ans.id %}" target="_self">{{ans.sub_categories_name}}</a> </li> </ul> {% endfor %} </div> </div> </div> {% endfor %} </div> </div> </ul> {% block content %}{% endblock %} </body> category.html {% extends "polls/shoppingpage.html" %} <h1>Hello,to categorybase world!</h1> {% block content %} <ul class="row products columns-3" id="appendproducts"> {% for product in products %} <li class="product-item wow fadeInUp product-item rows-space-30 col-bg-4 col-xl-4 col-lg-6 col-md-6 col-sm-6 col-ts-6 style-01 post-24 product type-product status-publish has-post-thumbnail product_cat-chair product_cat-table product_cat-new-arrivals product_tag-light product_tag-hat product_tag-sock first instock featured shipping-taxable purchasable product-type-variable has-default-attributes" data-wow-duration="1s" … -
Django filter data from multidabases
This is my first time using multidabases in django, and I encounter a problem when filtering data from many to many fields. Table1: class table1(models.Model): field1 = = models.ManyToManyField(blank=True, related_name='field',related_query_name='details', to=table2, verbose_name='field1') Table2: class table2(models.Model): multiple_fields = models.BooleanField(default=False) status = = models.ForeignKey(status, on_delete=models.PROTECT) data_type = models.ForeignKey(Type, on_delete=models.PROTECT) Table3: class table3(models.Model): field_rep_id = models.IntegerField() field_id = models.IntegerField() Id field_rep_id field_id 1 3 200 1 3 210 Then this is how I filter, field_details = table1.objects.using('default').get(pk=3) fields = field_details.field1 In table3 I dont have direct access on this so I call like above, the code is working when I use only One database but in Multidatabase I dont know what is the process so I got this error. django.db.utils.ProgrammingError: relation "app1_table3" does not exist LINE 1: ...updated_at" FROM "app2_table2" INNER JOIN "app1_table3... Expected Output: [200,210] -
The number of rows after narrowing-down
This is my serializer. class MixSerializer(serializers.ModelSerializer): pub_date = serializers.DateTimeField(format="%m/%d/%Y,%I:%M:%S %p") new_order = #I want to get the number order class Meta: model = Mix fields = ('id','pub_date','detail','user','u_key') And I narrowing-down the rows like this below. def get_queryset(self): queryset = Mix.objects.all() u_key = self.request.query_params.get('u_key') if u_key is not None: queryset = queryset.filter(u_key=u_key) return queryset For example, it returns the 30 items from 100 items. so id should be (1,4,5,6,9,11,13...) like this, However I want to get the number new_order (1,2,3,4,5,6,....) I guess I should do some trick in Serializer? or any other way ? Any help appreciated. -
setAttribute also also setting the value for the following element
I'm pretty sure this one is silly but I can't seem to figure it out myself. This is a Django website containing a little bit of Javascript. In my HTML, I have a button that should send a few values to a Javascript function. The javascript function should then find and update some divs in the HTML. The strange thing is that the value assigned to the setAttribute statement is automatically also used for the following innerHTML statement (overruling whatever was configured there). HTML Button: <button class="btn btn-outline-dark" onclick="monthStats( {{simple_total_monthly_sent_volume}}, {{average_monthly_delivery_rate}}, {{average_monthly_unique_open_rate}}, {{total_monthly_unique_open_volume}}, {{average_monthly_unique_click_rate}}, {{average_monthly_rejection_rate}}, )">Month</button> Javascript: function monthStats (sentvolume, deliveryrate, uniqueopenrate, uniqueopenvolume, uniqueclickrate, rejectionrate ) { document.getElementById("sent").innerHTML = (sentvolume).toLocaleString("en-US"); document.getElementById("delivered").innerHTML = deliveryrate+"%"; document.getElementById("uniqueopened").innerHTML = uniqueopenrate+"%"; document.getElementById("uniqueopened").setAttribute("title", uniqueopenvolume.toString()); document.getElementById("uniqueclicked").innerHTML = uniqueclickrate+"%"; document.getElementById("rejected").innerHTML = rejectionrate+"%"; } HTML divs that should get updated: <div class="container"> <div class="row"> <div class="col"> <div id="sent" class="keymetric">{{simple_total_monthly_sent_volume|intcomma}}</div><div class="text-muted keymetricexplanation">sent volume</div> </div> <div class="col"> <div id="delivered" class="keymetric">{{average_monthly_delivery_rate}}%</div><div class="text-muted keymetricexplanation">delivery rate</div> </div> <div class="col"> <div id="uniqueopened" class="keymetric" data-bs-toggle="tooltip" data-bs-placement="top" title="{{total_monthly_unique_open_volume|intcomma}}">{{average_monthly_unique_open_rate}}%</div><div class="text-muted keymetricexplanation">unique open rate</div> </div> <div class="col"> <div id="uniqueclicked" class="keymetric">{{average_monthly_unique_click_rate}}%</div><div class="text-muted keymetricexplanation">unique click rate</div> </div> <div class="col"> <div id="rejected" class="keymetric">{{average_monthly_rejection_rate}}%</div><div class="text-muted keymetricexplanation">rejection rate</div> </div> </div> </div> Clicking on the Month button in the HTML results in the title and … -
safe tag in django template
hi i have a blog and i'm using latest ckeditor . i configed and tested my ckeditor but it does not show correctly! why {{post.body|safe}} not working ??? -
How to create messages if condition is True in django?
I am working on authentication webapp and I want to display message if user input doesn't match some conditions. It should look something like this. For example: if password has length less than 8 characters then display message 'Password should be longer than 8 characters!' My view: def signup(request): if request.method == "POST": context = {'has_error': False, 'data': request.POST, 'length_error': False, 'password_match_error': False, 'validate_email_error': False, } global password global password2 global email global username email = request.POST.get('email') username = request.POST.get('username') password = request.POST.get('password') password2 = request.POST.get('password2') if len(password) < 8: ############custom message context['length_error'] = True if password != password2: ############custom message context['password_match_error'] = True if not validate_email(email): ############custom message context['validate_email_error'] = True if not username: ############custom message context['has_error'] = True if models.CustomUser.objects.filter(email=email).exists(): messages.add_message(request, messages.ERROR, 'This email is already registered!') context['has_error'] = True return render(request, 'authentication/signup.html', context, status=409) if context['has_error']: return render(request, 'authentication/signup.html', context) body = render_to_string('authentication/email/email_body.html', { 'username': username, 'token': token, }) send_mail( "Email Confirmation", body, 'tadejtilinger@gmail.com', [email] ) return redirect('email-confirmation') return render(request, 'authentication/signup.html') My signup.html {% include "_base.html" %} {% load static %} {% block title %}Sign Up{% endblock title %} {% block content %} <link rel="stylesheet" href="{% static 'css/authentication/signup.css' %}"> <div class="container"> <form class="signup_form" method="post" action="{% url 'signup' … -
external network for django Webpage
I have a project in Django and it is running on my local machine, I got to make the setting by putting: Allowedhosts = ["*"] and python manage.py runserver 0.0.0.0:8000 This is enough so that I can access the page through another machine on the same network, but I would like to know a way to make access available through an external network, the question is, how do I do it ?? -
How to fetch with multiple query parameters Genereic API view
so I am building an API and i want to fetch based on multiple parameters. Here is the code base. The Url path: path('<str:order_id>/consumers/<int:user_id>/', SingleConsumerTradeAPIView.as_view(), name="single-consumer-trade" ), path('<str:order_id>/producers/<int:user_id>/', SingleProducerTradeAPIView.as_view(), name="single-producer-trade" ), Models.py: from django.db import models from authApi.models import User class Order(models.Model): user = models.ForeignKey(User,related_name='user',null=True, on_delete=models.CASCADE) date = models.DateField(auto_now_add=True) class Trade(models.Model): consumer = models.ForeignKey(User,related_name='consumer',on_delete=models.CASCADE) producer = models.ForeignKey(User,related_name='producer',on_delete=models.CASCADE) order = models.ForeignKey(Order, related_name='trades',on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, max_length=255, decimal_places=2) location = models.CharField(max_length=255) energyQuantity = models.DecimalField(max_digits=10, max_length=255, decimal_places=2) startTime = models.DateField(auto_now_add=True) stopTime = models.DateField(auto_now_add=True) Serializers.py: class TradeSerializer(serializers.ModelSerializer): class Meta: model = Trade fields = ('id', 'order_id', 'startTime', 'stopTime', 'price', 'consumer_id', 'producer_id', 'location', 'energyQuantity', ) class OrderSerializer(serializers.ModelSerializer): trades = TradeSerializer(read_only=True, many= True) class Meta: model = Order fields = ('id', 'trades', 'date', ) What i tried: Views class SingleConsumerTradeAPIView(ListCreateAPIView): serializer_class=TradeSerializer queryset = Trade.objects.all() permission_classes = (permissions.IsAuthenticated,) lookup_fields = ('order_id', 'producer_id') def get_queryset(self): return self.queryset.filter(order_id=self.request.user,producer_id= self.request.user) I want to be able to fetch from the list of trades(via the trade model and serializers) using the order_id and the producer_id. -
Runtime Foreign Key vs Integerfield
I have a problem. I already have two solution for my problem, but i was wondering which of those is the faster solution. I guess that the second solution is not only more convienient- to use but also faster, but i want to be sure, so thats the reason why im asking. My problem is i want to group multiple rows together. The group won't hold any meta data. So im only interested in runtime. On the one hand i can use a Integer field and filter it later on when i need to get all entries that belong to the group. I guess runtime of O(n). The second solution and probably the more practicle way would be to create a foreign key to another model only using the pk there. Then i can use the reverse relation to find all the entries that belong to the group. -
Alert Message Not Rendering In Django
I am trying to create message before submitting the page, but i do not know why the message not rendering , can anyone help me to correct it. form.py class NameForm(forms.ModelForm): translated_names = TranslationField() class Meta: fields = "__all__" model = models.Name admin.py class NameAdmin(MasterDataBaseAdmin): form = forms.NameForm inlines = [AddressInline, RegistrationTypeInline] queryset = models.Name.objects.prefetch_related( "names", "name__id", "registrationstype") views.py class NameViewSet(viewsets.ReadOnlyModelViewSet): queryset = models.Name.objects.supported().prefetch_related("names", "registrationstype") serializer_class = serializers.NameSerializer def nametype(request): form = Form(request.POST) if form.is_valid(): return render(request, 'templates\ view2.html', form) view2.html {% extends "admin/base_site.html" %} {% load l10n %} <form action="" method="post">{% csrf_token %} <div> {% for obj in queryset %} <input type="hidden" name="{{ action_checkbox_name }}" value="{{ obj.pk|unlocalize }}" /> {% endfor %} <input type="hidden" name="post" value="yes" /> <input type="hidden" name="action" value="my_action" /> <input type="submit" value="Submit" /> </div> </form> -
Django & Migrate Error: I can't migrate my project
I was trying to run a Django project which I got from someone else. But I can't do the migration. I came from a mobile app development background. So I'm quite new to this backend thing including Django. Please have a look and help with this issue. Thank you Traceback (most recent call last): File "/Users/punreachrany/Desktop/MyProject/manage.py", line 22, in <module> main() File "/Users/punreachrany/Desktop/MyProject/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/punreachrany/opt/anaconda3/lib/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/Users/punreachrany/opt/anaconda3/lib/python3.9/site-packages/django/core/management/__init__.py", line 420, in execute django.setup() File "/Users/punreachrany/opt/anaconda3/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/punreachrany/opt/anaconda3/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Users/punreachrany/opt/anaconda3/lib/python3.9/site-packages/django/apps/config.py", line 228, in create import_module(entry) File "/Users/punreachrany/opt/anaconda3/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'bootstrap4' -
How to define models in django that provides custom values based on pre-selection for a field?
Given the following model that stores the user's wish list for reading books: class ReadingList(models.Model): user_id = models.ForeignKey(UserInfo, on_delete=models.DO_NOTHING, null=False, blank=False, default=None, db_column='user_id') book= models.CharField(max_length=255, blank=False) creation_time = models.DateTimeField(blank=True) class Meta: unique_together = (('user_id', book),) I want to create a model that helps in tracking the time spent in the reading the book on different days which looks something like this: class ReadingTracker(models.Model): user_id = models.ForeignKey(ReadingList, on_delete=models.DO_NOTHING, related_name='user', blank=False, db_column='user_id') book= models.ForeignKey(ReadingList, on_delete=models.DO_NOTHING, related_name='book-to-read', blank=False, db_column='book') time = models.DateTimeField(blank=True) time_spent = models.floatfield() On the client-side (corresponding to ReadingTracker) for both the fields user_id and book I see that ReadingList object (1), ReadingList object (2), ... are listed. But, this is not working as expected. What I want to achieve are the following: For user_id field I want to see the something like dummy_uid1, dummy_uid2, ... to be listed. Consider dummy_uid1 wants to read book1 and book2 whereas dummy_uid2 wants to read book1 and book3. When dummy_uid1 is selected as user_id, I want only book1 and book2 to be listed for selection. How do I define the model in django rest framework to achieve this? Any suggestions related to the above would be much appreciated and thank you in advance.