Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Bad Gateway on Geonode Advanced installation Ubuntu 20.04
I am going through the installation process, and when i reach the step 6.3 Update OAuth2 configuration in order to hit the new hostname. sudo PYTHONWARNINGS=ignore VIRTUAL_ENV=$VIRTUAL_ENV DJANGO_SETTINGS_MODULE=geonode.settings GEONODE_ETC=/opt/geonode/geonode GEOSERVER_DATA_DIR=/opt/data/geoserver_data TOMCAT_SERVICE="service tomcat" APACHE_SERVICE="service nginx" geonode_updateip -l localhost -p csdc.immap.org I got this errors related to database: Traceback (most recent call last): File "/home/geonode/.virtualenvs/geonode/bin/django-admin", line 8, in <module> sys.exit(execute_from_command_line()) File "/home/geonode/.virtualenvs/geonode/lib/python3.8/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/geonode/.virtualenvs/geonode/lib/python3.8/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/geonode/.virtualenvs/geonode/lib/python3.8/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/geonode/.virtualenvs/geonode/lib/python3.8/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/opt/geonode/geonode/base/management/commands/fixsitename.py", line 39, in handle site = Site.objects.get_current() File "/home/geonode/.virtualenvs/geonode/lib/python3.8/site-packages/django/contrib/sites/models.py", line 58, in get_current return self._get_site_by_id(site_id) File "/home/geonode/.virtualenvs/geonode/lib/python3.8/site-packages/django/contrib/sites/models.py", line 30, in _get_site_by_id site = self.get(pk=site_id) File "/home/geonode/.virtualenvs/geonode/lib/python3.8/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/geonode/.virtualenvs/geonode/lib/python3.8/site-packages/django/db/models/query.py", line 402, in get num = len(clone) File "/home/geonode/.virtualenvs/geonode/lib/python3.8/site-packages/django/db/models/query.py", line 256, in __len__ self._fetch_all() File "/home/geonode/.virtualenvs/geonode/lib/python3.8/site-packages/django/db/models/query.py", line 1242, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/home/geonode/.virtualenvs/geonode/lib/python3.8/site-packages/django/db/models/query.py", line 55, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "/home/geonode/.virtualenvs/geonode/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1142, in execute_sql cursor.execute(sql, params) File "/home/geonode/.virtualenvs/geonode/lib/python3.8/site-packages/django/db/backends/utils.py", line 99, in execute return super().execute(sql, params) File "/home/geonode/.virtualenvs/geonode/lib/python3.8/site-packages/django/db/backends/utils.py", line 67, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/home/geonode/.virtualenvs/geonode/lib/python3.8/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers return executor(sql, params, many, context) … -
Django and React realtime app architecture
In a nutshell, I'm designing an app similar to https://www.tradingview.com/. So I need previous data to get the OHLC (Open, High, Low, Close) for the previous 1 minute or 5 minutes or 1-hour, interval here can change, also other than that I need real-time data to populate the candlestick chart. I'm using Binance's services for both getting the previous data, by API calls, and the current real-time data, via connection to their WebSocket server. And the problem is I don't know to properly manage those data, I wrote all the scenarios that came to my mind: 1- Make the backend serves the previous data and let the frontend connect to the WebSocket and continue appending data. 2- Make the backend serves both the previous data and also set up a WebSocket server for the client to connect to 3- Make the frontend get both the previous data and connect to Binance's WebSocket server Which way shall I go, the third option for me is the easiest, but I'm afraid that it may put a huge load on the browser, and finally, the project will be hosted on AWS if there is any service that may help. -
Changing db schema django based heroku
I am adding a field to my existing Django model and when I push it to Heroku the new field didn't add and it shows an error : column [new field] does not exist. What did I miss? I did migrate it and the new field added in local Django but it's not changing in Heroku column quizTest_responden.nohp does not exist LINE 1: ...st_responden"."job", "quizTest_responden"."jobg", "quizTest_... -
Unable to install mod_wsgi package
I am trying to install mod_wsgi package using pip , in amazon linux 2 instance, but I keep facing an error: Command: python3 -m pip install mod_wsgi OUTPUT/ERROR: Defaulting to user installation because normal site-packages is not writeable Collecting mod_wsgi Using cached mod_wsgi-4.9.0.tar.gz (497 kB) ERROR: Command errored out with exit status 1: command: /usr/bin/python3 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-2sfljsxd/mod-wsgi/setup.py'"'"'; __file__='"'"'/tmp/pip-install-2sfljsxd/mod-wsgi/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-54w0mlq7 cwd: /tmp/pip-install-2sfljsxd/mod-wsgi/ Complete output (5 lines): Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-install-2sfljsxd/mod-wsgi/setup.py", line 91, in <module> 'missing Apache httpd server packages.' % APXS) RuntimeError: The 'apxs' command appears not to be installed or is not executable. Please check the list of prerequisites in the documentation for this package and install any missing Apache httpd server packages. ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. Steps taken trying to resolve the error: 1.I tried running python setup.py egg_info, but kept getting the error setup.py doesnt exist 2.I tried finding setup.py , using the command find . -name setup.py, but nothing was returned How do I solve this? PS: I know you … -
Django Foreign Key to Multiple Models
Is there a way to make one model be able to foreignkey to more than one model? For example class Tshirt(models.Model): ..... class Jeans(models.Model): ..... class Clothes(models.Model): item = ForeignKey(Tshirt and Jeans, on_delete = models.CASCADE) -
How to create a matrix type table with one form field where field name attribute will be different (like as matrix a_1_1, a_1_2, ...) in Django?
My form: class DatainputForm(forms.Form): def __init__(self, request, *args, **kwargs): super().__init__(*args, **kwargs) for i in range(3): for j in range(3): self.fields['costtp_sd%s%s' % (i, j)] = forms.DecimalField() In HTML template: {% for form in datatp_from %} # datatp_from is the name of the form in views.py {{ form }} {% endform %} Form shows in HTML page: Form shows in HTML page: But I want it in a matrix form like below: But I want it in a matrix form like below: -
How to upload an image temporarily on Heroku?
I am facing the following issue: I have deployed a Django-app to the Heroku and want to upload an image using file input. But it should not be storing there, it could be deleted after I reload the page, but I want to have URL to this image for that time. So, I have no idea how to do this at all, can someone help me? -
Django PostUpdateView isn't saving image ValueError thrown
In models.py I have: class Post(models.Model): title = models.CharField(max_length=100) post_content = models.TextField(max_length=10000) date_posted= models.DateTimeField(auto_now_add=True) image = models.ImageField(upload_to='blog-post-images/', blank=True, null=True) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 500 or img.width > 500: if img.height > img.width: factor=500/img.height nH=500 nW=img.width*factor output_size= (nH,nW) if img.width > img.height: factor=500/img.width nW=500 nH=img.height*factor output_size= (nH,nW) else: output_size=(500,500) img = ImageOps.exif_transpose(img) img.thumbnail(output_size) img.save(self.image.path) And then in views I have: class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Post fields = ['title', 'post_content', 'image'] 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 == post.author: return True return False Upon runserver, page renders html with form fields just fine, allows me to select image path, but then the error I get thrown when actually submitting image path is: "ValueError at /home/post/10/update/ The 'image' attribute has no file associated with it." And image doesn't save. However, when I do it through admin it does save image. I have image blank and null bc I want image to be optional attribute. Is this the reason I'm getting issues? Does something extra need to be added to PostUpdateView class? Thank … -
Make the output of Django runserver flush in Git Bash
When I issue python manage.py runserver under Git Bash, only one line of output appears: Watching for file changes with StatReloader The remaining output appear when I either stop the server or make a change in the code: Performing system checks... System check identified no issues (0 silenced). September 01, 2021 - 23:11:21 Django version 3.2.7, using settings 'newserver.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. How do I make it flush right away? -
Python: How to query a dictionary using a variable as a key
I have a list from a Django model, which can have dict_items with any key, from the model. E.g. I can have a list with 'country' attribute, or 'name' attribute from the same model using a function. x = dict_items([(<country: US>, 1), (<country: UK>, 1), (<country: Australia>, 2), (<country: Canada>, 1)]) x = dict_items([(<name: John>, 10), (<name: Jane>, 15), (<name: Smith>, 20), (<name: Jess>, 1)]) Now, I am trying to build another function to cleanup the keys, basically (<country: US>, 1) to {'key': 'US', 'val': 1} def pctTop5 (dict, keyy): pList = [] for (key,value) in dict: pdict = {} pdict['key'] = key.keyy pdict['val'] = value pList.append(pdict) df = pandas.DataFrame(pList) return df However, I am getting the following error: 'countryModel' object has no attribute 'keyy' 'countryModel' object here is the Django model, which obviously does not have an attribute called 'keyy'. What would be the correct way to pass a variable in order to query a dict key? I need to pass the variable as a key an reuse the function is different views. I tried searching, but most of the answers are for using variable to create a list of dicts, but couldn't find any to query one. TIA -
didn't return an HttpResponse object. It returned None instead Stripe Checkout
I have a problem because I can not make Stripe work with my django project. As in title I get an error. It is really rough to integrate Django with the Stripe. ValueError at /create_checkout_session The view shop.views.create_checkout_session didn't return an HttpResponse object. It returned None instead. Request Method: GET Request URL: http://127.0.0.1:8000/create_checkout_session Django Version: 3.2.6 Exception Type: ValueError Exception Value: The view shop.views.create_checkout_session didn't return an HttpResponse object. It returned None instead. views.py def create_checkout_session(request): MY_DOMAIN = 'localhost:8000' if request.method == 'POST': try: cart = Cart.objects.filter(order_user=request.user) stripe.api_key = os.environ.get('stripeAPI') checkout_session = stripe.checkout.Session.create( line_items=[ { 'price': 'price_1JUTtYIXuOafNhy8tmWVwgjG', 'quantity': 1, }, ], payment_method_types=[ 'card', 'p24', ], mode='payment', success_url=request.build_absolute_uri(reverse('success-page'))+ '?session_id={CHECKOUT_SESSION_ID}', cancel_url= request.build_absolute_url(reverse('cancel-page')), ) except Exception as e: return str(e) return redirect(checkout_session.url, code=303) -
Django Saving Path into Variable
I have a django path that passes the URL I need, but I want to store it into a variable which I can use in a mailing API the path is: path('activate/(<uidb64>[0-9A-Za-z_\-]+)/(<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})', views.activate, name='activate'), I want the string to have a value similar to this: http://127.0.0.1:8000/auth/activate/(NDM%5B0-9A-Za-z_%5C-%5D+)/(as9osn-a59ae3d7196bb1fa693e770fb87f19c1%5B0-9A-Za-z%5D%7B1,13%7D-%5B0-9A-Za-z%5D%7B1,20%7D) I am getting this: http://127.0.0.1:8000/auth/activate/NTQ/asbda1-165d68dbe6fee8c47f5099c4ab709c48 -
calc between points in django postgis
i have a model: class lctnp(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) pin = gmodel.PointField(geography=True, null=True, srid=4326) description = models.TextField() class Meta: ordering = ['created_at'] and input with: { "id": "", "owner": "1", "pin": "POINT(-95.3385 29.7245)", "description": "hello from here" } and try to calc distance with another point: query = ''' SELECT id, ST_Transform(pin, 4326), ST_Distance(pin, 'SRID=26918;POINT(-95.3385 30.7245)') AS dist FROM house_lctnp ORDER BY pin <-> 'SRID=26918;POINT(-95.3385 30.7245)'::geometry LIMIT 3; ''' for p in lctnp.objects.raw(query): return JsonResponse(p.description, safe=False) but seems i try a wrong way. plz help me -
Docker and Django Rest Framework "unexpectedly dropped the connection"
Overview I have a weird situation where when I apply DEFAULT_FILTER_BACKENDS to my Django Rest Framework (DRF) settings, I get a "Safari can't open 0.0.0.0:8000 because the server unexpectedly dropped the connection" error message. I should note that the config below works perfectly with a standard poetry run python manage.py runserver 0.0.0.0:8000 command, i.e. when I don't use Docker. My Django settings.py file is standard, except for: INSTALLED_APPS = [ ... "rest_framework", ... ] REST_FRAMEWORK = { "DEFAULT_FILTER_BACKENDS": ( "django_filters.rest_framework.DjangoFilterBackend", ), } and when I remove/comment out the "DEFAULT_FILTER_BACKENDS" section, the server works and my pages load perfectly. Dockerfile # pull official base image FROM python:3.9.0-buster # set work directory WORKDIR /usr/src/app # set environment variables ENV DJANGO_SETTINGS_MODULE=barrys_project.settings ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install dependencies RUN pip install --no-cache-dir --upgrade pip RUN pip install --no-cache-dir poetry COPY ./poetry.lock ./pyproject.toml ./ RUN poetry config virtualenvs.create false RUN poetry install # copy entrypoint.sh COPY ./entrypoint.sh ./ # copy project COPY . . # run entrypoint.sh ENTRYPOINT ["/usr/src/app/entrypoint.sh"] Docker Compose file version: '3.8' services: web: build: ./ volumes: - ./:/usr/src/app/ command: poetry run python manage.py runserver 0.0.0.0:8000 ports: - 8000:8000 env_file: - ./.env depends_on: - db db: image: postgres:13.3-alpine volumes: - … -
Django ArrayField - Choices from a class of constants - ERROR fields.E005
I have a file with constants declared inside classes: class LanguageChoices: EN = "English" FR = "French" @classmethod def choices(cls): return ( (cls.EN, _("English")), (cls.FR, _("French")), ) And my models: from django.contrib.postgres.fields import ArrayField from apps.users.constants import LanguageChoices class Data(models.Model): language = ArrayField( models.CharField( max_length=30, choices=LanguageChoices.choices()), blank=True, null=True ) ) When I try to run migrations it run into this error (this happens even if I erase all previous migration files and use a new database): SystemCheckError: System check identified some issues: ERRORS: users.Data.language: (postgres.E001) Base field for array has errors: 'choices' must be an iterable containing (actual value, human readable name) tuples. (fields.E005) ERROR: 1 Any ideas? -
Unable to use custom account adapter
I have the following in adapter.py: from allauth.account.adapter import DefaultAccountAdapter class CustomAllauthAdapter(DefaultAccountAdapter): pass # keeping it trivial for debugging At the very end of settings.py: import django django.setup() # complains about apps not being loaded yet without this... from .adapter import CustomAllauthAdapter ACCOUNT_ADAPTER = CustomAllauthAdapter # this is the line that results in the error! As soon as I submit the registration form for a new user, I get this error in the browser: AssertionError at /api/v1/users/auth/register/ No exception message supplied Here is the Traceback: File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\django\views\decorators\debug.py", line 89, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\dj_rest_auth\registration\views.py", line 47, in dispatch return super().dispatch(*args, **kwargs) File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\rest_framework\generics.py", line 190, in post return self.create(request, *args, **kwargs) File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\dj_rest_auth\registration\views.py", line … -
Get id from a card created in a crud django-oracle
I want to obtain the id code of a specific card when I select it so that it will then give me information. The card is created through a crud, so it is dynamic. I use oracle database. I got undefined in the alert. This is my template <section class="cards"> {% for c in Comidas %} <div class="card"> {% if c.imagen %} <img class="card__image" src="data:imagen/png;base64, {{ c.imagen }}" alt=""> {% endif %} <div class="card__title">{{ c.data.1 }}</div> <div class="card__id" id="id_Card" onclick="obtenerId()">Codigo Orden: {{ c.data.0 }}</div> <div class="card__snippet">{{ c.data.2 }}</div> <div class="card__description">{{ c.data.3 }}</div> <a href="comida_details" class="card__readmore">Detalles</a> </div> {% endfor %} </section> <script> function obtenerId(){ let id= document.getElementById("id_Card").value; alert(id) } </script> Thank you very much for your help -
When select different options shows different input, but all inputs of all options are required
I'm working with Django and I made a function that creates a person (employee, student, or worker) and as you can see I created the three different forms on create_person, so on the template, when you select an option on school_role to choose what kind of person you will create, its shows different inputs and select, it depends if you click on student, academic or employee. This is ok, but my problem is that I need to fill all of the inputs and selects on all of the three options to be able to send the form, and I need that you just have to fill one ( employee, academic, or student). def create_person(request): if request.method == 'POST': form = PersonForm(request.POST) daysform = AvailableDayForm(request.POST) studentForm = StudentForm(request.POST) academicForm = AcademicForm(request.POST) employeeForm = EmployeeForm(request.POST) if form.is_valid() and daysform.is_valid(): data = form.save() daysform.save(id=data.id) id = data.id if(data.school_role==1): if studentForm.is_valid(): studentForm.save(id = id) messages.success( request=request, message='success' ) return redirect('cases:list') elif(data.school_role == 2): if academicForm.is_valid(): academicForm.save(id = id) messages.success( request=request, message='success' ) return redirect('cases:list') else: if employeeForm.is_valid(): employeeForm.save(id = id) messages.success( request=request, message='success' ) return redirect('cases:list') else: form = PersonForm() daysform = AvailableDayForm() studentForm = StudentForm() academicForm = AcademicForm() employeeForm = EmployeeForm() context = … -
How to present excel document in datatables?
I'm working on a project, and I need to present data in web page from excel with multiple sheets (multiple documents). Is it possible with this https://datatables.net/ and how? I have tried with this but something is wrong, only get me confused. I wasn't able to run the example that they have been prepared. Any ideas how to present excel document with multiple sheets online with django? -
How to reverse the list inside django template?
I have a list and I wanted to order by descinding in django-html template, How can I do it ? This is my template code {% for unique_date in unique_dates %} <th>{{unique_date}}</th> {% endfor %} And this is my view file unique_dates = list({a.date for a in attendances}) unique_dates.sort() -
Django sessions instead of user model
Is there a way to use sessions in django instead of a user model? I know django creates sessions for each "new" client accessing the server. I want to be able to store attributes like I would on a user model and be able to retrieve a session based on a form. more like logging in an existing session on a "new" client. Whats the most elegant approach? I'm thinking of implementing a middleware -
Sorting DataTable by recent date
I have a table and it is sorted by the old date. I just want to make its default sorting is the recent date. the code is: <script> $(document).ready( function () { $('#table_id').DataTable({ dom: 'B<"clear">lfrtip', buttons: { name: 'primary', buttons: [ 'copy', 'csv', 'excel', 'pdf' ] } }); }); </script> and it looks like: I tried many solutions on the net but all didn't work! <script> $(document).ready( function () { $('#table_id').DataTable({ dom: 'B<"clear">lfrtip', buttons: { name: 'primary', buttons: [ 'copy', 'csv', 'excel', 'pdf' ] } }).asSorting([[0, "desc"]]); }); </script> and this <script> $(document).ready( function () { $('#table_id').DataTable({ dom: 'B<"clear">lfrtip', buttons: { name: 'primary', buttons: [ 'copy', 'csv', 'excel', 'pdf' ] } }).fnSort([[1, "acs"]]); }); </script> and this too <script> $(document).ready( function () { $('#table_id').DataTable({ "order": [[ 3, "desc" ]] dom: 'B<"clear">lfrtip', buttons: { name: 'primary', buttons: [ 'copy', 'csv', 'excel', 'pdf' ] } }); }); </script> and this one > <script> > $(document).ready( function () { > $('#table_id').DataTable({ > "aoColumnDefs": [ > { "asSorting": [ "asc" ], "aTargets": [ 0 ] } > ] > dom: 'B<"clear">lfrtip', > buttons: { > name: 'primary', > buttons: [ 'copy', 'csv', 'excel', 'pdf' ] > } > }); }); </script> any suggestions? -
Django ManifestStaticFilesStorage and imports within javascript files
The Django 3.2 ManifestStaticFilesStorage adds a hash value to javascript files called from within a template and this is working as expected. However, some javascript files import from other javascript files and those imported filenames are not translated to a hashed value. The ManifestStaticFilesStorage documentation indicates that this is done for for CSS files when it finds the import rule and url() statement but is silent on how to do it for javascript. Any suggestions on how to get this to work? As an example, this line in the html template: <script src="{% static 'myapp/js/myjavascript.js' %}" type="module"></script> is rendered like this in the browser (works as expected): <script src="/static/myapp/js/myjavascript.12345abc.js" type="module"></script> But within the myjavascript.js file, this line is left untouched, meaning that the browser could still have a cached version of the imported javascript file and use that instead of an updated version. import {func1, func2, func3} from './javascript_helper_lib.js'; -
django adds 127.0.0.1 to the links while running on a real server and not real web address
I run django on a Nginx server. The website is available at this address on the internet: www.website-example.com I have some links in one of the pages. But when I click on the I get this: 127.0.0.1:8000/books/book1.jpeg I should get the below address: www.website-example.com/books/book1.jpeg my allowed hosts in setting is like below: ALLOWED_HOSTS = ['www.website-example.com', '127.0.0.1'] What is wrong that I still get 127.0.0.1? I also removed 127.0.0.1 but the website stops working and says you should add 127.0.0.1 to allowed hosts. -
user with only password required
I want the user to authenticate only with his password and a field from another model that is not shown.I have here the BaseUser of django that I am trying to customize. In the code following the password and email are required.I don't want email to be required anymore class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): if not email: raise ValueError("L'adresse e-mail donnée doit etre definie") email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password, **extra_fields): extra_fields.setdefault("is_staff", False) extra_fields.setdefault("is_superuser", False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **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, password, **extra_fields) class User(AbstractUser): username = None email = models.EmailField('email adress', unique=True) telephone = models.CharField(max_length=20) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] I want only the password to be required. What should I do so that the email is no longer required?