Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Issue with Model form
forms.py from django import forms from .models import Topic class TopicForm(forms.Form): class Meta: model = Topic fields = ['text'] labels = {'text':''} I receive a runtime error when I run this this code. The error is 'TopicForm has no attribute 'save'. i am using a model form. views.py def new_topic(request): """Add a new topic.""" if request.method != 'POST': # No data submitted; create a blank form. form = TopicForm() else: # POST data submitted; process data. form = TopicForm(data=request.POST) if form.is_valid(): form.save() return redirect('learning_logs:topics') # Display a blank or invalid form. context = {'form': form} return render(request, 'learning_logs/new_topic.html', context) -
How to inject data in a template out of context in html django? form python
forms are passed to the template, which are loaded dynamically depending on the record in the database. that is, in a loop I add shape objects with a key in the form of a number you need to display all forms in a loop in html views class OrderAddView(TemplateView): template_name = 'orders/order_add.html' def get(self, request, *args, **kwargs): context = super().get_context_data(**kwargs) related = self.checkRelated() if related: tag = 0 for x in related: tag += 1 formPath = x.module_name + '.forms' app_form = importlib.import_module(formPath) context[tag] = app_form.RelatedAddForm context['count_form'] = range(1, tag+1) formOne = SimpleOrderAddForm() formOne.prefix = 'one_form' context.update({'formOne': formOne}) return self.render_to_response(context) html <form action="{% url 'order_add' tag %}" method="post"> {% csrf_token %} {% for x in count_form %} {{ context[x].as_p }} {{ x.as_p }} {% endfor %} {{ formOne.non_field_errors }} {{ formOne.as_p }} <button type="submit" class="btn btn-primary btn-block">Add order</button> </form> forms do not appear! how to specify a reference to an object by this key in a loop? if I output directly, for example {{1.as_p}}, it outputs the form, but if {{x.as_p}} is in a loop, where x = 1, it doesn't. how to be print context form {'tag': 'fast', 'view': <orders.views.OrderAddView object at 0x0000000007422DF0>, 1: <class 'clients.forms.RelatedAddForm'>, 'count_form': range(1, 2)} -
Error when running django-admin in command line "ModuleNotFoundError: No module named 'asyncio.base_events'"
Created the virtual env with pyenv pyenv init pyenv shell 3.9.0 python -m venv name_of_venv Installed Django through pip in a virtual env: pip install Django==3.1.7 Then when I run django-admin in cmd line I get the following error: File "/Users/sushensatturu/envs/excel/bin/django-admin", line 5, in <module> from django.core.management import execute_from_command_line File "/Users/sushensatturu/envs/excel/lib/python3.9/site-packages/django/core/management/__init__.py", line 12, in <module> from django.conf import settings File "/Users/sushensatturu/envs/excel/lib/python3.9/site-packages/django/conf/__init__.py", line 19, in <module> from django.utils.deprecation import RemovedInDjango40Warning File "/Users/sushensatturu/envs/excel/lib/python3.9/site-packages/django/utils/deprecation.py", line 1, in <module> import asyncio File "/Users/sushensatturu/.pyenv/versions/3.9.0/lib/python3.9/asyncio/__init__.py", line 8, in <module> from .base_events import * -
Django: Page not found , Raised by:django.views.static.serve
I am trying to display a static image in django. When I select image using django admin portal then it's works fine. it is displaying image. But when I select image from my front-end page, I get: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/media/destination-2.jpg Raised by: django.views.static.server Here are my codes: urls.py from django.urls import path,include from django.conf import settings from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns from mainapp import views urlpatterns = [ path('admin/', admin.site.urls), path('', include('mainapp.urls')), ] admin.site.site_header = "Login to our web Portal" admin.site.site_title = "This is Admin Portal" admin.site.index_title = "Welcome to Amnet" #urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) settings.py STATICFILES_DIRS=[os.path.join(BASE_DIR,'static') ] MEDIA_URL='/media/' MEDIA_ROOT=os.path.join(BASE_DIR,'media') models.py from django.db import models # Create your models here. class Amnet(models.Model): imagee = models.FileField(default='bg_2.jpg') views.py from django.shortcuts import render from mainapp.models import Amnet # Create your views here. def index(request): if(request.method == "POST"): imagee= request.POST.get('imagee') am = Amnet(imagee=imagee) am.save() return render(request,'image-main.html') else: return render(request,'image-main.html') html page <form action="" method="POST"> {% csrf_token %} <td><input type="file" name="imagee" id="file"></td> <td><img src="" id="profile-img-tag" width="200px" /></td> </tr> </table> <input type="Submit" value="Submit" id="btn"><br> </form> -
meaning of django migrate ModuleNotFoundError
https://tryhackme.com/room/django I am trying to follow the above django tutorial. django-admin startproject mysite cd mysite python3 manage.py migrate python3 manage.py startapp Articles In mysite/settings.py, I modified the following line. INSTALLED_APPS = [ 'Articles', # add 'django.contrib.admin', ... In mysite/urls.py, I changed the following lines. from django.urls import path, include # modified urlpatterns = [ path('Articles/', include('Articles.urls')), # added But when I run the following command, it fails. Does anybody know what is wrong? Thanks. $ python3 manage.py migrate Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 361, in execute self.check() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 65, in _run_checks issues.extend(super()._run_checks(**kwargs)) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/utils/functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/urls/resolvers.py", line 584, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File … -
Cual es la forma correcta de importar una app en INSTALLED_APPS cuando las app esta en una carpeta?
Estoy trabajando en un pequeño proyecto y tiene la siguiente estructura de directorios: Web/ apps/ crud login perfil necesito poner la configuraciones de mi app en INSTALLED_APPS pero no se de que forma ya que lo normal seria : perfil.apps.PerfilConfig lo hago de esta manera : apps.perfil.apps.PerfilConfig y me sale el siguiente error """ django.core.exceptions.ImproperlyConfigured: Cannot import 'perfil'. Checkthat'apps.perfil.apps.PerfilConfig.name' is correct """ mi pregunta es, cual es la manera de hacerlo cuando las app estan en otra carpeta, gracias -
{{ form.object }} in Django UpdateView
According to the docs self.object exists for UpdateView Template: {% block content %} <p> {{ form.object.some_foreign_key }} </p> <form method="post"> {{ form.as_p }} <input type="submit" value="Update"> </form> {% endblock %} But form.object does not exist: Failed: Undefined template variable 'form.object' in '/foo/bar_form.html' Why does form.object not exist in the template? -
How can I filter the results of a view with multiple contexts in Django?
I want to make a view that details the poll result listing the alternatives and the total votes for each alternative, but I can't filter the votes since a list of alternatives is returned when I take the poll's pk. So I can't filter the votes by the alternative pk. class Poll(models.Model): text = models.TextField(max_length=500, verbose_name="Poll") class Alternative(models.Model): poll = models.ForeignKey(Poll, on_delete=models.CASCADE) alternative_text = models.CharField(max_length=50, verbose_name="Alternative") class Vote(models.Model): alternative = models.ForeignKey(Alternative, on_delete=models.CASCADE) quantity_votes = models.IntegerField(default=0, null=True, blank=True) vote_date = models.DateField(auto_now=True) # My view def result_poll(request, pk): poll = Poll.objects.get(pk=pk) alternatives = Alternative.objects.filter(poll_id=poll.id) votes = Vote.objects.filter(alternatives) #just to exemplify context = { 'poll': poll, 'alternatives': alternatives, 'votes': votes, } return render(request, 'result.html', context) -
Django is loading template from the wrong app
I have a view under my elearning app named home(), which should load index.html from within the app's directory. Instead it loads an instance of index.html from a different app (symposium/templates/index.html). It should be loading it from (elearning/templates/index.html). Can someone please explain why this is happening and how to fix it? # Settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Machina dependencies: 'mptt', 'haystack', 'widget_tweaks', # Machina apps: 'machina', 'machina.apps.forum', 'machina.apps.forum_conversation', 'machina.apps.forum_conversation.forum_attachments', 'machina.apps.forum_conversation.forum_polls', 'machina.apps.forum_feeds', 'machina.apps.forum_moderation', 'machina.apps.forum_search', 'machina.apps.forum_tracking', 'machina.apps.forum_member', 'machina.apps.forum_permission', # SCORM apps: 'accounts', 'symposium', 'elearning'] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates'), MACHINA_MAIN_TEMPLATE_DIR,], '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', 'machina.core.context_processors.metadata', ], }, }, ] # root urls.py from django.contrib import admin from django.urls import path, include from machina import urls as machina_urls from accounts.views import CreateUser from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('forum/',include(machina_urls)), path('admin/', admin.site.urls), path('createuser',CreateUser.as_view()), path('symposium/', include('symposium.urls')), path('elearning/', include('elearning.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # elearning app urls.py from django.urls import include, path from . import views app_name = 'elearning' urlpatterns = [ path('', views.home, name='home'), ] # app: elearning/views.py from django.shortcuts import render # Create your views here. def home(request): return render(request,'index.html',{}) # index.html location … -
Send data to websocket via signals
I hope you all are doing well. I have been trying to create a notification system that will push messages to websocket via post_save signals from database. I have a Notification model that creates notification and I want to push notifications whenever a notification is created to the appropriate user, any help in it would be much appreciated. Signals.py def send_message(event): ''' Call back function to send message to the browser ''' message = event['text'] channel_layer = channels.layers.get_channel_layer() # Send message to WebSocket print("Sending message to websocket") async_to_sync(channel_layer.send)(text_data=json.dumps( message )) @receiver(post_save,sender=Notification) def notification_handler(sender,instance,created,*args,**kwargs): message={ 'text':instance.text } print(message) user=str(instance.to.pk) groupname=f"user_{user}" channel_layer = channels.layers.get_channel_layer() async_to_sync(channel_layer.group_send)( groupname, { 'type': 'send_message', 'text': message } ) This is how my consumer.py looks like consumer.py class NotificationConsumer(AsyncWebsocketConsumer): async def websocket_connect(self,event): print("connected",event) self.channel_layer=channels.layers.get_channel_layer() self.user = self.scope['url_route']['kwargs']['user_id'] self.group_name =f"user_{self.user}" await self.channel_layer.group_add( self.group_name, self.channel_name ) await self.accept() async def websocket_disconnect(self,event): print(event,"closed") -
Django Python Error: Reverse for 'user-posts' with arguments '('',)' not found
I'm building a Django app using a popular tutorial (by @CoreyMSchafer) as a starting point. I'm getting the below error when I load http://localhost:8000/test/ in my browser. Reverse for 'user-posts' with arguments '('',)' not found. 1 pattern(s) tried: ['user/(?P<username>[^/]+)$'] models.py: from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from datetime import datetime # timezone takes timezone into consideration (even though it doesn't seem to) # we're inheriting from the models.Model # https://docs.djangoproject.com/en/3.1/topics/db/models/ class Post(models.Model): title = models.CharField(max_length=100) # character field content = models.TextField() # Unrestricted text date_posted = models.DateTimeField(default=timezone.now) last_modified = models.DateTimeField(auto_now=True) # author is a one-to-many relationship which uses a foreign key # the argument to ForeignKey is the related table # on_delete tells django to delete all posts by a user when that user is deleted author = models.ForeignKey(User, on_delete=models.CASCADE) # Convenience method to print out the title of a Post def __str__(self): return self.title def get_absolute_url(self): # todo: uncomment return reverse('post-detail', kwargs={'pk': self.pk}) class Game_c(models.Model): name = models.TextField() # Unrestricted text platform = models.CharField(max_length=100) # character field created_date = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name # return game name when game.objects.all() is called blog/views.py: from django.shortcuts … -
django admin url raises error 500 on heroku
I am having persistent '500' errors in a django app deployed on heroku. I haven't checked my django admin in a few months since november 2020 but now the error appears when trying to login to admin via the url both in my staging and production versions of the app : django.contrib.sites.models.Site.DoesNotExist: Site matching query does not exist. I am clueless on what might have caused this error since it also affects the production one and no changes have been applied to it since its last working version. -
what is the django query equivalent this next sql query
This is the sql query: SELECT TOP (1000) * FROM [dbo].[app_register] WHERE DATEDIFF(DAY, [start_date], SYSDATETIME() ) > (([duration] *30)/ 2) - 10 AND [period] = 55 My model: -
if request.META.get('HTTP_REFERER') working with Chrome but not Safari
I have the following function redirecting users if they have not come to the page from a Stripe checkout. The page will load if coming from a checkout on google chrome but if using safari on laptop on IOS it will redirect. Is there a way I can fix this to work on safari? - def register(request): if request.META.get('HTTP_REFERER') == "https://checkout.stripe.com/": return render(request, 'users/register.html') else: return redirect('error') I also have the settings for my site as SECURE_REFERRER_POLICY = "no-referrer-when-downgrade" -
Regex not matching in url
I have designed the following url pattern re_path(r'^api/refresh-token/(?P<token>[1-9]+\_[0-9a-f]{32}\Z)/$',refresh_token) 1_6506823466dc409a93b83b2c5f3b7cf2 matches the pattern [1-9]+\_[0-9a-f]+\Z. But when i hit the url it is not found. System check identified no issues (0 silenced). March 15, 2021 - 02:10:29 Django version 3.1.7, using settings 'tokenproject.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Not Found: /api/refresh-token/1_6506823466dc409a93b83b2c5f3b7cf2/ [15/Mar/2021 02:10:32] "PUT /api/refresh-token/1_6506823466dc409a93b83b2c5f3b7cf2/ HTTP/1.1" 404 3279 -
Django Integrity Error: null value in non-existent column
I am working on adding a foreign key relation between two models (Experience & Scheduler) in Django. When I originally went to add the foreign key of Experience to Scheduler, I ended up receiving an integrity error. I then removed the foreign key relation and updated my models accordingly so I could test. This still resulted in an error when I went to save my Scheduler object (I don't 100% remember but I'm pretty sure it was still an IntegrityError). I looked into some different solutions to this and I decided to run python manage.py flush to clear the database entirely because I'm on my local host and my own branch. The integrity error is still there even after wiping the database and removing the foreign key relation and I do not know why. I have been trying to figure out what the failing row represents because it doesn't look like either one of the models. The only thing I have discovered about it is that when I refresh my error page, index 0 of the column increments by one. Experience Models: from django.db import models class Experience(models.Model): type = models.CharField(max_length = 10, null=False, blank=True) description = models.TextField(max_length=100, null=False, blank=True) … -
Testing a PUT request in Django Rest Framework
When I run this test def test_update_car(self): new_car = Car.objects.create(make='Chevy', model='Equinox', year=2012, seats=4, color='green', VIN='12345671234567abc', current_mileage=19000, service_interval='3 months', next_service='april') url = reverse('car-detail', kwargs={'pk': new_car.pk}) data = { 'make': 'test', 'model': 'test', 'year': 2014, 'seats': 5, 'color': 'blue', 'VIN': '12345671234567abc', 'current_mileage': 20000, 'service_interval': '6 months', 'next_service': 'July', } response = self.client.put(url, data=data) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(new_car.make, 'test') I get an assertion error AssertionError: 'Chevy' != 'test' How should I structure this differently so that the PUT request actually changes the make and model of the new_car? -
How to log into my multi user types in django rest api
I have created my extended my model.py having four different class User(AbstractUser): is_phamacy = models.BooleanField(default=False) is_restaurant = models.BooleanField(default=False) is_grocery_shop = models.BooleanField(default=False) is_rider = models.BooleanField(default=False) class Restaurant(models.Model): restaurant_user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) restaurant_name = models.CharField(max_length=255,blank=True) full_name_of_merchant = models.CharField(max_length=255,blank=True) government_id = models.ImageField(upload_to = 'media/government_id' , null = True, blank=True) images_of_restaurants = models.ImageField(upload_to = 'media/images_of_restaurants' , null = True, blank=True) position_in_restaurant = models.CharField(max_length=255,blank=True) is_your_business_registered = models.BooleanField(default=True) tin_number = models.CharField(max_length=255,blank=True) longitude = models.FloatField(default=0000) latitude = models.FloatField(default=0000) long_you_have_been_working = models.IntegerField() want_delivery_guy = models.BooleanField(default=True) is_verified = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) and the others to follows but they have a different details taken which not done but with this the serializer.py is class RestaurantRegistrationSerializer(RegisterSerializer): restaurant_user = serializers.PrimaryKeyRelatedField(read_only=True,) #by default allow_null = False restaurant_name = serializers.CharField(required=True) full_name_of_merchant = serializers.CharField(required=True) government_id = serializers.ImageField(required=True, use_url=True) images_of_restaurants = serializers.ImageField(required=True, use_url=True) position_in_restaurant = serializers.CharField(required=True) is_your_business_registered = serializers.BooleanField(required=True) tin_number = serializers.CharField(required=True) longitude = serializers.FloatField(required=True) latitude = serializers.FloatField(required=True) long_you_have_been_working = serializers.IntegerField(required=True) want_delivery_guy = serializers.BooleanField(required=True) def get_cleaned_data(self): data = super(RestaurantRegistrationSerializer, self).get_cleaned_data() extra_data = { 'restaurant_name' : self.validated_data.get('restaurant_name', ''), 'full_name_of_merchant' : self.validated_data.get('full_name_of_merchant', ''), 'government_id': self.validated_data.get('government_id', ''), 'images_of_restaurants': self.validated_data.get('images_of_restaurants', ''), 'position_in_restaurant': self.validated_data.get('position_in_restaurant', ''), 'is_your_business_registered': self.validated_data.get('is_your_business_registered', ''), 'tin_number': self.validated_data.get('tin_number', ''), 'longitude': self.validated_data.get('longitude', ''), 'latitude': self.validated_data.get('latitude', ''), 'long_you_have_been_working': … -
(Allauth) Resending verification redirects to another page
In a custom template for a profile page, I have this form to resend a verification email: {% extends "main/base.html" %} {% load static %} {% load account %} {% block title %}Home{% endblock %} {% block body %} <p>Username: {{user.username}}</p> <p>Email: {{user.email}} {% if emailadress.verified %}(Verified){% endif %} (Unverified)</p> <form action="/accounts/email/" method="post"> {% csrf_token %} <input style="display:none" type="text" name="email" value="{{user.email}}" readonly> <button class="btn-auth" type="submit" name="action_send">Resend Verification</button> </form> {% endblock %} This form is submitted from a view located at /accounts/profile/, but when submitted, it redirects the user to /accounts/email/. I looked through the source code for allauth, but I couldn't wrap my head around how the redirect URL is determined. I tried adding a next value in the form, but that didn't do anything. Is there any way to specify the URL to redirect to after resending the verification or should I just move the /accounts/profile/ template to /accounts/email/? -
How to implement something like f-string, which calls conditional_escape()?
I like f-Strings in Python. And I like Django's SafeString. I know Django's format_html() method, but f-Strings are easier to use. Is there a way to implement something like f-Strings, but all variables get passed to conditional_escape() first? What I would like to have: local and global variables are directly available I would like to be able to do method calls inside the string. -
Django ORM get data with two aggregations where one depends on other
I'm trying to write query with next two iterations: Get avg s_sum grouped by region and city - "avg_city" Get minimum "avg_city" for each region. Model: class RegionStat(models.Model): region = models.IntegerField() city = models.IntegerField() seller = models.IntegerField() s_sum = models.IntegerField() Code to fill data: d = ((1,1,1,100), (1,1,2,200), (1,2,3,300), (1,2,4, 400), (1,2,5, 500), (1,3,6, 600), (1,3,7,700), (2,1,1, 200), (2,1,2,300)) for i in d: r = RegionStat() r.region, r.city, r.seller, r.s_sum = i r.save() Expected result: |region|min_avg_reg| |:-:|:-:| |1|150| |2|250| My progress stopped on getting: <QuerySet [{'region': 1, 'avg_city': 150.0}, {'region': 1, 'avg_city': 400.0}, {'region': 1, 'avg_city': 650.0}, {'region': 2, 'avg_city': 250.0}]> With this query: a = RegionStat.objects.annotate(avg_city=Window(expression=Avg('s_sum'),partition_by=[F('region'), F('city')])).only('region').order_by('region', 'avg_city').values('region', 'avg_city').distinct() I tried to use Subquery, but problem is i can get only one column from subquery, but i need region and avg_city to make second aggregation. -
Pushing data from an api response to an active django channel
I am new to django channels and figuring out a way to push a response from an api to an active websocket connection. Here I have a chat with two users and if I am sending a response from an api, I need to show that message from the api response to the active room. I have something like this now for testing. async def send_message_from_api(message, chat): channel_layer = get_channel_layer() chat_room = f"chat_{chat}" await channel_layer.group_send( chat_room, { 'type': 'websocket.send', 'text': message, } ) and in django rest post function, something like this, ChatConsumer.send_message_from_api(serializer.data, chat.id) This might be a dumb try, but it doesn't work. Can someone suggests a proper way to do it? or can modifying this code make it work? Thanks -
Django: Resolving "Reverse for 'password_reset_complete' not found."
I am attempting to do a password reset using Django using custom html templates. I am able to request an password reset by email (using the EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'), and I then get an "email" in the console, as I would like. The email does lead me to the "password_reset_confirm.html" page as I would like, and I can input the new passwords for the user associated with the user. However I am getting the following error when I click the "Reset password!" button: "Reverse for 'password_reset_complete' not found. 'password_reset_complete' is not a valid view function or pattern name." Despite this error, the password does actually change, however I (obviously) do not want this error. The structure of the project has a users "app" within the main structure, so it is: project main_app users ----templates --------registration ------------password_reset_form.html ------------password_reset_confirm.html ------------password_reset_done.html ------------password_reset_email.html ------------password_reset_complete.html My code for urls.py in users is as follows: from django.urls import path, include, reverse_lazy from . import views from django.contrib.auth import views as auth_views app_name = 'users' urlpatterns = [ # Default authorisation urls. path('', include('django.contrib.auth.urls')), # Registration page. path('register/', views.register, name='register'), # Password reset urls. path( 'password_reset', auth_views.PasswordResetView.as_view( template_name='registration/password_reset_form.html', email_template_name='registration/password_reset_email.html', success_url=reverse_lazy('users:password_reset_done') ), name='password_reset' ), path( 'password_reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='registration/password_reset_done.html'), name='password_reset_done' … -
Download dynamic html with images as PDF with watermark using Django Python
I am trying to create a quiz webapp where users can take the quiz online or offline. In offline mode, the user should be able to click on a button and download the pdf content with images and watermark. My dynamic html content also contains mathematical equations which is printed using Mathjx and WIRIS plugin. I have tried the following , but Its super slow in rendering I am unable to print watermark in the middle diagonally. I have also tried printing using jquery/canvas but since the html is dynamically generated, the print isn't working. Can this be achieved using jquery and some javascript packages ? Please suggest a faster method if possible. Also, when I click ,it takes around 15 seconds to download the file. I wanted to use ajax method to show in progress but unable to achieve it. Any help is appreciated. class GeneratePdf(View): def get(self, request, *args, **kwargs): #template = get_template('dashboard/exam-pdf.html') quizid = request.GET.get('quizid') quiz = Quiz.objects.get(id=quizid) questions= #Rendering Questions from model with images and MCQ Options print("link clicked") context = { 'questions': questions, 'essayquestions': essayquestions, 'quizid':quizid, 'quiz': quiz } pdf = render_to_pdf('dashboard/exam-pdf.html',context) #rendering the template return HttpResponse(pdf, content_type='application/pdf') My exam-pdf.html {% extends 'base.html' %} {% … -
Why are my media files not working in production
For server I am using Linode, as DataBase MySql, and apache2. The static files working perfectly, but images(media files) does not display :(. Already tried to restart server and change the urls.py file! settings.py STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' # STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' urls.py STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' # STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' project configuration file <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName www.example.com ServerAdmin webmaster@localhost DocumentRoot /var/www/html # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. …