Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError: '>=' not supported between instances of 'str' and 'int' error happening while Django wagtail querying
Working fine from django templates but from postman it's giving this error. The main query is given below - query = reduce( or_, ( Q(path__startswith=page.path) & Q(depth=page.depth + 1) & Q(primary_category__in=list_categories) | Q(additional_categories__category__in=list_categories) for page in BlogPage.objects.filter(pk__in=blog_ids) ) ) -
How to display an image from the DB using folium
I'm trying to pull out an image inside the DB that's on my computer. And display it inside the folium object popup. I searched the internet but did not find a solution I would be happy to help def search_on_map(request): loc_list = [] img_list = [] for i in Add_Item.objects.all(): city = str(i.city) street = str(i.street) home = str(i.home_number) loc_list.append(city +" "+ street +" "+ home) img = i.header_img img_list.append(img) geolocator = Nominatim(user_agent="Your_Name") m = folium.Map(width=800, height=500, location=['32.078225', '34.768516'], zoom_start=15) for index, place in enumerate(loc_list): try: loc = loc_list[index] location = geolocator.geocode(loc) lat = location.latitude long =location.longitude # Add Marker folium.Marker([lat,long], tooltip= ,popup=img_list[index] , icon=folium.Icon(color='purple')).add_to(m) except Exception as e: print(e) return render(request, 'search_on_map.html', {"loc":m._repr_html_(),}) -
How to dynamically define and generate serializers in django
I am working on an event driven service which receives a lot of events and these events have payload. I want to validate all payloads with serializers. Since the events types and huge in numbers, I don't want to define serializers in code for every event as that would require a new release every time a new event is added or an existing one is changed. So, is there a way I can define these serializers dynamically for each event in a table instead of code and use it to validate the event payload ? Any new additions/changes can be done in the table itself. -
link MCO number to Reception number
I have a web page where the user is supposed to enter the reception number and the MCO number, so whatever reception number and MCO number is enter, it is supposed to be tag together like reception number: 123 and MCO number: 456, in the database it is supposed to show 123/456, how do I make it do that? This is how my webpage looks like (when the user click the submit button the reception number and the mco number will be tag together: But as shown in the picture below, the mco number will appear in another new row and not next to the reception number. views.py @login_required() def verifydetails(request): if request.method == 'POST': form = verifyForm(request.POST) if form.is_valid(): Datetime = datetime.now() status = 'Launching' mcoNum = form.cleaned_data['mcoNum'] if Photo.objects.filter(reception=form.cleaned_data['reception']): form = Photo(Datetime=Datetime, mcoNum=mcoNum, status=status) form.save() return redirect('ViewMCO') else: messages.success(request, 'The reception number you have enter is incorrect') return redirect('verifydetails') else: form = verifyForm() return render(request, 'verifydetails.html', {'form': form, }) forms.py class verifyForm(forms.Form): reception = forms.CharField(label='', widget=forms.TextInput( attrs={"class": 'form-control', 'placeholder': 'Enter Reception number'})) mcoNum = forms.CharField(label='', widget=forms.TextInput(attrs={"class": 'form-control', 'Placeholder': 'Enter MCO Number'})) class Meta: model = Photo fields = ("mcoNum", "status") ViewMCO.html {% extends "customerbase.html" %} {% block content … -
Django: Approach on how to realize IPC with other server/process
I have a Django App for user interaction which works perfectly fine. Now I want to have a communication channel with another primitive server a colleague of mine wrote. Probably will go for multiprocessing listeners via AF_UNIX. I don't know where to open a process that listens on the other servers messages and adds information to the database (also, I request information from the server but that shouldn't be much of a problem once the channel is open) Upon searching the web I found the suggestion to add a new command to the manage.py but I couldn't find out if I can execute two commands in parallel, also the GUI won't be executed as development server forever. If you have any suggestions on what tricks/technology/terms I should search for, I really appreciate the help! Still kind of a newbie to Django, so I might have missed something essential. -
How to add or remove objects in nested serializers Django using update function
I have 2 models - Module and Room. A module can have zero or multiple rooms and a room can be added into multiple modules. So, there is a simple many-to-many relationship between them. While updating the modules field using a put request, I don't want to update any rooms in it, I just want to add/remove rooms in the module. Here are my files - module/models.py - class Module(models.Model): module_id = models.AutoField(primary_key=True) title = models.CharField(max_length=100) desc = models.TextField() rooms = models.ManyToManyField(Rooms) rooms/models.py - class Rooms(models.Model): room_id = models.AutoField(primary_key=True) title = models.CharField(max_length=100) desc = models.TextField() level = models.CharField(max_length=100) is_deleted = models.BooleanField(default=False) module/serializers.py - class ModuleSerializer(serializers.ModelSerializer): rooms = RoomSerializer(read_only=True, many=True) class Meta: model = Module fields = "__all__" def create(self, validated_data): rooms_data = validated_data.pop('rooms') module = Module.objects.create(**validated_data) for data in rooms_data: room, created = Rooms.objects.get_or_create(**data) module.rooms.add(room) return module rooms/serialier.py - class RoomSerializerWrite(serializers.ModelSerializer): room_id = serializers.IntegerField() class Meta: model = Rooms fields = "__all__" module/views.py - class add_module(APIView): def post(self, request, format=None): module_serializer = ModuleSerializer(data=request.data) if module_serializer.is_valid(): module_serializer.save() return Response(module_serializer.data['module_id'], status = status.HTTP_201_CREATED) return Response(module_serializer.errors, status = status.HTTP_400_BAD_REQUEST) POST request body for updating a module in POSTMAN - { "module_id": 2, "rooms": [ { "room_id": 2, "title": "4", "desc": "22", "level": "2", … -
Django Rest Framework - Masking response values
I was wondering what the best way would be to mask a certain response parts. I will use an example to explain. Let's say I have a Person model with first_name, last_name and email. I use PersonSerializer to return that data. An example response can be { "first_name": "John", "last_name": "Doe", "email": "johndoe@gmail.com" } I want to "hide" an email when presenting it as response. I still want it to be present as the key, I just want to mask the value. So I want to achieve this response { "first_name": "John", "last_name": "Doe", "email": "__MSK__" // so it get's masked } So this should not impact the serialization when creating a new patient with same serializer class as well. Anyone has idea what the best way would be? Maybe overriding to_representation method or? -
Django: filter the logs which are coming from the front end
I had implemented the logging in my Django project, at Debug level. There is a whole lot of information coming to logger which make my system hang up. I want to filter the logs before going to save the logs. there are like useless logs that are unnecessarily getting saved to file. Like i have front end information from templates, i don't want frontend logs saved in the logger file. LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'verbose' }, 'file': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'filename': os.path.join(BASE_DIR + '/logs/debug.log'), 'formatter': 'verbose' }, 'info': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': os.path.join(BASE_DIR + '/logs/info.log'), 'formatter': 'verbose' }, }, 'loggers': { 'django': { 'handlers': ['file','info','console'], 'level': 'DEBUG', 'propagate': True, }, }, } Kindly Suggest -
can't connect to my database which i have in hiox india wit my django
just a week we brought a hosting service in hioxindia ,they provided the databaseso i'm trying to connect my django with that database but i can't.i'm seeking solutions for that .I need to know how to connect my django with that database -
Django REST framework on primary key
I am currently trying to display multiple models with a primary key to find that specific data but I am encounter the following error: selected() got an unexpected keyword argument 'pk' Heres the code: views.py from rest_framework.response import Response from rest_framework.decorators import api_view from .serializers import DeviceSerializers, DeviceDetailSerializers @api_view(['GET']) def selected(request,pk): devices = Device.objects.all(pk=pk) devicedetail = DeviceDetail.objects.all(DD2DKEY=pk) devserializer = DeviceSerializers(devices, many = True) devdserializer = DeviceDetailSerializers(devicedetail, many = True) results = devserializer.data + devdserializer.data return Response(results) serializers.py from rest_framework import serializers from .models import Device, DeviceDetail class DeviceSerializers(serializers.ModelSerializer): class Meta: model=Device fields = '__all__' class DeviceDetailSerializers(serializers.ModelSerializer): class Meta: model = DeviceDetail fields = '__all__' models.py SUBNET_CHOICES = ( ('16','16'), ('17', '17'), ('18','18'), ('19','19'), ('20','20'), ('21', '21'), ('22', '22'), ('23', '23'), ('24', '24'), ('25', '25'), ('26', '26'), ('27', '27'), ('28', '28'), ('29', '29'), ('30', '30'), ) DEV_MODS =( ('Catalyst 9606R', 'Catalyst 9606R'), ('C9300L-48T-4X', 'C9300L-48T-4X') ) mgt_interface = models.CharField(max_length=50) subnetmask = models.CharField(max_length=2, choices = SUBNET_CHOICES) ssh_id = models.CharField(max_length=50) ssh_pwd = models.CharField(max_length=50) enable_secret = models.CharField(max_length=50) dev_mod=models.CharField(max_length=50, choices = DEV_MODS) ##device_model replacement DD2DKEY = models.ForeignKey(Device, on_delete=models.CASCADE) ##The key to link up the tables def __str__(self): return self.hostname urls.py (In app) from django.urls import path from .views import DeviceListView from . import views from .views … -
Django - Have function inside of a view function automatically return a response to user if error?
So I have this post request below that gets a video upload then validates it. I'd ideally like validate_video_upload() to return a 400 response if the video is larger than the allowed size rather than raise a validation error, because I'd like to notify the user that the video is too large. How do I set it up so that if validate_video_upload() returns a Response, it'll just return the call with the status and message, if there's no response returned then it just proceeds normally? View.py def post(self, request): if 'video' in request.FILES.keys(): vid = request.FILES.get('video') validate_video_upload(vid) function.py def validate_video_upload(file): if not is_valid_file_of_format(file._name, VALID_VIDEO_EXTENSIONS): raise ValidationError("Video file format is invalid") if file.size>2296000000: raise ValidationError("Maximum size allowed for a video is 287 mb") -
Invoking Django-river manually for workflow management
Our application uses Django_river for workflow management. And currently, the river is being invoked based on the post save signal created by Django. But for performance-related issues, we had to use the bulk option for inserting data that does not support signals by default. We have generated signals manually, but this is slowing down our system. Is there any way to manually invoke the river from our code based on the business conditions? -
Django apps communication in abstraction layer
We are starting a new Django project which will consist of many different applications inside it. At first I was thinking of looking at some of these applications as individual services but department heads told us that at this stage we do not need scaling, distributing and balancing, so just keep them inside the same project. However, I was also asked to keep my design clean and move application communications into an abstract layer. So the idea is to have a well defined interface for each service (django apps), and in order for services to talk to each other they will read the implementation of these interfaces from a factory and call the methods. All sounded good to me till I was starting to implement this. I was told that one day we may extract these django apps and put them in a different project and run them in multiple machines so we can distribute and balance the load between them. So I have had to find an implementation of the "well defined interface" which would be very easy to change when applications get extracted from the project. Approach A I could not come up with a lot of ideas … -
Check if Many to Many exists in django?
I have two models, Model University: name = models.CharField(max_length=120) Model Students: name = models.CharField(max_length=120) wishlist = models.ManyToManyField(University, blank=True) Basically this is wishlist, user can add university to their wishlist and if the reclick on the heart icon i need to remove the wishlist: Here is my code: student = request.user.student university = University.objects.get(id=pk) if university.student_set.exists(): student.wishlist.remove(university) else: student.wishlist.add(university) So when, user1 added university1 to wishlist, then user2 couldnt able to add university1 to the wishlist, i dont know where is the mistake !Pleas guide, any students can add any university to their wishlist (its the requirement) I think the problem is with the if statment -
how to make paginations to this views
I can't do pagination to this get request! Can anyone help me ps Django Rest framework @api_view(["GET"]) def school_titul_list(request): if request.method == 'GET': try: data = {} user = request.user schools = user_utils.user_schools(user) data['warning'] = False if user.is_superuser: snippets = models.SchoolTitulHead.objects.filter(school__nash=True) if 'school' in request.query_params: snippets = snippets.filter(school_id__in=request.query_params['school'].split(',')) else: snippets = snippets.filter(school_id__in=[]) else: snippets = models.SchoolTitulHead.objects.filter(school__in=schools.values_list('school', flat=True), deleted=False) snippets = snippets.order_by('deleted', '-year', 'klass', 'liter_id').select_related('school', 'kurator', 'kurator__portfolio') work_places = p_models.PortfolioWorkTimeLine.objects.filter(current=True, portfolio__deleted=False, deleted=False, checked=True, ) # if not request.user.is_superuser: work_places = work_places.filter(school__in=schools.values_list('school', flat=True)) work_places = work_places.values_list('portfolio', flat=True) portfolios = p_models.Portfolio.objects.filter(pk__in=work_places).distinct().order_by('name_ru') data['users'] = serializers.PortfolioSerializers(portfolios, many=True).data data['liters'] = serializers.LiterSerializers(Liter.objects.filter(deleted=False), many=True).data data['data'] = serializers.GetHeadSchoolTitulSerializer(snippets, many=True).data data['languages'] = serializers.LanguageSerializer(p_models.Language.objects.filter(deleted=False), many=True).data data['studyDirections'] = serializers.StudyDirectionsSerializer( StudyDirections.objects.filter(deleted=False), many=True).data data['klasss'] = serializers.KlassSerializersID(p_models.Klass.objects.filter(deleted=False, klass_type=2), many=True).data data['datas'] = serializers.DateObjectsSerializer( p_models.DateObjects.objects.filter(deleted=False, id=9).order_by('id'), many=True).data return JsonResponse(data) except AccessToEdit.DoesNotExist: return JsonResponse({'errors': 'Нет доступа', 'warning': 0}, status=400) I can't do pagination to this views! Can anyone help me psI can't do pagination to this views! Can anyone help me psI can't do pagination to this views! Can anyone help me psI can't do pagination to this views! Can anyone help me psI can't do pagination to this views! Can anyone help me ps -
How can I integrate google calendar in django?
I am creating schedule management website and I want to show the user calendar in my website. If any user login into website, I would like to ask a permission to access the google calendar. my website does not have authentication using google and I am using MySql to store all the user information. if Any user edit the calendar and users google calendar will be updated. How will I achieve this. -
display picutre in grid layout djang-admin
first, I am having issues with displaying thumbnails in Django-admin, I tried the code below but it is not working it seems, class Pictures(models.Model): image = models.ImageField(null=True) date_added = models.DateField(auto_now_add=True) organization = models.ForeignKey(Organisation,on_delete=models.CASCADE) def __unicode__(self): return f"{self}" @mark_safe def image_img(self): if self.image: return format_html('<img src="{0}" style="width: 60px; height:65px;" />'.format(self.image.url)) else: return format_html('<img src="" alt={0} style="width: 60px; height:65px;" />'.format("noimagefound")) image_img.short_description = 'Image' image_img.allow_tags = True class PicturesAdmin(admin.ModelAdmin): list_display = ('image', 'date_added','image_img') autocomplete_fields = ['organization'] list_display_links = ('date_added',) I also want to display these thumbnails in the grid layout, how can I achieve that any simple approach -
Django filter ListViews
I am still rookie.. This is my first experience with CBV. My goal is to create one template with list that i can filter by my models field, like Date, Category, and more. My first try was to create more than one ListView, each for category but it's just doesn't look and feel right and I can't find anything to solve that on Google or django documentation.. What am I missing? This is the code: class TaskListView(ListView): context_object_name='list' model=models.Task_app class TaskWorkListView(ListView): context_object_name='work' template_name='Tasks/Task_app_work.html' model=models.Task_app def get_queryset(self): return Task_app.objects.filter(Q(Category__exact='Work')) template: <table class="table"> <tr> <th scope="col">Task:</th> <th scope="col">Content: </th> <th scope="col">Hour:</th> </tr> {% for task in list %} <tr> <td scope="row"><a href="{{ task.id }}">{{task.Task_Name}}</a></td> <td scope="row">{{task.Content}}</td> <td scope="row">{{task.Start_Time|time:"G:i"}}</td> </tr> {% endfor %} </table>``` Thanks -
How to filter queryset by another's Model CharField?
I have three models which are related to each other. Now I want to query a set of Poller entries which is filtered by the categories_selected by the user that stores strings of poller_category. # Models class Category(models.Model): """ Holds all available Categories """ poller_category = models.CharField(max_length=30) class UserCategoryFilter(models.Model): """ Holds Categories selected by user """ user = models.ForeignKey(Account, on_delete=models.CASCADE) categories_selected = models.CharField(max_length=2000) class Poller(models.Model): """ Holds Poller objects """ poller_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) poller_category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) # View def render_random_poller(request): # Get user category filter if logged in if request.user.is_authenticated: # Get the Users filter as a list of selections category_filter = UserCategoryFilter.objects.filter(user=request.user).values_list('categories_selected', flat=True) print(category_filter) # Get a Category instance filtered by user selection of categories category_instance = Category.objects.filter(poller_category__in=category_filter) print(category_instance) # Apply user's selection to the poller query and take 100 latest pollers qs_poller = Poller.objects.filter(poller_category__in=category_instance).order_by('-created_on')[:100] else: [...] However, print(category_instance) returns an empty queryset, even though print(category_filter) returns ['category_foo']. How to best build the queryset? -
Issue while creating Foreign Key constraint
Issue Details 'Can't create table django.clientauth_tblusers (errno: 150 "Foreign key constraint is incorrectly formed")') What am I doing? I created a tinyint auto increment field below but when referencing it in another table causing issue. Code in Model file class TinyIntField(AutoField): def db_type(self, connection): return "tinyint(3) AUTO_INCREMENT" class tblroles(models.Model): role_id = TinyIntField(primary_key=True, verbose_name = "role_id") name = CharField(max_length = 20) class tblusers(models.Model): user_id = BigAutoField(primary_key=True) role = ForeignKey(tblroles, on_delete = models.CASCADE) Code in Migration File migrations.CreateModel( name='tblroles', fields=[ ('role_id', clientauth.models.TinyIntField(primary_key=True, serialize=False, verbose_name='role_id')), ('name', models.CharField(max_length=20)) ], ), migrations.CreateModel( name='tblusers', fields=[ ('user_id', models.BigAutoField(primary_key=True, serialize=False)), ('role', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='clientauth.tblroles')), ], ), -
installing django in pycharm
Do I really need to install django in pycharm every time I'm going to run a project? I mean I already did it yesterday and today when I run in the terminal the "python manage.py runserver" it said that "ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?" Is there a way to install it just once so I can just run my project or is that how it really works?I'm sorry I am just a beginner please don't judge me. -
Django Rest Framework, group_by queries using .values(), and embedding a related record
I can't figure out how to embed a related record into a Django Rest Framework response when using .values() on a Django query set to return grouped by aggregated values. Sample Models, Serializers, and Viewset included below along with current response and a sample desired response. Each Trade has one security. Multiple trades can exist for a security. I have a need to display Trades individually and also grouped by security. When grouping by security, I want to return the embedded security in the response along with the aggregate values for the associated trades, but so far I can only get the security id returned. Any attempt to get the security itself in the response results in an exception 'int' object has no attribute 'pk' Trade model class Trade(models.Model): security = models.ForeignKey('Security') ticker = models.CharField( max_length=128, null=True, blank=True, db_index=True, ) shares = models.FloatField(db_index=True) value_usd = models.FloatField(db_index=True) days_to_trade = models.FloatField(db_index=True) trade_date = models.DateField( db_index=True, null=True, blank=True, ) Security model class Security(models.Model): name = models.CharField( db_index=True, blank=True, null=True, ) ipo_date = models.DateField( null=True, blank=True ) Trade View class TradeViewSet(viewsets.ModelViewSet): def get_queryset(self): // param and filter setup/defaults snipped for clarity ... qs = Trade.objects.filter(**qs_filter) // if group_by param is passed in, then group … -
'Photo' object is not iterable
I have a web page that show the details that is from my database, but when the user click on the view button, it did redirect me to the details page and get the id, but at the same time it give me an error 'Photo' object is not iterable, what is wrong with my code? How do I fix the error? Error: traceback error: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/details/6/ Django Version: 2.2.20 Python Version: 3.8.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'account.apps.AccountConfig', 'crispy_forms'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django_session_timeout.middleware.SessionTimeoutMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template E:\Role_based_login_system-master\templates\logisticbase.html, error at line 67 'Photo' object is not iterable 57 : &lt;/div&gt; 58 : {% endfor %} 59 : {% endif %} 60 : &lt;div id="home_body"&gt; 61 : {% block content %} 62 : 63 : {% endblock %} 64 : &lt;/div&gt; 65 : &lt;!-- Optional JavaScript --&gt; 66 : &lt;!-- jQuery first, then Popper.js, then Bootstrap JS --&gt; 67 : &lt;script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT 7abK41JStQIAqVgRVzpbzo5smXKp4Y fRvH+8abtTE1Pi6jizo" crossorigin="anonymous"&gt;&lt;/script&gt; 68 : &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"&gt;&lt;/script&gt; 69 : &lt;script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"&gt;&lt;/script&gt; 70 : &lt;/body&gt; 71 : &lt;/html&gt; Traceback: File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py" in … -
django why getting this error 'RelatedManager' object has no attribute 'email_confirmed'?
When I am using user.email_confirmed I am not getting any error but when using user.userprofile.email_confirmed getting RelatedManager error. Why I am getting this error when trying to get user details from userprofile model? here is my code: class UserManagement(AbstractUser): is_blog_author = models.BooleanField(default=False) is_editor = models.BooleanField(default=False) is_subscriber = models.BooleanField(default=False) is_customer = models.BooleanField(default=False) email_confirmed = models.BooleanField(default=False) #there is no error when obtaining email_confirmed object from abstract user model. class UserProfile(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name="userprofile") email_confirmed = models.BooleanField(default=False) #I am using this for email verification class AccountActivationTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.userprofile.email_confirmed) #error rising for this line #six.text_type(user.email_confirmed) #I am not getting error if I use this line ) account_activation_token = AccountActivationTokenGenerator() views.py ....others code if user is not None and account_activation_token.check_token(user, token): user.userprofile.email_confirmed = True #why it's not working and rising error? #user.email_confirmed = True #it's working user.save() .....others code -
Display only one instance of same object in model (Distinct other instances of same object)
I am building a simple question and answer site and I am trying to implement a functionality in which user can upload 4 answers But I am trying to hide show only any one answer And this is showing all the answers related to a question. For Example :- question_a has 4 answers then i am trying to show any one of them. models.py class Question(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30) marked = models.BooleanField(booleanField) class Answer(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) question_of = models.ForeignKey(BlogPost, on_delete=models.CASCADE) body = models.CharField(max_length=30) views.py def page(request): query_2 = Answer.objects.filter(question_of__marked=True)[:1] context = {'query_2':query_2} return render(request, 'page.html', context) In this query I am trying to show Answers of qustions which have marked=True and i am also trying to show only one answer of a question But it is showing 4. And after using [:1] it is only showing result in all. I will really appreciate your Help. Thank You