Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Coverage wrongly reports for Django rest framework
I tried to create simple api with Django Rest Framework and use structure like in book Two Scopes of Django 3.x. I tried to create simple test and coverage reports almost 100% coverage on all python sources in my app. Even if I completely remove that test. I tried pytest, nose, and anything what I found here and still same results. My project structure is following: . ├── api │ ├── apps.py │ ├── __init__.py │ ├── urls.py │ └── v1 │ ├── admin.py │ ├── __init__.py │ ├── migrations │ ├── models.py │ ├── serializers.py │ ├── tests │ │ ├── __init__.py │ │ ├── test_api.py │ │ ├── test_models.py │ │ ├── test_serializers.py │ │ └── test_views.py │ ├── urls.py │ └── views.py ├── config │ ├── asgi.py │ ├── __init__.py │ ├── settings │ │ ├── base.py │ │ ├── dev.py │ │ ├── __init__.py │ │ ├── production.py │ │ └── test.py │ ├── urls.py │ └── wsgi.py ├── manage.py ├── README.md ├── requirements │ ├── base.txt │ ├── dev.txt │ ├── production.txt │ └── test.txt └── venv I also tried to modify manage.py with following changes: is_testing = 'test' in sys.argv if is_testing: import coverage … -
Django ServiceWorker not in scope
Thanks for your time. i got a Django web app and am trying to set a PWA for it. I've been seting the files (sw.js, manifest.json, install_sw.html) through urls with TemplateView class: urls.py urlpatterns = [ path('admin/', admin.site.urls), path('config/', include('config.urls')), path('products/', include('products.urls')), path('cart/', include('cart.urls')), path('accounts/', include('allauth.urls')), path('home/', home_view, name='home'), path('sw.js/', (TemplateView.as_view(template_name="admin/sw.js", content_type='application/javascript', )), name='sw.js'), path('manifest.json/', (TemplateView.as_view(template_name="admin/manifest.json", content_type='application/json', )), name='manifestjson'), path('install_sw/', (TemplateView.as_view(template_name="admin/install_sw.html", content_type='text/html', )), name='install_sw'), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) although i keep getting this error: no matching service worker detected. You may need to reload the page, or check that the scope of the service worker for the current page encloses the scope and start URL from the manifest and even with the serviceworker being found and his code running, i don't think its getting installed. Lighthouse told me so, and when i leave the page the service worker ain't in the list anymore, so im not able to run it offline because the cache gets deleted. files under: sw.js: { const cacheName = 'cache-v1'; const resourcesToPrecache = [ "{% url 'sw.js' %}", "{% url 'home' %}", "{% url 'install_sw' %}" ]; self.addEventListener('install', function (event) { console.log('sw install event!'); event.waitUntil( caches.open(cacheName) .then(function (cache) { console.log('cache added') … -
TemplateSyntaxError at /: Cannot Parse the remainder
I am trying to update my homepage whenever a new "article" is added, however it is giving me this error whenever I try to update the page using my updateHomepage view it doesn't work and I get the error TemplateSyntaxError at / Could not parse the remainder: ' 'update_homepage'' from 'url 'update_homepage'' I am very new to django so any help with this would be amazing. My Views.py def index(request): articles = Article.objects.all() context = {'articles': articles} return render(request, 'able/homepage.html', context) def updateHomepage(request, pk): form = EditorForm(instance=task) context = {'form': form} article = Editor.objects.get(id=pk) return render(request, 'able/update_homepage.html', context) if request.method == 'POST': form = EditorForm(request.POST, instance=task) if form.is_valid(): form.save() return redirect('/') def editorview(request): editor = EditorForm context = {'editor': editor} return render(request, 'able/editor.html', context) if request.method == 'POST': form = EditorForm(request.POST) if form.is_valid(): form.save() return redirect('/') urls.py urlpatterns = [ path('', views.index, name='homepage'), path('editor/', views.editorview), path('update_homepage/<str:pk>/', views.updateHomepage, name='update_homepage') ] homepage.html <h1>My Blog</h1> {% for article in articles %} <div class="article"> {% csrf_token %} <h1>{{ article.title }}</h1> <h3>{{ article.text }}</h3> </div> {% endfor %} <a href="{{ url 'update_homepage'}}">Update</a> update_homepage.html <h3>Update Homepage</h3> <form action="" method="POST"> {% csrf_token %} {{form}} <input type="submit"> </form> -
Render Django @property method in html template
I am relatively new to django. I am trying to render my @property method inside my django template. I am taking the difference between two dads to determine wether or not this object is suitable to be issued out or must recalibrated. I get an issue: 'int' object is not callable My model: class Tools_Calibrated(models.Model): description = models.CharField(max_length=50, blank=True, null=True) serial_number = models.CharField(max_length=50, blank=True, null=True) part_number = models.CharField(max_length=50, blank=True, null=True) recieved = models.DateTimeField(auto_now_add=False, auto_now=True) calibrated = models.BooleanField(default='True', blank=True, null=True) calibrated_date = models.DateTimeField( auto_now_add=False, blank=True, null=True) expiry_date = models.DateTimeField( auto_now_add=False, blank=True, null=True) cert_no = models.CharField(max_length=50, blank=True, null=True) range_no = models.CharField(max_length=50, blank=True, null=True) issued = models.BooleanField(default='False', blank=True, null=True) workorder_no = models.ForeignKey( WorkOrders, null=True, blank=True, on_delete=models.SET_NULL) def __str__(self): return self.description @property def timecalculated(self): exp = self.expiry_date cali = self.calibrated_date total = exp-cali return total.days() My Template: {% for tool in Cali %} <tr> <td style="text-align:center">{{tool.description}}</td> <td style="text-align:center">{{tool.part_number}}</td> <td style="text-align:center">{{tool.serial_number}}</td> <td style="text-align:center">{{tool.recieved|date:"M d, Y"}}</td> <td style="text-align:center">{{tool.calibrated_date|date:"M d, Y"}}</td> <td style="text-align:center">{{tool.expiry_date|date:"M d, Y"}}</td> <td>{{tool.timecalculated}}</td> <td style="text-align:center">{{tool.cert_no}}</td> <td style="text-align:center">{{tool.range_no}}</td> <td style="text-align:center"><a class="btn btn-sm btn-info sb-btn" href="{% url 'editCali' tool.id%}">Edit</a></td> <td style="text-align:center"><a class="btn btn-sm btn-danger sb-btn" onClick='return confirmDelete()' href="{% url 'deleteCali' tool.id %}">Delete</a></td> <td style="text-align:center"><a class="btn btn-sm btn-warning sb-btn" href="{% url 'change_calibration_status' tool.id%}" onClick='return confirmCali()'>Calibrate</a></td> <td style="text-align:center"><a … -
Best way to query Django ORM to sum items by category per year (for time series)
Assume we have the models: class Category(models.Model): description = models.CharField(...) # Ex: 'horror', 'classic', 'self-help', etc. class Book(models.Model): category = models.ForeignKey(Category, ...) written_date = models.DateField(...) I want to make a query that will eventually get me the total number of books per category per year! Like so: { '2019-01-01': { 'horror': 2, 'classic': 1}, '2020-01-01': { 'horror': 2, 'classic': 1, 'self-help': 4}, ... } I was only able to come up with the following query: Book.objects \ .annotate(year=TruncYear('written_date')) \ .values('year', 'category__description') \ .order_by('year') \ .annotate(total=Count('id')) However this only gets me { { "category__description": "Horror", "year": "2019-01-01", "total": 2 }, { "category__description": "Classic", "year": "2019-01-01", "total": 1 }, { "category__description": "Horror", "year": "2020-01-01", "total": 2 }, ... } Is there any way to do this via ORM? Or I have to do this by manipulating the result directly? Thanks! -
Should small specific views be implemented with Function Based views or CBVs?
I'm developing an app in Django and would like to know what is the correct way to implement some small views that need to implement some specific function. I'm still a beginner and I've been using CBVs from the start but I'm not sure if I should use FBVs for this. I now need to implement some specific functions when integrating Stripe, for example, to reactive a canceled subscription or to upgrade a subscription and was wondering if I should use FBVs for this? If not, should I for example use the POST of class SubscriptionView(APIView): def post(self, request): # Make a new subscription... that I use to create a subscription and just check if the user is trying to reactive/upgrade with a parameter or something like that? -
Django: Making sure a complex object is accessible throughout multiple view calls
for a project, I am trying to create a web-app that, among other things, allows training of machine learning agents using python libraries such as Dedupe or TensorFlow. In cases such as Dedupe, I need to provide an interface for active learning, which I currently realize through jquery based ajax calls to a view that takes and sends the necessary training data. The problem is that I need this agent object to stay alive throughout multiple view calls and be accessible by each individual call. I have tried realizing this via the built-in cache system using Memcached, but the serialization does not seem to keep all the info intact, and while I am technically able to restore the object from the cache, this appears to break the training algorithm. Essentially, I want to keep the object alive within the application itself (rather than an external memory store) and be able to access it from another view, but I am at a bit of a loss of how to realize this. If someone knows the proper technique to achieve this, I would be very grateful. Thanks in advance! -
How to serialize different fields in different depths from the same model?
I'm trying to send a JSON to and some fields need to be in different depths, like this: "amount": 21000, "card_number": "4111111111111111", "card_cvv": "123", "card_expiration_date": "0922", "card_holder_name": "Morpheus Fishburne", "customer": { "external_id": "#3311", "name": "Morpheus Fishburne", "type": "individual", "country": "br", "email": "mopheus@nabucodonozor.com", "documents": [ { "type": "cpf", "number": "30621143049" } All the nested fields in this example are from the same model and same form, and I tried this in order to serialize it: from rest_framework import serializers from apps.booking.models import Booking class DocumentsSerializer(serializers.ModelSerializer): class Meta: model = Booking fields = ( 'document_type', 'tax_number', ) class CustomerSerializer(serializers.ModelSerializer): documents = DocumentsSerializer(many=True) class Meta: model = Booking fields = ( 'client_name', 'client_type', 'country', 'email', 'documents', ) class BookingSerializer(serializers.ModelSerializer): customer = CustomerSerializer(many=True) class Meta: model = Booking fields = ( 'card_hash', 'payment_choice', 'customer' ) But it returns this error to me: Got AttributeError when attempting to get a value for field customer on serializer BookingSerializer. The serializer field might be named incorrectly and not match any attribute or key on the BookingScheduleFrontOfficeForm instance. Original exception text was: 'BookingScheduleFrontOfficeForm' object has no attribute 'customer'. This is the part of the views.py related: data = json.loads(request.session[guid]) data.update(request.POST.dict()) booking_form = self._get_form(activity, data) context = dict() if … -
Proper practice for URL structure with Django
I've already partially solved an issue I was struggling with but I would like some clarity on if this is the right way to do it in the first place. Ultimately, I wanted to my URL's to follow something like this: www.whatever.com/company/{company_id}/person/{patient_id} (i.e. whatever.com/company/4/patient/2) That's not actually perfect because what I really want is the name of the company and patient where the ID is, so www.whatever.com/company/ryan-corp/patient/jim-jones. I'll leave that for another day for now. What I ended up doing to get the result with the ID is this: my_project/urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', views.home), path('company/', include('scraper.urls', namespace="company")), ] my_app/urls.py app_name = "scraper" urlpatterns = [ path('', company), path('<int:pk>/', company_detail), path('<int:company>/patient/<int:pk>/', patient_detail), ] my_app/views.py def patient_detail(request, pk, company): patient = Patient.objects.get(id=pk) return render(request, 'scraper/patient_detail.html', {'patient':patient}) This doesn't feel like I am following a best practice and I feel like I literally guessed to get this working by reading the documentation found here: https://docs.djangoproject.com/en/3.1/topics/http/urls/ It esentially laid out how Django processes the URL's and I noticed that it basically grabs each part of the URL as kwargss. Which is why I passed the company variable in the patient_detail function in views. Then I took a guess and added <int:company> … -
Hide Fields with Django and GenericViews
I'm using Django with Generic views to create my api. From the image below, I would like to hide the field status process and only show the topic field. This is the code I'm using class ListCreateTopic(generics.ListCreateAPIView): queryset = models.Topics.objects.order_by('-time_stamp')[:5] serializer_class = serializers.TopicSerializer -
How to write dynamic (Django) URLs for serving images using Whitenoise on Heroku?
I followed this answer here and read the tips here about serving static images. But I'm baffled: The official Whitenoise docs said to write the URLs this way: <img src="{% static "images/hi.jpg" %}" alt="Hi!" /> And NOT this way: <!-- DON'T WRITE THIS --> <img src="/static/images/hi.jpg" alt="Hi!" /> But if I were to use a dynamic URL, such as src="{{recipe.image.url}}", how do I do it? -
Django ModelChoiceField with Dynamic Query Won't Validate
I'm trying to get this code to validate and it just keeps staying broken. I could use some help because not everything I've seen seems to match what I'm doing exactly. Model: class CardPreconDecklists(models.Model): deck_name = models.OneToOneField('CardPreconDecks', models.DO_NOTHING, db_column='deck_name', primary_key=True) card = models.ForeignKey(CardData, models.DO_NOTHING) class Meta: managed = False db_table = 'card_precon_decklists' unique_together = (('deck_name', 'card'),) app_label = 'edh_escalation' Form: class ChooseDecks(forms.ModelForm): class Meta: model = CardPreconDecks fields = ('deck_name',) deck_name = forms.ModelChoiceField( label='Deck Name', queryset= CardPreconDecks.objects.none()) def __init__(self, *args, **kwargs): qs = CardPreconDecks.objects.all().values_list('deck_name', flat=True).order_by('deck_name') super(ChooseDecks, self).__init__(*args, **kwargs) self.fields['deck_name'].queryset = qs View: @login_required() def ChooseDeck(request, game_id, player_id): # Add Validation to correct user access selectionform = ChooseDecks() if request.method == 'POST': form = ChooseDecks(request.POST) if form.is_valid(): cards = CardPreconDecklists.objects.filter(deck_name= form.cleaned_data.get('deck_name')) CardPool.objects.bulk_create([CardPool(player_id=player_id, card_id=card) for card in cards]) return redirect(reverse('ManageLeague', args=[game_id])) else: return HttpResponse('broke') context = {'form': selectionform, 'game_id': game_id, 'player_id': player_id} return render(request, "edh_escalation/ChooseDeck.html", context=context) -
Save a Value From an HTML Form in a Javascript File Without Page Refresh
So as the title describes I would like to essentially grab a value submitted in an HTML form and then save that to a Javascript file without resetting everything on the page. Also in case it's important I am using Django. I tried to use onsubmit to call a method in the Javascript file that would store the input elements value into a variable and then return false but that did not work. This is the code baseline I'm working on right now. <form onsubmit="return commandSubmission()"> <input class="play-button-style" type="hidden" id="send" value="Send" disabled="disabled"/> <input type="hidden" id="command" name="command" disabled="disabled"> </form> And the Javascript: function commandSubmission(){ //PREVENT HTML FORM SUBMIT return false; } -
How can I see my MySQL database in Django admin site?
I am developing a Django application and I have created a MySQL database (I am using Laragon to manage it) and connected it with the App. I am using the database for another Python script that inserts data in the database too. What I want it to see all the database data in my Django admin site, but for some reason, I can't manage to do it? Do I have to add the tables to the Django models? or what should I do? My settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'nlpwords', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': 3306, } } I am using that database that has some data in some of the tables, but when I enter localhost/admin in my Django app I can't manage to see all those tables. Help is much appreciated. -
How do I turn Json response into a dropdown option picker? [Django]
I am working with an API and there is a high likelihood that people will entre in wrong information, so what I can do is send their information to the API and it will give out its best guess of what they want and it gives out 10 packets of guesses, how do I turn that into like a dropdown box that people can pick from and when they click on an element it gives me some value at the backend. Think of it like google suggestions. Here is what I kinda want it to look like, in this example, if I entre in tata, it spits out these "suggestions" it might have and I am having trouble understanding what to do. -
i'm not able to understand why i have to restart the server to see the changes made by a Put request (django rest framework)
The put request is working, but if i want to see the post updated i have to restart the server. This is the view function: from rest_framework import status from rest_framework.response import Response from rest_framework.decorators import api_view from blog.models import Post from .serializers import PostSerializer from django.contrib.auth.models import User @api_view(['PUT']) def api_update_post_view(request, Slug): try: blog_post = Post.objects.get(slug=Slug) except Post.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) serializer = PostSerializer(blog_post, data=request.data, partial=True) data = {} if serializer.is_valid(): serializer.save() data['succes'] = 'update successful' return Response(data=data) return Response(serializer.errors, status.HTTP_400_BAD_REQUEST) -
I got 502 Bad Gateway after deploying django in aws. How to solve this?
502 Bad Gateway nginx/1.18.0 Is the problem with the port? if yes, how can i change the port then? I am following exactly this tutorial https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html#python-django-setup-venv -
django Mptt counter le nombre des produts classés dans une categorie données
j'ai les modeles suivants: class Extension(MPTTModel): STATUT = ( ('True', 'True'), ('False', 'False'), ) parent = TreeForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.CASCADE) title = models.CharField(max_length=100) slug = models.SlugField() description = models.CharField(max_length=255) STATUT = models.CharField(max_length=100, choices=STATUT) create_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title class MPTTMeta: order_insertion_by = ['title'] def get_recursive_eglise_count(self): return Eglise.objects.filter(extension=self.get_descendants(include_self=True)).count def related_eglise_count(self, instance): return instance.eglise_count class Actualite(models.Model): title = models.CharField(max_length=255) content = RichTextUploadingField() status = models.BooleanField() keywords = models.CharField(max_length=255) lieu = models.TextField(max_length=255) extension = models.ForeignKey(Extension, on_delete=models.CASCADE) image = models.ImageField(blank=False, upload_to='images/', null=False) slug = models.SlugField(null=False, unique=True) tags = TaggableManager() create_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title je voudrais afficher la liste de toutes les extensions et le nombre d'actualités pour chaque extension enfant comme ceci RDC kinshasa (8) -Goma (12) comment résoudre ce problème svp? -
console_script not working in editable mode and giving ModuleNotFoundError
I am building a wheel package for my project and using setuptools for the same, my project tree structure is as follows: Note : I'm using a pyenv local based virtualenvironment named demo2 with python 3.7.5 $tree -L 3 . ├── Makefile ├── README.md ├── feedback_report.csv ├── pyproject.toml ├── setup.py ├── src │ ├── __init__.py │ └── mypkg │ ├── QuestionGeneration │ ├── README.md │ ├── api │ ├── data │ ├── fitb │ ├── login │ ├── manage.py │ ├── poetry.lock │ ├── pyproject.toml │ ├── requirements.txt │ ├── static │ └── templates ├── test_sample.py ├── tests │ └── context.py ├── tox.ini ├── zero1.sh └── zero_out.sh and my setup.py file is as follows: from setuptools import setup setup( name='fitbapp', version='1.0', packages=['mypkg'], package_dir = {'mypkg': 'src/mypkg'}, description='FITB app', long_description='App to generate fill in the blanks type questions from sentences', classifiers=['Programming Language :: Python'], py_modules= ['manage'], #install_requires = [ 'docutils', 'numpy' ], package_data={'mypkg': ['fitb/*','api/*', 'api/migrations/*.py','static/*.css', 'templates/*.html', 'templates/registration/*.html', 'login/*', 'QuestionGeneration/*', 'fitb/migrations/*.py', 'templatetags/*.py', 'data/pickles/nb-predictor.pkl'] }, entry_points = { 'console_scripts' : ['manage-server=mypkg.manage:main'], } #data_files = [("/", ['static/static.css', 'src/templates/*.html', 'src/templates/registration/login.html'])] ) And my entry_point is specified as manage-server, when I execute the build command using the build package using - python -m build and install … -
Crispy Forms - Icon in Input Field
I read mainly here and here but fail to achieve the correct result. I want to place a fontawesome icon in the input field of my crispy form. My code so far: class ProductForm(ModelForm): class Meta: model = Product fields = ("name", "price") def __init__(self, *args, **kwargs): super(OrderForm, self).__init__(*args, **kwargs) field_symbol = mark_safe("""<i class="fas fa-exclamation-circle"></i>""") self.helper = FormHelper() self.helper.field_class = 'mb-2' self.helper.form_method = 'POST' self.helper.form_show_errors = False self.helper.layout = Layout(Field(AppendedText("name", field_symbol)), Field(AppendedText("price", field_symbol))) Looks like: Should look like: [1]: https://stackoverflow.com/questions/58956947/django-crispy-forms-with-bootstrap4-not-showing-selected-result-in-browse-file-f [2]: https://stackoverflow.com/questions/41221880/prepend-or-append-icon-in-field-of-django-crispy-forms [3]: https://i.stack.imgur.com/CBtRO.png -
Django UUID field throwing IIntegrityError at /admin/books/book/add/
import uuid from django.db import models from django.urls import reverse class Book(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False ) title = models.CharField(max_length=200) author = models.CharField(max_length=200) price = models.DecimalField(max_digits=6, decimal_places=2) def __str__(self): return self.title def get_absolute_url(self): return reverse('book_detail', args=[str(self.id)]) -
(Django) Moving Queryset data to a different model with a button press
I am trying to make a web app for IT staffing similar to a dating app like tinder in which a hiring manager can search a database of candidates and accept or decline a candidate and save it to their profile. I thought a good way to do this would be using a carousel to either accept or decline candidate information. Right now the accept and decline buttons just move the slides but I want the accept button to save whatever data is in the slide to a model set up specific to the user so they can view the candidates they have liked so far. Is this even possible to do? I'm having a hard time conceptualizing it. Any help would be appreciated I am still new to web development. Carousel Code in Template: <div class="row"> <!-- Carousel to toggle through Candidates --> <div id="candidateCarousel" class="carousel slide" data-bs-interval="false" data-bs-ride="false" data-bs-keyboard="false" data-bs-wrap="false" data-bs-touch= "false"> <!-- Carousel inner: what gets displayed inside the carousel --> <div class="carousel-inner"> <!--Display data on website with for loop--> {% for candidate in queryset %} <!-- Carousel item tag. If else statement to make first active --> {% if forloop.first %} <div class="carousel-item active"> {% else … -
Django ORM + async views + non-blocking IO
Is it fundamentally wrong to use an async view with thread_sensitive=False performing an Django ORM call? For instance: def call_to_a_3rd_party_API(): something = requests.post(...) return something @sync_to_async(thread_sensitive=False) def do_something_to_a_product(request, id): product = Product.objects.get(pk=id) result = call_to_a_3rd_party_API() product.some_value = result product.update() return HttpResponse(status=200) The goal here is that I am migrating some of my Django 2.2 views due to blocking IO behaviour (from calling 3rd party APIs) to Django 3.1 async views. In my tests, the only way I could turn the 3rd party API call in non-blocking is using thread_sensitive=False. Reading the docs (https://docs.djangoproject.com/en/3.1/topics/async/) it feels like we should never use thread_sensitive=False with Django ORM. So the alternative I guessed would be: @sync_to_async(thread_sensitive=False) def call_to_a_3rd_party_API(): something = requests.post(...) return something async def do_something_to_a_product(request, id): product = await sync_to_async(Product.objects.get, thread_sensitive=True)(Product, pk=id) result = await call_to_a_3rd_party_API() product.some_value = result await sync_to_async(product.save, thread_sensitive=True) return HttpResponse(status=200) It feels like this way I can turn the call_to_a_3rd_party_API() into a non-blocking function, while keeping all the Django ORM in the main thread. But the code feels a lot more complex. Could someone help me with this? Extra question: I have two projects, one of them using wsgi and the other asgi. Does it make a difference … -
Docker django runs server but browser doesn't show landing page
I have successfully build docker and the server runs without error but when I browse the website it doesn't show anything. Here are the configuration files I'm using: .env.dev DEBUG=1 SECRET_KEY=foo DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1] Dockerfile FROM python:3.9.1-slim-buster # set working directory RUN mkdir -p /usr/src/app WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install dependencies RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt # add app COPY . . docker-compose.yml version: '3.8' services: movies: build: ./app command: python core/manage.py runserver 0.0.0.0:8000 volumes: - ./app/:/usr/src/app/ ports: - 8009:8000 env_file: - ./app/.env.dev Any idea why it isn't browsing? -
TypeError: MyUser() got an unexpected keyword argument 'is_superuser - Django REST
I am using Django REST Framework for my REST API. I am creating a custom user model. Here is my code: from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager from django.contrib.auth.models import UserManager from django.db import models import time # Create your models here. class MyUserManager(BaseUserManager): def create_user(self, first_name, last_name, email, password, **kwargs): if(not email): raise ValueError("No Email Provided!") email = self.normalize_email(email) user = self.model(email, **kwargs) user.set_password(password) user.save() return user def create_superuser(self, first_name, last_name, email, password, **kwargs ): kwargs.setdefault('is_staff', True) kwargs.setdefault('is_superuser', True) kwargs.setdefault('is_active', True) if(kwargs.get('is_staff') is not True): raise ValueError("Super User must be a staff in order to be in!") if(kwargs.get('is_superuser') is not True): raise ValueError("User must be a SuperUser!") if(kwargs.get('is_active') is not True): raise ValueError("Super User must be active!") return self.create_user(first_name, last_name, email, password, **kwargs) class MyUser(AbstractBaseUser): first_name = models.CharField(max_length= 200, blank= False) last_name = models.CharField(max_length= 200, blank= False) email = models.EmailField(unique= True, blank= False) phone_number = models.IntegerField() company_name = models.CharField(max_length= 200, blank= False) date_joined = models.DateTimeField(auto_now= True) last_login = models.DateTimeField(auto_now= True, null= False) is_staff = models.BooleanField(default= False) is_active = models.BooleanField(default= True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name', 'phone_number', 'company_name'] objects = MyUserManager() Here is the Error that I am getting: File "C:\Program Files (x86)\Python38-32\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 189, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) File …