Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to restrict AuthenticateCallbackView in django-microsoft-auth only to registered accounts?
I am using django-microsoft-auth in my Django project. I am trying to restrict this option only to registered users so only people who have already registered themselves are allowed to use Log in with Microsoft button. I found in AuthenticateCallbackView method called _authenticate. Code below: def _authenticate(self, code): if "error" not in self.context["message"]: if code is None: self.context["message"] = {"error": "missing_code"} else: # authenticate user using Microsoft code user = authenticate(self.request, code=code) if user is None: # this should not fail at this point except for network # error while retrieving profile or database error # adding new user self.context["message"] = {"error": "login_failed"} else: login(self.request, user) I am wondering how can I restrict authentication only to those who have accounts. In case someone doesn't have an account it would send a message: Please register your account first. -
django how to fetch upload folder path
I know how to upload multiple files through Django, but I have a problem when uploading a folder if there are subfolders in it. So I want the user to upload the folder and I get the root, dirs, and files of that folder the user upload. HTML code: <input type="file" name="file_name" multiple = "true" webkitdirectory="true" directory = "true"/> python code: def uploader_folder(request): data = {} if request.method == 'POST': file = request.FILES.getlist('file_name') for i in file: print(i) and here I received only file names. but I want to know the dir, or root path also -
Unable to submit the regitrations form in django
enter image description here while clicking register, the details not saving to database and the page is not redirected to the index page. views.py from django.shortcuts import render,redirect from django.views.generic import View from Angram.forms import RegistrationForm # Create your views here. class IndexView(View): def get(self,request,*args,**kwargs): return render(request,"index.html") class RegistrationView(View): def get(self,request,*args,**kwargs): form=RegistrationForm() return render(request,"register.html",{"form":form}) def post(self,request,*args,**kwargs): form=RegistrationForm(request.POST) if form.is_valid(): User.objects.create_user(**form.cleaned_data) return redirect("index-main") else: return render(request,"register.html",{"form":form}) forms.py from django import forms from django.contrib.auth.models import User class RegistrationForm(forms.ModelForm): class Meta: model=User fields=["first_name","last_name","username","email","password"] urls.py from django.contrib import admin from django.urls import path from Angram import views urlpatterns = [ path('admin/', admin.site.urls), path("index/",views.IndexView.as_view(),name="index-main"), path("accounts/register/",views.RegistrationView.as_view(),name="signup"), ] -
Django Send Email ( Add logo on mail)
I would like to send an email in Django by add the logo of the website I am sending from something the user will know that this mail is coming from me just like LinkedIn or any platform where you see the company logo before clicking on the mai Example -
Allow Celery Worker to consumes messages from non task queue
I have a django backend which is running Celery for distributed tasks. I have created a Service bus queue which stores temperature data coming from hundred of frontend devices. I am running Celery periodic task every 5 seconds to consume those messages. But the problem is the tasks will be scheduled even if there are no messages in the TEMPERATURE queue. Is there a way I can set up a Celery worker that can listen to the this queue and operate on it when there is a new task available? Keep in mind this queue is not a tasks queue. -
How to pass params using fetch API in vuejs vuex store action
I am trying to pass a dict using fetch API to django views but unable to get it in request dict of views. I have tried below steps fetch(`/api/getnames`, [{'a': name, 'b': name}]) .then() .catch((err) => { console.log('Fetch Error :-S', err); }); def getnames(request): print(request.__dict__) I am trying to get the dict passed in params while calling the url but dict is not present. Kindly suggest a solution to resolve this issue. -
Data class serialization with blank string in Django
I have a data class in Django using the rest framework, that has a string field and a serializer for it. class Foo: string_field:str class FooSerializer(Dataclass): class Meta: dataclass = Foo My problem is that, if the string_field is blank, the serializer cannot be validated. The JSON I am calling with: {'string_field': ''} And the error: {'string_field': [ErrorDetail(string='This field may not be blank.', code='blank')]} Declaring the fields in the serializer and not using a data class is a solution, but I'd prefer to use the data class way if its possible. In my project I am using Django 3.0.5, Python 3.8 and 3.11 of the rest framework. -
When i change db postgres to mysql,Its showing Django 2026, SSL connection error
I change my database postgres to sql ,Now its showing ssl error Nothing expect or try, just need answer , so thank you -
Django: Create a dynamic sidebar template and use it in other templates
NOTE: This question is not about creating or using a base template! I'm creating a products app in my project, using only django and html/css, and all pages in this part has a sidebar nav menu that categorizes different product models and types. So this sidebar will be used in all other product pages. Inorder to categorize products, I've created this view for the sidebar: def sidebar_data(request): usage_queryset = Usage.objects.all() sub_usage_queryset = SubUsage.objects.all() main_model_queryset = MainModel.objects.all() pump_type_queryset = PumpType.objects.all() context = { "usage_queryset": usage_queryset, "sub_usage_queryset": sub_usage_queryset, "main_model_queryset": main_model_queryset, "pump_type_queryset": pump_type_queryset, } return render(request, "products/products_sidebar.html", context) And the sidebar template is as shown below: <ul class="nav flex-column list-unstyled my-3 ms-3"> {% for usage_item in usage_queryset %} <li class="nav-item p-2 ms-4"> <a href="#" class="text-decoration-none nm-text-color fw-semibold" data-bs-toggle="collapse" data-bs-target="#usage_{{ usage_item.usage_name_fa }}"> <i class="fa-solid fa-angle-left me-2 icon-selector"></i> الکتروپمپهای {{ usage_item.usage_name_fa }} </a> <ul class="submenu collapse" id="usage_{{ usage_item.usage_name_fa }}" data-bs-parent="#nav_accordion"> {% for sub_usage in sub_usage_queryset %} {% if sub_usage.usage == usage_item %} <li class="my-2 ms-4"> <a href="#" class="text-decoration-none nm-text-color fw-semibold"> {{ sub_usage }} </a> </li> {% endif %} {% endfor %} </ul> </li> {% endfor %} </ul> And now I'm creating a proucts main page for example, which should implement this sidebar. I included this … -
how to filter by date with datetimefield in Django with MYSQL
Datetimefield in MYSQL cannot be filtered by date. class Data(models.Model): created_at = models.DateTimeField(default=timezone.now) As docs, it could be filtered by date: qs = Data.objects.fitler(created_at__date__lte='2022-01-01') It works fine with sqlite3, but it always return empty queryset with MYSQL. -
Override Django Slug
I have a blog in wagtail. Wagtail's default Page model already has a slug field defined. Full Example is here slug = models.SlugField( verbose_name=_("slug"), I have a Subclass AddStory of the Page class, so I am unable to define slug there. And I am getting a clashing error. Problem: The slug field automatically generates a slug from the Title. So There are some kind of event whose title will be same always. Like Jokes of the day, So for the first 10 or 20 days, editors will know that they have added 20 posts with day_1,day_2... at the end of the slug and when these days will increase it will be impossible for them to remember how many they have entered?! Probable Solution So if I can automate the slug as it will generate a slug from random ids or strings and it will be unique. I tried this in the subclass AddStory def pre_save(self): def randomid1(self): return(get_random_string(length=10)) self.slug = randomid1 How can I define that it will not generate slug from the title instead it will generate a slug from given random strings? -
This field is required DRF Nested Serializers
I'm getting This field is required error while creating a nested serializer. I have ReviewRatings and ReviewImages models in which ReviewImages is FK to ReviewRatings so that an user can upload single or multiple images along with reviews. And the problem arises when i don't add required=True in serializer. If it's False then there is no problem at all. #Models.py class ReviewRatings(models.Model): user = models.ForeignKey(Account, on_delete=models.CASCADE) product = models.ForeignKey(Products, on_delete=models.CASCADE) rating = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(5)]) created_at = models.DateField(auto_now_add=True) review = models.CharField(max_length=500, null=True) updated_at = models.DateField(auto_now=True) class Meta: verbose_name_plural = "Reviews & Ratings" def __str__(self): return self.product.product_name class ReviewImages(models.Model): review = models.ForeignKey( ReviewRatings, on_delete=models.CASCADE, related_name="review_images", null=True, blank=True, ) images = models.ImageField(upload_to="reviews/review-images", null=True, blank=True) def __str__(self): return str(self.images) #Serializers.py class ReviewImagesSerializer(ModelSerializer): class Meta: model = ReviewImages fields = ["images"] class ReviewSerializer(ModelSerializer): user = SerializerMethodField() review_images = ReviewImagesSerializer(many=True, required=False) class Meta: model = ReviewRatings fields = [ "user", "rating", "review", "created_at", "updated_at", "review_images", ] def get_user(self, obj): return f"{obj.user.first_name} {obj.user.last_name}" def validate(self, obj): review_images = self.context["images"] max_size = [5 * 1024 * 1024] rev_img_size = [i.size for i in review_images] if rev_img_size > max_size: raise ValidationError({"error": "Size cannot exceed 5 MB"}) elif len(review_images) > 3: raise ValidationError({"error": "you cant upload more than 3 photos"}) … -
AttributeError: 'GenericRelatedObjectManager' object has no attribute
I tried to use generic relation in django project. but it gives attribute error. Generic relation is between UniqueSourcePresenter and UniqueDbSource i have an instance of TextTable which has a foreignkey attribute for UniqueSourcePresenter i tried to use reverse relation as self.presenter.texttable in UniqueDbSource's instance method. but it gives error es below File "/usr/src/app/apps/tableau/models/source.py", line 191, in create_datum backend | if self.presenter.texttable is not None: backend | AttributeError: 'GenericRelatedObjectManager' object has no attribute 'texttable' My models are like follows class UniqueSourcePresenter(models.Model): """ Generic Relation Manager of all types of source """ # Below the mandatory fields for generic relation limit = models.Q(app_label = 'tableau', model = 'UniqueDbSource'.lower()) | models.Q(app_label = 'tableau', model = 'UniqueAPISource'.lower()) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, limit_choices_to = limit) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() pass class DataSource(models.Model): pass class UniqueSource(DataSource): presenter = GenericRelation(UniqueSourcePresenter) class Meta: abstract = True class UniqueDbSource(UniqueSource): """ THIS CLASS ADDED TO CONTENTTYPE """ def create_datum(self): """ THIS METHOD CALLED WITH SIGNAL """ d = DatumDb() d.title = f"{self.title}_datum" if self.presenter.texttable is not None: ## THIS LINE GIVES ERROR d.connector = self.presenter.texttable.init_source.data.connector query = self.presenter.texttable.init_source.data.query elif self.presenter.charttable is not None: d.connector = self.charttable.presenter.init_source.data.connector query = self.charttable.presenter.init_source.data.query query.pk = None query.save() d.query = query d.save() … -
Error while installing mysqlclient in django
I'm trying to install mysqlclient using pip install mysqlclient But facing the following error Collecting mysqlclient Using cached mysqlclient-2.1.1.tar.gz (88 kB) Preparing metadata (setup.py) ... done Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error ERROR: Command errored out with exit status 1: command: /home/pixarsart/PycharmProjects/video_slicing/venv/bin/python -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-uljhxj0e/mysqlclient_bcf14369053645289dd7e777e689db38/setup.py'"'"'; __file__='"'"'/tmp/pip-install-uljhxj0e/mysqlclient_bcf14369053645289dd7e777e689db38/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-r6zmjoeu cwd: /tmp/pip-install-uljhxj0e/mysqlclient_bcf14369053645289dd7e777e689db38/ Complete output (43 lines): mysql_config --version ['8.0.31'] mysql_config --libs ['-L/usr/lib/x86_64-linux-gnu', '-lmysqlclient', '-lpthread', '-ldl', '-lssl', '-lcrypto', '-lresolv', '-lm', '-lrt'] mysql_config --cflags ['-I/usr/include/mysql'] ext_options: library_dirs: ['/usr/lib/x86_64-linux-gnu'] libraries: ['mysqlclient', 'pthread', 'dl', 'resolv', 'm', 'rt'] extra_compile_args: ['-std=c99'] extra_link_args: [] include_dirs: ['/usr/include/mysql'] extra_objects: [] define_macros: [('version_info', "(2,1,1,'final',0)"), ('__version__', '2.1.1')] running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-3.11 creating build/lib.linux-x86_64-3.11/MySQLdb copying MySQLdb/__init__.py -> build/lib.linux-x86_64-3.11/MySQLdb copying MySQLdb/_exceptions.py -> build/lib.linux-x86_64-3.11/MySQLdb copying MySQLdb/connections.py -> build/lib.linux-x86_64-3.11/MySQLdb copying MySQLdb/converters.py -> build/lib.linux-x86_64-3.11/MySQLdb copying MySQLdb/cursors.py -> build/lib.linux-x86_64-3.11/MySQLdb copying MySQLdb/release.py -> build/lib.linux-x86_64-3.11/MySQLdb copying MySQLdb/times.py -> build/lib.linux-x86_64-3.11/MySQLdb creating build/lib.linux-x86_64-3.11/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.linux-x86_64-3.11/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-3.11/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.linux-x86_64-3.11/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.linux-x86_64-3.11/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-x86_64-3.11/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.linux-x86_64-3.11/MySQLdb/constants running build_ext creating build/temp.linux-x86_64-3.11 creating build/temp.linux-x86_64-3.11/MySQLdb x86_64-linux-gnu-gcc … -
django migrate throw (1070, 'Too many key parts specified; max 1 parts allowed')
I have 73 table's with django table's and any of this model's may be has indexes. while run python manage.py migrate, is thrown (1070, 'Too many key parts specified; max 1 parts allowed') I use percona mysql -
Optimizing Nested DRF Serializers
Help, pliz, to optimize the monstrous code in the serializer, which is very slow ... As I understand it, the main problem is in several SerializerMethodFields, where get_tasks () are called. Tell me, please, how to do it right here - in init, load all the tasks that are in self.tasks. And in the to_representation method, all 4 SerializerMethodField call keys - equipment_types, recovery_days, completed_days, work_in_progress_days? And most importantly - how to properly optimize the call of nested serializers? class MonthPlanViewSerializer(serializers.HyperlinkedModelSerializer): year_plan_id = serializers.PrimaryKeyRelatedField(queryset=YearPlan.objects.all(), source='year_plan.id') equipment_id = serializers.PrimaryKeyRelatedField(queryset=Equipment.objects.all(), source='equipment.id', required=False) equipment = EquipmentSerializer(many=False, read_only=True) transport_id = serializers.PrimaryKeyRelatedField(queryset=Transport.objects.all(), source='transport.id', default=None) transport = TransportSerializer(many=False, read_only=True) equipment_types = serializers.SerializerMethodField() tasks = SimpleTaskSerializer(many=True, read_only=True) recovery_days = serializers.SerializerMethodField() completed_days = serializers.SerializerMethodField() work_in_progress_days = serializers.SerializerMethodField() @staticmethod def get_tasks(instance: MonthPlan): return instance.tasks.all() @staticmethod def get_work_in_progress_days(instance: MonthPlan) -> set: tasks = MonthPlanViewSerializer.get_tasks(instance) return set(int(task.planned_date.strftime("%d")) for task in tasks if task.work_in_progress) @staticmethod def get_completed_days(instance: MonthPlan) -> list: return MonthPlanViewSerializer.get_common_days(instance, 'is_completed') @staticmethod def get_recovery_days(instance: MonthPlan) -> list: return MonthPlanViewSerializer.get_common_days(instance, 'is_broken') @staticmethod def get_common_days(instance: MonthPlan, attribute: str) -> list: tasks = MonthPlanViewSerializer.get_tasks(instance) days = set() for task in tasks: for item in task.maintenance_executions: if getattr(item, attribute): if task.closing_date: days.add(int(task.closing_date.strftime("%d"))) elif task.planned_date: days.add(int(task.planned_date.strftime("%d"))) return list(days) @staticmethod def get_equipment_types(instance: MonthPlan): tasks = MonthPlanViewSerializer.get_tasks(instance) … -
django core exceptions ImproperlyConfigured:
I had my django up and running last night at around midnight, everything was kawa when i closed but in the morning when i open my pc i get django.core.exceptions.ImproperlyConfigured: error !error Note that only Django core commands are listed as settings are not properly configured (error: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.). I tried closing the VScode and Terminal, reopened them, started virtualenvironment again but the error persists \env\Scripts\python.exe: No module named django I have django installed on the virtudal env as well as set as a global environment variable thanks in advance I expected python to get django installed on the virtual environment -
Django : Using the register form i gave the url in the lastline for redirecting to the loginpage it is not getting it is showing the page not found
when i click the login button here im getting page not found.. This is my template file i gave like this im getting like this error plz any one can solve this im new Django framework Im trying to click the login button but it not redirecting to the login page it getting like the page is not found i gave the correct url <a href="{% url 'login'}" but im not getting plz any solve this issue -
Hi I'm having trouble customizing authentication in Django
I am a newbie and I am designing Django authentication software My problem is that I have to check four separate levels for which there are predefined codes in the permission check. A model class named province and a model class named city and a model named Student My review model is such that I should be able to give a user the membership of the central office or the membership of a province or the membership of a city in a province. The user can only be for one of these situations My models is like this class Province(models.Model): province_id = models.IntegerField(primary_key=True, serialize=True, verbose_name='ID') province_title = models.CharField(max_length=30, verbose_name=_('Province')) class Meta: ordering = ['province_id'] def __str__(self): return self.province_title class Center(models.Model): id = models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID') center_title = models.CharField(max_length=150, verbose_name=_('Name of the training center'), null=True) center_title_id = models.CharField(max_length=64, verbose_name=_('Code of the training center'), null=True) province = models.ForeignKey(Province, on_delete=models.CASCADE, verbose_name=_('Province')) class Meta: verbose_name = _("center") verbose_name_plural = _("centers") def __str__(self): return self.center_title` class CulturalUser(AbstractUser): pass class UserPositions(models.Model): class Position(models.TextChoices): UNIVERSITY_STUDENT = '1', _('University student') TRAINING_CENTER = '2', _('Training center') PROVINCE = '3', _('Province') CENTRAL_OFFICE = '4', _('Central office') user = models.ForeignKey(CulturalUser, on_delete=models.CASCADE, verbose_name=_('User')) position = models.CharField(max_length=2, verbose_name=_('Access level'), choices=Position.choices, default=Position.UNIVERSITY_STUDENT) province … -
Why is my HTML template in Django not rendering in browser?
I am having issues with rendering an HTML template that has variables passed to it from my views.py in the Django project. Everything seems to be working with the exception that when you visit the HTML in a browser on my local machine it renders the HTML code, instead of the designed page with content. the files are below. VIEWS.PY from django.shortcuts import render import datetime import firebase_admin from firebase_admin import credentials from firebase_admin import firestore db = firestore.Client() config = { "apiKey": "XXXXXXXXXXXXXXXXXXX", "authDomain": "XXXXXXXXXXXXXXXXXXX.firebaseapp.com", "databaseURL": "https://XXXXXXXXXXXXXXXXXXX.firebaseio.com", "projectId": "XXXXXXXXXXXXXXXXXXX", "storageBucket": "XXXXXXXXXXXXXXXXXXX.appspot.com", "messagingSenderId": "XXXXXXXXXXXXXXXXXXX", "appId": "XXXXXXXXXXXXXXXXXXX", "measurementId": "XXXXXXXXXXXXXXXXXXX", "serviceAccount": "XXXXXXXXXXXXXXXXXXX.json", } # DATABASE # Use the application default credentials. cred = credentials.ApplicationDefault() firebase_admin.initialize_app(cred) firestore_client = firestore.client() # TIME & DATE today_date = datetime.datetime.now() tomorrow_date = today_date + datetime.timedelta(days=1) games_today = today_date.date() games_tomorrow = tomorrow_date.date() games_today_formatted = games_today.strftime("%Y-%m-%d") games_tomorrow_formatted = games_tomorrow.strftime("%Y-%m-%d") def basketball_nba(request): ############################################################################ # ENTAIN (NEDS/LADBROKES) ############################################################################ # Query firestore database for NBA games nba_events = db.collection('entain_au').document('basketball_nba').collection('event_odds').stream() event_info = [doc.to_dict() for doc in nba_events] # print(event_info) # Filter NBA games by dates events_today = [event for event in event_info if event['event_odds']['Event']['StartTime'][:10] == games_today] events_tomorrow = [event for event in event_info if event['event_odds']['Event']['StartTime'][:10] == games_tomorrow] # print(events_today) # print('Tomorrow:', events_tomorrow) # … -
Assign image to a form field in django.views
I am in the middle of a project and I am stuck. I have a edit profile feature where a user can edit their profile. Everytime a profile is created with an empty profile_picture field a default value is provided. But once an image is assigned to field and then deleted. The field gets blank. What I want is everytime the field becomes None I want to reassign the default image by mentioning the file path. Heres My view where I save the model form:- if form.is_valid(): form.save(commit=False) print(form.cleaned_data) if 'avatar' in form.cleaned_data: if form.cleaned_data.get('avatar') is False: form.cleaned_data['avatar'] = image form.save() I want to mention the image path in place of image. Also suggest me some better ways for doing this. -
How to get distinct list of names from a consultation list, and show only latest consultation in Django?
What I want to accomplish is to get a unique list of the names of customers with their lastest consultation date. I have defined these models in my models.py file, using mySQL as my database: class Customer(models.Model): class ContactChoice(models.IntegerChoices): DO_NOT_CONTACT = 0 EMAIL = 1 TXT_SMS_VIBER = 2 mobile_num = models.CharField('Mobile Number', max_length=10, unique=True,) email_add = models.EmailField('Email', max_length=150, unique=True,) last_name = models.CharField('Last Name', max_length=30,) first_name = models.CharField('First Name', max_length=30,) contact_for = models.CharField('Contact For', max_length=60,) contact_on = models.IntegerField('Contact Using', choices=ContactChoice.choices, default=0,) customer_consent = models.BooleanField('With Consent?', default=False,) def __str__(self): return self.last_name + ', ' + self.first_name class Consultation(models.Model): consultation_date = models.DateTimeField('Date of Consultation', default=now) customer = models.ForeignKey(Customer, on_delete=models.SET_DEFAULT, default=1) concern = models.ForeignKey(SkinConcern, on_delete=models.SET_DEFAULT, default=1) consultation_concern = models.CharField('Other Concerns', max_length=120, null=True,) product = models.ForeignKey(Product, on_delete=models.SET_DEFAULT, default=1) user = models.ForeignKey(User, on_delete=models.SET_DEFAULT, default=1) store = models.ForeignKey(Store, on_delete=models.SET_DEFAULT, default=1) consultation_is_active = models.BooleanField('Is Active', default=True) def __str__(self): return self.customer.last_name + ", " + self.customer.first_name In my views.py, I have this for the Consultations page: distinct = Consultation.objects.values('customer').annotate(consultation_count=Count('customer')).filter(consultation_count=1) consults = Consultation.objects.filter(customer__in=[item['customer'] for item in distinct]) As mentioned, I was expecting to get a unique list of customer names with their latest consultation dates. This code results in only 1 record being shown. Can you point me in the … -
No Reverse Match at /admin/ in Wagtail
I'm getting this error while logging into my wagtail admin site. Please note, I'm just setting up the server in my Putty so it would be great to help me out on this. NoReverseMatch at /admin/ Reverse for 'wagtailadmin_explore' with arguments '('',)' not found. 1 pattern(s) tried: ['admin/pages/(?P<parent_page_id>[0-9]+)/\\Z'] Error during template rendering In template /home/ubuntu/venv/lib/python3.10/site-packages/wagtail/admin/templates/wagtailadmin/home/site_summary_pages.html, error at line 5 Reverse for 'wagtailadmin_explore' with arguments '('',)' not found. 1 pattern(s) tried: ['admin/pages/(?P<parent_page_id>[0-9]+)/\\Z'] 1 {% load i18n wagtailadmin_tags %} 2 3 <li> 4 {% icon name="doc-empty" %} 5 <a href="{% url 'wagtailadmin_explore' root_page.pk %}"> 6 {% blocktrans trimmed count counter=total_pages with total_pages|intcomma as total %} 7 <span>{{ total }}</span> Page <span class="visuallyhidden">created in {{ site_name }}</span> 8 {% plural %} 9 <span>{{ total }}</span> Pages <span class="visuallyhidden">created in {{ site_name }}</span> 10 {% endblocktrans %} 11 </a> 12 </li> 13 Page after login. I've tried migrations after dropping the table. I want the wagtail dashboard to be displayed with new pages to be added. It's not necessary to add existing data (I did try loaddata data.json method but I'm getting another issue for another time) but if there's any way to avoid this issue would be helpful. Thank you -
django queryset filter with back reference
I'm a C++ developer and noob of python, just following django tutorials. I want to know how to filter queryset by its back references' information. Below is my models. # models.py import datetime from django.db import models from django.utils import timezone class Question(models.Model): pub_date = models.DateTimeField('date published') class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) Now, I want to get query set of Question which pub_date is past from now AND is referenced by any Choice. The second statement causes my problem. Below are what I tried. # First method question_queryset = Question.objects.filter(pub_date__lte=timezone.now()) for q in question_queryset.iterator(): if Choice.objects.filter(question=q.pk).count() == 0: print(q) # It works. Only @Question which is not referenced # by any @Choice is printed. # But how can I exclude @q in @question_queryset? # Second method question_queryset = Question.objects.filter(pub_date__lte=timezone.now() & Choice.objects.filter(question=pk).count()>0) # Not works. # NameError: name 'pk' is not defined # How can I use @pk as rvalue in @Question.objects.filter context? Is it because I'm not familiar with Python syntax? Or is the approach itself to data wrong? Do you have any good ideas for solving my problem without changing the model? -
Pass a variable to another function and render an html template at the same time in django
We want to access the same variable in every function inside our views.py. Since it is not constant, we cannot use it as a global variable. Is it possible to pass a variable to another function while also rendering an HTML template? What are the alternatives if none exist? This is our login function in views.py def loginpage(request): errorMessage = '' # Applicant Login if request.method=="POST": if request.POST.get('username') and request.POST.get('pwd'): try: currentUser=Applicant.objects.get(username=request.POST['username'],pwd=request.POST['pwd']) currentUser=Applicant.objects.get(username=request.POST['username']) first = currentUser.firstname middle = currentUser.middleinitial last = currentUser.lastname AppDashboard = ApplicantDashboardPageView(currentUser, request) except Applicant.DoesNotExist as e: errorMessage = 'Invalid username/password!' return render(request, 'home.html') The currentUser variable inside our login function is the variable we want to pass in this function def ApplicantdashboardPageView(currentUser, request): appPeriod = ApplicationPeriod.objects.all() exam = ExaminationSchedule.objects.all() posts = Post.objects.all().order_by('-created_on') form = PostForm() name=userNaCurrent print('from storeCurrentUser', name) if request.method == "GET": try: posts = Post.objects.all().order_by('-created_on') form = PostForm() #applicantID=currentUser.id #applicantNotification = Applicant.objects.get(id=applicantID) return render(request, 'applicantdashboard.html', context={'UserName' : name, 'posts':posts, 'appPeriod':appPeriod, 'exam':exam}) except ObjectDoesNotExist: return render(request, 'applicantdashboard.html', context={'UserName' : name, 'posts':posts,}) return render(request, 'applicantdashboard.html', context={'UserName' : name, 'posts':posts, 'appPeriod':appPeriod, 'exam':exam}) I am new to Django so please bear with me if my question seem too basic. Thank you