Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NOT NULL constraint failed: issue_tracker_label.project_id
I am trying to create a 'Label'. Basically, you click on 'label' button, and it will show title and content under. I am using POST method. But when I click on 'submit', it gave me this error: IntegrityError at /project/1/issue/2/label/ NOT NULL constraint failed: issue_tracker_label.project_id Btw, I am using crispy form and I did do makemigrations and migrate after I modified my model.py. Not sure why I still get this error. view.py @csrf_exempt def label_create(request, project_id,issue_id): issue = get_object_or_404(Issue, id=issue_id) project = Project.objects.get(id=project_id) if request.method == 'POST': form = LabelForm(request.POST) if form.is_valid(): label = form.save(commit=False) label.issue = issue label.save() return redirect('project:issue_tracker:issue_detail', project_id=project.id, issue_id=issue.id) else: form = LabelForm() template = 'issue_tracker/issue/label.html' context = {'form': form, 'project': project} return render(request, template, context) model.py class Label(models.Model): issue = models.ForeignKey(Issue, related_name='issue_label', on_delete=models.CASCADE) project = models.ForeignKey(Project, related_name='project_label', on_delete=models.CASCADE) title=models.CharField(max_length=20,default='Debug') color=models.CharField(max_length=20,default='red') def __str__(self): return self.title form.py class LabelForm(forms.ModelForm): class Meta: model = Label fields = ('title','color',) -
Django 2.0 Integrity error Not NULL constraint failed
I am trying to display the notes' contents which are accepted from a logged in user through a NotesCreateForm. The Form is displayed properly but when I click submit, instead of displaying DetailView, it gives below error. I am new to Django so please help! Also please suggest if CBV is proper here or it should be changed to FBV? Views.py class NotesCreateView(LoginRequiredMixin,CreateView): model=Notes form_class=NotesCreateForm redirect_field_name='notes_detail.html' class NotesListView(ListView): model=Notes class NotesDetailView(LoginRequiredMixin,DetailView): model=Notes Models.py class Notes(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE) title=models.CharField(max_length=255) subject=models.CharField(max_length=255) text=models.TextField() def get_absolute_url(self): return reverse('notes_detail',kwargs={'pk':self.pk}) Forms.py class NotesCreateForm(forms.ModelForm): class Meta: model=Notes fields=('title','subject','text') -
python django AttributeError: 'QuerySet' object has no attribute 'region'
Recently, I am moving an Django project from an old machine with Django 1.4 to a new machine with Django 1.11. The code runs well in the old machine, while I have met the following problem. Any suggestions and hints are very appreciated. The code is cabinet=Cabinet.objects.all() sc = cabinet.serializers.CabinetSerializer(cabinets) sc.data Cabinet is a Django Model class Cabinet(models.Model): region = models.ForeignKey(Region) lat = models.DecimalField(max_digits=13, decimal_places=10) lon = models.DecimalField(max_digits=13, decimal_places=10) corridor = models.PositiveIntegerField() type = models.CharField(max_length=2) milepost = models.DecimalField(max_digits=5, decimal_places=2) def name(self): 'Returns the WSDOT name for this cabinet' return "%03i%s%05i" % (self.corridor, self.type, self.milepost * 100) CabinetSerializer is a serializer class, which uses rest_framework from rest_framework import fields from rest_components import HyperlinkedModelSerializer from models import Cabinet class CabinetSerializer(HyperlinkedModelSerializer): class Meta: model = Cabinet fields = ('id', 'region', 'lat', 'lon', 'corridor', 'type', 'milepost', 'url') In rest_components.py from rest_framework.fields import Field as RF_Field from rest_framework.serializers import HyperlinkedModelSerializer as HMS class HyperlinkedModelSerializer(HMS): 'Identical to original, but supports exposing primary key' def get_pk_field(self, model_field): print("Hello") 'Returns a RF_Field instance, per BaseSerializer behavior' return RF_Field() After I run "sc.data", I got the following error message: AttributeError: 'QuerySet' object has no attribute 'region' However, I check in python >>>dir(cabinets[0]) ['DoesNotExist', 'MultipleObjectsReturned', '__class__', '__delattr__', '__dict__', '__doc__', '__eq__', … -
Extending the Django user model with a __getattr__ method
In a Django project, I have a module which extends Django's user model, similar to the following: from django.contrib.auth.models import User def __str__(self): return "%s %s" % (self.first_name, self.last_name) User.add_to_class('__str__', __str__) I've noticed that this works. However, if I try to define a __getattr__ method, like so: def __getattr__(self, attr): if self.user_profile: return getattr(self.user_profile, attr) else: raise AttributeError(f"'{self.__class__.__name__}' has no attribute '{attr}'") I get the following error upon importing the module: (lucy-web-CVxkrCFK) bash-3.2$ python manage.py shell Traceback (most recent call last): File "manage.py", line 28, in <module> execute_from_command_line(sys.argv) File "/Users/kurtpeek/.local/share/virtualenvs/lucy-web-CVxkrCFK/lib/python3.7/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/Users/kurtpeek/.local/share/virtualenvs/lucy-web-CVxkrCFK/lib/python3.7/site-packages/django/core/management/__init__.py", line 347, in execute django.setup() File "/Users/kurtpeek/.local/share/virtualenvs/lucy-web-CVxkrCFK/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/kurtpeek/.local/share/virtualenvs/lucy-web-CVxkrCFK/lib/python3.7/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/Users/kurtpeek/.local/share/virtualenvs/lucy-web-CVxkrCFK/lib/python3.7/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/Users/kurtpeek/.local/share/virtualenvs/lucy-web-CVxkrCFK/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/lucy_web/models/__init__.py", line 25, in <module> from .user import User File "<frozen importlib._bootstrap>", line 1019, in _handle_fromlist TypeError: __getattr__() missing 1 required positional … -
type object is not iterable Django
I am creating a personal portfolio website using Django. I am making a new model, called 'Skill', and I want a different instance of the model for each skill which I have. I have previous experience with Django, so I am simply doing the same process as always. However, for some reason, this time I get an error when registering the model - TypeError: 'type' object is not iterable. I have already added the skills app to my list of apps. Does anyone know why this is happening? Here is my views.py from django.shortcuts import render from .models import Skill # Create your views here. def skills(request): Skills = Skill.objects.all() return render(request,'skills\skills.html') Here is my models.py from django.db import models # Create your models here. class Skill(): title = models.CharField(max_length = 250) def __str__(self): return (self.title) And here is my admin.py from django.contrib import admin from .models import Skill # Register your models here. admin.site.register(Skill) I am not even calling this model yet in any html file - making migrations or running the server will give me this error. All help is appreciated. Thank you. -
Django Smooth Scroll
I have a simple page where I've tried to get to different sections via anchor-links. I justed wanted to get this "jumps" to smooth scrolls. After trying different jQuery-Code-Snippets I'm hoping that some of you could give me a tip, why it's still not working on my Django-Site. // Select all links with hashes $('a[href*="#"]') // Remove links that don't actually link to anything .not('[href="#"]') .not('[href="#0"]') .click(function(event) { // On-page links if ( location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname ) { // Figure out element to scroll to var target = $(this.hash); target = target.length ? target : $('[name=' + this.hash.slice(1) + ']'); // Does a scroll target exist? if (target.length) { // Only prevent default if animation is actually gonna happen event.preventDefault(); $('html, body').animate({ scrollTop: target.offset().top }, 1000, function() { // Callback after animation // Must change focus! var $target = $(target); $target.focus(); if ($target.is(":focus")) { // Checking if the target was focused return false; } else { $target.attr('tabindex','-1'); // Adding tabindex for elements not focusable $target.focus(); // Set focus again }; }); } } }); <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Font Family … -
What does request.GET.get('page', '1') means here?
views.py from django.core.paginator import Paginator def index(request): posts_list = Post.objects.all().order_by('-id') paginator = Paginator(posts_list, 5) try: page = int(request.GET.get('page', '1')) except: page = 1 try: posts = paginator.page(page) except(EmptyPage, InvalidPage): posts = paginator.page(paginator.num_pages) return render_to_response('home/index.html', { 'posts' : posts }, context_instance=RequestContext(request)) -
possible to print or check how many db connection is open and if closed? django
Recently I am having errors of too much request that the host ip is blocked that I have to flush hosts in order for the connection to work again, I event went to mariadb configuration to change the max_connetions, max_connect_errors as I found in other forums but this error still happens sometimes even though not as often anymore. I just want to double check and see if there's any part of my code that somehow the connection got opened but didn't close because there aren't that much people using the request (as I know of) when the error happens. Is there a way in django or somewhere I can print out / see how many connections are opened and if they are closed after requests are done or something like that? Thanks in advance for any help and suggestions. -
Receive Django signals accross different containers
I'm currently working on a Django project and I have some issues handling signals across different containers. I have a first container that is connected to a data pipeline upstream and populating Django's database. I have an other container for the backend itself and on which I am running the server. I would like to use the signal "post save" to signal one of my app that a new model instance has been saved. Thus, I use the next piece of code in my app to receive this signal and process the instance that has been saved. @receiver(post_save, sender=Organization) def index_post_save(sender, instance, **kwargs): connections.create_connection(hosts=['elasticsearch']) instance.indexing() This works perfectly if I create manually an Organization instance on the Django admin interface, but the signal is not received when I'm populating the database with my first container. Here is a part of my docker-compose file with the two containers I described: worker: build: context: . dockerfile: Dockerfile command: ./run_celery.sh env_file: - ./.envs/.local/.workers volumes: - .:/app web: restart: always build: context: . dockerfile: Dockerfile hostname: web command: /app/run_web.sh env_file: - ./.envs/.local/.web volumes: - .:/app ports: - "80:8000" links: - db - pipeline_db depends_on: - db - pipeline_db - elasticsearch Is there a way … -
Django cant connect to redis in docker
Sorry for my english. I have project in django, In my project i want use celery for background task and now i need set settings in docker for this library. This my docker file: FROM python:3 MAINTAINER Alex2 RUN apt-get update # Install wkhtmltopdf RUN curl -L#o wk.tar.xz https://downloads.wkhtmltopdf.org/0.12/0.12.4/wkhtmltox-0.12.4_linux-generic-amd64.tar.xz \ && tar xf wk.tar.xz \ && cp wkhtmltox/bin/wkhtmltopdf /usr/bin \ && cp wkhtmltox/bin/wkhtmltoimage /usr/bin \ && rm wk.tar.xz \ && rm -r wkhtmltox RUN apt-get install -y cron # for celery ENV APP_USER user ENV APP_ROOT /src RUN groupadd -r ${APP_USER} \ && useradd -r -m \ --home-dir ${APP_ROOT} \ -s /usr/sbin/nologin \ -g ${APP_USER} ${APP_USER} # create directory for application source code RUN mkdir -p /usr/django/app COPY requirements.txt /usr/django/app/ WORKDIR /usr/django/app RUN pip install -r requirements.txt this my docker-compose.dev version: '2.0' services: web: build: . container_name: api_dev image: img/api_dev volumes: - .:/usr/django/app/ - ./static:/static expose: - "8001" env_file: env/dev.env command: bash django_run.sh nginx: build: nginx container_name: ng_dev image: img/ng_dev ports: - "8001:8001" volumes: - ./nginx/dev_api.conf:/etc/nginx/conf.d/api.conf - .:/usr/django/app/ - ./static:/static depends_on: - web links: - web:web db: image: postgres:latest container_name: pq01 ports: - "5432:5432" redis: image: redis:latest container_name: rd01 command: redis-server ports: - "8004:8004" celery: build: . container_name: cl01 command: … -
Update only fields with text using ModelForm
I've an update view that is based on ModelForm , I'm using instance to update the current row , but the problem is user maynot need to update all the fields. but when the form saves data . it saves everything and gives me blank fields ( which user didn't fill). Here are my codes : forms.py class EditYellowForm(forms.ModelForm): business_title = forms.CharField(required=False, widget=forms.TextInput( attrs={ 'placeholder': 'New Title', 'style': 'width: 100%; max-width: 500px' } ) ) contact_address = forms.CharField(required=False, widget=forms.TextInput( attrs={ 'placeholder': 'New Address', 'style': 'width: 100%; max-width: 500px' } ) ) class Meta: model = YellowPages fields = ['business_title', 'contact_address'] views.py def yellow_edit(request, pk): current_yellow_ad = get_object_or_404(YellowPages, pk=pk) if request.method == "POST": edit_yellow_form = EditYellowForm(instance=current_yellow_ad, data=request.POST, files=request.FILES) if edit_yellow_form.is_valid(): instance = edit_yellow_form.save(commit=False) instance.save() return redirect('yellow_pages') else: edit_yellow_form = EditYellowForm(instance=current_yellow_ad, data=request.POST, files=request.FILES) context = { 'edit_yellow_form': edit_yellow_form, 'current_yellow_ad': current_yellow_ad, } return render(request, 'yellow_pages/edit.html', context) the model in case it is needed: class YellowPages(models.Model): type_of_business_chioces = ( ('service', 'service '), ('product ', 'product '), ) business_title = models.CharField(max_length=120) contact_address = models.CharField(max_length=120, blank=True, null=True) contact_number = models.IntegerField(blank=True, null=True) contact_email = models.EmailField(blank=True, null=True) website = models.CharField(validators=[URLValidator()], max_length=120, blank=True, null=True) image = models.ImageField(upload_to=content_file_name, blank=True, null=True) category = models.ForeignKey(YelllowPagesCategory, on_delete=CASCADE) tags = TaggableManager() owned = models.BooleanField(default=False) … -
Proxy error while django installation on python 3.7 in windows
I am trying to install django in windows 10. I have already installed Python 3.7 and running this command to install django. pip install django As only Python 3 is installed on my PC, so I didn't have to use pip3. Error: Proxy Error() Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refuses it. From the error, I can see it is some kind of proxy error and ask me to change or provide a proxy. But I am not using any proxy and my Firewall is all set (it is not blocking it). Tried for solution I have already searched it a lot and most of them recommended me to provide --proxy with pip but I can't, as I am not using any proxy. -
Cannot upload file with AttributeError : 'str' object has no attribute 'get'
when i try to upload a file(gif,mp4) or image in the user_post.html page to the database, i get this AttributeError : 'str' object has no attribute 'get' Can someone tell me what i miss? Thank you! Traceback: File "C:\Users\GIAM ZENG KEAT\Anaconda3\lib\site-packages\django\core\handlers\exception.py" in inner 35. response = get_response(request) File "C:\Users\GIAM ZENG KEAT\Anaconda3\lib\site-packages\django\utils\deprecation.py" in __call__ 97. response = self.process_response(request, response) File "C:\Users\GIAM ZENG KEAT\Anaconda3\lib\site-packages\django\middleware\clickjacking.py" in process_response 26. if response.get('X-Frame-Options') is not None: Exception Type: AttributeError at /userpost/post/ Exception Value: 'str' object has no attribute 'get' models.py class UserPost(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) cinemagraph = models.FileField(upload_to="user_post/", validators=[FileExtensionValidator(allowed_extensions=['gif','png','jpg'])]) c_description = models.CharField(max_length=500,default='') date_time = models.DateTimeField(auto_now=True) def __str__(self): # Built-in attribute of django.contrib.auth.models.User ! return self.user.username views.py def Post(request): if request.method == 'POST': form_post = UserPostForm(request.POST, request.FILES, instance= request.user.userpost) if form_post.is_valid(): posted = form_post.save(commit=False) posted.user = request.user posted.save() return reverse('home') else: return HttpResponse('Posting failed') else: form_post = UserPostForm() return render(request,'post/user_post.html',{'form_post':form_post}) -
How do I send cookies from an Angular 2+ application to a Django backend?
Angular sets cookies in the browser, but when I do a POST request to Django, request.COOKIES is empty in the Django view. -
Pagination in a Wagtail project: Better way to separate pagination logic in model?
I have here a snippet from a HomePage model in a Wagtail project that is acting as my blog index page. Since get_context() was getting a little lengthy while I was adding Django's pagination logic to it, I decided to try to put it in its own method and just have get_context() grab the paginated collection of Page objects from that. Here's how my code looked at first: class HomePage(RoutablePageMixin, Page): description = models.CharField(max_length=255, blank=True, null=True) content_panels = Page.content_panels + [ FieldPanel('description', classname='full') ] def get_context(self, request, *args, **kwargs): context = super(HomePage, self).get_context(request, *args, **kwargs) context['posts'], context['page_range'] = self.pagination(self.get_posts()) # End attempt context['home_page'] = self context['search_type'] = getattr(self, 'search_type', '') context['search_term'] = getattr(self, 'search_term', '') return context def get_posts(self): return BlogPage.objects.descendant_of(self).live().order_by('-date') def pagination(self, posts): paginator = Paginator(posts, 5) try: page = request.GET.get('page', '1') except: page = 1 try: posts = paginator.page(page) except PageNotAnInteger: posts = paginator.page(1) except EmptyPage: posts = paginator.page(paginator.num_pages) # Get a page_range index = posts.number - 1 max_index = len(paginator.page_range) start_index = index - 5 if index >= 5 else 0 end_index = index + 5 if index <= max_index - 5 else max_index page_range = paginator.page_range[start_index:end_index] print('\n', posts, '\n') return posts, page_range I didn't see the … -
How to POST one-to-one relationship foreign key data
This is the current models I'm trying to save with rest_framework. class ModelA(models.Model): model_b = models.OneToOneField(ModelB, on_delete=models.CASCADE) some_integer_field = models.IntegerField() class ModelB(models.Model): data = models.TextField() My serializers: class ModelASerializer(serializers.ModelSerializer): class Meta: model = ModelA fields = ('id', 'some_integer_field', 'model_b') class ModelBSerializer(serializers.ModelSerializer): class Meta: model = ModelB fields = ('id', 'data') What I'm trying to accomplish is that when I POST (ModelA): { "some_integer_field": 123, "model_b" : "123,123,123,432,432" } I would like that when the ModelB is created in the database that the "data" field should be populated and then the ModelA would use ModelB's pk to create itself. "data" is not nullable. It has to be there. -
AttributeError: 'Settings' object has no attribute 'FILE_SYSTEM_BASE'
I'm following the GitHub instructions here: https://github.com/jsfenfen/990-xml-database I'm getting the error AttributeError: 'Settings' object has no attribute 'FILE_SYSTEM_BASE' Any suggestions on where to input this FILE_SYSTEM_BASE property, and what it should be set to? -
Relation does not exist with Django uwsgi spooler function
I'm running a Django 1.8 app using uwsgi. I'm trying to run a function in a spooler using the @spool decorator. The function is adding data to my models. But I get this error when the spooler function tries to save an object: psycopg2.ProgrammingError: relation "bgsite_person" does not exist LINE 1: UPDATE "bgsite_person" SET "title" = NULL, "first_names" = N... Here's my uwsgi config file: [uwsgi] http = :8000 module = BGMS.wsgi:application chdir = /home/pete/GitHub/BGMS/BGMS check-static = /home/pete/GitHub/BGMS/BGMS/BGMS/build/ home = /home/pete/.virtualenvs/bgms env = DJANGO_SETTINGS_MODULE=BGMS.settings.development master = true processes = 4 threads = 1 lazy-apps = 1 spooler = /home/pete/Documents/ shared-import = /home/pete/GitHub/BGMS/BGMS/bgsite/spooler_functions.py I've no problems when I run this function in a normal worker. Any ideas? Thanks. -
django model forms, display text for a foreign key (not using __str__ in model)
I have a mapping table which I am referencing as a foreign key for another table, i.e. mapping table: class DeviceCircuitSubnets(models.Model): device = models.ForeignKey(Device, on_delete=models.CASCADE) circuit = models.ForeignKey(Circuit, on_delete=models.CASCADE, blank=True, null=True) then in my interface table: class InterfaceData(models.Model): device_circuit = models.ForeignKey(DeviceCircuit, verbose_name="Device", on_delete=models.CASCADE) interface_name = models.CharField(max_length=100, verbose_name='Interface name') dashboard = models.BooleanField(default=False, verbose_name="Display on monitoring dashboard?") wallboard = models.BooleanField(default=False, verbose_name="Display on wallboards?") Im building a form for interface data in forms.py but the display text of the drop down is just DeviceCircuit Object. I know this is because I haven't set def str(self), but it is my understanding that I would be making uncessecary calls to other models if I did this (i.e. the str would reference device.hostname and circuit.circuit_type.circuit_type and so on which I dont want. I would just like to change the display for drop downs as and when I need them. so far I have filtered and renamed the field but cannot seem to set the display, is this possible using a model form? class InterfaceDataForm(forms.ModelForm): class Meta: model = InterfaceData fields = ['device_circuit','interface_name','dashboard','wallboard'] def __init__(self, *args, **kwargs): self.is_add = kwargs.pop("is_add", False) device_id = kwargs.pop("device_id") super(InterfaceDataForm, self).__init__(*args, **kwargs) self.fields['device_circuit'].queryset = DeviceCircuit.objects.filter(device_id=device_id) \ .select_related('device') \ .select_related('circuit') \ .select_related('circuit__circuit_type') \ … -
error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\x86_amd64\\link.exe' failed with exit status 1120
I am new to Django and I am trying to connect Django to MySQL database instead of using the default database. I am using Python 3.6 and Django 2.0.7 on Windows7. And I have mySQL Server 5.7 installed. I am deploying the environment in virtual environment but when I tried to run the command: pip install django mysqlclient it gave the error as the header. Previously my error was visual c++ 14.0 is required so I installed visual studio 2015. But now it gave the another and I haven't seen a clear solution of solving this problem. -
Django parallel tests not creating database tables
I'm trying to run Django tests in parallel using the following command: python manage.py test myproject.myapp.tests --parallel=4 --keepdb However, I get errors like the following: ... File "/home/daniel/Envs/myproject/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: relation "settings_currency" does not exist LINE 1: INSERT INTO "settings_currency" ("name", "symbol", "code") V... ^ which means that the tables are not being created in the test postgres DBs. I have created DBs named test_myproject_1, test_myproject_2 and so on, and upon inspection in pgAdmin, I see the tables are indeed not there. I have no problems running the tests on a single thread, i.e. when I use the --parallel=1 option. Is there anything else I need to configure so that the tables are created and the tests run without errors? -
redirect React traffic to Django REST in development
In production, my Django serves all API calls (/api) to Django REST services and rest (/) serves React static files. So, when my React calls services, it simply calls APIs by calling /api. However, it causes problem in development. python manage.py runserver serves Django REST in localhost:8000. And React website is available at localhost:3000 by npm start. It is a problem because /api calls localhost:3000/api instead of localhost:8000/api. In order for Django to serve React code locally, we have to compile React code which is expensive to do every modification. What is the best way to solve this issue? Should Django dev server somehow redirect the traffic from 8000 to 3000? Or React dev server redirect? -
Login student model django
I am learning django framework and I stuck in a Teacher/student problem.I have student model in which i have students username and password whereas teachers accounts are directly created from admin site users model.I have successfully created login for teachers by using built-in login system of django. Now I wanted to make login of students,their username/password are stored in student models.In my case,student account(username and password) are created by their teachers and are stored in student model.So student only needs to login and i have only one login form (both for teacher and student). How can I login student by checking from students models.I have searched about it but it makes me confusing.Need some help for this. -
How ListView and Detailview work in Django? What is the difference between ListView and Detailview and and wat is the use of both
Class MetroTrain(ListView): #Statements Class MetroTrainDetail(DetailView): #Statements -
'Currencysys' Object is not iterable
I have a problem with my model and serialization, I do a inner join of two tables like this: # file views.py from Wallet class WalletBalances(generics.ListAPIView): serializer_class = WalletSerializer def get_object(self, current_user): return Wallet.objects.filter(currencysys__id=F('currencysys_id'), user_id=current_user) def get(self, request, format=None): current_user = request.user list_balances = self.get_object(current_user.id) serializer = self.serializer_class(list_balances, many=True) get_data = serializer.data return JsonResponse({'data': get_data}, safe=False, status=status.HTTP_200_OK) the error shows me is = " 'CurrencySys' object is not iterable " my file Wallet / Serialization is from other_project.serializers import CurrencySysSerializer class WalletSerializer(serializers.ModelSerializer): # currencysys = CurrencySysSerializer(many=True) currencysys = serializers.StringRelatedField(many=True) class Meta: model = Wallet fields = '__all__' my models are: # Currency / models.py class CurrencySys(models.Model): currency_symbol = models.CharField(max_length=45, blank=True) currency_name = models.CharField(max_length=45, blank=True) currency_status = models.BooleanField(blank=True) currency_crypto = models.BooleanField(blank=True) # wallet / models.py class Wallet(models.Model): addresskey = models.CharField(max_length=40, blank=True) name_wallet = models.CharField(max_length=45, blank=True) currencysys = models.ForeignKey(CurrencySys, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) why show me that error and how to fix this problem, please help me thank for your attention.