Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django loading image from url - ImageField objected has no attribute _committed
I am using Django 3.2 I am trying to programatically create a model Foo that contains an ImageField object, when passed an image URL. This is my code: image_content = ContentFile(requests.get(photo_url).content) # NOQA image = ImageField() # empty image data_dict = { 'image': image, 'date_taken': payload['date_taken'], 'title': payload['title'], 'caption': payload['caption'], 'date_added': payload['date_added'], 'is_public': False } foo = Foo.objects.create(**data_dict) # <- Barfs here foo.image.save(str(uuid4()), image_content) foo.save() # <- not sure if this save is necessary ... When the code snippet above is run, I get the following error: ImageField object does attribute _committed I know this question has been asked several times already - however, none of the accepted answers (from which my code is based) - actually works. I'm not sure if this is because the answers are old. My question therefore is this - how do I fix this error, so that I can load an image from a URL and dynamically create an object that has an ImageField - using the fetched image? -
Add columns in django model table postgres
I recently edited my table and had overriden the primary_key to a title attribute. I tried deleting all previous migrations and even so, the model id, which should be the pk by default, isn't so. Since then I've been trying to add a new column id to my appname_model table. Here the appname is courses and model-class is course (written in lowercase in reference to the tablename statement I just made) I've entered the following commands multiple times and none have managed to add the field id: ALTER TABLE courses_course ADD COLUMN id int constraint; I've tried several other variants of the same syntax from other stackoverflow questions but none have worked out so far. I also want to set id to the primary key in that table. -
Django raw sql %d for ID not working for integer parameters
I have this raw sql for my Django model: cursor.execute('SELECT crowdfunding_offering.offering_name FROM crowdfunding_offering WHERE crowdfunding_offering.id = %d ORDER BY crowdfunding_offering.id DESC LIMIT 1', (int(self.offering.id),)) Which does not work. I am receiving this error: Exception Value: near "%": syntax error Then I try to change %d to %s, only then it works. I thought %d are for number parameters and %s are for strings, but why is it not working for %d? Here is the table with the id clearly being an integer: -
Cannot assign "'1'": "Offers.state must be a "States" instance
I have read several answers to this same question, but none have worked for me. Here's my model: class States(models.Model): name = models.CharField(max_length=20) abrev = models.CharField(max_length=3) def __str__(self): return self.abrev class Offers(models.Model): *other fields* state = models.ForeignKey(States on_delete=models.PROTECT) so in views i am doing this: if request.method == 'POST': try: **other fields** state = States.objects.get(pk=request.POST['state']) Offers.objects.create(**other fields**, state=state) except Exception as e: print ("error in form") But am always getting the same Error Cannot assign "'1'": "Offers.state must be a "States" instance. And as you can see, i am passing an instance, not the id of the element. I use the id that comes from the form just to query the DB and find the instance with this: state = States.objects.get(pk=request.POST['state']) The form works just fine, and I tried to do it with forms.py and if form.is_valid(), but got the exact same result. am on: django 3.2.3 python 3.9.2 -
Django automatically appending csrftoken to cookies send by React Native request
I've got a React Native app that is making requests using axios to my django server. const axios = require("axios").create({ baseURL: BASE_URL, headers: { 'cookie': `credentials=abc123;`, 'X-Requested-With': 'my_custom_app', } }); On my Django app, I am printing out the cookies for the request. print(request.COOKIES) When I'm printing the cookies on my local instance of the backend, things look fine: Here's the output from my local instance: {'credentials': 'abc123'} But on my prod instance of the server, the output is different: {'csrftoken': 'B17DuZmxWPyuTAEdcldsJqZX0dsDct4k6nHLXYtRPiJQFEpBrSPIH5G7M6rty0FH,credentials=abc123'} This obviously gets read incorrectly by the server and it thinks that my credentials are not available in the cookie. I'm not sure what is going on here, or why this only happens on my production instance. -
Optimal way for letting user download big files in the server using Django
I am making a Django application for an experiment and it will offer the possibility to the user to be able to download really big image files to a specific directory in the server. I have a PoC of that working, where the user sees a button clicks on it and the process to download begins. I have put the download process inside views.py which means it occurs upon visiting a specified URL. The code responsible for the download part similar to the following: with open(loc, "wb") as f: response = s.get(pos, stream=True) total_length = response.headers.get('content-length') if total_length is None: f.write(response.content) else: dl = 0 total_length = int(total_length) for data in response.iter_content(chunk_size=4096): dl += len(data) f.write(data) The problem is that for some images which are > 500MB the process takes quite some time and there are several issues, like if the user closes the app, or clicks away then the process stops. How can I make it in such a way so the user visits that page and clicks that button and the download process begins on the background without binding the user to stay to that page. Also maybe creating another endpoint which could update the user about the … -
Django jquery sortable save in database
I'm new in django and javascript and I have an issue that I can't find a solution . I'm trying to save in my database the position of a sortable with jquery . The model is call : Reflexion Model class Reflexion(models.Model): name = models.CharField(max_length=100) content = RichTextUploadingField(null=True ,blank=True) position = models.IntegerField(default=1) project = models.ForeignKey('project.Project', on_delete=models.CASCADE, null=True) class Meta: ordering = ['position'] def __str__(self): return self.name **The url ** path('<slug:pslug>/reflexion/', views.reflexion_list, name='reflexion_list'), path('reflexion/<int:pk>/', views.sort, name='sort'), Page : Reflexion_list - HTML , the draggable item <div class="block draggable-item" data-pk="{{ reflexion.id }}"> </div> Same page , jquery <script type="text/javascript" charset="utf-8" > $(document).ready(function() { $(".draggable-column").sortable({ update: function(event, ui) { window.CSRF_TOKEN = "{{ csrf_token }}"; var serial = $('.draggable-column').sortable('serialize'); $.ajax({ url: "reflexion/"+ $(this).data('pk'), type: "post", data: {csrfmiddlewaretoken: window.CSRF_TOKEN , serial } }); }, }).disableSelection(); }); </script> The view for sorting @csrf_exempt def sort(request, pk): for index, pk in enumerate(request.POST.getlist('reflexion[]')): reflexion= get_object_or_404(Reflexion, pk=pk) reflexion.order = index reflexion.save() return HttpResponse('') What did a do wrong ? I think is the link with my url in the script but I don't know what to do , please help me -
forex_python.converter CurrencyRates Failed to establish a new connection: [Errno 11001] getaddrinfo failed
I use forex python CurrencyRates in many of my project, but now it doesn't work, none of them. Is there any problem with my code or are the server down? or what happend? Here is my Code: from forex_python.converter import CurrencyRates c = CurrencyRates() usd = c.get_rate('EUR', 'USD') And the error: Traceback (most recent call last): File "D:\MeineDaten\Programmieren\Python\Projekte\Flask\ProjectX\main.py", line 2, in <module> from files.currency import currency File "D:\MeineDaten\Programmieren\Python\Projekte\Flask\ProjectX\files\currency.py", line 7, in <module> usd = c.get_rate('EUR', 'USD') File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\forex_python\converter.py", line 66, in get_rate response = requests.get(source_url, params=payload) File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\requests\api.py", line 76, in get return request('get', url, params=params, **kwargs) File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\requests\api.py", line 61, in request return session.request(method=method, url=url, **kwargs) File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\requests\sessions.py", line 542, in request resp = self.send(prep, **send_kwargs) File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\requests\sessions.py", line 655, in send r = adapter.send(request, **kwargs) File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\requests\adapters.py", line 516, in send raise ConnectionError(e, request=request) requests.exceptions.ConnectionError: HTTPSConnectionPool(host='api.ratesapi.io', port=443): Max retries exceeded with url: /api/latest?base=EUR&symbols=USD&rtype=fpy (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x000001F0C1D056A0>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed')) -
How can I solve the issue: No module named 'simple_history'
I have my application and I would like to track the historical models for each modification in Django. I have followed the instruction in this link: https://django-simple-history.readthedocs.io/en/latest/quick_start.html#install However, I am getting the error ModuleNotFoundError: No module named 'simple_history' I uninstalled the package and reinstalled it but still getting the same error when I run the command python manage.py makemigrations. Here is my model.py import uuid from django.db import models from django.contrib.auth.models import User # from django import forms from django.forms.widgets import RadioSelect from ckeditor.fields import RichTextField from django.utils.translation import ugettext_lazy as _ from django.urls import reverse from random import randint from simple_history.models import HistoricalRecords class CourrierArrive(models.Model): category_choice = ( ('Entrant exterieur','Entrant exterieur'), ('Entrant locale ','Entrant locale'), ('Entrant locale interieur','Entrant locale interieur'), ) statut = ( ('Prioritaire','Prioritaire'), ('Rappel prévu','Rappel prévu'), ('Pour affectation','Pour affectation'), ('Pour signature','Pour signature'), # ('Envoyer','Envoyé'), ('Annulé','Annulé'), ('A imprimer','A imprimer'), ('A archiver','A archiver'), ('A rappeler','A rappeler'), ('A Encours de validation','Encours de validation'), ('Attente','En attente'), ('Rejecte','Rejeté'), ('Terminé','Terminé'), ('A ranger','A ranger'), ('A enregistrer','A enregistrer'), ('Avis favorable','Avis favorable'), ('Avis défavorable','Avis défavorable'), ('Pour facturation','Avis facturation'), ('Pour de traitement','Encours de traitement'), ) nature_courrier = ( ('Lettre avec A/R', 'Lettre avec A/R'), ('Lettre simple','Lettre simple'), ('Lettre remise en main propre','Lettre remise en main propre'), ('Facture','Facture'), … -
Why my url in "not matching any url" when it is? I have no idea how to fix it, am I doing something wrong?
Im not gonna lie, this doesnt make any sense to me, why is this trying to access 'post-details' instead of 'create-post' and how do I fix it? Thank you in advance error: NoReverseMatch at /create/ Reverse for 'post-details' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P[-a-zA-Z0-9_]+)/post/$'] Request Method: GET Request URL: http://127.0.0.1:8000/create/ Django Version: 3.2.2 Exception Type: NoReverseMatch Exception Value: Reverse for 'post-details' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P[-a-zA-Z0-9_]+)/post/$'] Post create view: class PostCreate(CreateView): model = Post form_class = PostCreateForm template_name = 'post/post_create.html' context_object_name = 'form' def get_success_url(self): return reverse('post:home') def form_valid(self, form): form.instance.author = self.request.user.profile return super().form_valid(form) My urls: from django.urls import path, include from . import views app_name = 'post' urlpatterns = [ path('', views.PostList.as_view(), name='home'), path('<slug:slug>/post/', views.PostDetails.as_view(), name='post-details'), path('search/', views.search, name='search'), path('comment-delete/<pk>/', views.CommentDelete.as_view(), name='comment-delete'), path('comment-update/<pk>/', views.CommentUpdate.as_view(), name='comment-update'), path('tag/<str:name>/', views.PostTagList.as_view(), name='tag-posts'), path('create/', views.PostCreate.as_view(), name='create-post') ] post_create.html file from my PostCreate view: {% extends 'base.html' %} {% block content %} <div class="container mt-5 mb-5"> <form action="" class="commenting-form" method="post" enctype="multipart/form-data"> <div class="row"> <div class="form-group col-md-12"> {% csrf_token %} {{ form.tags }} <div class="form-group col-md-12"> <button type="submit" class="btn btn-secondary mt-2">Edit comment</button> </div> </div> </div> <div class="row"> <div class="form-group col-md-12"> {% csrf_token %} {{ form.body }} {{ form.picture … -
Select2 multi-select items showing outside the input field, overlapping with other fields
I'm using Select2 multi select in a Django app, and I'm having an issue where the selected items are being drawn outside the input field. Any thoughts on how the css has been mucked up to cause this? image showing multi-select items outside the field Thanks, Glenn -
Handle/fix django.core.exceptions.SuspiciousFileOperation in unit testing Django (nosetests)
I want to write a test for a Managment command that reads a file and does something. Everything works as expected. And for clean organization of my test files (in this case I check whether the read CSV file has certain validations), I want to place the test CSV file under my_project/my_app/tests/files/test_me.csv. And, when I run the test, Django is throwing this error django.core.exceptions.SuspiciousFileOperation: The joined path (/code/my_project/my_app/test/files/test_me.csv) is located outside of the base path component (/code/media). Here is my test code, class CommandTestCase(TestCase): def test_command_load_client(self): """Happy path for load client from a CSV File""" call_command('my_command_that_does_some_csv_checks', os.path.join(BASE_DIR, "my_app/tests/files/test_me.csv"),) # self.assertEqual(some_assertions, 1) If I put this file under /code/media however, this error does not occur. But I do not want to store it under /code/media. How to solve this problem? Note: I come from a Rails background. -
Renaming a field on a Django queryset with group by
I'm counting the users by month that have been registered this year. from rest_framework.response import Response from django.db.models.functions import TruncMonth from django.db.models import Count from django.db.models import F return Response(User.objects .filter(date_joined__year=timezone.now().year) .annotate(month=TruncMonth('date_joined')) .values('month') .annotate(qtd=Count('id')) .values('date_joined__month', 'qtd') The result of this queryset it's been returned as: [{"date_joined__month": 1,"qtd": 5},{"date_joined__month": 2,"qtd": 35}] I want to change the name of the field "date_joined__month" to "month_id" and keep the counting and group by logic. I already tried to add the following approaches, but they both returned the full date format instead return only the month id: "month_id": "2021-01-07T15:26:53.080136Z" .annotate(month_id=F('date_joined__month')) .values('qtd', 'month_id')) or .values('qtd', month_id=F('date_joined__month'))) -
How can I get the value for type "textinput" as manytomanyfield data in django's modelform?
goal : The data on the board has a tag. To update and save the tag,'forms.py' must first fetch the data using modelform. Problem : I was trying to get data as dict type using'value_from_datadict'. The modelform class couldn't access it. And'print message' was put in'value_from_datadict' to confirm, but it was not displayed. # forms.py class ManyToManyInput(forms.TextInput): def value_from_datadict(self, data, files, name): print("value_from_datadict inside") value = data.get(name) if value: return value.split(",") class BoardUpdateForm(forms.ModelForm): class Meta: model = Board fields = ["title", "contents", "tags"] # fields = "__all__" labels = { "title": ("title"), "contents": ("contents"), "tags": ("tag"), } widgets = { "contents": forms.Textarea(attrs={"cols": 80, "rows": 20}), "tags": ManyToManyInput().value_from_datadict(), } help_texts = {} error_messages = { "title": { "required": ("Please enter the title."), }, "contents": { "required": ("Please enter your content."), }, } In order to use the update form, I sent the data using the "Instance" option like the following source code. # view.py def board_update(request, pk): try: board = Board.objects.get(pk=pk) except Board.DoesNotExist: raise Http404("There are no board data") if request.method == "POST": form = BoardUpdateForm(request.POST) if form.is_valid(): print("inside is_valid") user_id = request.session.get("user") usert = Usert.objects.get(pk=user_id) tags = form.cleaned_data["tags"].split(",") board.title = form.cleaned_data["title"] board.contents = form.cleaned_data["contents"] board.writer = usert board.save() print("board :", … -
Confusing field accessing on m2m field in a query set
I have a django project with several models. Two of this models are: class Attack(models.Model): spell = models.ForeignKey("Spell", models.CASCADE, null=True) attacker = models.ForeignKey("Ent", models.CASCADE, related_name='attacker') defender = models.ForeignKey("Ent", models.CASCADE, related_name='defender') defender_pts_before = models.IntegerField(default=0, blank=False, null=False) damage_caused = models.IntegerField(default=0, blank=False, null=False) and class Ent(models.Model): name = models.CharField(max_length=50, blank=False, null=False) raze = models.CharField(max_length=50, blank=False, null=False) damage = models.CharField(max_length=50, blank=False, null=False) weakness = models.CharField(max_length=50, blank=False, null=False) health = models.FloatField(default=100, blank=False, null=False) attacks = models.ManyToManyField('self', through=Attack, symmetrical=False, related_name='attacked_from') battles = models.ManyToManyField(Battle, through=BattleParticipant, related_name='battles_part') As you can see the Ent model has a m2m field to itself through the Attack model. This is for representing the attacks between ents. The attack model stores all the damage the attacker caused to the defender in the damage_caused field (which is calculated when the attack is saved). I need to know for each ent the total damage it has caused in all the attacks, so I built the following query: Ent.objects.all().annotate(dmg=Sum('attacks__attacker__damage_caused')) but this doesn't seems to work. It only seems to work the right way with this query: Ent.objects.all().annotate(dmg=Sum('attacks__defender__damage_caused')) Tests I've created some entries to check the query (a single attack from one ent to another) In [106]: e1, e2 = Ent.objects.all().annotate(dmg=Sum('attacks__attacker__damage_caused'))[:2] In [107]: e1, e2 Out[107]: (<Ent: … -
DJANGO - How to store Model data in another model by modifying the __init__ and save() methods, with a Test Driven development approach?
So, lets assume I have two models, my main model where I have the data that goes to my endpoint, and a second model that I'm using to store the changes made to a field of the main model. They're very simple, like this: Main Model: M class MyModel(TimeStampedModel, models.Model): """A simple model""" field_1 = models.CharField(max_length=255, null=True, blank=True) field_2 = models.CharField(max_length=255, null=True, blank=True) choice_field = models.CharField( max_length=32, choices=ChoiceModel.choices, default=None, null=True, blank=False ) And the storing Model: Class MyModelHistory(models.Model): choice_field_from = models.CharField(max_length=32, null=True, blank=False) choice_field_to = models.CharField(max_length=32, null=True, blank=False) changed_at = models.DateTimeField() Now, there are various ways to connect these two. To make it easier, I'm only intereseted in tracking the changes made to choice_field. We could do it with signals or by modifying the __init__ and save methods of MyModel. For my application, I have to do with the latter, so here's what I've got so far: def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) #import pdb; pdb.set_trace() if self.pk is None: self._old_choice = None else: self._old_choice = self.choice_field def save(self, *args, **kwargs): super().save(*args, **kwargs) if self._old_choice != self.choice_field: MyModelHistory.objects.create( choice_field_from=self._old_choice, choice_field_to=self.choice_field, changed_at=timezone.now(), ) I'm making the tests to make sure this approach works in all possible scenarios. For example, when you … -
How to estabilish ContentType relation in Django for Laravel Polymorphic related data?
I have a database that was created and working for the Laravel application, it contains a table with shared data for multiple models using "Laravel Polymorphic Relationships" For example, this is Comment model that contains comments for the Product, Post, Seller. id commentable_type commentable_id Comment 1 App\Product 1 Comment text 2 App\Product 2 Comment text 3 App\Seller 1 Comment text I need to use this table in the Django application, I tried to create relation using ContentType Framework but no success because it's requires ContentType (int) relation to determine the model, but in the database, I have string values for _type. Any suggestions on how to deal with it? -
Multiple values using GET method in my template? with django
I am trying to send info using GET method and the django paginator. I am using buttons to send the request and on my views display the corresponding list, that works fine. However, the problem is when I change page to page=2 or whatever, the url is replaced. For example: you click the button A and the url should appear webpa.com/expedient?letter=A and when you clic next page, it is replaced webpa.com/expedient?page=2 instead of webpa.com/expedient?page=2&letter=A My template is as follows: <form action="expedient" method="GET"> <button type="submit" name="letter" value="A">A</button> <button type="submit" name="letter" value="B">B</button> <button type="submit" name="letter" value="C">C</button> <button type="submit" name="letter" value="G">G</button> <button type="submit" name="letter" value="L">L</button> <button type="submit" name="letter" value="N">N</button> </form> and the paginator also in the same template is: {% if is_paginated %} <nav aria-label="Paginador de portafolio"> <ul class="pagination"> <li class="page-item"><a class="page-link" {% if page_obj.has_previous %} href="?page={{ page_obj.previous_page_number }}"{% else %} href="#" {% endif %}>Anterior</a></li> {% for num in page_obj.paginator.page_range %} <li class="page-item"><a class="page-link" href="?page={{ num }}">{{num}}</a></li> {% endfor %} <li class="page-item"><a class="page-link" {% if page_obj.has_next %} href="?page={{ page_obj.next_page_number }}" {% else %} href="#" {% endif %}>Siguiente</a></li> </ul> </nav> {% endif %} How can I send the value of the letter in the form and the page number? -
Capturing Images from Webcam Using OpenCV , Django and show the captured image in HTML Page
I want to capture the image using OpenCV in Django web application and show captured image in HTML page and needed to compare the captured image with the previously detected images. can anyone give me idea how to code ? -
how can i use try and except while getting model objects?
i am new to python and django, i have to use a try and except block with the following code, as i am trying to get a model class object but in case if database is empty so for that i need to use try and except. if(txStatus=='SUCCESS'): order=Order.objects.get(id=id) #NEED TRY ACCEPT BLOCK FOR THIS URL = payment_collection_webhook_url request_data ={} json_data = json.dumps(request_data) requests.post(url = URL, data = json_data) return Response(status=status.HTTP_200_OK) -
How can I completely convert my django application to a andriod mobile application
How to convert my django web application to a complete andriod mobile application to use in the andriod platforms -
IntegrityError: FOREIGN KEY constraint failed in django
I have a django view that causes FOREIGN KEY constraint failed. This is coming from a related question def return_book(request,pk): books = Books.objects.filter(school = request.user.school).get(id = pk) book = Issue.objects.get(book_id_id=pk,book_id__school_id = request.user.school.id) user = CustomUser.objects.get(id=request.user.id) Return.objects.create(borrowed_item_id=book.id,returner=user) Books.Addbook(books) Issue.objects.get(book_id_id=pk).delete() return redirect("view_books") The erro is returned at Issue.objects.get(book_id_id=pk).delete() I don't know the exact cause of this error. Could somebody explain to me what's going on hat causes the error> The Traceback is below. Traceback (most recent call last): File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "D:\Python\Django\test projects\library manage\lib_system\Library-System\libman\views.py", line 209, in return_book Issue.objects.get(book_id_id=pk).delete()#Borrower_id is also required in the filter File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\base.py", line 947, in delete return collector.delete() File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\deletion.py", line 396, in delete count = sql.DeleteQuery(model).delete_batch([instance.pk], self.using) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\sql\subqueries.py", line 43, in delete_batch num_deleted += self.do_query(self.get_meta().db_table, self.where, using=using) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\sql\subqueries.py", line 23, in do_query cursor = self.get_compiler(using).execute_sql(CURSOR) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\sql\compiler.py", line 1156, in execute_sql cursor.execute(sql, params) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", line 98, in execute return super().execute(sql, params) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", … -
Issue in Login with Django sqlite3 database
enter image description here **I want to login with the email that existed in the table named "user" in the sqlite3 database. Whenever I am trying to find matching the emails as given photo. The "for" loop checking only the 1st email from the table of the database. What should I do to check all the emails existed there and then login when both are matched. Please help me to solve it. ** -
i tried to deploy my Django app in Heroku
I used this command to do it but I have an error : pip install python-git pip install gunicorn pip install django-heroku pip freeze > requirements.txt npm install -g heroku heroku login heroku create dmracademy git init git status git add . git commit -m "first version uploaded" heroku git:remote -a dmracademy git push heroku master after I write git push heroku master i have this error: enter image description here -
Unable to login to django admin after a customized Models
I have successfully created several superusers using python manage.py createsuperuser but I am unable to login in the admin despite providing the right credentials. Here is my models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.contrib.auth import get_user_model from django.utils import timezone class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, full_name, phone, password, next_of_kin_name, next_of_kin_number, **extra_fields): values = [email, full_name, phone, next_of_kin_name, next_of_kin_number] field_value_map = dict(zip(self.model.REQUIRED_FIELDS, values)) for field_name, value in field_value_map.items(): if not value: raise ValueError('The {} value must be set'.format(field_name)) email = self.normalize_email(email) user = self.model( email=email, full_name=full_name, phone=phone, next_of_kin_name=next_of_kin_name, next_of_kin_number= next_of_kin_number, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, full_name, phone, next_of_kin_number, next_of_kin_name, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, full_name, phone, next_of_kin_name, next_of_kin_number, password, **extra_fields) def create_superuser(self, email, full_name, phone, next_of_kin_number, next_of_kin_name, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, full_name, phone, next_of_kin_name, next_of_kin_number, password, **extra_fields) class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) full_name = models.CharField(max_length=150) phone = models.CharField(max_length=11) next_of_kin_number= models.CharField(max_length=11) next_of_kin_name = models.CharField(max_length=150) #date_of_birth = models.DateField(blank=True, null=True) #picture = models.ImageField(blank=True, null=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True,) …