Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django KeyError at /manhattan/{% url 'activity' }
I was given the task to create an NYC Guide project out of Python and Django. I am iterating through a nested dictionary to render boroughs, activities, and venues. The home page lists a handful of boroughs. The boroughs page lists a handful of activities in each borough. The activities page lists a handful of venues to select. My issue is when I click on one of the venues I get a keyerror. I am trying to at least render the venues page that has a simple 'VENUES PAGE' on it. I'd love any advice or feedback. This is my first Django project so forgive me if I didn't explain this thoroughly enough. Feel free to ask for further explanation! What I am ultimately trying to do is create a url that takes me to the venue.html page. It doesn't have to render a specific venue. I can take it from there. I am stuck on this one step. //Here is my boroughs.py `boroughs = { 'brooklyn': { 'beaches': { 'brighton beach': { 'img_link': '', 'description': 'Also known as "Little Odessa" due its tight-knit Russian and Eastern European communities, Brooklyn\'s Brighton Beach is a lively neighborhood with many high-rise residential … -
Django for loop to display all objects in database
def homepage(response): data = Project_types.objects.all() return render(response, 'main/homepage.html',{'projects':data}) def hacks(response): return render(response, 'main/hacks.html', {}) def games(response): return render(response, 'main/games.html', {}) All I need to know is how to iterate through each object in the variable "data" in html. I want it displayed in the most simple way possible ! -
Why this loop doesn't work correctly? Python, Selenium
So im building an Django API, and im trying to put a bunch of information through Selenium, i have a JSON file that i converted to an Excell file and using xlrd, i read it and i want to put the data in Django like this : for curr_row in range(1, sheet.nrows): titlevalue = sheet.cell_value (curr_row, 0) descriptionvalue = sheet.cell_value(curr_row, 2) imagevalue = sheet.cell_value (curr_row, 1) keywordsvalue = sheet.cell_value (curr_row, 3) title.send_keys(titlevalue) description.send_keys(descriptionvalue) image.clear() image.send_keys(imagevalue) keywords.send_keys(keywordsvalue) save.click() addarticle.click() This loop in my mind it should do it, like post an article after article with the data from the Excell file, but it only work once, it writes the first article with the first row and then it stops, it doesn't run again, why? -
Getting Data from the Frontend & CORS
i´m stuck at a little demo project from udemy with django and api calls. I have this in main.js and I want to get array of object and not just a json list in console. let projectsUrl = 'http://127.0.0.1:8000/api/projects/' let getProjects = () => { fetch(projectsUrl) .then(response => response.json()) .then(data => { console.log(data) buildProjects(data) }) } let buildProjects = (projects) => { let projectsWrapper = document.getElementById('testz') for (let i = 0; projects.lenght > i; i++){ let project = projects[i] console.log(project) } } getProjects() The result : Console Log and the result should be something like this : Console Log -
How can I access to data stored in a ManyToMany related table in Django?
I want to make a query to obtain all the users that another user is "following" for a learning project. When I execute the following python code: user = User.objects.get(id=user_id) followers = user.follows.all() I don't get an error but instead I get a list with an object ( called Follow object (4) ) from wich I can't access the user related properties. I've checked this documentation here: https://docs.djangoproject.com/en/3.2/topics/db/examples/many_to_many/ But I can't find where I'm falling to use properly this type of model-relation. Here are my Django models: class User(AbstractUser): pass class Follow(models.Model): user = models.ForeignKey(User, null=False, on_delete=models.CASCADE, related_name="follows") follow = models.ManyToManyField(User, blank=True, related_name="followed_by") I searched in my Django DB to see what is happening and I saw that there is a relational table called "network_follow_follow" that in fact has all the info that I need and is related with the object that I get from my Query, here are two pictures about the table that I can access and the one that I don't know how to access: Table data requested by my code Table that I need to query So now I'm looking a way to access that last table, but to know how can I access straight forward … -
Getting HTTP 405 Method error on POST view
I'm working with the Django rest framework and I'm getting this error when I'm trying to make a post view. HTTP 405 Method Not Allowed Allow: POST, OPTIONS Content-Type: application/json Vary: Accept { "detail": "Method \"GET\" not allowed." } my API view @api_view(['POST']) def createroom(request): account = User.objects.get(pk=1) account2 = Topic.objects.get(pk=2) create_room = Room(host=account, topic=account2) if request.method == "POST": serializer = RoomSerializer(create_room, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_401_BAD_REQUEST) This is my model class Room(models.Model): host = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) topic = models.ForeignKey(Topic, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) participants = models.ManyToManyField(User, related_name='participants', blank=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-updated', '-created'] def __str__(self): return self.name and the serializer class RoomSerializer(ModelSerializer): class Meta: model = Room fields = '__all__' It's saying that "GET" is not allowed but I'm making a POST view. How can I fix this? -
Storing a matrix in django model
I would like to store a matrix (from a file) in django and upload it to sqlite. I have seen that some people advise to store it per cells, but as it is a huge matrix (more than a thousand elements) I wouldn't like to store it that way, but as a whole. I am thinking about storing it as a list, but it is also not easy, because the elements are floats. Is there a simple/doable way to store my matrix? view.py new_file = [[8.2, 14.2, -6.1], [12.6,7.0,4.7], [-1.1,3.6,21.1]] def file_list(request): content = new_file[:] content = chain.from_iterable(zip(*content)) extract_data = Cell(content = content) extract_data.save() model.py class Cell(models.Model): content = models.FloatField() #ok, obviously this doesn't work -
Django template tag if/else/endif always goes to "else"
I need some help to figure out where is a problem. For example i have similar code: views.py context = { 'Tru': 1 == 1, 'perm': {} } context['perm']['can_do'] = some_var == 1 context['perm']['also_can'] = another_var == True template.html {% if perm.can_do or perm.also_can or perm.can_do is True or perm.can_do == 1 or perm.can_do == Tru %} PASS {% else %} {{ perm.can_do }} {{ perm.can_do|typeof }} {% endif %} But when page is rendered i see True <class 'bool'> instead of PASS. Is there something wrong with Django or i miss something? Btw, Django 3.2 and Python 3.10 if it matter. -
How do I use the ModelSerializer with the ListSerializer in Django Rest Framwork?
I want to be able to send POST requests which include lists of the location model. The reason for this is that I want to send the sensor data periodically. I have tried the following but end up with this error. How should I implement the create method and am I doing this the correct way? raise NotImplementedError('`create()` must be implemented.') NotImplementedError: `create()` must be implemented. serializers.py class LocationSerializer(serializers.ModelSerializer): class Meta: model = Location fields = ['latitude'] class MultiLocationSerializer(serializers.Serializer): items = LocationSerializer(many=True) views.py class LocationViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = Location.objects.all() serializer_class = MultiLocationSerializer permission_classes = [permissions.IsAuthenticated] urls.py router = routers.DefaultRouter() router.register(r'locations', ph.BookViewSet) # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] -
How to make django-crontab execute commands in Docker container?
In order to periodically execute tasks in my Django app I have installed django_crontab extension. https://pypi.org/project/django-crontab/ I have done every step as it is described in setup paragraph. settings.py INSTALLED_APPS = [ ... 'django_crontab', ] ... CRONJOBS = [ ('*/1 * * * *', 'config.cron.fun') ] cron.py def fun(): print("hello cron") with open("./test.txt", "a") as f: f.write("Hello") I also add cron job in docker-entrypoint.yml: python manage.py crontab add python manage.py crontab show In Dockerfile I use python:3.8 image and install cron: RUN apt-get install -y cron && touch /var/log/cron.log And no response after running the container. When I enter the container, I can see that cron sees the job, but still does not execute it. root@bar:/back# crontab -l */1 * * * * /usr/local/bin/python /back/manage.py crontab run ebcca28ea3199afe6d09a445db5d5fd8 # django-cronjobs for config How can I fix it? -
How can I include in the JSON's GET request the list of foreign keys of a model in Django?
My models have users that can have multiple devices. When I do a GET request on users it returns only the fields specified in the user model, as it should. But I want the option to include in the JSON returned by the GET request the list of devices the user has. How can I do that? It would be nice to specify in the query string a boolean or something in order do specify if I want the user's JSON to have or not the list of devices. But this is just my ideea, maybe it could be done diffrently and better. Also, I am really new to Django, and I would appreciate a lot code examples to understand better, if possible. These are my models: class User(models.Model): name = models.CharField(max_length=100) birth_date = models.DateField() address = models.CharField(max_length=200) class Device(models.Model): description = models.CharField(max_length=200) location = models.CharField(max_length=200) max_energy_consumption = models.FloatField() avg_energy_consuumption = models.FloatField() user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) My serializers: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' class DeviceSerializer(serializers.ModelSerializer): class Meta: model = Device fields = '__all__' And the following default ModelViewSets for CRUD api calls: class UserViewSet(ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer class DeviceViewSet(ModelViewSet): queryset = … -
Djongo (not django, djongo): pymongo.errors.ServerSelectionTimeoutError: cluster0 [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed:
I have a simple web application and I need to connect to my mongodb instance so I can perform basic queries and also update the database. I have djongo and pymongo[srv] installed. DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'strands', 'ENFORCE_SCHEMA': False, 'CLIENT': { 'host': "mongodb+srv://db-admin:"+ PASS + CLUSTER } } } -
How to add a field with POST using Fetch API in Django app?
Hello I am trying to use the fetch api to call the POST request and create/add a new item to the table using vue. I am not sure where and how to create a form to input details. I have this code until now: I already have delete and edit functions working, I just need the POST one. countries.html <table class="table"> <thead> <tr> <th scope="col">#</th> <th scope="col">Country</th> <th scope="col">Code</th> <th width="100" scope="col"></th> </tr> </thead> <tbody> <tr v-for="(country, index) in countries"> <th scope="row"> [[ index ]] </th> <td> <input v-if="country.editing" type="text" v-model="country.name" /> <a v-else :href="country.url"> [[ country.name ]] </a> </td> <td> <input v-if="country.editing" type="text" v-model="country.code" /> <span v-else>[[ country.code ]]</span> </td> <td class="d-flex justify-content-between"> <button v-if="!country.editing" @click="country.editing = true" class="btn btn-sm btn-secondary"> Edit </button> <button v-else @click="saveCountryChanges(country)" class="btn btn-sm btn-success"> Save </button> <button @click="deleteCountry(country)" class="btn btn-sm btn-danger"> Delete </button> </td> </tr> </tbody> </table> <script> methods: { async addCountry(country) { let response = await fetch(country.api, { method: "POST", body: JSON.stringify({ name: country.name, code: country.code, }), headers: { "Content-Type": "application/json", "X-CSRFToken": document.querySelector("[name=csrfmiddlewaretoken").value, } }); if (response.ok) { country.adding = false; } else { // country add failed alert("Failed to add changes"); } } </script> api.py def country_api(request, country_id): country = get_object_or_404(Country, id=country_id) … -
azure static files missing/ wrong MIME
Django website deployed to Azure (F1 - free subscription) Linux, all static files are missing/ not rendered. Even the files from admin which are not changed. Locally works fine, I've googled around tried to upload without VS code etc. still does not work. Source code of app - https://github.com/Azure-Samples/python-docs-hello-django Tutorial - https://docs.microsoft.com/en-us/azure/app-service/quickstart-python?tabs=bash&pivots=python-framework-django Deployed via Azure CLI, any pointers I would gladly take. -
Page not found - The current path, matched the last one
I have created an update view. I want to add a button to the post that directs to the update view. However when you click the button you get this error. 404 Page not found post/<int:pks>/build-log/<int:pk>/update/ [name='build-log-update'] post/75/build-log/127/update/, matched the last one.` The reason for this error occurring is because it is flipping the PK when you click the button. Example. /post/127/build-log/75/ after button clicked /post/75/build-log/127/update/ you can see it is flipping the PK. If just just append update to the good url it works fine I cannot figure out why it is flipping the pks html: <a class="delete-btn" href='{% url "build-log-delete" pk=log.post_id pkz=log.pk %}'>Delete</a> <a class="update-btn" href='{% url "build-log-update" pk=log.post_id pkz=log.pk %}'>Update</a> urls: path('post/<int:pk>/build-log/<int:pkz>/', views.BuildLogDisplay, name='build-log-view'), path('post/<int:pk>/build-log/<int:pkz>/delete/', views.BuildLogDelete, name='build-log-delete'), path('post/<int:pks>/build-log/<int:pk>/update/', UpdateBuildLog.as_view(), name='build-log-update') model: class BuildLog(models.Model): title = models.CharField(max_length=100) content = RichTextUploadingField(blank=True, null=True) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey('Post', on_delete=models.CASCADE) def get_absolute_url(self): return reverse('build-log-view', kwargs={'pkz': self.pk}) view: class UpdateBuildLog(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = BuildLog form_class = BuildLogupdateForm template = 'blog/buildlog_update.html' def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): post = self.get_object() if self.request.user.id == post.author_id: return True return False -
How to combine 2 queries in Postgresql?
I face with a problem, I have 2 selects and I need to combine them into one output? I want to get one select table with column shop.name, COUNT("Fins_shop"."name") as count_goods MAX("Fins_price"."price") as max_price, Count("Fins_shop"."name") as count_department, SUM("Fins_department"."staff_amount"), first select SELECT "Fins_shop"."name", COUNT("Fins_shop"."name") as count_goods MAX("Fins_price"."price") as max_price FROM "Fins_shop" INNER JOIN "Fins_department" ON "Fins_department"."shop_id" = "Fins_shop"."id" INNER JOIN "Fins_item" ON "Fins_item"."department_id" = "Fins_department"."id" GROUP BY "Fins_shop"."name" second select SELECT "Fins_shop"."name" , Count("Fins_shop"."name") as count_department, SUM("Fins_department"."staff_amount"), FROM "Fins_shop" INNER JOIN "Fins_department" ON "Fins_department"."shop_id" = "Fins_shop"."id" GROUP BY "Fins_shop"."name" if table table has foreign key to department and table department has foreign key to shop Also have models of this tables: class Shop(models.Model): name = models.CharField(max_length=200) address = models.CharField(max_length=200) staff_amount = models.PositiveIntegerField(default=0) def __str__(self): return f'{self.id}{self.name} with staff {self.staff_amount}' class Meta: verbose_name = 'Shop' verbose_name_plural = 'Shops' ordering = ['id'] def get_absolute_url(self): return reverse('shop_detail', kwargs={'pk': self.pk}) class Department(models.Model): sphere = models.CharField(max_length=200) staff_amount = models.PositiveIntegerField(default=0) shop = models.ForeignKey( Shop, on_delete=models.CASCADE, related_name='department_relate', related_query_name='department_filter', ) def __str__(self): return f'{self.id}-{self.sphere}-{self.shop}' class Meta: verbose_name = 'Department' verbose_name_plural = 'Departments' ordering = ['id'] def get_absolute_url(self): return reverse('department_detail', kwargs={ 'shop_pk': self.shop.id, 'pk': self.id}) class Item(models.Model): name = models.CharField(max_length=200) description = models.TextField() price = models.PositiveIntegerField(default=0) is_sold = models.BooleanField(default=False) comments … -
django-rest-auth with allauth customuser TypeError: 'PhoneNumber' object is not subscriptable
models.py class CustomUser(AbstractUser): username = PhoneNumberField(unique=True) payloads: { "username": "+8801700000000", "password1": "demo", "password2": "demo", "email": "demo@demo.com", } response: Internal Server Error: /api/rest-auth/registration/ Traceback (most recent call last): File "venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "venv\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "venv\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "venv\lib\site-packages\django\views\decorators\debug.py", line 89, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "venv\lib\site-packages\rest_auth\registration\views.py", line 46, in dispatch return super(RegisterView, self).dispatch(*args, **kwargs) File "venv\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "venv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "venv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "venv\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "venv\lib\site-packages\rest_framework\generics.py", line 190, in post return self.create(request, *args, **kwargs) File "venv\lib\site-packages\rest_auth\registration\views.py", line 65, in create user = self.perform_create(serializer) File "venv\lib\site-packages\rest_auth\registration\views.py", line 73, in perform_create user = serializer.save(self.request) File "venv\lib\site-packages\rest_auth\registration\serializers.py", line 210, in save adapter.save_user(request, user, self) File "venv\lib\site-packages\allauth\account\adapter.py", line 242, in save_user self.populate_username(request, user) File "venv\lib\site-packages\allauth\account\adapter.py", line 209, in populate_username user_username( File "venv\lib\site-packages\allauth\account\utils.py", line 120, in user_username return user_field(user, app_settings.USER_MODEL_USERNAME_FIELD, *args) File "venv\lib\site-packages\allauth\account\utils.py", line 110, in user_field v = … -
Group by in and nesting result in Django Rest Framework
im working in an API and i want to order by id DESC but i want to group by client_id too, so i could have all the questions from same clients ordered, nesting the results: This is my code: models.py class QuestionsModel(models.Model): id = models.IntegerField() publication_id = models.IntegerField(blank=True, null=True) publication_title = models.CharField(max_length=255) publication_link = models.CharField(max_length=255) question = models.CharField(max_length=255) member_id = models.IntegerField() client_id = models.IntegerField() class Meta: managed = False db_table = 'questions' serializers.py class QuestionsSerializer(serializers.ModelSerializer): class Meta: model = QuestionsModel fields = '__all__' views.py class QuestionsAPIView(generics.ListAPIView): def get_queryset(self): queryset = '' member_id = self.request.query_params.get('member_id') if member_id is not None and member_id.isnumeric(): queryset = QuestionsModel.objects.filter(member_id=member_id).order_by('-id') return queryset Result: { "id": 848484, "publication_id": 4444, "publication_title": "Title publication", "publication_link": "Link", "question": "This is a test question", "member_id": 123456, "client_id": 500 } What i want: Group questions by client_id, so desire output JSON could be: { "client_id": 500, "question" : [ "id": 848484, "publication_id": 4444, "publication_title": "Title publication", "publication_link": "Link", "question": "This is a test question", "member_id": 123456, "client_id": 500 ], [ "id": 848485, "publication_id": 4445, "publication_title": "Title publication", "publication_link": "Link", "question": "This is a test question", "member_id": 123456, "client_id": 500 ] } Notes: I'm using SQL Server as db engine. -
how to set dynamic seo tags in in django template
I'm working on a djanog project and i want to render dynamic meta tags and titles for every page in it. for now i'm trying to do it like this i have added block in header.html file like this {% block seo %} {% endblock %} hierarchy of main template (from which all other templates are extending) {% include 'header.html' %} {% include 'menu.html' %} {% block body %} {% endblock %} {% include 'footer.html' %} now on app templates i'm trying to render those seo tags like this {% extends 'main.html' %} {% block seo %} <title>example.cpm</title> <mete name="description" content="lorem ipsum"> {% endblock %} but this approach is not working for me, please help me in this regard -
TypeError at ManyRelatedManager
Please help me with this code. Code is showing 'ManyRelatedManager' object is not iterable enter image description here def index(request): parms = { 'posts': Post.objects.filter(publish = True), } return render(request, 'index.html',parms) -
Django website deploy errors: Failed building wheel for Pillow, Reportlab in cPanel
My website is working fine on the local server. This error is coming up when I try to install Pillow on the server (Namecheap Shared Hosting). I talked to Live Support, they have enabled the compiler, but still, I am getting these errors. Is there anybody to help me, how can I fix this? enter image description here enter image description here enter image description here -
Can you do SQL queries on the table generated by Django ORM?
I have a few question concerning this weird mix/frankenstein monster idea. Namely I would like to make SQL queries on some tables managed by Django (tables corresponding to models). Can you safely use SQL queries alongside Django ORM? Basically go around Django ORM but at the same time use Django ORM? Can you use Django ORM in many parallel threads? ( I do not mean sharing queryset/objects between threads) I know it is not thread safe. Django devs had problem making ORM async, however I am confused about what exactly is not allowed. Can you use Django ORM in different python interpreters ? Where could I look for more information about this ? I guess there could be some problem with synchronization of the db state? -
Sending large zip files to Django/Tastypie server
I want to send some zip files from a raspberry Pi to my windows server. The zips are about 2GB each. I'm using python sockets to send them. def sendFile(): s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) print('Socket created') s.connect(("http://192.168.0.21:8000/api/v1/ziptest/", 8000)) print("Connected") for x in range(len(zipTypes)): filename = '/logs/rel_5_0608.3800_val2/{}.zip'.format(zipTypes[x]) print("filename {} ".format(filename)) with open(filename,'rb') as infile: d = infile.read(1024) while d: s.send(d) d = infile.read(1024) infile.close() I've then got my resource function: class ResponseZipTest(ModelResource): class Meta: limit = 100000 queryset = TestZipModel.objects.all() resource_name = "ziptest" authorization = Authorization() always_return_data = True # Hydration function def hydrate(self, bundle): print("Server is ready to receive") def dehydrate(self, bundle): return bundle When I run sendTest() I get Name or service not known but I can use curl on that URL just fine. My resource function never gets triggered. My url file: v1_api = Api(api_name='v1') v1_api.register(ResponseZipTest()) test_model = ResponseZipTest() urlpatterns = [ url(r'^api/', include('api.urls')), url(r'^api/', include(v1_api.urls)), url(r'^api/', include(test_model.urls)) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Are sockets the best way to send these files? Is there another way that'll make this easier? -
Django arrayfield search?
I have an arrayfield named 'hashtags' in game.models. I want to make search by giving title ,also giving hashtags to search bar. object_list = Oyunlar.objects.annotate(search=SearchVector('title','hashtags')).filter(search=query).order_by('-click_count') This is my model: class Oyunlar(models.Model): game_id = models.AutoField(primary_key=True) title = models.CharField(max_length=10000) youtube_link=models.URLField(blank=True,null=True) video_aciklamasi=models.TextField(blank=True,null=True) platform = models.CharField(max_length=10) image = models.CharField(max_length=255, blank=True, null=True) release_date = models.DateField(blank=True, null=True) click_count = models.IntegerField(default=0) categories=models.ManyToManyField(Kategoriler,through='OyunlarKategoriler') base_price=models.DecimalField(default=0,max_digits=65535, decimal_places=2) big_discount=models.BooleanField(default=False) en_ucuz = models.DecimalField(default=0,max_digits=65535, decimal_places=2) popularite = models.IntegerField(blank=True, null=True,default=0) discount_rate = models.DecimalField(default=0,max_digits=65535, decimal_places=2) title_edit = models.CharField(max_length=500, blank=True, null=True) description = models.CharField(max_length=100000, blank=True, null=True) steam_id = models.CharField(max_length=1000, blank=True, null=True) metacritic = models.FloatField(blank=True, null=True) recommendation = models.BigIntegerField(blank=True, null=True) full_game = models.BooleanField(blank=True, null=True) age = models.CharField(max_length=500, blank=True, null=True) minimum = models.CharField(max_length=10000, blank=True, null=True) recommended = models.CharField(max_length=10000, blank=True, null=True) developer = models.CharField(max_length=500, blank=True, null=True) publisher = models.CharField(max_length=500, blank=True, null=True) oyun_foto = ArrayField(models.CharField(max_length=10000, blank=True, null=True),blank=True,null=True) # This field type is a guess. windows = models.BooleanField(blank=True, null=True) mac = models.BooleanField(blank=True, null=True) linux = models.BooleanField(blank=True, null=True) gamehunterz_yorumu = models.CharField(max_length=100000, blank=True, null=True) slugyap = AutoSlugField(default=None,null=True,populate_from='title_and_id',editable=True,max_length=10000) platformurl=AutoSlugField(default=None,null=True,editable=True,max_length=10000) hashtags = ArrayField(models.CharField(max_length=500, blank=True, null=True), blank=True, null=True) This is not working, what can I do to make it work? -
ensure one type of user cannot log in as another type of user django
In Django, how can I make sure that one type of user cannot log in as another type of user? For example, if there are two types of users on my website, teachers and students, teachers should not be able to use their credentials to log in as a student and vice versa.