Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
cant change images through html forms but i can change them from django admin panel
I have a form where users can change their profile picture, but for some reason it just stopped working, but when I try to change their profile picture from the admin panel it works, here is a few of my code. settings.html <form method="POST">{% csrf_token %} <div class="VpWhO text-center" style="height: 80px"> <div> <h4 style="text-transform: capitalize;"> {{request.user.username}} </h4> {{form.profile_pic}} </div> </div> <button type="submit">Save Changes</button> </form> views.py for setting.html def settings_view(request): myinstance = User.objects.filter(username=request.user).first() form = SettingsForm(instance=myinstance) if request.method == 'POST': form = SettingsForm(request.POST, request.FILES, instance=myinstance) if form.is_valid(): obj = form.save(commit=False) obj.username = slugify(obj.username) obj.save() messages.success(request, 'Profile Saved.') return redirect('/') else: messages.error(request, 'Can\' save changes.') else: myinstance = User.objects.filter(username=request.user).first() form = SettingsForm(instance=myinstance) class User(AbstractBaseUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) name = models.CharField(max_length=30, null=True, blank=True) bio = models.TextField(null=True, blank=True) profile_pic = models.ImageField(default='default_pfp.jpg', upload_to="user_uploaded") date_joined = models.DateTimeField(verbose_name="date joined", auto_now_add=True) last_login = models.DateTimeField(verbose_name="last login", auto_now_add=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', ] @property def imageURL(self): try: url = self.profile_pic.url except: url = 'default_pfp.jpg' return url urls.py from django.conf import settings from django.conf.urls.static import static urlpatterns = [ MY URLS HERE ] if settings.DEBUG: urlpatterns … -
How to call Django model method from admin
I have a model that is seperate to a user model which stores passwords, I have implemented a set_password method on that model, and this works ok, the only place I am facing issues is the admin panel, if I try to update a password in the model from the admin it does not call this set_password method. Instead it inputs the password as plain text. Is there a way to override the admin panel so it calls the set_password method? class MyModel(models.Model): name = models.CharField(max_length=255) created_on = models.DateTimeField(default=timezone.now) encrypted_pass = models.CharField(max_length=255, null=False) def set_password(self, raw_password): self.encrypted_pass = make_password(raw_password) -
Django Annotate using a model method
I'm trying to do an annotate in this model, but considering the get_is_secure into the result. class ScoringStudyLog(TimeStampedModel): scoring_status = models.CharField('Estudio', max_length=255, choices=_STATUS_CHOICES, default='pending') class Meta: # pylint: disable=too-few-public-methods """ Sets human readable name """ verbose_name = "Registro de estudio" verbose_name_plural = "Histórico de estudios" def get_is_secure(self): return self.scoring_status == "approved" How could I do a query like this? indicators["studies_by_status"] = ScoringStudyLog.objects.filter( **studies_filters ).values('is_secure').annotate(times=Count('is_secure')) -
still in same page when i use get_absolute_url in django
i work in django 3.2.7, but when i use get_absolute_url() function (in list of objects) return with no object and still in same page (list of objects), any idea ? models.py : def __str__(self): return self.title def get_absolute_url(self): return reverse("post_detail", kwargs={'slug': self.slug}) def headline(self): return self.content[:50]+'...' views.py : def post_list(request): post_list=Post.objects.all().order_by('-created_at') lastest=post_list.order_by('-created_at')[:4] last_post= post_list.order_by('-created_at')[0] context={ 'allpost':post_list, 'latest':lastest, 'lastpost':last_post } return render(request,'post/post_list.html',context) urls.py : from django.urls import path from . import views app_name="allpost" urlpatterns = [ path('', views.post_list), path('<slug:slug>',views.PostDetail.as_view(),name='post_detail'), ] in templates post_list.html : {% for post in allpost %} <small> نُشر من قبل : {{post.author}}|| </small> <small>بتاريخ : {{post.created_at}}</small> </div> <h3 class="mb-0"style="direction: rtl;">{{post.title}}</h3> <p class="mb-auto"style="direction: rtl;">{{post.headline}} </p> <a href="{{ post_detail.get_absolute_url }}"class="stretched-link">Continue reading</a> </div> <img class="rounded float-left m-1" src="{{post.image.url}}" alt="" style="height: 260px; width: 250px;"> </div> </div> </div> {% endfor %} with this,<a href="{{ post_detail.get_absolute_url }}" class="stretched-link">Continue reading</a> , link doesn't work, but no error shown. how can i resolve this problem ? thanks! -
Article.objects.order_by('order') vs type(self).objects.order_by('order')
I have a model: class Post(models.Model): title = models.CharField(max_length=15) create = models.DateTimeField(auto_now_add=True) order = models.PositiveIntegerField() And I override save: def save(self, *args, **kwargs): max_order_obj = type(self).objects.order_by('-ordering').first() --- some logics --- super().save(*args, **kwargs) But I can do it: def save(self, *args, **kwargs): max_order_obj = Post.objects.order_by('-ordering').first() --- some logics --- super().save(*args, **kwargs) Without type(self). And it works the same way! But which is better? What is more correct? And what's the difference in that? -
React Native and Django Rest Framework connection problem at local,Cors settings
I am building a react native project. I have already done the same project's website. I deployed it on Heroku and without any problem it works. When I try to fetch data on local server with react native app, It does not work but when I use deployed project url it works. For example; http://127.0.0.1:8000/api/sosyalmedya/ does not work. http://mydeployedwebsite/api/sosyalmedya/ work. My settings.py is the same with deployed one. In my settings.py, I have added these; ALLOWED_HOSTS = ['*'] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True -
GeoDjango - osm2geojson - IllegalArgumentException: Shell is not a LinearRing
Django is throwing IllegalArgumentException: Shell is not a LinearRing, when I'm trying to convert a osm json to geojson with osm2geojson. The exception is only thrown when osm2geoson is trying to make a MultiPolygon out of a relation. It returns a geojson, but without coordinates. Points are transformed correctly. -
Binding vue js to django template not showing any content
I am trying to binding vue js component into django HTML template file, but it is not showing any content. I am not getting any error. Just blank component. Here is my django HTML template: {% load render_bundle from webpack_loader %} {% render_bundle 'product-filter-app' %} {% block section_main %} <section id="section_main" class="guide_section"> <div id="product-filter-app"> <product-filter-app></product-filter-app> </div> </section> {% endblock %} Here is my vue js app. main.js import Vue from 'vue' import * as Sentry from '@sentry/browser' import 'vue-select/dist/vue-select.css' import ProductFilterApp from './ProductFilterApp' import { sentryOptions } from '@/utils/settings' if (process.env.VUE_APP_MODE !== 'dev') { Sentry.init(sentryOptions) } new Vue({ components: { ProductFilterApp } }).$mount('#product-filter-app') Here is ProductFilterApp.vue <template> <h1>Test</h1> </template> <script> export default { name: 'ProductFilterApp', components: { }, props: { }, data () { return { } }, methods: { } } </script> <style scoped> </style> Web-pack is generating app successfully there is not any error but just showing empty component as per screen shot. Any help will be appreciated. -
No module named myapp
I have this project directory structure: . .pylintrc |--myproj . |--myapp |--myproj (settings.py is here) __init__.py manage.py . In settings.py, INSTALLED_APPS I have the first entry 'myapp'. From the root folder (containing .pylintrc), I call $ DJANGO_SETTINGS_MODULE=myproj.myproj.settings pylint myproj --load-plugins pylint_django However, I get error no module named 'myapp'. If I change the INSTALLED_APPS entry to 'myproj.myapp', then it is able to continue, but now I'm unable to start the project normally with manage.py runserver. What am I doing wrong, and what can I do to proceed? -
ERR_SSL_PROTOCOL_ERROR while local development django
I had set up some https settings for Production and as python manage.py check was giving me warnings. So I added some new lines in settings.py. import os from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent from environs import Env env=Env() env.read_env() # read .env file, if it exists DEBUG = env.bool("DEBUG",default=True) SECRET_KEY=env.str("SECRET_KEY") ALLOWED_HOSTS = ['127.0.0.1','localhost','theopra.herokuapp.com'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.sitemaps', 'EHub.apps.EhubConfig', 'MCourses.apps.McoursesConfig', 'MArticles.apps.MarticlesConfig', 'MProgrammingLanguage.apps.MprogramminglanguageConfig', 'MSoftwareDevelopment.apps.MsoftwaredevelopmentConfig', #ThirdPartyPlugin 'ckeditor', 'ckeditor_uploader', 'taggit', 'mptt', 'admin_honeypot', ] APP_DIRS=True SITE_ID=1 CKEDITOR_UPLOAD_PATH = 'ckeditor/uploads/' CKEDITOR_CONFIGS={ 'default':{ 'toolbar':'Custom', 'uiColor' : '#FFFFFF', 'height':500, 'toolbar_Custom':[ ['Styles','Format','Bold','Italic','Underline','Strike','SpellChecker','Undo','Redo'], ['Link','Unlink','Anchor'], ['Image','Flash','Table','HorizontalRule'], ['TextColor','BGColor'], ['Smiley','SpecialChar'], ['Source'], ] }, 'sourcecode':{ 'codeSnippet_theme': 'monokai', 'toolbar':'SourceCode', 'toolbar_SourceCode':[ ['Styles','Format','Bold','Italic','Underline','Strike','SpellChecker','Undo','Redo'], ['Link','Unlink','Anchor'], ['Image','Flash','Table','HorizontalRule'], ['TextColor','BGColor'], ['Smiley','SpecialChar'], ['CodeSnippet'], ], 'extraPlugins': 'codesnippet', }, } MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'Dtheopra.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'templates'),], '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 = 'Dtheopra.wsgi.application' DATABASES = { "default": env.dj_db_url("DATABASE_URL") } #NEW SETTINGS FOR HTTP SESSION_COOKIE_SECURE = True #new CSRF_COOKIE_SECURE = True #new SECURE_SSL_REDIRECT = True #new AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization … -
ManytoManyField save and calculate
I just started self learning Python and Django as a hobby recently, and have been trying to self develop a project which helps me in my construction business. I have developed certain functions in my project which give me the result I want, but is not the most ideal in terms of coding practises. However, I am just learning from scratch and modifying my code as I learn. However, now I am stuck (maybe because my basic concept is only not correct?). Require help on how to proceed. So here is my models.py class FootingQuantity(models.Model): member_name = models.CharField(max_length=8, unique=True) --more fields hidden-- x_axis = models.FloatField() y_axis = models.FloatField() class BeamQuantity(models.Model): work = models.ForeignKey(Work, default=1, on_delete=models.CASCADE) member_name = models.CharField(max_length=8, unique=True) location = models.ManyToManyField(FootingQuantity) length = models.FloatField(blank=True) breadth = models.FloatField() height = models.FloatField() -- more fields -- @property def length_of_beam(self): yy = self.location.all().values_list('y_axis', flat=True) xx = self.location.all().values_list('x_axis', flat=True) ylist = list(yy) xlist = list(xx) return abs(ylist[1] - ylist[0] + xlist[1] - xlist[0]) @property def total_concrete_quantity(self): return float(self.length) * float(self.breadth) * float(self.width) def save(self, *args, **kwargs): self.length = self.length_of_beam self.total_quantity = self.total_concrete_quantity super(BeamQuantity, self).save(*args, **kwargs) def __float__(self): return self.length, self.total_quantity I want my model to accept ManytoManyRelation of 2 Footings selected and then … -
Django reset password url in email only works if copy and paste it, not click on it
When I request a password reset with the built in django machinery, it will generate a URL in the email like this: https://example/accounts/reset/MTA/atspc3-7c45df8a600243fde3dfb60c44873f15/ In gmail if I go show URL, the text is indentical since it is being generated as a plain/text email. If I click the link in gmail, or outlook then it goes to (maybe after a redirect, I can't tell since its so fast): https://example.com/accounts/reset/MTA/set-password/ And it says Password reset unsuccessful The password reset link was invalid, possibly because it has already been used. Please request a new password reset. However if I copy and paste the URL into the browser, then it works. However no-one copies and paste the URL, they all click the link and say it does not work. I don't get why clicking on the link does not work since it is correct? How does one even debug this? -
Project Ideas for Django
I look for project suggestions. Or if you are working on it and ready for collaboration. I really interested in. Project stack: Django REST Any DB Or anything just want to learn!!! -
nested serializer not returning expected values Django Rest Framework
I've started learning django recently and can't seem to figure out how to get the data I want. I'm looking to build an object that can give me each part name and all of the reports of that part and then get the report data but only for the part I'm currently on This is an example of the data I would want. { "count": 2536, "next": "http://127.0.0.1:8000/esd/salesreportsdetail2/?page=2", "previous": null, "results": [ { "id": 2, "name": "A0012", "sales_report_parts": [ { "id": 5, "date": "2021-08-31T00:00:00Z", "sales_report_items": [ { "quantity": 1, "site": "FBA" }, { "quantity": 3, "site": "Vendor" }, { "quantity": 4, "site": "Main" } ] } ] } ] } But instead, I keep getting all the sales report items for each item. { "count": 2536, "next": "http://127.0.0.1:8000/esd/salesreportsdetail2/?page=2", "previous": null, "results": [ { "id": 2, "name": "A0012", "sales_report_parts": [ { "id": 5, "date": "2021-08-31T00:00:00Z", "sales_report_items": [ { "quantity": 1, "site": "FBA" }, { "quantity": 3, "site": "Vendor" }, { "quantity": 4, "site": "Main" }, { "quantity": 45, "site": "FBA" }, { "quantity": 102, "site": "Vendor" }, { "quantity": 161, "site": "Main" }, { "quantity": 7, "site": "FBA" },... and so on gets me all of the data Below are my … -
KeyError: 'user_id' when using PUT request
Recently started working with Django REST framework. I have a user table and another table that stores some relevant data for each user. I've set up POST/GET/DELETE methods fine, but I can't get the method for perform_update working - I keep getting a KeyError at /api/sdgdata/1 'user_id' error in Postman when I attempt a put request for a user. Plz see code below: Models: class TestDataTwo(models.Model): user = models.ForeignKey("auth.User", related_name="testdatatwo", on_delete=models.CASCADE) test_name = models.CharField(max_length=1024, null=True, default="N/A") Serializers: class TestDataTwoSerializer(serializers.ModelSerializer): class Meta: model = TestDataTwo fields = ( "id", "test_name", ) def update(self, instance, validated_data): # get user id from validated data: user_id = validated_data.pop('user_id') # get user: user = User.objects.get(id=user_id) # set user on instance: instance.user = user instance.save() # continue with update method: super().update(instance, validated_data) Views: class TestDataTwoViewSet(ModelViewSet): queryset = TestDataTwo.objects.all().order_by('id') serializer_class = TestDataTwoSerializer paginator = None # CREATE NEW TESTDATATWO ROW FOR USER def perform_create(self, serializer): serializer.save(user=self.request.user) # GET ALL ENTRIES OF TESTDATATWO FOR SPECIFIC USER, EXCEPT IF SUPERUSER, THEN RETURN ALL def get_queryset(self): # if self.request.user.is_superuser: # return self.queryset # else: return self.queryset.filter(user=self.request.user) def perform_update(self, serializer): instance = self.get_object() serializer.save(user=self.request.user) return Response(serializer.data, status=status.HTTP_200_OK) # DELETE TESTDATATWO ID def destroy(self, request, *args, **kwargs): instance = self.get_object() self.perform_destroy(instance) return … -
How to generate multiple .pdf docs at once
I am currently trying to print financials for an app that I am using , I would like these to print with the push of a button. However, the system that I am using now (tempFile) can only print one at a time with the following code: import tempfile def printReports(request , reports_pk): pkForm = get_object_or_404(SettingsClass , pk=reports_pk) complexName = pkForm.Complex if pkForm.Trial_balance_Monthly == True: ### Printing Trial Balance PDF response = HttpResponse(content_type= 'application/pdf') response['Content-Disposition']= 'attachment; filename=TrialBalance' + \ str(datetime.now()) + '.pdf' response['Content-Transfer-Encoding'] = 'binary' content = {"x_AlltrbYTD":x_AlltrbYTD , 'xCreditTotal':xCreditTotal , 'xDebitTotal':xDebitTotal , 'complexName':complexName , 'openingBalances': openingBalances ,'printZero':printZero , 'printDesc':printDesc , 'printAcc':printAcc} html_string=render_to_string('main/reports/trialBalanceYear.html' , content) html=HTML(string=html_string) result=html.write_pdf() with tempfile.NamedTemporaryFile(delete=True) as output: output.write(result) output.flush() output.seek(0) response.write(output.read()) return response if pkForm.Trial_balance_Monthly == True: ### Printing Trial Balance PDF response = HttpResponse(content_type= 'application/pdf') response['Content-Disposition']= 'attachment; filename=TrialBalanceMonthly' + \ str(datetime.now()) + '.pdf' response['Content-Transfer-Encoding'] = 'binary' content = {"xtrbMonth":xtrbMonth , 'xCreditTotalM':xCreditTotalM , 'xDebitTotalM':xDebitTotalM , 'complexName':complexName , 'printZeroM':printZeroM} html_string=render_to_string('main/reports/trialBalanceMonthly.html' , content) html=HTML(string=html_string) result=html.write_pdf() with tempfile.NamedTemporaryFile(delete=True) as output: output.write(result) output.flush() output.seek(0) response.write(output.read()) This code only executes the first file instead of both of the files. Does anyone have any other way to print more than 1 pdf document or any changes that I can make to my … -
django form : Data is duplicated instead of updating when i edit in the UI
When I tried to edit the existing data in the Django form it just creating the duplicate entry along with new one. How could I able to get rid of the duplicate entries in the forrm and I have attached the code here. pls someone help me out.Thanks in advance views.py def homeview(request,id=0): userb = Userbase.objects.all() if request.method == 'GET': # new if id==0: form = Userform() # form_mode = 'new' else: # edit user = Userbase.objects.get(pk=id) form = Userform(instance = user) # form_mode = 'update' # post data both adding and updating else: if id==0: # if id==0: form = Userform(request.POST) else:# save from edit user = Userbase.objects.get(pk=id) form = Userform(request.POST, instance=user) if form.is_valid(): form.save() else: messages.error(request, form.errors) return redirect('app:home') return render(request, 'home.html', {'form':form, 'userb':userb}) forms.py class Userform(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['username'].widget.attrs.update( {'class': 'form-control mb-3', 'placeholder': 'Username'}) self.fields['email'].widget.attrs.update( {'class': 'form-control mb-3', 'placeholder': 'E-mail', 'name': 'email', 'id': 'id_email'}) self.fields['timezone'].widget.attrs.update( {'class': 'form-control mb-3', 'name': 'timezone', 'id': 'id_timezone', 'placeholder':'timezone'}) self.fields['my_date'].widget.attrs.update( {'class': 'form-control mb-3', 'placeholder':'Select Timeformat','name': 'my_date', 'id': 'id_my_date'}) class Meta: model =Userbase fields = '__all__'''' urls.py urlpatterns = [ path('', homeview, name='home'), path('<int:id>/', homeview, name='home') ] -
NoReverseMatch Django Project
I want to create the products through the customer's profile, so that the customer's name is attached to the form when creating the product that is related to it. But when I try to enter the user profiles from the dashboard it throws this error urls.py urlpatterns = [ path('', views.home, name="home"), path('products/', views.products, name="products"), path('customer/<str:pk_test>/', views.customer, name="customer"), path('create_order/<str:pk>', views.createOrder, name='create_order'), path('update_order/<str:pk>', views.updateOrder, name='update_order'), path('delete_order/<str:pk>', views.deleteOrder, name='delete_order'), path('create_customer/', views.createCustomer, name='create_customer'), ] views.py Here I focus on the "create Order" function passing the customer's primary key and using "initial" to append the customer's name to the form def home(request): orders_value = Order.objects.all() customer_value = Customer.objects.all() total_orders_value = orders_value.count() total_customers_value = customer_value.count() pending_value = orders_value.filter(status='Pending').count() delivered_value = orders_value.filter(status='Delivered').count() context = {'orders_key': orders_value, 'customer_key': customer_value, 'total_orders_key':total_orders_value, 'pending_key': pending_value, 'delivered_key': delivered_value} return render (request, 'accounts/dashboard.html', context) def products(request): products_value = Product.objects.all() return render (request, 'accounts/products.html', {'products_key': products_value}) def customer(request, pk_test): customer_value = Customer.objects.get(id=pk_test) orders_value = customer_value.order_set.all() orders_value_count = orders_value.count() context = {'customer_key':customer_value, 'orders_key': orders_value, 'orders_key_count': orders_value_count} return render (request, 'accounts/customer.html', context) def createOrder(request, pk): customer = Customer.objects.get(id=pk) form_value = OrderForm(initial={'customer':customer}) if request.method == 'POST': form_value = OrderForm(request.POST) if form_value.is_valid: form_value.save() return redirect('/') context = {'form_key':form_value} return render(request, 'accounts/order_form.html', context) def updateOrder(request, pk): order = … -
Background Task Django Heroku
I have a problem after deploying my web app at HEROKU, the request lasts 30 second. my app consists to treat excel files and returns new excel files with modifications. The process take more than 30 seconds. I see this tuto https://devcenter.heroku.com/articles/python-rq , but I don't know how to deploy the background task. Ty -
how to reset password by using html template in django djoser
I created classed based view rest api. where I used django djoser. My activation template and all links are worked. but now I am working on reset password where I used template for rest password. but giving 405 error. I was getting reset password link. also my html page is working but when I changed my password and hit on submit its giving me 405 error views.py class ResetPasswordView(View): def get (self, request, uid, token): return render(request, 'password_reset_email.html') # display activation page when user click on link which recieved fron gmail def post (self, request,uid,token): print('In Password Reset Post') new_password=request.post.get("new_password") print("new_password :",new_password) re_new_password=request.post.get("re_new_password") print("re_new_password : ",re_new_password) payload = json.dump({'uid': uid, 'token': token, 'new_password': new_password, 're_new_password': re_new_password}) protocol = 'https://' if request.is_secure() else 'http://' # will evaluate to True if the connection is secure (HTTPS: HTTP over TLS) or False if non-secure (standard HTTP). web_url = protocol + request.get_host() + '/' password_reset_url = "users/reset_password_confirm/" # url used for activate user password_post_url = web_url + AUTHENTICATION_BASE_ROUTE + password_reset_url # for activate user print('url : ', password_post_url) response = request.post(password_post_url,data=payload) return HttpResponse(response.text) urls.py re_path(r'^password/reset/confirm/(?P<uid>[\w-]+)/(?P<token>[\w-]+)/$', ResetPasswordView.as_view()), password_reset_email.html <form action="" method="post"> {% csrf_token %} {{ form.as_p}} <div class="container"> <h1>Register</h1> <p>Please fill this form to create … -
Formset does not create an object in the db
I have this "Recipient" model: # Models.py class Recipient(models.Model): Account = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,) First_name = models.CharField(max_length=100) Last_name = models.CharField(max_length=100) Email = models.EmailField(_('email address'), unique=True) Permitted = models.BooleanField(default=False) def __str__(self): return self.Email And this form, # Forms.py class AddRecipientForm(forms.ModelForm): First_name = forms.CharField(required=True, label = 'First_name', widget = forms.TextInput()) Last_name = forms.CharField(required=True, label = 'Last_name', widget = forms.TextInput()) Email = forms.EmailField(required=True,label = 'Email_address', validators=[validators.EmailValidator()], widget=forms.TextInput()) Permitted = forms.BooleanField(required=False, widget=forms.CheckboxInput()) class Meta(): model = Recipient fields = ('First_name', 'Last_name', 'Email', 'Permitted') I tried to create a Generic FormView where users can add multiple recipient instances using formsets like the code below # Views.py class AddRecipients(LoginRequiredMixin, FormView): context_object_name = 'AddRecipient' template_name = 'Awareness/CyberAwarenessRecipients.html' form_class = AddRecipientForm success_url = reverse_lazy('Awareness:AwarenessHome') Recipient_FormSet = formset_factory(AddRecipientForm, min_num = 1, max_num=100) formset = Recipient_FormSet() def form_valid(self, form): for recipient in self.formset: if recipient.is_valid(): recipient.save() return super().form_valid(form) def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['formset'] = self.formset return context But when I check the django admin page, the FormView doesn't commit the recipients to the DB neither redirects me to the success_url after submitting. -
How can i add my company logo in django-oscar homepage?
I am trying out django-oscar for the first time and just for practice I want to add a custom logo in homepage...which template should I modify in order to achieve that -
How to associate a column in a table with a specific user
I am building a social website for delivering objects. I'm trying to assign a location to a user. If the user adds location the location is added to the user only and saved in DB so that the next time he comes to add a product he can select the location he has already added. The problem that I can not assign a location to a specific user is added to DB and appears to all users. class Profile(models.Model): user = models.OneToOneField(User, related_name="pro", on_delete=models.CASCADE) profile_pic = models.ImageField(null=True, blank=True, upload_to='img/profile/') phone = models.CharField("Phone Number", max_length=10 , blank=True) def __str__(self): return str(self.user) def get_absolute_url(self): return reverse('home') class Location(models.Model): city = models.CharField(max_length=50, choices=cy.city, blank=True) street = models.CharField(max_length=100, blank=True) home_number = models.CharField(max_length=100, blank=True) def __str__(self): return self.city +" "+self.city+" "+ self.street+" "+ self.home_number class Add_Item(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE, default=None, null=True) title = models.CharField(max_length=255) categories = models.CharField(max_length=255 , choices= all_categories) description = RichTextField(blank=True,null=True) condition = models.CharField(max_length=100, choices=cond) header_image = models.ImageField(null=True, blank=True, upload_to='img/') more_imges = models.ImageField(null=True, blank=True, upload_to='img/') Pub_date = models.DateField(auto_now_add=True) location = models.ForeignKey(Location, related_name="loc" , on_delete=models.CASCADE ,blank=True, null=True) def get_absolute_url(self): return reverse('home') def __str__(self): return self.title +" "+self.condition View: class AddLocationView(CreateView): model = Location form_class = AddLocationForm template_name ='add_location.html' success_url = reverse_lazy("add-item") def form_valid(self, form): … -
Change value of dropdown in django forms
im trying to update my dropdown (which is in my django forms ) with the id that gets passed. For example views.py form = UploadRoomForm(initial={'companies': company_id}) forms.py companies = forms.ModelChoiceField(queryset=Company.objects.all().order_by('id')) but for some reason. it doesnt pick it up. what am i overlooking here ? when i output the form i get <option value="1" selected>Number 1</option> but in the loaded page i get <option value="" selected>---------</option> -
How to add tensorflow serving in my django postgres container?
Here is my Django container, docker-compose.yml version: "3.9" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data web: build: ./backend command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/usr/src/app ports: - "8000:8000" depends_on: - db My tensorflow serving run as follows docker run -p 8501:8501 --name tfserving_classifier --mount type=bind,source=C:\Users\Model\,target=/models/img_classifier -e MODEL_NAME=Model -t tensorflow/serving How can I add the above command for tensorflow serving into the same docker-compose of Django and postgres?