Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to validate OAuth2 State in Django?
I looked at the GitHub OAuth API and saw that one requirement to send to the endpoint is state. Sending it is trivial - but how do you validate that the state you sent is the same one you’re receiving? I thought of using browser caching but it seems like it’s for views of Django and improving performance. I thought of sending a CSRF token as the state but it seems it’s meant for forms you generate. In short, how do you validate state in Django? Is there a Pythonic way in Django to do so? -
Define Celery email backend in local
I'm using Celery as the first time and I would like to execute my Celery task on localhost. I have to get an email at the end of my task. I'm getting troubles with celery settings and email_backend. I'm using Maildev in localhost (port 1025). This is my settings.py file : # MAIL # ------------------------------------------------------------------------------ DEFAULT_FROM_EMAIL = 'noreply@test.eu' EMAIL_SENDER = DEFAULT_FROM_EMAIL EMAIL_HOST = 'localhost' EMAIL_PORT = 1025 EMAIL_USER = '' EMAIL_PASSWORD = '' # CELERY # ------------------------------------------------------------------------------ CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_IGNORE_RESULT = False CELERY_TASK_TRACK_STARTED = True # Add a one-minute timeout to all Celery tasks. CELERYD_TASK_SOFT_TIME_LIMIT = 60 But I don't know How I can configure Celery to send email to Maildev. The task is well executed, but I don't receive any email. I launched Celery like this : $celery -A main worker --loglevel=info -
Information from the template after redirection, Django - Python
I have a simple view that allows me to add comments in my Django template. if request.method == 'POST': review_form = ReviewForm(data=request.POST) if review_form.is_valid(): rating = review_form.cleaned_data['rating'] comment = review_form.cleaned_data['comment'] user_name = review_form.cleaned_data['user_name'] order_code = review_form.cleaned_data['order_code'] review = Review() review.masseurs = masseur review.rating = rating review.comment = comment review.user_name = user_name review.order_code = order_code review.pub_date = datetime.datetime.now() review.save() return HttpResponseRedirect(reverse('app:masseur_detail', args=(masseur.id,))) else: review_form = ReviewForm() After adding the comment, the user is redirected to the basic page. I would like to display a thank you and information here, the comment has been added. How can I create an element in my view that will check if a new comment has just been added (after redirection). I tried to use something like 'new_comment = review_form.save (commit = Waves)' but it does not work properly (or I am doing something wrong). Any help will be appreciated. -
Django Rest Framework - How to import image as JPEG and save it as base 64 using serializer?
Model: class Item(models.Model): class Meta: db_table = 't_item' item_name = models.CharField(max_length=200) image = models.ImageField(upload_to='item_images') created_at = models.DateTimeField(default=datetime.now, blank=True) updated_at = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.item_name Serializer: class ItemSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Item # Fields you want to be returned or posted fields = ('item_name', 'image', 'created_at', 'updated_at') In the web view form, I want to import an image in JPEG format, and when it is posted, I want it to be saved as Base 64 format in the location specified in 'upload_to'. Is this possible? -
Django form validation when editing existing Model with a FileField
I am new to Django and I have an issue with form validation when editing a Model that has a FileField. My model has two FileField's, one that is mandatory, one that is not: models.py class Entrega(models.Model): """ People's submissions """ tid = models.AutoField(_('Código de entrega'), primary_key=True) titulo = models.CharField(max_length=500) memoria = models.FileField(upload_to=user_upload_memoria_directory_path) anexos = models.FileField(null=True, blank=True, upload_to=user_upload_anexos_directory_path) The same view should be able to create new Entrega or edit existing one. urls.py urlpatterns = [ ... path('entregas/<int:pk>/edit/', views.edit_or_create_Entrega, name='edit_create_entrega'), path('entregas/new/', views.edit_or_create_Entrega, name='edit_create_entrega'), ... ] views.py @login_required def edit_or_create_Entrega(request, pk=None): """ Shows the form to create/edit Entrega's """ if request.method == "POST": # create form instance and populate it with data from the request form = EntregaForm(request.POST, request.FILES) if form.is_valid(): nueva_entrega = form.save() return HttpResponseRedirect(reverse('list_all_entregas')) else: return render(request, 'envio/base.html', {'avisos': _("Errors were found...")}) else: if not pk: # if a GET (or any other method) and no pk is provided, create a blank form form = EntregaForm() else: # if GET (or any other method) and pk is provided, we'll fill the form with # entrega, if it exists and it belongs to the user e = get_object_or_404(Entrega,pk=pk) if not e.matricula.persona.user==request.user: return render(request, 'envio/base.html', {'avisos': _("You cannot edit other users … -
how to use custom variables in header/footer wkhtmltopdf for django?
I'm trying to convert html files into pdf using django-wkhtmltopdf. But I'm unable to use custom variables with header and footer because I didn't find the exact synatax or correct implementation and also I'm not able to use cover page in wkhtmltopdf v 0.12.5 (patched qt) It throws an error unknown long argument --cover? *VIEWS.PY* from django.http import HttpResponse from django.views.generic import View from django.template.loader import get_template from django.template import Context import pdfkit class GeneratePdf(View): def get(self, request, *args, **kwargs): template = get_template("report.html") options = { 'page-size': 'A4', 'margin-top': '0.6in', 'margin-right': '0.00in', 'margin-bottom': '0.6in', 'margin-left': '0.00in', 'encoding': "UTF-8", 'no-outline': None, 'disable-smart-shrinking': False, 'cover': 'cover.html', 'header-html': 'header.html', 'footer-html': 'footer.html', 'header-spacing': 10, 'footer-spacing': 5, 'header-right': '[page]', } pdfkit.from_string(html, 'reports_demo.pdf', options=options) pdf = open("reports_demo.pdf") response = HttpResponse(pdf.read(), content_type='application/pdf') return response -
in django submit image chosen by javascript to the database
I am using django, and a system of multiple fields, for example the user can select between 5 images, they can select only 1, 2 or 5 for example, in the code I show below that is just the example and is running on the site link code but I wanted to know how I pass the selected images to the django database and most important how I look for them, so when the user enters your profile, only see the image he has selected, remembering that he can select more than one image at the same time. Same time. I'm having this difficulty and would appreciate any help html: <!-- Image Checkbox Bootstrap template for multiple image selection https://www.prepbootstrap.com/bootstrap-template/image-checkbox --> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css"> <div class="container"> <h3>Bootstrap image checkbox(multiple)</h3> <div class="col-xs-4 col-sm-3 col-md-2 nopad text-center"> <label class="image-checkbox"> <img class="img-responsive" src="https://dummyimage.com/600x400/000/fff" /> <input type="checkbox" name="image[]" value="" /> <i class="fa fa-check hidden"></i> </label> </div> <div class="col-xs-4 col-sm-3 col-md-2 nopad text-center"> <label class="image-checkbox"> <img class="img-responsive" src="https://dummyimage.com/600x400/000/fff" /> <input type="checkbox" name="image[]" value="" /> <i class="fa fa-check hidden"></i> </label> </div> <div class="col-xs-4 col-sm-3 col-md-2 nopad text-center"> <label class="image-checkbox"> <img class="img-responsive" src="https://dummyimage.com/600x400/000/fff" /> <input type="checkbox" name="image[]" value="" /> <i class="fa fa-check hidden"></i> </label> </div> <div class="col-xs-4 … -
Temporary failure in name resolution channel 2 django
I have implemented channel2 in my django project , after some time i start it i have received this error on my server , i have apache on ubuntu for my code. 2019-02-12 10:30:51,863 ERROR Exception inside application: [Errno -3] Temporary failure in name resolution File "/var/www/RPG/python/lib/python3.6/site-packages/channels/consumer.py", line 59, in _call_ [receive, self.channel_receive], self.dispatch File "/var/www/RPG/python/lib/python3.6/site-packages/channels/utils.py", line 59, in await_many_dispatch await task File "/var/www/RPG/python/lib/python3.6/site-packages/channels/utils.py", line 51, in await_many_dispatch result = task.result() File "/var/www/RPG/python/lib/python3.6/site-packages/channels_redis/core.py", line 429, in receive real_channel File "/var/www/RPG/python/lib/python3.6/site-packages/channels_redis/core.py", line 484, in receive_single index, channel_key, timeout=self.brpop_timeout File "/var/www/RPG/python/lib/python3.6/site-packages/channels_redis/core.py", line 324, in _brpop_with_clean async with self.connection(index) as connection: File "/var/www/RPG/python/lib/python3.6/site-packages/channels_redis/core.py", line 820, in _aenter_ self.conn = await self.pool.pop() File "/var/www/RPG/python/lib/python3.6/site-packages/channels_redis/core.py", line 70, in pop conns.append(await aioredis.create_redis(**self.host, loop=loop)) File "/var/www/RPG/python/lib/python3.6/site-packages/aioredis/commands/__init__.py", line 178, in create_redis loop=loop) File "/var/www/RPG/python/lib/python3.6/site-packages/aioredis/connection.py", line 108, in create_connection timeout, loop=loop) File "/usr/lib/python3.6/asyncio/tasks.py", line 339, in wait_for return (yield from fut) File "/var/www/RPG/python/lib/python3.6/site-packages/aioredis/stream.py", line 19, in open_connection lambda: protocol, host, port, **kwds) File "/usr/lib/python3.6/asyncio/base_events.py", line 739, in create_connection infos = f1.result() File "/usr/lib/python3.6/concurrent/futures/thread.py", line 56, in run result = self.fn(*self.args, **self.kwargs) File "/usr/lib/python3.6/socket.py", line 745, in getaddrinfo for res in _socket.getaddrinfo(host, port, family, type, proto, flags): [Errno -3] Temporary failure in name resolution -
Why is no data showing out from my database using two Choice Fields?
My project's purpose is to get data out of the database and only show it on the template. However, it is not showing anything. There are two Choice Fields that determine what data to retrieve from the database. One for topics and one for question type. This is the model.py that I am using: from django.db import models from home.choices import * # Create your models here. class Topic(models.Model): topic_name = models.IntegerField( choices = question_topic_name_choices, default = 1) def __str__(self): return '%s' % self.topic_name class Image (models.Model): image_file = models.ImageField() def __str__(self): return '%s' % self.image_file class Question(models.Model): question_type = models. IntegerField( choices = questions_type_choices, default = 1) question_topic = models.ForeignKey( 'Topic', on_delete=models.CASCADE, blank=True, null=True) question_description = models.TextField() question_answer = models.ForeignKey( 'Answer', on_delete=models.CASCADE, blank=True, null=True) question_image = models.ForeignKey( 'Image', on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return '%s' % self.question_type class Answer(models.Model): answer_description = models.TextField() answer_image = models.ForeignKey( 'Image', on_delete=models.CASCADE, blank=True, null=True) answer_topic = models.ForeignKey( 'Topic', on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return '%s' % self.answer_description This is the forms.py from django import forms from betterforms.multiform import MultiModelForm from .models import Topic, Image, Question, Answer from .choices import questions_type_choices, question_topic_name_choices class TopicForm(forms.ModelForm): topic_name = forms.ChoiceField( choices=question_topic_name_choices, widget = forms.Select( attrs = {'class': 'home-select-one'} … -
JsonResponse with related object fields Json Serialize Problem
I am creating api for the application. So my api structure looks like: {error : false, data : data} I have tried json.dumbs or serializer.serialize('json', queryset) and serializer.serialize('python', queryset) raw_data = Work.objects.select_related('employee_id').values('work_title', 'work_desc','employee_id_employee_name','employee_id__employee_photo') return HttpResponse(json.dumps(list(raw_data), cls=DjangoJSONEncoder), content_type='application/json', status=status.HTTP_200_OK) This works but unable to add error=False field. raw_data = serializers.serialize('python', Work.objects.all().values(raw_data = Work.objects.select_related('employee_id').values('work_title', 'work_desc','employee_id_employee_name','employee_id__employee_photo')) data = [d['fields'] for d in raw_data] res = {'error': False, 'data': data} return JsonResponse(res, status=status.HTTP_200_OK) This produce 'dict' object has no attribute '_meta' raw_data = serializers.serialize('python', Work.objects.select_related('employee_id').values_list('work_title', 'work_desc','employee_id_employee_name','employee_id__employee_photo') data = [d['fields'] for d in raw_data] res = {'error': True, 'data': data} return JsonResponse(res, status=status.HTTP_200_OK) And this one produce 'tuple' object has no attribute '_meta' -
How to post request for multiple strings in django rest framework?
I am writing a viewsets that takes in an array of string values from the user and validates a table based on the post request. I dont know how to take in an array in request.POST from the user and use the rest APIs in the Postman. As for instance: class newView(viewsets.ModelViewset): authentication_classes = (BasicAuthentication) serializer_class = NewSerializer def create(self,request,*args,**kwargs): stringslist = ??? # request.POST.???? # Work with stringslist Also, how to check this in Postman? -
ValueError: needs to have a value for field "id" before this many-to-many relationship can be used
I have created an eCommerce application of Digital products where I have created a ManyToMany relationship in my Profile model of the Product model. After I added the many-to-many field, in my Profile model it is obstructing me to create a new Profile and gives the following error message:- ValueError: "<Profile: surajkar>" needs to have a value for field "id" before this many-to-many relationship can be used. This are my models: class Profile(models.Model): date = models.DateTimeField(auto_now_add=True) name = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) subscribed_products = models.ManyToManyField(Product,related_name='products_subscribed',blank=True) class Product(models.Model): title = models.CharField(max_length=32) price = models.DecimalField(default=10000.00,max_digits=10,decimal_places=2) class OrderItem(models.Model): product = models.OneToOneField(Product, on_delete=models.SET_NULL, null=True) is_ordered = models.BooleanField(default=False) date_added = models.DateTimeField(auto_now=True) date_ordered = models.DateTimeField(null=True) def __str__(self): return self.product.title class Order(models.Model): ref_code = models.CharField(max_length=15) owner = models.ForeignKey(Profile, on_delete=models.SET_NULL, null=True) is_ordered = models.BooleanField(default=False) items = models.ManyToManyField(OrderItem) date_ordered = models.DateTimeField(auto_now=True) def get_cart_items(self): return self.items.all() def get_cart_total(self): return self.items.aggregate(total=Sum('product__price'))['total'] or 0 def __str__(self): return '{0} - {1}'.format(self.owner, self.ref_code) class Transaction(models.Model): profile = models.ForeignKey(Profile, on_delete=models.CASCADE) order_id = models.CharField(max_length=120) amount = models.DecimalField(max_digits=100, decimal_places=2) success = models.BooleanField(default=True) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) def __str__(self): return self.order_id I have done this in my views.py: def get_user_pending_order(request): # get order for the correct user user_profile = get_object_or_404(Profile, Name=request.user) order = Order.objects.filter(owner=user_profile, is_ordered=False) if order.exists(): # get the only … -
how to Auto page reload in angular 7
Using API I fetch the data from python framework to (Angular 7). But when I add more value in database than at (Angular 7) side its shows me added data when I click on refresh. But I wants to auto reload my page when I change in database. Than give me some suggestion. I already tried the pusher in angular but it's can't work. -
how can I implement one-to-many relationships in Django model?
I am trying to create one-to-many relationships in Django model. I want to implement it as the bellow images shows. here is my code: class Book(models.Model): book_id = models.IntegerField(primary_key=True) name = models.CharField(max_length=255) isbn = models.CharField(max_length=255) class Author(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=255) mobile_no = models.CharField(max_length=255) book_id = models.ForeignKey(Book)//I want to link it with Book.book_id -
Is django-channels 2 good enough for real time multiplayer?
I’m between django-channels 2 and a Golang WebSocket implementation right now for a real-time game. I expect to send a message every 20ms or so. Is django-channels performant enough for this? I’ve seen some posts about it potentially being slow. -
Problem reading sqllite table as csv file in recommender system
I have to import a rating sqllite table as a csv file for my recommender system. The recommender.py looks like this: import pandas as pd import numpy as np from .models import movies,rating ratings=pd.read_csv('rating.csv') I have a basic webapp in django that takes ratings of various movies from a user. After the user rates all the movies, the recommender system then recommends certain movies to the user. I am saving the ratings data in a rating model. However, I can't read a database table directly in my recommender.py as shown above as I need a csv file - 'rating.csv'. How can I directly import the rating table in my sqllite database as a csv file in the code posted above? Please help. -
Make a calculation on data using fields from Django model
I would like to compute the XIRR using the data from several attributes of a Model Pretty new to Django, so haven't given it an actual try so far. Though, for the past days actively checking on the web/documentation on how to get started. Basically I want to compute the XIRR of an investment. So far, I have created a model (Investment) which has 3 attributes: name, date and cash flow. An investment can have of multiple instances (cf an investment can have multiple cash-flows at different dates), and the idea is to compute (and output) the XIRR using this data. How can I tackle this? Aggregations? Annotations? Model Methods? Does anyone has a different function which I can use as an example? Many thanks to give me some guidance so I can get started !! -
bash export command in powershell
I'm trying to follow this guide to test Django on Azure: https://github.com/carltongibson/rest-framework-tutorial/blob/master/docs/azure/2-appservice.md , however i'm stuck at running the following command since i'm doing it from PowerShell: $ export $(grep -v '^#' .azure-env | xargs) What would the command be in PowerShell and can someone explain what it does ? Thanks -
View didn't return an HttpResponse object. It returned None instaed
I'm using Django 1.11 and I'm trying to improve an existing code which let to export data to an Excel file. There are 2 cases : File contains less than 70.000 rows. In this way, user can directly download the generated output file. File contains more than 70.000 rows. In this case, the file is written in the media folder. I'm getting an issue with the second part. The file is well-written in the Media folder, but I don't find a way to provide an HttpResponse object. In my HTML template, I have this link : <a title="Export to Excel" class="button btn btn-default" href="{% url 'ocabr:export-xls' model=model %}"> <span class="glyphicon glyphicon-export"></span> </a> In my view, I have this file : class ExportOCABR(View): def export_xls(self, model=""): app_label = 'ocabr' # create a workbook in memory output = io.BytesIO() book = Workbook(output, {'constant_memory': True}) sheet = book.add_worksheet('Page 1') # Sheet header, first row row_num = 0 #Part which fill the file, adjust columns etc .. ... book.close() if len(rows) < 70000: # construct response output.seek(0) name = 'Obsolete' if obsolete else '' name += str(model._meta.verbose_name_plural) response = HttpResponse(output.read(), content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") response['Content-Disposition'] = 'attachment; filename="' + name + '.xlsx"' return response #The interesting part … -
The data values are overlaping on y-axis (multiple tooltips on same line) in Charts JS although having different lablels
I am having unique label values however the data for the close labels values are stacked on top of each other. I want them to be plotted side by side. I'm using charts.js in django. I have been going over this since morning. Please suggest. <canvas id="densityChart" width="1850" height="600"></canvas> <script> var bangaloreData = { label: 'Bangalore', data: {{ bang }}, backgroundColor: 'rgba(0, 99, 132, 0.6)', borderWidth: 0, yAxisID: "y-axis-density" }; var siteData = { labels: {{ date|safe }}, datasets: bangaloreData }; var densityCanvas = document.getElementById("densityChart"); var ctx = densityCanvas.getContext("2d"); var chartOptions = { responsive: false, maintainAspectRatio: true, scales: { xAxes: [{ stacked: false, barPercentage: 1, categoryPercentage: 0.6, }], yAxes: [{ stacked: false, id: "y-axis-density", }] } }; var barChart = new Chart (densityCanvas, { type: 'line', data: siteData, options: chartOptions }); Here is the image sample -
Django PyTests - Visual Studio code - No tests discovered, please check the configuration settings for the tests
VS Code keeps failing to discover Unit tests for my Django project. I have installed pytest and pytest-django libraries Project structure (simplified) - root_project - pytest.ini - etc - docs - tests - test_app.py - django_project - project_name - settings - develop.py - testing.py - production.py - app_1 - app_2 - manage.py pytest.ini file content [pytest] DJANGO_SETTINGS_MODULE = "django_project.project_name.settings.testing" python_files = test_*.py settings.json file content "python.unitTest.unittestArgs": [ "-v", "-s", "root_project/tests", "-p", "test_*.py" ], "python.unitTest.pyTestEnabled": true, "python.unitTest.nosetestsEnabled": false, "python.unitTest.unittestEnabled": false, I keep getting this error and no tests are discovered: -
error rendering images in multiple choices
I have this field of multiple choices, that the user can choose dog, cat, bir, varios at the same time, however as he enters his profile I want instead of the animals name he sees an image of each animal that registered, and it is exactly what I can not do, how to render the images based on the animals he chose. if it were possible I would like these same pictures to appear already at the time of the choice she will select forms.py from django.forms import ModelForm from django import forms from django.forms.widgets import CheckboxSelectMultiple from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from PIL import Image from django import forms from django.core.files import File from .models import ( Usuario, Negocio ) cat = 'cat.svg' PET_CHOICES = ( ('dog','dog.jpg'), ('cat','cat.jpg'), ('bird', 'Pássaros'), ('fish','Peixes'), ('rep','Reptéis'), ('horse','Cavalos'), ('rat','Roedores') ) STATE_CHOICES = ( ('AC', 'Acre'), ('AL', 'Alagoas'), ('AP', 'Amapá'), ('AM', 'Amazonas'), ('BA', 'Bahia'), ('CE', 'Ceará'), ('DF', 'Distrito Federal'), ('ES', 'Espírito Santo'), ('GO', 'Goiás'), ('MA', 'Maranhão'), ('MT', 'Mato Grosso'), ('MS', 'Mato Grosso do Sul'), ('MG', 'Minas Gerais'), ('PA', 'Pará'), ('PB', 'Paraíba'), ('PR', 'Paraná'), ('PE', 'Pernambuco'), ('PI', 'Piauí'), ('RJ', 'Rio de Janeiro'), ('RN', 'Rio Grande do Norte'), ('RS', 'Rio Grande do Sul'), ('RO', … -
How to improve or modify my code when I get a "504 Time-out" error?
Server: MySQL5.7, Django2.1, uWSGI, Nginx I am working on a Django project, I deployed Project on one server and put MySQL on another. When I use django admin to change or add some items, it is super slow, sometimes I can not get 'change' pages(Nginx gives me a 504 page), sometimes I can not get auto-complete-list(chrome developer view give me a 504 error). I've tried 3 ways to improve. The 1st one is changing both servers Mbps from 1 Mbps to 5 Mbps, it helped a little, on some pages. But did not solve all problems. The 2nd one is change uWSGI config, add buffer-size as 32768. I am not sure does it helped, doesn't feel helped. The 3rd one is change NGINX config, I tried "add fastcgi_connect_timeout 300" into conf file, doesn't work. I tested use django runserver and use uwsgi to run my project, it also kind of slow(~50s), but no 504 time-out error, so I think it maybe something wrong with NGINX config, but I don't know how to change. My uWSGI.ini code: [uwsgi] socket = 127.0.0.1:9002 chdir = /home/user/project wsgi-file = project/wsgi.py master = true processes = 4 threads = 2 static-map = /static=static vacuum = … -
Extand Django User model and show this on admin
I use the latest django for an intranet project. Well, I followed the django documentation to extend my models: from django.db import models from django.contrib.auth.models import AbstractUser class Employee(AbstractUser): DEPARTMENTS = ( ('ARE', 'Area Manager'), ('IT', 'IT'), ('CAT', 'Category manager'), ('CON', 'Controling') ) departement = models.CharField(max_length = 3, verbose_name = "Département", choices = DEPARTMENTS) After that, I rewrited the admin.py: from django.contrib import admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth.models import User from .models import Employee # Define an inline admin descriptor for Employee model # which acts a bit like a singleton class EmployeeInline(admin.StackedInline): model = Employee can_delete = False verbose_name_plural = 'Employees' # Define a new User admin class UserAdmin(BaseUserAdmin): inlines = (EmployeeInline,) # Re-register UserAdmin # admin.site.register(User) # return error: django.contrib.admin.sites.NotRegistered: The model User is not registered admin.site.unregister(User) admin.site.register(User, UserAdmin) As you can see on the 3 last line of my admin.py, if I register User model I have an error. If I comment my last lines # Re-register UserAdmin #admin.site.unregister(User) admin.site.register(User, UserAdmin) I haven't my User administration: -
How to make Django Server URL config-driven instead of being hard-coded?
I am using Django with React, each time I have to use React to get the data from the database I have to do something like this: var URL = 'http://127.0.0.1:8000/users/api/games/' var API_URL = URL + '?term=' + this.props.token await axios.get(API_URL) .then(res => { temp = res.data }) How can I avoid hardcoding "http://127.0.0.1:8000/" like this and set up it in the setting.py? Can someone show me how to do it? Thanks a lot!