Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
follower system in django "bool is not callable"
I'm trying to make a follower system using django and have come accross this issue can someone please help me with it, or give me some suggestions regarding making a follower system with django. the traceback is as following Traceback: File "C:\Users\Mustafa Lakhani\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\Mustafa Lakhani\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "C:\Users\Mustafa Lakhani\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Mustafa Lakhani\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\generic\base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "C:\Users\Mustafa Lakhani\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\generic\base.py" in dispatch 88. return handler(request, *args, **kwargs) File "D:\sb\blog\views.py" in get 186. if request.user.is_authenticated(): Exception Type: TypeError at /user/mustafalakhani/follow Exception Value: 'bool' object is not callable the code is given below models.py class Profile(models.Model): user=models.OneToOneField(User, on_delete=models.CASCADE) image=models.ImageField(default='default.jpg',upload_to='profile_pics',blank=True) description=models.TextField(max_length=200, blank=True) following = models.ManyToManyField(User, related_name='followed_by', blank=True) def __str__(self): return f'{self.user.username} Profile' def saveimg(self): super().save() img=Image.open(self.image.path) if img.height>300 or img.width>300: output_size=(300,300) img.thumbnail(output_size) img.saveimg(self.image.path) views.py class UserFollowView(View): def get(self, request, username, *args, **kwargs): toggle_user=get_object_or_404(User,username__iexact=username) if request.user.is_authenticated(): user_profile, created=Profile.objects.get_or_create(request.user) if toggle_user in user_profile.following.all(): user_profile.following.remove(toggle_user) else: user_profile.following.add(toggle_user) return HttpResponseRedirect(home) urls.py path('user/<str:username>/follow', UserFollowView.as_view(),name='follow_user'), -
How can i prevent Stripe from redirecting to email verification code when the customer email is entered?
The stripe checkout.js is working properly but when everytime i entered customer email address it always redirecting to enter email erification code, I want it to be always entered automatically. <form action="" method="POST"> {% csrf_token %} <script> src="https://checkout.stripe.com/checkout.js" class="stripe-button" data-key="{{ data_key }}" data-amount="{{ stripe_total }}" data-name="" data-description="{{ description }}" data-image="" data-locale="auto" data-currency="cad" data-shipping-address="false" data-billing-address="True" data-zip-code="false" data-allow-remember-me="false" data-label="Pay with card and Pick up in store"> </script> </form> -
Why is Django throwing me this attribute error even though I am passing a slug to the url?
I am trying to use the UserPassesTestMixin in some of my generic views, but Django keep giving me this attribute error as if I were not passing a pk or slug to the url for a specific page (in my case, I pass a slug). Here's the AttributeError: Generic detail view PostUpdateView must be called with either an object pk or a slug in the URLconf. Here's the url conf for your reference: urlpatterns = [ path("create/", views.CreateObjView.as_view(), name="create-obj-upn"), path("update/<slug:slugstring>/", views.ObjUpdateView.as_view(), name="obj-update-upn"), path("delete/<slug:slugstring>/", views.ObjDeleteView.as_view(), name="obj-delete-upn"), ] Here's two of the generic views I am trying to use with the UserPassesTestMixin: class PostCreateView(LoginRequiredMixin, UserPassesTestMixin, CreateView): model = Post fields = ["content"] template_name = "post/post_create.html" def test_func(self): return self.request.user == self.get_object().author class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Post fields = ["content"] template_name = "post/post_update.html" def test_func(self): return self.request.user in self.get_object().author What might I be doing wrong? Thanks in advance. -
How to call a view as a command in Heroku's Scheduler?
I've a test app that goes to a page, do some webscrapping and create a record with some of the contents of this page. I'm calling the view that is the core of the app, and do all the webscraping and saves the object. I call the view when the user just goes to the home path ("/"). As you'll see, the view is called when accessing the home page. But I don't know what to enter so Heroku call this view everyday, what should I put in the field?: Enter a command and select a dyno size to use for this job. urls.py: urlpatterns = [ path('admin', admin.site.urls), path("", views.today_editorial, name="today_editorial"), ] view.py: def today_editorial(request): ec_editorial = requests.get("https://elcomercio.pe/opinion/editorial") ec_editorial_scr = ec_editorial.content soup = BeautifulSoup(ec_editorial_scr) enlace = soup.find('a', class_='page-link') titulo = soup.find('h2', class_='flow-title').find('a', class_='page-link').getText().strip() texto = soup.find('p', class_='flow-summary').getText().strip() tz = pytz.timezone('America/Bogota') fecha = soup.find('time')['datetime'] fecha = time.localtime(int(fecha)) fecha = datetime.fromtimestamp(mktime(fecha)).date() imagen = soup.find('source')["data-srcset"] full_url = "https://elcomercio.pe" + enlace['href'] # today_date = datetime.now().date().strftime('%d %b %Y') today_date = datetime.now(tz).date() try: todays_editorial = Editorial.objects.get(date = datetime.now(tz).date()) print("Se obtuvo la editorial de la BD") except: todays_editorial = Editorial.objects.create( date = fecha, title = titulo, body = texto, url = full_url, image = imagen ) … -
How do I create Django custom form fields validation, so that custom validations depends on another field
I'm trying to make a custom validator in my form. I have there three input-fields in 'model', first for 'content_type', Second for 'content_text' and another for 'content_file'. 'content_type' is one of these values: 'text' or 'file'. My models: class ContentType(models.Model): title = models.CharField(unique=True, max_length=100) class Suggest(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.DO_NOTHING) content_text = models.TextField(blank=True) content_file = models.FileField(upload_to='media/upload/suggest_files', null=True) How do I create custom form fields validation, so that if 'content_type==text' then 'content_text' required? and if 'content_type==file' then 'content_file' required? -
how to solve a "Manager isn't accessible via Profile instances" error
I am trying to make a follower system using django and am getting the above mentioned error code models.py class Profile(models.Model): user=models.OneToOneField(User, on_delete=models.CASCADE) image=models.ImageField(default='default.jpg',upload_to='profile_pics',blank=True) description=models.TextField(max_length=200, blank=True) following = models.ManyToManyField(User, related_name='followed_by', blank=True) def __str__(self): return f'{self.user.username} Profile' def saveimg(self): super().save() img=Image.open(self.image.path) if img.height>300 or img.width>300: output_size=(300,300) img.thumbnail(output_size) img.saveimg(self.image.path) views.py def follow_user(request, username): creator = get_object_or_404(Profile, user__username__iexact=username) is_followed=False if request.user.profile.objects.filter(following=creator).exists(): request.user.profile.objects.remove(following=creator) is_followed=False else: creator.profile.add(following=creator) is_liked=True context={ 'creator':creator, 'is_followed': request.user.profile.filter(following=creator).exists(), } return HttpResponseRedirect(home) urls.py path('user/<str:username>/follow', views.follow_user,name='follow_user'), traceback Traceback: File "C:\Users\Mustafa Lakhani\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\Mustafa Lakhani\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "C:\Users\Mustafa Lakhani\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\sb\blog\views.py" in follow_user 186. if request.user.profile.objects.filter(following=creator).exists(): File "C:\Users\Mustafa Lakhani\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\manager.py" in get 176. raise AttributeError("Manager isn't accessible via %s instances" % cls.name) Exception Type: AttributeError at /user/mustafalakhani/follow Exception Value: Manager isn't accessible via Profile instances -
Django Admin multiple Inlines without cascading\nested tables
(I'm struggling with how to title this, so please feel free to edit or suggest an edit) In Django Admin, I would like to be able to view all the details for a "flagged" album, including the photos themselves. class Album(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) title = models.CharField(max_length=40) class Photo(models.Model): album = models.ForeignKey(Album, on_delete=models.CASCADE) name = models.CharField(max_length=255) photo = models.ImageField(upload_to='photos/%Y/%m/%d/', height_field='photo_height', width_field='photo_width') class Flag(models.Model): album = models.ForeignKey(Album, on_delete=models.CASCADE) description = models.TextField(blank=True) The problem I'm running into is that Photo and Flag are "sister" tables of Album (not sure how to describe that) so there's not cascading one-to-many relationships. Viewing the photos from the Album is easy with an inline... class PhotoInline(admin.TabularInline): model = Photo class AlbumAdmin(admin.ModelAdmin): inlines = (PhotoInline, ) admin.site.register(Album, AlbumAdmin) but how do I then include THAT in my FlagAdmin class? All I really care about is seeing the photo names\url (or eventually preview.) are "inlines" the wrong way of going about this since I'm not needing to edit the "child" records? -
How to solve a "cannot unpack non-iterable Profile object" error?
I was making a project for my university assignment using django. I want to make a follower system using django, I wrote the code and am getting the following error cannot unpack non-iterable Profile object models.py class Profile(models.Model): user=models.OneToOneField(User, on_delete=models.CASCADE) image=models.ImageField(default='default.jpg',upload_to='profile_pics',blank=True) description=models.TextField(max_length=200, blank=True) following = models.ManyToManyField(User, related_name='followed_by', blank=True) def __str__(self): return f'{self.user.username} Profile' def saveimg(self): super().save() img=Image.open(self.image.path) if img.height>300 or img.width>300: output_size=(300,300) img.thumbnail(output_size) img.saveimg(self.image.path) views.py def follow_user(request, username): creator = get_object_or_404(Profile, user__username__icontains=username) is_followed=False if request.user.profile.following.filter(creator).exists(): request.user.profile.following.remove(creator) is_followed=False else: request.user.profile.add(following=creator) is_liked=True context={ 'creator':creator, 'is_followed': request.user.profile.filter(following=creator).exists(), } return HttpResponseRedirect(home) urls.py path('user/<str:username>/follow', views.follow_user,name='follow_user'), -
Django Oscar Razorpay Integration
I'm trying to integrate Razorpay payment gateway to a default Django-Oscar project. I'm not sure how to pass the checkout.js generated payment id to Django server to capture payment. As per my limited understanding, the checkout.js code of Razorpay generates a unique payment id after every time the user fills up the payment information and initiates authorization. payment_details.html <form action="{% url 'checkout:preview' %}" method="POST"> <!-- Note that the amount is in its subunit value = 599 --> <script src="https://checkout.razorpay.com/v1/checkout.js" data-key="rzp_test_XXUUnffGta42gL" data-amount="{{ order_total_incl_tax_cents }}" data-currency="INR" data-buttontext="Pay with Razorpay" data-name="{{ shop_name }}" data-description="{{ basket.num_items }} items ({{ order_total.incl_tax|currency }})" data-image="https://your-awesome-site.com/your_logo.jpg" data-prefill.name="Gaurav Kumar" data-prefill.email="test@test.com" data-theme.color="#F37254" ></script> <input type="hidden" value="Hidden Element" name="hidden"> </form> I have forked the checkout app. checkout/__init__.py PAYMENT_EVENT_PURCHASE = 'Purchase' PAYMENT_METHOD_STRIPE = 'Razorpay' RAZORPAY_EMAIL = 'razorpayEmail' RAZORPAY_TOKEN = 'razorpayToken' default_app_config = 'checkout.apps.CheckoutConfig' checkout/forms.py class StripeTokenForm(forms.Form): razorpayEmail = forms.EmailField(widget=forms.HiddenInput()) razorpayToken = forms.CharField(widget=forms.HiddenInput()) checkout/views.py class PaymentDetailsView(CorePaymentDetailsView): @method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): return super(PaymentDetailsView, self).dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs): ctx = super(PaymentDetailsView, self).get_context_data(**kwargs) if self.preview: ctx['razorpay_token_form'] = forms.RazorpayTokenForm(self.request.POST) ctx['order_total_incl_tax_cents'] = ( ctx['order_total'].incl_tax * 100 ).to_integral_value() else: ctx['order_total_incl_tax_cents'] = ( ctx['order_total'].incl_tax * 100 ).to_integral_value() ctx['razorpay_publishable_key'] = settings.RAZORPAY_PUBLISHABLE_KEY return ctx def handle_payment(self, order_number, total, **kwargs): razorpay_ref = Facade().charge( order_number, total, card=self.request.POST[RAZORPAY_TOKEN], description=self.payment_description(order_number, total, **kwargs), … -
Multiple Todo lists in Django
I am currently learning Django and as a starter Project, I thought of making a Todo List website. I need help arranging the views to show multiple todo lists in a "title" : "text" kinda manner. eg: "June todo" : "1.Learn Django", "2.Create a Django App" etc So far this is what I have done: todo.html HTML: <h1>Todo List!</h1> <ul> {% for todo in all_items %} <li><a href="/todos/{{todo.id}}">{{todo.title}}</a>: {{todo.text}}</li> {% endfor %} </ul> <form action="/addTodo/" method="POST">{% csrf_token %} <h3>Create New Todo List</h3> <input type="text" name="text", placeholder="Enter Title Here"> <input type="Submit" name="Create"> </form> models.py : class SimpleTodo(models.Model): title = models.CharField(max_length = 100) text = models.CharField(max_length = 100) def __str__(self): return (self.title) views.py: def TodoView(request): all_items = SimpleTodo.objects.all() return render(request, 'blog/todo.html', {'all_items':all_items}) Current output: Todo List! - June: Todo List #1 - June: My first todo - June: My second todo - Aug: My First todo Aug Expected Output: Todo List! - June: Todo List 1 My first todo My second todo - Aug: My First todo Aug PS: the goal is to kinda create a website such that people can share their todolists on a common newsfeed, would appreciate any help in that aspect as well. -
How do you add 2 specific people to a specific chat and then redirect them to another page in chat in django channels
I want to take anyone who connects to our server and immediately connect them with someone from our team and redirect both of them to a unique chat page. I don't know how to connect them with someone from our team and redirect both of them. I am stuck on that part. I really appreciate the help. I tried redirecting from the consumer page, but that did not seem to work whatever I did. It would get to the redirect and then do nothing. I then tried closing the socket connection and then redirecting them and that did not work either. I am stuck on how to group them and redirect both of them. class ChatConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() # mine! # finds which user just connected to the websocket user = self.scope['user'] print(user) ready.append(user) # trying to group person online and from our team # async_to_sync(self.channel_layer.group_add)( # self.room_group_name, # self.channel_name, # ready[0], # team[0], # ) # trying different ways to redirect, none worked # self.disconnect(close_code=redirect('https://www.yahoo.com/')) # self.close() # redirecting() # ready.append(user) # print(ready[0]) # self.disconnect(self.redirectIT('home')) # # raise channels.exceptions.StopConsumer # redirect('room', 'hi') … -
Counting objects based on multiple relationships
I've got three models; class User(AbstractUser): id = UUIDField(primary_key=True, default=uuid.uuid4, editable=False) class UserProfile(Model): id = UUIDField(primary_key=True, editable=False) user = OneToOneField(User, CASCADE) subscription = CharField(max_length=250, null=True, blank=True) class Image(Model): id = UUIDField(primary_key=True, editable=False) owner = ForeignKey(User, on_delete=CASCADE, null=True) I would like to count all Image objects where the owners subscription doesn't equal a string (eg 'free'). Is this possible? -
Model Form Fails to Validate and Post
Having issues with the first form validating and posting. The second form, form2 works fine. The view code is the same structure so curious as what is causing the issue. .is_valid() by default should validate the fields. What am I missing? # views.py def create(request): if request.method == 'POST': form = CreateForm(request.POST) form2 = CreateTimeForm(request.POST) if form.is_valid(): form.save() return redirect('organizer-create') if form2.is_valid(): form2.save() return redirect('organizer-create') else: form = CreateForm() form2 = CreateTimeForm() context = { 'form': form, 'form2': form2, } return render(request, 'organizer/create.html', context) # forms.py class CreateForm(ModelForm): class Meta: model = Event fields = ['title', 'date',] # models.py class Event(models.Model): title = models.CharField(max_length=50) date = models.DateField() datetimecreated = models.DateTimeField(auto_now_add=True) def get_absolute_url(self): return reverse('organizer-admin') def __str__(self): return str(self.date) + ", " + self.title -
How to POST over multiple variables using forms in Django
Using HTML forms if you wanted to POST over multiple variables you would have to set the name of your input field to "name[]", and then when you POST['name'] you can get the information form every input field with the name "name[]". Currently I am working with Django, and implementing a view that involves a form that will POST over a variable amount of variables. When I try to implement the same method as described above in Django, I am getting a "MultiValueDictKeyError" instead. By removing the brackets in the input variables name I no longer get the error, but it will only POST over the last value, and I need it to POST over all the values. <form action = "{% url view_name %}" method = POST> /* Variable amount of these inputs */ <input type = "input" name = "name[]"> <input typy = "input" name = "name[]"> <input type = "submit" name = "submit" value = "Submit"> </form> postVar = request.POST["name"] -
Viewing "tree" on a mac in Django without seeing virtualenv tree
I have an older django project in django 1.11 on a mac. When I use the "tree" command to view the file structure in the terminal, it shows all the typical django files, but also hundreds of lines of virtualenv files. Is there a way to view the "tree" structure without viewing the virtualenv part? -
Django if table in template is empty display something else
i would like to know how i can display a message like "Currently no Data Available" if the table is empty <table> <thead> <tr style="font-size: small"> <th>Ranking</th> <th>Symbol</th> <th>Name</th> <th>Price</th> <th>Market Cap (USD)</th> </tr> </thead> <tbody> {% for price in price %} <tr style="font-size: small"> <td>{{ price.rank }}</td> <td>{{ price.symbol }}</td> <td>{{ price.key|title }}</td> <td>{{ price.value|intcomma }} $</td> <td>{{ price.market_cap_usd|intcomma }} $</td> </tr> {% endfor %} </tbody> </table> Thanks and Br -
Data from Views.Py not showing up on the template
I am trying to find out why some data from my views.py are not showing up. Here's my code views.py profile = get_object_or_404(User, pk=user_id) rnk = Ranks.objects.all() context = { 'profile' : profile, 'rnk' : rnk, } return render(request, 'user/user.html', context) I am trying to show, for example the rank_name from my model and I use {{rnk.rank_name}} in the HTML template but it's not showing up. ON the other hand, data from profile like {{profile.user_name}} are showing up. Note that rnk and profile are from this model: rank_name = models.CharField(max_length=300) description = models.TextField(blank=True) def __str__(self): return self.br_rank_name class User(models.Model): b_rank = models.ForeignKey(Ranks, on_delete=models.DO_NOTHING) name = models.CharField(max_length=20) link = models.URLField(max_length=100) weekly = models.BooleanField(default=False) biweekly = models.BooleanField(default=False) def __str__(self): return self.name -
Is it possible to have multiple Django caches on the same ElastiCache node?
I currently have a Django installation on AWS EC2 that uses an ElastiCache node for database result memcaching. The Django cache is defined as follows in the settings.py: CACHES = { 'default': { 'BACKEND': 'django_elasticache.memcached.ElastiCache', 'LOCATION': 'cacheurl.amazonaws.com:portnumber', } } I'd like to specify a new cache for a specific app in Django (I need to clear it for certain tasks, and I don't want to clear cache for all apps), like so: CACHES = { 'default': { 'BACKEND': 'django_elasticache.memcached.ElastiCache', 'LOCATION': 'cacheurl.amazonaws.com:portnumber', }, 'appname_cache:' { 'BACKEND': 'django_elasticache.memcached.ElastiCache', 'LOCATION': 'cacheurl.amazonaws.com:portnumber', } } My question is: can I do this and still use the same ElastiCache node, or do I need to create a new ElastiCache node to make sure the cache is separate? Which is to say, in this code: from django.core.cache import caches cache1 = caches['default'] cache2 = caches['appname_cache'] Are cache1 and cache2 referencing the same cache, or different ones (if the same node is used)? -
django admin TabularInline - how to access fields when using `through`
I have a couple of models, Game and GameRound which are something like this: class Game (models.Model): away_team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name="away_team") away_score = models.IntegerField(blank=True, null=True) home_team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name="home_team") home_score = models.IntegerField(blank=True, null=True) stadium = models.ForeignKey(Stadium, on_delete=models.CASCADE) match_date = models.DateTimeField() class GameRound (models.Model): name = models.CharField(max_length=101) games = models.ManyToManyField(Game) end_date = models.DateTimeField() is_complete = models.BooleanField(default=False) The key point is the ManyToMany relationship. In admin.py I've declared class GameTabularInline(admin.TabularInline): model = GameRound.games.through BUT I want to be able to edit the fields within the Game model as well rather than popping a window. I've tried adding: fields = ['games__home_team','games__home_score','games__away_score','games__away_team','games__match_date'] which works for a ManyToOne relationship (ie when Game has a ForeignKey to GameRound) but here gives the error: Unknown field(s) (games__home_team, games__home_score, games__away_team, games__away_score, games__match_date) specified for GameRound_games Is there a way to achieve this? -
Best approach for AWS permissions to allow upload new files and publicly read static/media files for Django website on Heroku
AWS Permissions What is the best approach to make sure the account, bucket and everything is properly secured and on top of that by pushing code to Heroku (Django Website) and using boto s3 library it can upload files to bucket (static, media - via Django Admin / Forms) and the website is properly working. These are the settings in the settings.py AWS_ACCESS_KEY_ID = env('DJANGO_AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = env('DJANGO_AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = env('DJANGO_AWS_STORAGE_BUCKET_NAME') AWS_S3_REGION_NAME = env('REGION_NAME') # e.g. us-east-2 AWS_S3_CUSTOM_DOMAIN = '{}.s3.amazonaws.com'.format(AWS_STORAGE_BUCKET_NAME) AWS_AUTO_CREATE_BUCKET = True AWS_QUERYSTRING_AUTH = False AWS_S3_CALLING_FORMAT = OrdinaryCallingFormat() AWS_DEFAULT_ACL = "public-read" Right now my settings are: OFF OFF ON ON Is this proper combination - or what else I should do to protect the bucket more that I have no some security holes but keeping in mind that website is working including uploading files / images via admin and static files. -
Redirecting to root URL from another app's view
I am trying to redirect to root URL when an app's URL is accessed without the user being logged-in. I've tried to do so in 2 ways: Using a decorator @login_required(login_url = '') def index(request): return render(request, 'professors/index.html') Which returned a 404 error saying the current path is accounts/login Passing the views of the root page to redirect def index(request): if request.user.is_authenticated: return render(request, 'professors/index.html') else: return redirect('login.views.index') Which returned a 404 error saying the current path is professors/login.views.index The root URL is localhost:8000/ and I am trying to redirect to it after accessing localhost:8000/professors/ when the user is not logged-in. This problem is similar to what I've found here: Django redirect to root from a view However, applying the solution did not work for me. It looks like when redirecting to root from an app's view, the root it is redirecting to is the app's root, and not the website's, and this is true for any URL redirected after accessing an app's URL. E.g., if the root URL is localhost:8000 and the app's URL is localhost:8000/professors/, then trying to access any other URL from the latter, will mean that localhost:8000/professors/ is the starting point and what I write in … -
How to update a model field using templates?
I am working on a project that allows users to register, but the model contains a verified field and only admin can change it. User can log in only when verified = True. Also, I need to implement that once a user is verified, he gets notified through a mail. Is there a way to connect the mail url to the verified field? If it can be done through templates, How? I want to redirect to mail url as soon as admin updates the verified field. -
Why is form_valid not getting the sent POST parameters?
I am trying to send a POST request with a parameter by using a form with a hidden input in Django. However, the receiving view does not get the POST parameter I am sending. Here's the form in my post_detail.html template: <form action="{% url 'something-create' %}" method="POST"> {% csrf_token %} <input type="hidden" name="id_name" value="2"> <button type="submit">Add</button> </form> Then, here's the view that is called by the 'something-create' url pattern: class SomethingCreateView(CreateView): model = Something template_name = "something_create.html" def form_valid(self, form): # id_name always returns None... id = self.request.POST.get("id_name") if id is not None: form.instance.sm = Something.objects.get(id=int(id)) return super().form_valid(form) Can anyone tell me what I'm doing wrong? Thank you in advance. -
how to fix a problem where a django template isn't displayed correctly in the email
I have a template which is supposed to display an html template for a reset password. I do receive the email, but the result is not the template itself but the code inside the template. I've tried to see if there was any error in the html file, but i didn't find any What is inside the Template is only HTML code : <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>Réinitialisation de votre mot de passe</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <style type="text/css"> ... ... ... I do receive the email but i receive the code inside the file, not the compiled html code. Thank you -
Proper way to do Mixins for Django models
I have the following mixins: class AbandonableMixin(object): is_abandoned = models.BooleanField( default=False, verbose_name=_('Abandoned?')) class ReadyMixin(object): is_ready = models.BooleanField( default=False, verbose_name=_('Ready?')) class StoppableMixin(object): is_stopped = models.BooleanField( default=False, verbose_name=_('Stopped?')) I would like to use these in my class like ordinary mixins: class MyObject(models.Model, AbandonableMixin, StoppableMixin): ... class MySecondObject(models.Model, ReadyMixin, StoppableMixin): ... This results in the following error: TypeError: Cannot create a consistent method resolution order (MRO) for bases Model, AbandonableMixin What am I doing wrong?