Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django image.url returning values appended with random text
I am quite new to Django. I have made a django project, where I upload some images through admin panel. And a template which takes values from the model and display the images accordingly. This is working fine on Localhost and after first commit. Then when I checked after next commit no images can be found! Later I realized, media directory is being overwritten, and then I added a .gitignore file which contains: *.log *.pot *.pyc __pycache__/ local_settings.py db.sqlite3 media .env .venv env/ venv/ ENV/ env.bak/ venv.bak/ then, just for checking purposes, I edited some comments and recommitted. But same error happened again! Media folder is overwritten again! Could anyone highlight what I am missing here? my file structure: ├───media │ └───media ├───Personal_website │ ├───migrations │ └───templatetags ├───Resume │ └───migrations │ └───__pycache__ ├───templates │ ├───Personal_website │ ├───Resume │ └───Visitors ├───manage.py ├───requirements.txt ├───.gitignore ├───procfile ├───db.sqlite3 -
Django - itertools.chain on different models with different cols
I have two different models each with different columns connected by one id. I want to create a searh page that would search the result from both the models, joining them with the id and show the results. This is the simple sql i want to execute: 'SELECT "SSDatabase_metadataform".*, "SSDatabase_uploadmeta"."datafile", CASE WHEN "SSDatabase_metadataform"."Embargo_Time" <= current_date THEN "SSDatabase_uploadmeta"."path_id" END AS link from "SSDatabase_metadataform" INNER JOIN "SSDatabase_uploadmeta" ON "SSDatabase_metadataform"."id" = "SSDatabase_uploadmeta"."path_id" order by "id"' I creates a search query, and it works fine showing the data from one of the model and it does not show the col form the second model. I am not sure how to write a join statement to fetch the corresponding data from the second model class SearchResultsView(ListView): template_name = 'searchresults.html' def get_queryset(self): # new query = self.request.GET.get('q') meta_list= Metadataform.objects.filter(Q(id__icontains=query) | Q(Authors_Name__icontains=query) | Q(Affliations__icontains=query) | Q(Methods__icontains=query) | Q(Instruments__icontains=query) | Q(Software__icontains=query)| Q(Models__icontains=query)| Q(Device__icontains=query)) dataset_list = uploadmeta.objects.filter(Q(datafile__icontains=query)) object_list = list(chain(meta_list, dataset_list)) return object_list And this is my html page. The datafile from the other model is not fetched <table class="table table-striped"> <thead> <tr> <th>Meta ID</th> <th>Author</th> <th>Affiliations</th> <th>Methods</th> <th>Instruments</th> <th>Models</th> <th>Device</th> <th>Configuration</th> <th>Download</th> </tr> </thead> <tbody> {% if object_list %} {% for a in object_list %} <tr> <td><a id="idclicked" … -
how to set pagination in SQL query as per page?
how to set pagination as per page in SQL query, i tried with django default pagination but it didn't worked in my code and i am direct fetching data using SQL raw-query instead of ORM. i think the another way is set pagination using SQL query LIMIT or OFFSET but i have no idea about url-endpoint when i am searching next-page. class Order_ListAPIView(APIView): def get(self,request,format=None): if request.method == 'GET': cur,conn = connection() order_query = ''' SELECT * FROM orders''' order_detail_query = ''' SELECT * FROM order_details''' with conn.cursor(MySQLdb.cursors.DictCursor) as cursor: cursor.execute(order_query) order_result = cursor.fetchall() order_data = list(order_result) ... ... #rest_code ... return Response({"order_data":order_data},status=status.HTTP_200_OK) else: return Response(status=status.HTTP_400_BAD_REQUEST) -
How to disable suffix generated when upload on a FileField in Django?
I have a model which has a FileField. When I upload on that field, a suffix is generated. How do I disable adding this suffix? class RawFile(models.Model): file = models.FileField( upload_to=settings.RAW_IMAGE_UPLOAD_PATH, null=True, max_length=500 ) When I upload something like this: MFC_CAP190519_142958_976940_DEC190606_040944.rg3 It gets renamed to something like this: MFC_CAP190519_142958_976940_DEC190606_040944_gqHQEiE.rg3 -
How to make the documents downloadable from wagtail?
I have uploaded pdf's to my wagtail page but I cant work out how to get them to actually be downloadable from the web page itself. This is my code for the models.py file. What html code do I need to make these? class ArchitectPage(Page): pdf_files = models.ForeignKey( 'wagtaildocs.Document', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) search_fields = Page.search_fields + [ ] # these are if adding a search to the website # content tab panels content_panels = Page.content_panels + [ MultiFieldPanel( [InlinePanel('architect_pdf', max_num=20, min_num=0, label="architect pdf")], heading="architect pdf" ), ] # what to call the panels on wagtail edit_handler = TabbedInterface([ ObjectList(content_panels, heading='Content'), ObjectList(Page.promote_panels, heading='SEO'), ObjectList(Page.settings_panels, heading='Settings', classname='settings'), # classname settings adds the cog ]) class ArchitectDownloads(Orderable): page = ParentalKey(ArchitectPage, on_delete=models.CASCADE, related_name='architect_pdf') architect_pdf = models.ForeignKey( 'wagtaildocs.Document', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) panels = [ DocumentChooserPanel('architect_pdf'), ] -
Working on the same git with two different pc's. Two different postgresql settings in the settings.py file
I'm very new to databases and I'm trying to find out what the best practise for what I'm trying to achieve. I have the one repository which is a Django backend with a postgresql database attached. I'm working with this on my main pc but recently I've had to work on my laptop. My laptop has another postgresql database running on 5432, so I've had to change some of that info to be on port 54324. These changes I don't want pushed to the repository, but I would still like to track the settings.py file in the repository. So far I've just created a branch for each pc to maintain the separate settings, but I'm sure this is not a great way to do it. I've heard about setting up environment files, but I'm unsure about if this is the 'right way' to do it either. I'm a little confused with the best way I can do this, hopefully I'm making sense. Any help would be appreciated greatly. Thanks, Darren -
How can I generate Django static files on Windows properly?
For deployment of static files one uses usually the command python manage.py collectstatic like described in the docs. This will generate the static files into STATIC_ROOT = "/var/www/example.com/static/" (settings.py). I am developing under Windows right now. Means /var/www/example.com/static/ does not exist and I need a way to control into which directory the static files are generated. How can I get this done on Windows? -
Django Session Cookie won't work in Safari (subdomain)
In my Django Webapp i have multiple Tenants (identifies by Subdomain). One User can have Access to multiple Tenants. This are my Cookies Settings in settings.py # Cookie Settings SESSION_COOKIE_DOMAIN = ".boncompagni.test" DOMAIN_NAME = "boncompagni.test" Work's fine on Google Chrome and Firefox, but Safari doesn't set the Session Cookie. Safari: Safari Dev-Screen Chrome: Chrome Dev-Screen Have anybody an idea why this won't work in Safari? -
Testing CreateView with JsonResponse
I want to test my CreateView but since I newly started to learn to test Django codes, I don't know how to test it. I use Ajax, therefore, I return JsonResponse, and before returning the response I save the form. I have tried a couple of methods but I was not able to write a successful test. Either it throws an error or could not post the data successfully to the URL. my CreateView: class MyCreateView(generic.CreateView): template_name = 'template.html' model = my_model form_class = my_form success_url = reverse_lazy('my_url') def get_request_page(self, page): page = self.request.POST[page] page = page.split('/')[-2] if page == '': page = 'Main Page' return page def form_valid(self, form): if self.request.is_ajax(): obj = form.save(commit=False) obj.page = self.get_request_page("page") obj.save() redirect_url = self.success_url return JsonResponse({'info': 'Successfully sent', 'redirect_url': redirect_url, }) def form_invalid(self, form): super(ArrangementFormView, self).form_invalid(form) return JsonResponse({'info': form.errors}) -
django class based view pass url parameter in create post to current category
lets's say that i have three categories (tutorials, news, jobs). and i have class based views to list all posts, list posts by category and create new posts. and sure post is the same model and fields to all categories. my problem is : if user was in category list template (let's say tutorial) .. i want the user when he create new post .. it is saved directly to tutorial category .. and if user was in list template (let's say news) .. he will create new post which will be saved directly to news category. i mean create new post saved directly to current category. i believe i will use (pass url parameter to class based views) but actually i failed to do that .. and i searched tonnage of questions without got what i want. can any body help .. with sample please. models.py class Category(models.Model): name = models.CharField(max_length=50) slug = models.SlugField(max_length=50, unique=True) def save(self, *args, **kwargs): if not self.slug and self.name: self.slug = slugify(self.name) super(Category, self).save(*args, **kwargs) class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) author = models.ForeignKey(User, on_delete=models.CASCADE) views.py def PostListView(request, category_slug=None): category = None posts = Post.objects.all().prefetch_related().annotate(commentscountperpost=Count('comments')) categories = … -
Django disable low level caching with context manager
One of my methods in a project I'm working on looks like this: from django.core.cache import cache from app import models def _get_active_children(parent_id, timestamp): children = cache.get(f"active_seasons_{parent_id}") if children is None: children = models.Children.objects.filter(parent_id=parent_id).active( dt=timestamp ) cache.set( f"active_children_{parent_id}", children, 60 * 10, ) return children The issue is I don't want caching to occur when this method is being called via the command line (it's inside a task). So I'm wondering if there's a way to disable caching of this form? Ideally I want to use a context manager so that any cache calls inside the context are ignored (or pushed to a DummyCache/LocalMem cache which wouldn't effect my main Redis cache). I've considered pasisng skip_cache=True through the methods, but this is pretty brittle and I'm sure there's a more elegant solution. Additionally, I've tried using mock.patch but I'm not sure this works outside of test classes. -
Django view demands an item not on form
I have extended the Django user model with some extra fields models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) telephone = models.CharField(max_length=15, blank=True) date_of_birth = models.DateField(null=True, blank=True) forms.py class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ('telephone', 'date_of_birth') widgets = { 'date_of_birth': forms.DateInput(attrs={'type': 'date'}), } user_update.html <form action="/user-updated/{{ user.pk }}/" method="post"> {% csrf_token %} <table> <tr><td>User:</td><td>{{ user.username }}</td></tr> <tr><td>First Name:</td><td>{{ user_form.first_name }}</td></tr> <tr><td>Last Name:</td><td>{{ user_form.last_name }}</td></tr> <tr><td>Email:</td><td>{{ user_form.email }}</td></tr> <tr><td>Telephone:</td><td>{{ profile_form.telephone }}</td></tr> <tr><td>Date of birth:</td><td>{{ profile_form.date_of_birth }}</td></tr> </table> <input type="submit" value="Submit" /> </form> views.py form(request, user_pk): user = User.objects.get(pk=user_pk) if request.method == 'POST': user_form = UserForm(request.POST, instance=request.user) profile_form = ProfileForm(request.POST, instance=request.user.profile) print(profile_form.errors) if user_form.is_valid() and profile_form.is_valid(): profile, created = Profile.objects.get_or_create(user=request.user) user_form.save() profile_form.save() messages.success(request, ('Your profile was successfully updated!')) date_of_birth = profile_form.cleaned_data['date_of_birth'] user = profile_form.cleaned_data['user'] context = {'user': user,} template = loader.get_template('user_updated.html') return HttpResponse(template.render(context, request)) else: messages.error(request, ('Please correct the error below.')) else: user_form = UserForm() profile_form = ProfileForm() context = {'user': user, 'user_form': user_form, 'profile_form': profile_form } return render(request, 'user_details.html', context) On submit, the profile_form throws an error in views.py: <ul class="errorlist"><li>user<ul class="errorlist"><li>This field is required.</li></ul></li></ul> Can someone please suggest how I might correct this? -
Can't use the python output formatting in Django db models
I am testing a very simple class in Django db : class Airport(models.Model): code = models.CharField(max_length=3) city = models.CharField(max_length=64) def __str__(self): return f"{self.city} ({self.code})" However, when makemigrations, it returns syntax error on the use of return f"{self.city} ({self.code})" : Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/jello/.local/lib/python3.5/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/jello/.local/lib/python3.5/site-packages/django/core/management/__init__.py", line 347, in execute django.setup() File "/home/jello/.local/lib/python3.5/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/jello/.local/lib/python3.5/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/home/jello/.local/lib/python3.5/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 661, in exec_module File "<frozen importlib._bootstrap_external>", line 767, in get_code File "<frozen importlib._bootstrap_external>", line 727, in source_to_code File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/mnt/c/Users/green/desktop/project3/orders/models.py", line 11 return f"{self.city} ({self.code})" ^ SyntaxError: invalid syntax When I modify the line with : return '{} ({})'.format(self.city, self.code) or return self.city + "(" + self.code + ")" Both works well. Anyone knows why the return f"{self.city} ({self.code})" gives error? I am using … -
How to generate a a value for a field based on other field on Django models?
I want to generate a value for name field based on the file field. class Files(models.Model): name = models.CharField(max_length=100, blank=True, null=True) file = models.FileField( upload_to=settings.RAW_IMAGE_UPLOAD_PATH, null=True, max_length=500 ) def name(self): return os.path.basename(self.file.name) def __str__(self): return self.name I am not successful when doing some Serialization/Deserialization. -
How to communicate with an external server using django application?
Currently I have a requirement,I need to communicate with external server using django application. The server is already up,Next section is the data transfer. I need some time samples and values from server and I need to send responses back to server. How django port can listen to external server.? How it can response back? I need asynchronous communication and REST responses -
Django dynamic URL tree
I'm new in Django and can't find a solution for my problem. How to make a dynamic URL tree in Django like - site.com/{categoryName}/{itemName}/ Now I have this URL tree: site.com/item/{itemSlug}/ site.com/category/{itemCategorySlug}/ But I need: site.com/{itemCategorySlug}/{itemSlug}/ How can I crate this URL tree without installing 3rd party plugins? Models from django.db import models from django.shortcuts import reverse from services.slug.generator import generate_slug class Category(models.Model): name = models.CharField(max_length=400, unique=True) description = models.TextField(max_length=1000, unique=True) slug = models.SlugField(max_length=500, unique=True, blank=True) seo_title = models.CharField(max_length=180, unique=True) seo_description = models.TextField(max_length=280, unique=True) class Meta: verbose_name = 'category' verbose_name_plural = 'categories' def get_absolute_url(self): return reverse('progress_category_url', kwargs={'slug': self.slug}) def save(self, *args, **kwargs): if not self.id: self.slug = generate_slug(self.name) super().save(*args, **kwargs) def __str__(self): return self.name class Progress(models.Model): name = models.CharField(max_length=400, unique=True) description = models.TextField(max_length=1000, unique=True) slug = models.SlugField(max_length=500, unique=True, blank=True) seo_title = models.CharField(max_length=180, unique=True) seo_description = models.TextField(max_length=280, unique=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) tags = models.ManyToManyField(Tag) date = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=False) is_verified = models.BooleanField(default=False) profile = models.ForeignKey(Profile, on_delete=models.CASCADE, blank=True, null=True) promo_image = models.ImageField(upload_to='progress/promo_images/', null=True, blank=True) class Meta: verbose_name = 'progress' verbose_name_plural = 'progresses' def get_absolute_url(self): return reverse('progress_url', kwargs={'slug': self.slug}) def save(self, *args, **kwargs): if not self.id: self.slug = generate_slug(self.name) super().save(*args, **kwargs) def __str__(self): return self.name Views from django.views.generic.list import ListView from … -
Django AUTH_LDAP_GROUP_SEARCH ObjectClass values from none to overkill
I have lil bit problem with my LDAP groups. i have: AUTH_LDAP_GROUP_SEARCH = LDAPSearchUnion( LDAPSearch("OU=U3,OU=UserGroups,OU=U1,OU=CompanyUsers,DC=ad,DC=net", ldap.SCOPE_SUBTREE, "(objectClass=groupOfNames)"), LDAPSearch("OU=Apps,OU=Security Groups,OU=Groups,OU=B2,OU=Tenants,DC=ad,DC=net", ldap.SCOPE_SUBTREE, "(objectClass=groupOfNames)")) ... AUTH_LDAP_GROUP_TYPE = GroupOfNamesType() AUTH_LDAP_REQUIRE_GROUP = ( LDAPGroupQuery("CN=ENGINEER,OU=U3,OU=UserGroups,OU=U1,OU=CompanyUsers,DC=ad,DC=net") | LDAPGroupQuery("CN=READER,OU=U3,OU=UserGroups,OU=U1,OU=CompanyUsers,DC=ad,DC=net") | LDAPGroupQuery("CN=ADMIN,OU=Apps,OU=Security Groups,OU=Groups,OU=B2,OU=Tenants,DC=ad,DC=net")) AUTH_LDAP_USER_ATTR_MAP = {"first_name": "givenName", "last_name": "sn", "email": "mail"} I can login via LDAP user but it does not populating my groups (in admin view) Now when i change code to: AUTH_LDAP_GROUP_SEARCH = LDAPSearchUnion( LDAPSearch("OU=U3,OU=UserGroups,OU=U1,OU=CompanyUsers,DC=ad,DC=net", ldap.SCOPE_SUBTREE, "(objectClass=group)"), LDAPSearch("OU=Apps,OU=Security Groups,OU=Groups,OU=B2,OU=Tenants,DC=ad,DC=net", ldap.SCOPE_SUBTREE, "(objectClass=group)")) ... AUTH_LDAP_GROUP_TYPE = GroupOfNamesType() AUTH_LDAP_REQUIRE_GROUP = ( LDAPGroupQuery("CN=ENGINEER,OU=U3,OU=UserGroups,OU=U1,OU=CompanyUsers,DC=ad,DC=net") | LDAPGroupQuery("CN=READER,OU=U3,OU=UserGroups,OU=U1,OU=CompanyUsers,DC=ad,DC=net") | LDAPGroupQuery("CN=ADMIN,OU=Apps,OU=Security Groups,OU=Groups,OU=B2,OU=Tenants,DC=ad,DC=net")) AUTH_LDAP_USER_ATTR_MAP = {"first_name": "givenName", "last_name": "sn", "email": "mail"} Itpopulates my groups with ALL groups in LDAP where member exists, we don;t want to do that, we only need to consider those 3 mentioned groups. Tried also with objectClass=top and it also populate with all LDAP groups that user has assigned. AUTH_LDAP_GROUP_TYPE = GroupOfNamesType(name_attr="CN") changes nothing in both cases -
How can one pass a json as a filter to a django query?
In below query, project_name contained in list ["ABC", "XYZ"], is coded as ('exact', 'in') query abcd { ple_presets { all_preset (filter: {project_name__in: ["ABC", "XYZ"], extra: {context1: a, context2:b}}) { edges { node { ...fields } } } } } Question is, for a json to be passed as a filter - 'extra', what should come here <==== class PlePreset(DjangoObjectType): class Meta: model = presets.Preset interfaces = (Node,) filter_fields = { 'project_name': ('exact', 'in',), 'extra': (.....) <===== } -
Django Rest Framework, TypeError: __init__() takes 1 positional argument but 2 were given
Models.py: class Bookmark(models.Model): """Bookmar for a quiz""" quiz = models.ForeignKey( Quiz, on_delete=models.PROTECT, verbose_name='Викторина', related_name='bookmarks' ) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name='Пользователь', related_name='bookmarks' ) date = models.DateTimeField(auto_now_add=True, verbose_name='Дата добавления') def __str__(self): return f'{self.user} - {self.quiz}' Urls.py: urlpatterns = [ path('quiz/bookmark/create-remove/<slug:slug>/', views.CreateRemoveBookmarkAPI, name="bookmark-create-remove-api"), ] Views.py: class CreateRemoveBookmarkAPI(APIView): """API for create or remove quiz bookmark. Get a quiz slug, and create or remove bookmark at it """ permission_classes = (IsAuthenticated,) def post(self, request, slug): quiz = get_object_or_404(Quiz, slug=slug) bookmark = Bookmark.objects.filter(quiz=quiz, user=request.user) data = {} if bookmark.exists(): bookmark.delete() data['bookmarked'] = False else: Bookmark.objects.create(quiz=quiz, user=request.user) data['bookmarked'] = True data['bookmarks'] = quiz.get_bookmarks_count() return Response(data, status=status.HTTP_200_OK) I got it: Internal Server Error: /api/quiz/bookmark/create-remove/dd-69/ Traceback (most recent call last): File "C:\Users\user\Desktop\quizapp\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\user\Desktop\quizapp\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\user\Desktop\quizapp\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) TypeError: __init__() takes 1 positional argument but 2 were given [05/Mar/2020 12:04:33] "POST /api/quiz/bookmark/create-remove/dd-69/ HTTP/1.1" 500 21733 In front-end, I just send ajax request. The data attribute is empty because it doesn't matter. I don't know why it doesn't work. Please help me. gggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg -
Pass uploaded excel file data to python via ajax
I currently have a choose file option in which a user can upload an excel file. Following is the code. HTML <div class="col-md-6"> Upload excel <input type="file" id="file_upload" class="file_upload"> <button type="button" id="upload_submit" class="btn btn-primary upload_submit">Upload</button> </div> JS $("body").on("click", ".upload_submit", function () { // debugger var filepath = $("#file_upload").val() }) I am trying to extract the file-path and send the path to python so that i can do my operations in the back end. but I am getting the path as 'C:\fakepath\dummy_data.xls' After some googling, I came to know that latest browsers restrict revealing the users directory from the client side. So, Pls suggest, how do i send this excel data to my python function in the back end? -
Django: how to set pagination?
here i tried django default pagination in my views but that's does not worked for me. i want to make a custom pagination as per my code. it would be great if anybody could help me where i made mistake in my code. from rest_framework.pagination import PageNumberPagination class DefaultResultsSetPagination(PageNumberPagination): page_size = 2 page_size_query_param = 'page_size' max_page_size = 100000 class Order_ListAPIView(APIView): pagination_class = DefaultResultsSetPagination def get(self,request,format=None): if request.method == 'GET': cur,conn = connection() order_query = ''' SELECT * FROM orders''' order_detail_query = ''' SELECT * FROM order_details''' ... ... #rest_code ... return Response({"order_data":order_data},status=status.HTTP_200_OK) else: return Response(status=status.HTTP_400_BAD_REQUEST) -
Query regarding django forms
I'm trying to make a form using Django which consists of a question and different possible answers(radio button options). So my question is how can I give weightage(score) to different options and store it in the database? -
django return render popup message
i have this code in my views.py that inserting record to the database for desc in request.POST.getlist('coredescription'): coredescription = CoreValuesDescription(id=desc) V_insert_data = StudentsCoreValuesDescription( Teacher=teacher, . . . ) V_insert_data.save() m=+1 **return render (messages.success(request, 'Profile details updated.'))** this is my html {% if messages %} <ul class="messages"> {% for message in messages %} <li>{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> {% endif %} I just want that if the user add record, popup message appeard -
filter and edit model_set of object and return query set of that object in one to many relation in django
Overview: I have two models that there is one-to-many relationship between them.I want to get a search QuerySet of Exams that has questions with text that contains 'Question1' but question_set of these Exams should be limited to my search value;it means that questions with text 'Question2' should not appear in question_set of these Exams.(I mean question_set of these Exams should be filtered or edited too) my models are : models.py : class Exam(models.Model): name = models.CharField(max_length=50) level = models.CharField(max_length=10) type = models.CharField(max_length=20) city = models.ForeignKey(City, on_delete=models.CASCADE) class Question(models.Model): text = models.CharField(max_length=400, default='how are you?') exam = models.ForeignKey(Exam, on_delete=models.CASCADE) In Database , text of Question object contains only 'Question1' or 'Question2' now I want to get Exams that text of questions in question_set of them contains 'Question1' so I use this code : Exam.objects.filter(question__question_text__icontains='Question1') If I use this code I get Exams but in question_set of these Exams also there is some questions with question_text that constains 'Qusetion2' but I want just questions that contains 'Question1' so It's not correct result. I need to filter question_set of Exams too. so I used this code: Exam.objects.filter(question__question_text__icontains='Question1')[i].question_set.all().filter(question_text__icontains='Question1') But the problem is that the output of this code is QuerySet of Question model but … -
How to get Django LoginRequiredMixin working?
I'm working with Django 3 and I would like to restrict my views only to logged-in users. So I decided to implement Djangos method of LoginRequiredMixin, to controll access to my whole view. But this is not working in my view. class UsersView(LoginRequiredMixin, View): def user_list(request): users = adg_users.objects.all() return render(request, 'care/user/users.html', {'users': users}) The view is still open, although I'm not logged in. What could be the problem here? What do I have to do to make it working?