Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
error: legacy-install-failure - When I try to install mysqlclient package for django
I get this error everytime i try to install mysqlclient for my django app. I need to transfer my db to a new one on mysql db. I try to install it by doing this command: python3 -m pip install mysqlclient I am using a macOS 11. Thank you. Collecting mysqlclient Using cached mysqlclient-2.1.0.tar.gz (87 kB) Preparing metadata (setup.py) ... done Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error error: subprocess-exited-with-error × python setup.py bdist_wheel did not run successfully. │ exit code: 1 ╰─> [43 lines of output] mysql_config --version ['8.0.28'] mysql_config --libs ['-L/usr/local/Cellar/mysql/8.0.28_1/lib', '-lmysqlclient', '-lz', '-lzstd', '-lssl', '-lcrypto', '-lresolv'] mysql_config --cflags ['-I/usr/local/Cellar/mysql/8.0.28_1/include/mysql'] ext_options: library_dirs: ['/usr/local/Cellar/mysql/8.0.28_1/lib'] libraries: ['mysqlclient', 'resolv'] extra_compile_args: ['-std=c99'] extra_link_args: [] include_dirs: ['/usr/local/Cellar/mysql/8.0.28_1/include/mysql'] extra_objects: [] define_macros: [('version_info', "(2,1,0,'final',0)"), ('version', '2.1.0')] running bdist_wheel running build running build_py creating build creating build/lib.macosx-11-x86_64-3.9 creating build/lib.macosx-11-x86_64-3.9/MySQLdb copying MySQLdb/init.py -> build/lib.macosx-11-x86_64-3.9/MySQLdb copying MySQLdb/exceptions.py -> build/lib.macosx-11-x86_64-3.9/MySQLdb copying MySQLdb/connections.py -> build/lib.macosx-11-x86_64-3.9/MySQLdb copying MySQLdb/converters.py -> build/lib.macosx-11-x86_64-3.9/MySQLdb copying MySQLdb/cursors.py -> build/lib.macosx-11-x86_64-3.9/MySQLdb copying MySQLdb/release.py -> build/lib.macosx-11-x86_64-3.9/MySQLdb copying MySQLdb/times.py -> build/lib.macosx-11-x86_64-3.9/MySQLdb creating build/lib.macosx-11-x86_64-3.9/MySQLdb/constants copying MySQLdb/constants/init.py -> build/lib.macosx-11-x86_64-3.9/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.macosx-11-x86_64-3.9/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.macosx-11-x86_64-3.9/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.macosx-11-x86_64-3.9/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.macosx-11-x86_64-3.9/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.macosx-11-x86_64-3.9/MySQLdb/constants running build_ext building 'MySQLdb.mysql' extension creating build/temp.macosx-11-x86_64-3.9 … -
Domain-maked Django app not working as expected
I am running a Django app alongside a basic html website using Apache2, by attaching the django app through my.site/myapp When I access it like my.site/myapp/some-location it works just fine, but if I access it through my domain with masking enabled such as domain.site/some-location it returns a 404. The domain points to my.site/myapp with masking enabled as mentioned. Site configuration: <VirtualHost *:80> Alias /static /var/www/myapp/static <Directory /var/www/myapp/static> Require all granted </Directory> <Directory /var/www/myapp/myapp> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myapp python-path=/var/www/myapp python-home=/var/www/djangoenv WSGIProcessGroup myapp WSGIScriptAlias /myapp /var/www/myapp/myapp/wsgi.py </VirtualHost> A specific example that doesn't work: domain.site/admin, which however works well on my.site/myapp/admin. -
Way to query internal data structure for running python program [closed]
Hi I a newbie to software development, I wanted to build a python application that will open TCP connection and listen to logs and do some action based on them. I am planning to use dictionary to store my datas. Just wondering is there a way or CLI package that I can use to query the internal data structure while program is running. I googled and found flask as an option but from what I understand its mainly for web-development. Does it make sense to use Flask for these kind of my application ? Am I going in right direction or is there any other resources that will point me in right direction ? -
New bid is not updating to show the Users input (amount) Django
Trying to create an e-bay like platform where users can select an item and bid on it, the bid amount should update to the latest valid bid inputted by a user. Currently, the amount is not updating to show that a user has made bid, it shows me the pop up message of messages.success(request, 'Successfully added your bid') Could you please give me an insight of what is causing this? MODELS.PY class Auction(models.Model): title = models.CharField(max_length=25) description = models.TextField() current_bid = models.IntegerField(null=False, blank=False) image_url = models.URLField(verbose_name="URL", max_length=255, unique=True, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) category = models.ForeignKey(Category, max_length=12, null=True, blank=True, on_delete=models.CASCADE) is_active = models.BooleanField(default=True) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return f"(self.title)" def no_of_bids(self): return self.bidding.all().count() def current_price(self): if self.no_of_bids() > 0: return self.bidding.aggregate(Max('new_bid'))['new_bid__max'] else: return self.current_bid def current_winner(self): if self.no_of_bids() > 0: return self.bidding.get(new_bid=self.current_price()).user else: return None class Meta: ordering = ['-created_at'] class Bids(models.Model): auction = models.ForeignKey(Auction, on_delete=models.CASCADE, related_name='bidding', null=True) user = models.ForeignKey(User, on_delete=models.PROTECT, related_name='bidding') new_bid = models.DecimalField(max_digits=8, decimal_places=2) done_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.new_bid) class Meta: ordering = ['auction', '-new_bid'] VIEWS.PY @login_required def make_bid(request, listing_id): if request.method == 'POST': auction = Auction.objects.get(pk=listing_id) bid_form = BidForm(request.POST) if bid_form.is_valid(): bid_form.instance.user = request.user bid_form.instance.item = auction if bid_form.instance.new_bid > auction.current_price(): bid_form.save() … -
How to assert that a class has a class exclusive property in Django/Python?
I have two models in Django, one that is the base and the other that is inherited. The base model has a database field (which in Python is an attribute of the class) and the inherited model has a property that is exclusive to the Class (not of every instance created). Both can yield different things. from django.db import models from django.utils.decorators import classproperty class Parent(models.Model): somefield = models.TextField() class Child(Parent): @classproperty def somefield(cls): return 'something' How can I create a test to ensure that all the child models created from the parent model have that class exclusive property? Because if I use hasattr() it will consider the field and the property. Something like this assertTrue(hasattr(Child, 'somefield')) assertFalse(hasattr(Parent, 'somefield')) -
UpdateView is not removing image when updating form - Django
I have a form that the user can upload the pictures into the post, this is working fine, but the problem is when the user wants to remove that current picture that the post has. It can be updated to another picture, but it can't be removed from the post to be "Blank". Models.py class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): form_class = PostEditForm model = Post 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 forms.py class PostEditForm(forms.ModelForm): thumb = forms.ImageField(required=False, widget=forms.FileInput) class Meta: fields = ['title', 'content', 'thumb', 'date_start', 'start_time', 'date_end', 'end_time', ] model = Post -
Django Query - How can do Prefetch filter with values based on root query?
For better performance, i use prefetch selected to get all in one single query like this profile = Profile.objects.only('id','series_following').prefetch_related( Prefetch('books_reading', queryset=Book.objects.only('id').filter( series_id=`series_following_id`), to_attr='books')).get(user=request.user_id) I want to get all books are reading with series_following, but i dont know how to put it to filter. Here are my models: class Profile(models.Model): user = models.OneToOneField(User) series_following = models.ForeignKey('Series') books_reading = models.ManyToManyField('Book', related_name="readers_reading_book", null=True, blank=True) ... class Series(models.Model): name = models.CharField() ... class Book(models.Model): name = models.CharField() series = models.ForeignKey(Series) ... -
Django Can't get ListView to reorder based on date
I am attempting so change the display order of a ListView to show the most recently added item. I have tried several methods in the view but so far none has had an effect on the output. The page still displays the oldest entry first. Here is an example of a view I have tried: class CompanyAnnouncementList(ListView): model = CompanyAnnouncement template_name = 'company_accounts/announcements.html' ordering = ['-date'] The model: from django.db import models from accounts.models import CustomUser from tinymce import models as tinymce_models class CompanyAnnouncement(models.Model): title = models.CharField(max_length= 200) author = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True) body = tinymce_models.HTMLField() date = models.DateField(auto_now_add=True, null=True) def __str__(self): return self.title The template: {% extends 'base.html' %} {% block content %} <div class="section-container container"> {% for post in object_list %} <div class ="announcements-entry"> <h2><a href=" ">{{ post.title }}</a></h2> <h3>made on {{ post.date }}</h3> <p>{{ post.body | safe }}</p> </div> {% endfor %} </div> {% endblock content %} I know there are ways to change the order at the model but I would prefer to use the view. Any ideas about how to get this to work? -
How to override update method with nested serializer?
How can i update people field? class VisitsSerializer(serializers.Serializer): value = serializers.CharField(max_length=200) people = TrendingCardsPeopleListV3Serializer(many=True, read_only=True) def update(self, instance, validated_data): instance.value = validated_data.get('value', instance.value) # TODO: update people instance.save() return instance -
how to check if the object is already created in Django rest framework serializer's to_present function
I need to check if the object is already created before adding some data to be viewed in the serializer's response. my code class AppUserSerializer(serializers.ModelSerializer): ''' Serializing App User model ''' main_user = MainUserSerializer(read_only=True) class Meta: ''' Defining main data for AppUserSerializer ''' model = AppUser # fields = "__all__" fields = [ "first_name", "last_name", "mobile", "email", "birthdate", "password", "confirm_password", "image", "main_user", "generated_code", "user_langauge", "dark_mode", ] def to_representation(self, instance): ''' Adds more data to be serialized back with AppUserSerializer ''' data = super().to_representation(instance) if AppUser.objects.filter().exists(): #need to check if object already there here, what to add inside filter() !! if instance.playerprofile_set.all().count() > 0: player_profile = instance.playerprofile_set.all()[0] data['player_profile'] = PlayerProfileSerializer( player_profile).data for item in Team.objects.all(): if player_profile in item.players.all(): data['team'] = TeamSerializer(item).data if item.cap.id == player_profile.id: data['team'] = TeamSerializer(item).data return data -
How to limit the input in DateTime picker?
I am making a django app which is going to collect data from a form. In the form I'm gonna put some normal fields and a DateTime field, but I wanna limit that DateTime field so the user can only select: For the Date: from today to lets say 1 year ahead For the Time: from the current local time(so if the date is today, they won't be able to pick a time before the current local time) afterwards every day from 10:00 until 21:00 Is there a way to do that? Thank You! -
how can I get month from date in django models
I want to make a query and return only the month of the year of the date field from my models then compare the return result to the current month of the year. current_date = datetime.date.today() _history = PayrollModel.objects.filter(employee_id_id=employee_id) if(_history == None or _history.count() == 0): return True if(_history != None and _history.count() != 0): # entity = _history.get(month_year=current_date) for history in _history: print(history.employee_id_id) if(history.month_year__month != current_date.month and history.month_year.year == current_date.year): return True else: return False -
Django not recognised inside Container in Docker
I have Django on my computer and it works perfectly fine. However, when I am in a Docker container, it seems like Django doesn't work anymore (for exemple if I run import Django in the Python shell it won't recognise Django). Does anyone have an idea on how to use Django in Docker? -
Django - how to display all users that are present?
I have created an attendance system in Django but I cannot seem to retrieve all users that are currently present. My code is displayed below: Models: class Meta: model = User fields = ("username", 'email', 'password1', 'password2') class is_Present(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateField(default=datetime.date.today) is_present = models.BooleanField(default=False) class clocked_Time(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateField(default=datetime.date.today) time = models.DateTimeField(null=True, blank=True) signed_out = models.BooleanField(default=False) views.py: # Displays admin attendance portal functions def attendance_portal(request): if not request.user.is_authenticated: messages.warning(request, f'Please sign in to mark attendance out') return redirect('login') elif not request.user.is_superuser or not request.user.is_staff: messages.warning(request, f'Must be admin to access this feature') return redirect('home') elif request.user.is_superuser: count_employees_all = count_employees() # shows count of employees present_employee_all = present_employees() # shows count present employees today present_employee_all_week = present_week_employees() # shows count present employees in last 7 days # Gets the employees present today today = datetime.today() # Gets employees displayed and paginated user = get_user_model() user_list = user.objects.all() p = Paginator(is_Present.objects.filter(date=today).filter(is_present=True).select_related('user').values('user__username'), 5) page = request.GET.get('page', 1) users = p.get_page(page) try: users = p.get_page(page) # returns the desired page object except PageNotAnInteger: # if page_number is not an integer then assign the first page users = p.page(1) except EmptyPage: # if page is empty … -
Django confuses same DB name runs on different ports
I am running two different MongoDB on different ports and configured DB router to find the proper database. Also, the DB name and tables are the same in both. Assume that I have 2 app first_app and second_app where the DB connection names are the same as well. settings.py ... 'first_app': { 'ENGINE': 'djongo', 'NAME': os.environ.get("FIRST_DB_DATABASE", 'mymongodb'), 'CLIENT': { 'host': os.environ.get("FIRST_DB_HOST", "localhost"), 'port': 27019, 'username': os.environ.get("FIRST_DB_USER"), 'password': os.environ.get("FIRST_DB_PASSWORD"), } }, 'second_app': { 'ENGINE': 'djongo', 'NAME': os.environ.get("SECOND_DB_DATABASE", 'mymongodb'), 'CLIENT': { 'host': os.environ.get("SECOND_DB_HOST", "localhost"), 'port': 27020, 'username': os.environ.get("SECOND_DB_USER"), 'password': os.environ.get("SECOND_DB_PASSWORD"), } }, ... and here is the reason why app names are the same as connection names to find proper DB in router based on app name: db_router.py class MultiDatabaseRouter: app_labels = {'first_app', 'second_app'} mongodb_app_labels = {'first_app', 'second_app'} def db_for_read(self, model, **hints): if model._meta.app_label in self.app_labels: return model._meta.app_label return None def db_for_write(self, model, **hints): if model._meta.app_label in self.app_labels: return model._meta.app_label return None def allow_relation(self, obj1, obj2, **hints): return None def allow_migrate(self, db, app_label, model_name=None, **hints): """Do not migrate MongoDB.""" if app_label in self.mongodb_app_labels: return False return None Also, I have the same Models in both apps using the same db_table. But, when I retrieve data in Django admin the result comes always … -
docs2pdf unable to convert the pdf
Traceback (most recent call last): File "C:\Users\jaint\Desktop\student_internship_backend\administration\views.py", line 3546, in deployCandidate response = pdf_genrator(candidate_name, application_no, adress, office_name, hod_dm, dept_dist) File "C:\Users\jaint\Desktop\student_internship_backend\administration\utils.py", line 356, in pdf_genrator convert("template/Name.docx") File "C:\Users\jaint\AppData\Local\Programs\Python\Python310\lib\site-packages\docx2pdf_init_.py", line 106, in convert return windows(paths, keep_active) File "C:\Users\jaint\AppData\Local\Programs\Python\Python310\lib\site-packages\docx2pdf_init_.py", line 19, in windows word = win32com.client.Dispatch("Word.Application") File "C:\Users\jaint\AppData\Local\Programs\Python\Python310\lib\site-packages\win32com\client_init_.py", line 117, in Dispatch dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch, userName, clsctx) File "C:\Users\jaint\AppData\Local\Programs\Python\Python310\lib\site-packages\win32com\client\dynamic.py", line 106, in _GetGoodDispatchAndUserName return (_GetGoodDispatch(IDispatch, clsctx), userName) File "C:\Users\jaint\AppData\Local\Programs\Python\Python310\lib\site-packages\win32com\client\dynamic.py", line 88, in _GetGoodDispatch IDispatch = pythoncom.CoCreateInstance( pywintypes.com_error: (-2147221008, 'CoInitialize has not been called.', None, None) 2022-03-09 19:36:49,588 administration.views INFO < =================== End - Deploy Candidate To Office =================== > -
Django missing data from database
Having a problem that shouldn't appear. Created a django project. all the steps on windows OS. Now when went to do everything the same on Ubuntu 20.04 then my index.html is not displaying any data from database even if there is a data ( i checked ) Html:: <!DOCTYPE html> <html lang="en"> <head> <title>Django CRUD Operations</title> <meta charset="utf-8"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <table class="table table-striped"> <thead> <tr> <th>Flight ID</th> <th>Aircraft</th> <th>Registration</th> <th>Latitude</th> <th>Longtitude</th> </tr> </thead> <tbody> {% for c in flight %} <tr> <td>{{c.id}}</td> <td>{{c.aircraft}}</td> <td>{{c.registration}}</td> <td>{{c.latitude}}</td> <td>{{c.longtitude}}</td> </tr> {% endfor %} </tbody> </table> </div> </body> </html> Views.py:: from .models import Flights from django.shortcuts import render def show(request): flights = Flights.objects.all() return render(request,"show.html",{'flight':flights}) Database is connected. Any ideas? Maybe Ubuntu 20.04 has something that have to do differently like windows os? -
Passing a variable from views.py to models.py django
I am still very new to programming. My issue is this I have 2 models, one for Sale and one for Agent. now to render each Agent and the sales they made(with different attributes) uniquely I needed to write model methods under my sale model to allow to me to call them in the template. Now my issue is this, I want to be able to render that exact thing but by what dates the user chooses, I have tried manually doing this through my project files and it works, but I want to know is it possible to have those values moved from user into my method? What I mean is there is a basic form in the nav bar that allows the person to choose a from and to date, but those values I am not sure how to pass them into my models.py under the method where I need this date range applied. I will show an example. #this is my view that grabs relevant dates def asearch_stats(request): if request.method == 'POST': from_date = request.POST['from'] to_date = request.POST['to'] return render(request,"Sales/salesfilter.html",{"flookup":flookup}) # this is my model with the methods I'm referring to below: class SalesAgent(models.Model): user = models.OneToOneField(User,on_delete=models.SET_NULL,null=True,related_name="sauser") … -
Why am I not getting CSRF warning from django?
So usually when you try to make a POST request to the server in Django without CSRF token it gave you this page but for the past 3 months I've been playing with DRF and custom user model and I didn't even realized until now that I've actually not been getting that error despite not using CSRF in my postman header. There's also some more details made it more confusing to me first I made a post request to TokenObtainPairView from djangorestframework_simplejwt containing username and password (I'm using base user model) for login and it was successful Right after that I made another post request to add a title (a model that only have 1 field which is a charfield) and then it gave me CSRF warning I also have an almost identical project to this the only difference being the other projects uses custom user model and it never gave me any CSRF warning. So I suspect this has something to do with the user model somehow So to summarize my question: Why doesn't it gave me CSRF warning in the first POST request? does this have anything todo with custom user model? if so what am I missing? … -
Django DRF: Take extra input from user using serializer but not present in the model
I have one ModelSerializer class which is used for user input & validation. I am using it with a ModelViewset which automatically creates a new entry in the database using the serializer. Now what I want to do is that I want to have a extra field in the serializer say roles which will be given by the user. It is an array of roles for a user. So I wrote my serializer like this, class UserCreateSerializer(serializers.ModelSerializer): """ Serializer to create new user """ class Meta: model = User fields = ["name", "email", "is_active", "roles"] read_only_fields = ['roles'] roles = serializers.MultipleChoiceField(choices=[(e.name,e.value) for e in AuthGroup]) def validate_roles(self, value): if not value: raise ValidationError(detail=constants.NAMED_FIELD_REQUIRED.format(field="roles")) My model looks like this, class User(AbstractBaseUser, PermissionsMixin): class Meta: db_table = "auth_user" app_label = "users" USERNAME_FIELD = "email" REQUIRED_FIELDS = [] name = models.CharField(max_length=255, null=True) email = models.EmailField("email address", unique=True, null=True) is_active = models.BooleanField(default=True) is_superuser = None is_admin = None is_verified = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = UserManager() def __str__(self): return self.name or self.email def is_admin(self): return self.groups.filter(name=AuthGroup.ADMIN.name).exists() This is the request body which is coming from user. { "name": "test4", "email": "test4@example.com", "is_active": true, "roles": [ "ADMIN", "OPERATOR" ] } So … -
django 3.2 how to loop a field with foreign-keys
I'd like to loop a field based from the Question Model. Here are my models.## Heading ## models.py from django.db import models from django.db.models.deletion import CASCADE from django.conf import settings class Question(models.Model): id = models.BigAutoField(primary_key=True) title = models.CharField(max_length=50, unique=True) question = models.CharField(max_length=255, unique=True) class Declaration(models.Model): id = models.BigAutoField(primary_key=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='declarations', on_delete=models.CASCADE) class Checklist(models.Model): id = models.BigAutoField(primary_key=True) declaration = models.ForeignKey(Declaration, related_name='checklist_declaration', on_delete=models.CASCADE) question = models.ForeignKey(Question, related_name='checklist_question', on_delete=models.CASCADE, limit_choices_to={'is_active': 'True'}) is_yes = models.BooleanField() and my forms.py from django.utils.safestring import mark_safe from django import forms from declaration.models import Checklist, Question class HorizontalRadionRenderer(forms.RadioSelect): def render(self): return mark_safe(u'\n'.join([u'%s\n' % w for w in self])) class ChecklistForm(forms.ModelForm): is_yes = forms.TypedChoiceField( coerce=lambda x: x == True, choices=((True, 'Yes'), (False, 'No')), widget=forms.RadioSelect() ) class Meta: model = Checklist fields = ['is_yes'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) questions = Question.objects.filter(group='symptom') for q in questions: self.fields['question_id'] = q.id and here is my expected output enter image description here I dunno how to do it in the forms.py since django's only way to validate fields is through forms. -
sprite.svg not displaying icons when deployed to heroku but working locally (Django, Heroku, SVG)
I am coding a landing page using django, html, css. I have a sprite.svg file containing different icons(svg drawings wich can be accessed using "" for instance). The sprite.svg file is located in my static file. When I launch the page on my local server the icons appear with no problem. When I deploy to heroku the icons are not showing. Could you please help me with this problem? The architecture is the following django project -----main app ----------settings.py ----------urls.py -----second app -----static ----------css ----------img ---------------sprite.svg ----------js -----templates ----------secondapp ---------------index.html -----manage.py -----Procfile The settings.py file: Django settings for leadinsightmarketing project. Generated by 'django-admin startproject' using Django 3.2.6. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path import os import django_heroku # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATE_DIR = os.path.join(BASE_DIR, "templates") STATIC_DIR = os.path.join(BASE_DIR, "static") # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-aorn6ipmi+r4pai&^e^edrn)v^80*q8!=x2=99a%rd4^9p6qcc' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['localhost', '127.0.0.1', … -
After I made a migration I get this error RelatedObjectDoesNotExist at /admin/login/ User has no profile
I just start to learn django. I want to creat a bookmanager. First time I creat Model Book, after this I creat users and after this I create another model Categories. After this migration I get the error RelatedObjectDoesNotExist at /admin/login/ User has no profile. I can acces the old users profile, but I can not create new and can not acees it's profile. Also I can not acees the admin. How can I resolve the problem. models.py from django.contrib.auth.models import User from PIL import Image # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='person.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self): super().save() img = Image.open(self.image.path) if img.height > 500 or img.width > 500: output_size = (500, 500) img.thumbnail(output_size) img.save(self.image.path) signals.py from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwards): user = instance if created: Profile.objects.create(user=user) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwards): instance.profile.save() -
Django Redirect to Second URL
I'm trying to redirect to an custom url as it's coded in the below. However there might be a broken url. Therefore, I like to redirect to an second url in case of error. Is there any way to redirect to an second url in case of an error? page = self.request.POST.get('ex_page') return redirect(page) -
Authenticate users in my django app using an existing ASP.Net IdentityServer login app
I'm trying to authenticate users in my django app using an existing ASP.Net IdentityServer login app. I've seen the documentation has an example for an angular or react(Javascript based app) but not django. Does anyone have some sample code or tutorial that shows how to do in django? I'm new at this. Especially when it comes to the call back. I'm not sure i need to use an open iD client package to do this. Can this work with django? I appreciate any assistance https://identityserver4.readthedocs.io/en/latest/quickstarts/4_javascript_client.html?highlight=authority#add-your-html-and-javascript-files