Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django SQLite3, attempt to write a readonly database
Im using sqlite3 as a database to my project, it's working when i manually serve a temporary port by typing python manage.py runserver however the exception throws after deploying in apache server shown in figure below. at first i thought this is a file permission issue and when i ran commands in django e.g. python manage.py runserver, python manage.py mycommand, python manage.py createsuperuser the error not occur and working but when i use the designated port that i created in /etc/apache2/sites-enabled/000-default.conf the error comes. I am using ubuntu 20.04 and apache 2.4.41 as my environment and the virtual host configuration below is my port designate to my project. Listen 112 <VirtualHost *:112> Alias /assets /home/yuan04/Projects/Lotto/assets <Directory /home/yuan04/Projects/Lotto/assets> Require all granted </Directory> <Directory /home/yuan04/Projects/Lotto/lotto> <Files wsgi.py> Require all granted </Files> <Files db.sqlite3> Require all granted </Files> </Directory> WSGIDaemonProcess lotto python-home=/home/yuan04/Projects/Lotto/venv python-path=/home/yuan04/Projects/Lotto WSGIProcessGroup lotto WSGIScriptAlias / /home/yuan04/Projects/Lotto/lotto/wsgi.py </VirtualHost> -
django app is not able to find a url using slugs
I have a simple blog app that has a blog home and the details. I am using slug for detail URLs and prepopulating the slug field with the post title. everything works fine local but after I deployed the app online, when I click the post to go to its' blog detail it won't find the page. this is my post models: class PostManager(models.Manager): def get_queryset(self): return PostQuerySet(self.model, using=self._db) def search(self, query=None): return self.get_queryset().search(query=query) class Post(models.Model): objects = PostManager() title = models.CharField(max_length=150) paragraph = models.TextField(blank=True) published = jmodels.jDateField() tags = TaggableManager() slug = models.SlugField(max_length=200, unique=True, allow_unicode=True) def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Post, self).save(*args, **kwargs) this is my urls: path('maghaalaat/', views.MaghaleMain.as_view(), name="blog-page"), path('maghaalaat/tags/<slug:tag_slug>/', views.MaghaleTags.as_view(), name="tagged"), re_path(r'maghaalaat/(?P<the_slug>[-\w]+)/', views.MaghaleDetail.as_view(), name='post-detail'), this is my views: class MaghaleMain(ListView): model = MaghaalaatPost template_name = 'Blog/Blog-elmi.html' queryset = MaghaalaatPost.objects.all() context_object_name = 'posts' ordering = ['-published'] paginate_by = 3 def get_context_data(self, **kwargs): context = super(MaghaleMain, self).get_context_data(**kwargs) context['tags'] = MaghaalaatPost.tags.all() return context class MaghaleTags(ListView): model = MaghaalaatPost template_name = 'Blog/Blog-elmi.html' context_object_name = 'posts' def get_queryset(self): return MaghaalaatPost.objects.filter(tags__slug=self.kwargs.get('tag_slug')) def get_context_data(self, **kwargs): context = super(MaghaleTags, self).get_context_data(**kwargs) context['tags'] = MaghaalaatPost.tags.all() return context class MaghaleDetail(DetailView): model = MaghaalaatPost template_name = 'Blog/Blog-elmi-detail.html' context_object_name = 'maghaale' slug_url_kwarg = 'the_slug' slug_field = 'slug' def … -
Adding foreign_key on before_import
I have a model, which has two foreign keys that are not technically part of the CSV. The customer model should be a foreign key of monthly_bill but the CSV only contains customer information instead of dumping everything on monthly_bill, I extracted the customer info into a separate table. So Ideally I need to do a get_or_create. The other field is just a company that should be derived from the token of the user that uploaded the CSV. I tried overriding the before_import_row and before_import but it still says null-constraint on customer_id. I did do it like this row["customer_id"] = customer.id but still nothing. Any ideas? Here is the snippet of my before_import def before_import(self, dataset, using_transactions, dry_run, **kwargs): for row in dataset.dict: """ Get the correct organization """ # TODO: should be dynamic organization = Organization.objects.get(name="JBA") account_number = row.get("account_number") name = row.get("customer_name") address_line_1 = row.get("address_line_1") address_line_2 = row.get("address_line_2") city = row.get("city") state = row.get("state") zip_code = row.get("zip") property_size = row.get("lot_size") customer, created = Customer.objects.get_or_create( name=name, account_number=account_number, defaults={ "name": name, "organization": organization, "account_number": account_number, "address_line_1": address_line_1, "address_line_2": address_line_2, "city": city, "state": state, "zip_code": zip_code, "property_size": property_size } ) row["organization_id"] = organization.id row["customer_id"] = customer.id return dataset -
Adding a second or multiple device for a user django two factor authentication
I am using two-factor authentication for a django project. It is working fine but I want to implement few more features in my code. But I am unable to implement Expected Behavior: I want that a user has to face a 2F authentication prompt whenever the user logins from a new device. Also I want to increase code validation time. Current Behavior: Currently, if a user logins for the first time, the user is shown an authentication prompt. But when the user logins from a new device, the user is not shown an authentication and easily logs in. But I want that the user has to face 2F from every new device. Also Whenever I change step the validate code does not valid. For example if i give step=60, then the validation code get invalid. I am unable to increase time for code validation. I checked TOTPDevice model in the database. It shows that now new key is not generating for new device. I am using the below codes. def get_user_totp_device(self, user, confirmed=None): """ Gets user's time based one time password devices """ devices = devices_for_user(user, confirmed=confirmed) for device in devices: if isinstance(device, TOTPDevice): return device class TOTPCreateView(APIView): permission_classes = … -
Is it possible to create login in Django with HTML forms?
I am new to Django and I am creating a simple register and login functionality. I followed a youtube tutorial where the person used Django forms. I am trying to use just HTML forms for login and registration. The registration part is done and I see data on admin url. For login I am getting None on this line: user = authenticate(request, username=username, password=password) Which is why I am not able to pass the if user is not None condition. Can anyone help? Here is the code: This is the register part: def createUser(request): if request.method == 'POST': if request.POST.get('username') and request.POST.get('password'): post = FormDetails() post.register_email = request.POST.get('username') post.register_pass = request.POST.get('password') post_save = post.save() print("data posted and saved") return redirect('login') messages.success( request, f'Your account has been created ! You are now able to log in') return render(request, 'users/register.html') FormDetails is my model with email and password field(That's why i am seeing the password as plain text in admin page). The login is: def loginScreen(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') print("username={}".format(username)) user = authenticate(request, username=username, password=password) print("user={}".format(user)) if user is not None: login(request, user) messages.success(request, f' welcome {username} !!') print("here") return HTTPResponseRedirect('index') else: messages.info(request, f'account done … -
How can I delete a request.session variable inside the Django HTML template?
Code: {% if request.session.message %} <div class="alert alert-warning alert-dismissible fade show" role="alert"> <i class="bi bi-check2-circle"></i> {{request.session.message}} <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> </div> {% endif %} {% request.session.remove('message') %} Error: TemplateSyntaxError at / Could not parse the remainder: '('message')' from 'request.session.remove('message') -
NoReverseMatch at /edit_profile/ Reverse for 'profile' with no arguments not found. 1 pattern(s) tried: ['profile/(?P<username>[^/]+)$']
I am trying to build a blog website. In the profile update section I am getting this error. NoReverseMatch at /edit_profile/ Reverse for 'profile' with no arguments not found. 1 pattern(s) tried: ['profile/(?P[^/]+)$'] I understand the error but I don't know how solve it. Please help me. models.py: from django.db import models from django.contrib.auth.models import User from PIL import Image GENDER = ( (None, 'Choose your gender'), ('male', 'Male'), ('female', 'Female'), ('custom', 'Custom'), ('Prefer Not To Say', 'Prefer Not To Say'), ) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='profile_default.png', upload_to= 'profile_pics') bio = models.TextField(max_length=50, blank=True) gender = models.CharField(max_length=50, choices=GENDER, verbose_name="gender", blank=True) def __str__(self): return f'{self.user}\'s Profile' def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.width > 300 or img.height > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) forms.py class UserEditForm(forms.ModelForm): first_name = forms.CharField(label='Full Name' ,max_length=150) email = forms.EmailField() class Meta: model = User fields = ['first_name', 'username', 'email'] class EditProfileForm(forms.ModelForm): class Meta: model = Profile fields = ['gender','image', 'bio'] widgets = { forms.Select(attrs={'class': 'custom-select md-form'}) } urls.py urlpatterns = [ path('admin/', admin.site.urls), # post_stuff urls path('', include('post_stuff.urls')), # user urls path('signup/', user_views.signup, name='signup'), path('login/', user_views.Login.as_view(template_name='user/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='user/logout.html'), name='logout'), path('profile/<str:username>', user_views.profile, name='profile'), path('edit_profile/', user_views.edit_profile, name='edit_profile') ] … -
url path is matching the wrong view in drf viewsets
Django beginner here, I have two similar endpoints as shown below, they differ in their url_path of the action decorator and the request parameters requester_id and approval id The problem both /workflow_approvals/{requester_id}/ and /workflow_approvals/{approval_id}/ are routing to the requester method view(the first below) @action(methods=['GET'], detail=False, serializer_class=WorkflowRequesterActivitySerializer, url_path='(?P<requester_id>[^/.]+)') def requester_activities(self, request, requester_id, pk=None): try: approval = WorkflowApproval.objects.filter(requester=requester_id).first() if approval is None: return Response({'success': False, 'errors': 'No workflow for specified requester'}, status=status.HTTP_404_NOT_FOUND) activities = WorkflowActivity.objects.filter( workflowapproval=approval ) serializer = self.get_serializer(activities, many=True) return Response({'success': True, 'data': {'total_count': activities.count(), 'activities': serializer.data}}, status=status.HTTP_200_OK) except Exception as e: return Response({'success': False, 'errors': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) @action(methods=['GET'], detail=False, serializer_class=WorkflowActivitySerializer, url_path='(?P<approval_id>\w+)',) def approval_activities(self, request, approval_id, pk=None): try: approval = WorkflowApproval.objects.filter(id=approval_id).first() if approval is None: return Response({'success': False, 'errors': 'Workflow Approval does not exist'}, status=status.HTTP_404_NOT_FOUND) activities = WorkflowActivity.objects.filter( workflowapproval=approval) serializer = self.get_serializer(activities, many=True) return Response({'success': True, 'data': {'total_count': activities.count(), 'activities': serializer.data}}, status=status.HTTP_200_OK) except Exception as e: return Response({'success': False, 'errors': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) my urls.py file looks like this from django.urls import include, path from rest_framework.routers import DefaultRouter from .views import WorkflowApprovalsViewset app_name = "workflow_approvals" router = DefaultRouter() router.register("", WorkflowApprovalsViewset) urlpatterns = [ path("", include(router.urls)), ] -
How to sort by decending order in django by timestamp
Model.py createdAt = models.DateTimeField(auto_now_add=True) views.py @api_view(['GET']) def getProducts(request): products = Product.objects.all() serializer = ProductSerializer(products, many=True) return Response(serializer.data) So how can I sort this product list by decending order so that there show latest products -
Handle Paypal Payments/Checkout in a Django Rest Framework
I want to implement payment/checkout, preferably the user stays on my website (Angular frontend). I have been wandering around the docs of paypal for weeks, and googling too, but I don't seem to find an EFFECIENT way to do it (lack of drf tutorials and guides). I also have seen django-payments, django-paypal, dj-paypal. but none of them has a clear docs about an integration with DRF... I feel like I'm lost here. any help? hints? -
username saving as null in django custom model
when i am sending post request to register new user from postman, username saves as blank/dash . why username saving as blank i dont get it. but when i add from django admin it saves correctly. here is postman image postman post request image and here is the result django result after sending post request Custom Account Manager class CustomAccountManager(BaseUserManager): def create_superuser(self, email, username, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_active', True) other_fields.setdefault('is_admin', True) other_fields.setdefault('is_superuser', True) if other_fields.get('is_staff') is not True: raise ValueError( 'Superuser must be assigned to is_staff=True.') if other_fields.get('is_superuser') is not True: raise ValueError( 'Superuser must be assigned to is_superuser=True.') return self.create_user(email, username, password, **other_fields) def create_user(self, email, username, password, **other_fields): if not email: raise ValueError(_('You must provide an email address')) if not username: raise ValueError(_('You must provide an username')) if " " in username: raise ValueError(_('Username should not contain space')) email = self.normalize_email(email) user = self.model(email=email, username=username, **other_fields) user.set_password(password) user.save() return user Custom User Model class NewUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True, null=False, blank=False) username = models.CharField(max_length=150, unique=True, null=True) first_name = models.CharField(max_length=150, blank=True) objects = CustomAccountManager() # more class Meta: verbose_name = 'NewUser' USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] def __str__(self): return str(self.username) model serializer class RegisterNewUserSerializer(serializers.ModelSerializer): class … -
I can't upload files on MySQL server while using Firebase APIs and it shows: V/FA: Inactivity, disconnecting from the service
I'm working on Firebase real time database and APIs. But in the same activity, I tried to upload files on MySQL database, but it didn't work at all, just with showing this log: V/FA: Inactivity, disconnecting from the service. Other APIs worked but just I can't upload files on server in the same case. Can you please help me? -
Understanding Django (Python) and databases
new to Django and hope someone can help me understand. I see how in Django you can set up models that become tables in say PostgreSQL. Great. What approach should I use where the schema and tables already exist in a database? I don't want to change the tables in anyway but use the data in views. I would normally think 'make an SQL statement to return the data I want and join tables where needed'. Lets say the tables are Orders and Customers and I would use an SQL: SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate FROM Orders INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID; What is the approach for: the abstraction in django for this SQL any best practices makemigrations / migrate so I don't interfere with the source tables but keep my models up to date in the DB join to a table that is a django model? Much appreciated! -
Upload multiple files Django
models.py file_1 = models.FileField(blank=True, upload_to='PN_files/%Y/%m/%d/', verbose_name="File 1", validators=[validate_file_size], help_text="Allowed size is 50MB") views.py class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['title', 'file_1'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) HTML code: <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Fill the form</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Submit</button> </div> </form> I use this code to upload a file in my form. Now I need to upload multiple files, but when I follow the examples on Django Uploading multiple files, I can't get it to works. My views.py now looks like (and none of 3 examples work for me): class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['title', 'file_1'] def form_valid(self, form): form.instance.author = self.request.user widgets = {'file_1': form.ClearableFileInput(attrs={'multiple': True})} form.instance.file_1 = form.FileField(widget=form.ClearableFileInput(attrs={'multiple':True})) form.instance.file_1 = form.FileField(widget=form.FileInput(attrs={'multiple': True})) return super().form_valid(form) -
get dictionary value sent from Django in Vuejs row
I have used Django to develop a web app. The front end is vuejs. I want to render the dictionary in vuejs table. I have tried to access the dictionary using the dictionary name in vue, but failed to get the vaule. view.py: def Browse_and_adopt(request): query_results_book = Title.objects.values() return render(request, 'main.html', { "query_results_book": query_results_book }) HTML: <div id="app"> &emsp;&nbsp;Search: <input type="text" placeholder="By title, iSBN, VBID, publisher, Author, course code" v-model="filter" size="45"/> <br> <table> <thead> <tr> <th>Course Material Title</th> <th>Author/Editor</th> <th>Edition</th> <th>Publisher</th> <th>iSBN</th> <th>e-iSBN/VBID</th> <th>Category</th> <th>Material Format</th> <th>Distribution Mode</th> <th>Course Codes using title</th> <th>Adopt: Course Code</th> <th>Adopt: Starting Semester</th> </tr> </thead> <tbody data="{{ json_data }}"> <tr v-for="(row, index) in filteredRows" :key="`iSBN-${index}`"> <td>{{ row.title }}</td> <td>{{ row.author }}</td> </tr> </tbody> </table> </div> <script> const app = new Vue({ el: '#app', data: { filter:'', rows: [ { title: query_results_book.title, author: query_results_book.author } ] }, query_results_book: { type: Object, required: true, }, }); In this line: title: query_results_book.title, I get error: query_results_book not defined. How to pass my dictionary to row in vue? -
how to change two dates to number of days and hours jango
i'm trying to change two dates check_in and check_out to days and hours my models.py check_in = models.DateTimeField(default=datetime.now) check_out = models.DateTimeField() i tried this check_in_date = obj.check_in check_out_date = obj.check_out days = check_in_date - check_out_date day = days.days hour = days.seconds / 60 for the day it works as i expect except that when i select this two dates check_in=05-07-2021 04:46 PM to check_out=05-07-2021 10:46 PM i want to show 0 days 6 hours but it show 1 days 1080.0 hours ! is it possible to return such date format -
Django Paypal: 'VALIDATION_ERROR' 'MALFORMED_REQUEST_JSON'
I am trying to verify my webhooks but i am getting a key error: verification_status. This is because the response of the api call is giving an error instead of the json dump i should be getting. The error from the response is {'name': 'VALIDATION_ERROR', 'message': 'Invalid request - see details', 'debug_id': 'd303f5f9323d6', 'details': [{'field': '/webhook_event', 'location': 'body', 'issue': 'MALFORMED_REQUEST_JSON'}], 'links': []} which shows that the error is in the webhook event i think. What do i have to change to fix this? headers = { "Content-Type": "application/json", "Authorization": bearer_token, } print(request.body) print('') data = { "auth_algo": request.headers["PAYPAL-AUTH-ALGO"], "transmission_id": request.headers["PAYPAL-TRANSMISSION-ID"], "transmission_sig": request.headers["PAYPAL-TRANSMISSION-SIG"], "transmission_time": request.headers["PAYPAL-TRANSMISSION-TIME"], "webhook_id": id_is_here, "webhook_event": request.body, "cert_url": request.headers["PAYPAL-CERT-URL"], } data["webhook_event"] = data["webhook_event"].decode("utf-8") print(data["webhook_event"]) response = requests.post('https://api-m.sandbox.paypal.com/v1/notifications/verify-webhook-signature', headers=headers, json=data).json() print('worked') print(response) if response["verification_status"] == "SUCCESS": print('success') if [i["event_type"] for i in request.body] == "BILLING.SUBSCRIPTION.CREATED": print('sub created') elif [i["event_type"] for i in request.body] == "BILLING.SUBSCRIPTION.CANCELLED": print('sub cancelled') -
How to make the user able to filter on certain field in a model (Django)
Say I have a model of cars #models.py class Car(models.Model): user = models.ForeingKey(settings.AUTH_USER_MODEL, on_delete = models.CASCADE) n_doors = models.IntegerField(default=5) name = models.CharField(max_length=16) and a user has created 6 Car, where 3 have 5 doors, 2 have 4 doors and 1 have 1 door. Is there a way I can let the user filter on, say, n_doors either by a choice-list of available numbers ([5,4,1]), or by letting the user write numbers theirself? -
Django Values + Annotate Avg() doesn't group properly
I am stuck into this obviously basic issue, it feels I am missing something obvious to make this work properly. My db model is: class Review(models.Model): SCORE_CHOICES = [(1, '1'), (2, '2'), (3, '3'), (4, '4'), (5, '5')] user = models.ForeignKey(get_user_model(), related_name="reviews_by_user", on_delete=models.CASCADE) recipe = models.ForeignKey(Recipe, related_name="reviews_by_recipe", on_delete=models.CASCADE) score = models.IntegerField(choices=SCORE_CHOICES) date_created = models.DateTimeField(default=timezone.now) def __str__(self): return f"{self.user} rated {self.recipe} with {self.score}" class Meta: ordering = ['-date_created'] I am trying to group by recipe counting avg review score. This approach feels to work fine but it doesn't: Review.objects.values('recipe').annotate(Avg('score')) as result i get: <QuerySet [{'recipe': 1, 'score__avg': 5.0}, {'recipe': 1, 'score__avg': 5.0}, {'recipe': 2, 'score__avg': 4.0}, {'recipe': 2, 'score__avg': 3.0}, {'recipe': 5, 'score__avg': 3.0}, {'recipe': 5, 'score__avg': 2.0}]> Which is absolutely weird for me. I've gone through the Django Aggregation documentation but can't find any restrictions or special clauses that could help to understand what I am missing. Please let me know if someone has an idea of what's going on. -
Django Crispy Forms does not use specified template pack
I have a Django project where I use django-crispy-forms to style my forms. (I use {{ form|crispy }} in my template file to insert the template) Works perfectly fine. Now I upgraded from Bootstrap 4 to Bootstrap 5 and wanted to update my forms accordingly. I pip installed crispy-bootstrap5 (package recommended on django-crispy-forms GitHub) and added "crispy_bootstrap5" to INSTALLED_APPS as well as added CRISPY_ALLOWED_TEMPLATE_PACKS = "bootstrap5" and CRISPY_TEMPLATE_PACK = "bootstrap5" to my settings.py file. All according to crispy-bootstrap5's GitHub Page. But nothing changed. It still renders the same html as before. Maybe you can help me with getting that to work. Thank you. -
how do you identify a user every time they load up the page in React, Django rest framework web app
So usually in regular Django you can identify a user doing request.user but in django rest framework and in a completely separated frontend and backend how do you identify a user when a frontend makes a request to the backend? So lets just say I'm using react and I have an access JWT token in my localStorage and and the user object in my state. Should I just make a useEffect hook and call fetch and make a POST request in it before the component loads? and if I did, should I fetch out the user object or the access token? Or maybe there's other way of doing this? -
How to create a nice post form like the ones in forum or in stack overflow?
I am currently building a forum app in my website from scratch with django. I am quite happy with the result so far however I want to improve it. So far, when users want to post a message they need to fill a simple text form : my app Because it's only a simple text field, users can not use emojis, images or add links and the layout looks terrible. It does not look pro and any other forum would embbed a richer message form. How can I make it look like the one from stack overflow ? : my goal Thanks in advance. -
Getting a specific field (e.g. name) instead of pk in object_list for rendering
I have an app for example: class example(models.Model, TemplateHelperClass): reviewer = CharField(max_length=255, verbose_name="Title") book = ForeignKey(books, on_delete=models.PROTECT) review = TextField() ... class books(models.Model, TemplateHelperClass): author = CharField(max_length=255, verbose_name="Author") book_title = CharField(max_length=255, verbose_name="Title") publisher = CharField(max_length=255, verbose_name="Author") def __str__(self): return self.book_title ... class templateHelperClass(): paginate_by = 15 def get_fields(self): return [(field, field.value_to_string(self)) for field in self._meta.fields] *views.py* class bookReviewList(ListView): model = example template_name = "bookreviews.html" ... *bookreviews.html* {% extends "base.html" %} {% block content %} <table class="table"> <thead> <tr> {% for fld, val in object_list.0.get_fields %} <th>{{ fld.verbose_name |title }}</th> {% endfor %} <th></th> </tr> </thead> <tbody> {% for object in object_list %} <tr> {% for fl1, val1 in object.get_fields %} <td>{{val1}}</td> {% endfor %} <td><a class="btn btn-dark" href='{{ object.get_absolute_url }}'>Update</a></td> </tr> {% endfor %} </tbody> </table> {% endblock %} The output html displays the pk for the book, and not the book title (the __str__ method) in this case. I'd like to display the __str__ method. Two questions, both related: (1) Is there a more elegant way to represent the form with my attributes in table format. (I'm using bootstrap for some of the formatting) (2) If not, how do I get the foreignkey field to display the __str__ return … -
Django + django-oauth-toolkit: How to Register OpenIdConnect Endpoints?
How can I access OpenId Connect endpoints in a django + oauth environment? I'm trying to set up a Django (3.2.5) env with OAuth v2 + OpenId Connect using django-oauth-toolkit (1.5.0). I was able to follow the tutorials, which means that I have oauth support. I'm able to get Oauth tokens, and protect endpoints with them. But when I try to configure OpenId Connect, I'm unable to access o/.well-known/... end-points, they simply are not registered. I get a HTTP 404, and the debug page shows that django only knows about o/authorize/, o/token/, and o/revoke-token/. OpendId Connect section seems to imply I don't need to do anything else but enable OpenId for those views to appear. My urls.py looks like: oauth2_endpoint_views = [ path('authorize/', oauth2_views.AuthorizationView.as_view(), name="authorize"), path('token/', oauth2_views.TokenView.as_view(), name="token"), path('revoke-token/', oauth2_views.RevokeTokenView.as_view(), name="revoke-token"), ] urlpatterns = [ path('admin/', admin.site.urls), re_path('^accounts/', admin.site.urls), path('o/', include((oauth2_endpoint_views, 'oauth2_provider'), namespace="oauth2_provider")), path('api/hello', ApiEndpoint.as_view()), # an example protected resource endpoint path('api/secret', secret_page, name='secret'), # requires authentication ] As a part of OAuth config I already Added oauth2_provider to settings.INSTALLED_APPS. Added oauth2_provider.middleware.OAuth2TokenMiddleware to settings.MIDDLEWARE. Added django.contrib.auth.backends.ModelBackend, oauth2_provider.backends.OAuth2Backend, django.contrib.auth.backends.ModelBackend to settings.AUTHENTICATION_BACKENDS. Since this is a testing env, CORS_ORIGIN_ALLOW_ALL is set to True. Added path('o/', include((oauth2_endpoint_views, 'oauth2_provider'), namespace="oauth2_provider")) to `urls. Registered a … -
Django Many-To-One IntegrityError
I am new to Python and Django. I created database due to documents. I tested it and there has been error to many-to-one relationship between two models. It looks weird to me because It works like one to one relationship between those classes but it gives error if I try to add many. There are other classes with same relationship as many-to-one. I created same way and they work just fine. I am using sqlite by the way. class unites (models.Model): id = models.IntegerField(primary_key=True) unitename = models.CharField(max_length=128) class intensivecare_forms (models.Model): id = models.IntegerField(primary_key=True) hospitals_id = models.ForeignKey(hospitals, on_delete=models.CASCADE) formname = models.CharField(max_length=128) data = models.JSONField() unites_id = models.ForeignKey(unites, on_delete=models.CASCADE) It gives this error if I try to add second form into unites. IntegrityError at /admin/LocalManager/intensivecare_forms/add/ UNIQUE constraint failed: LocalManager_intensivecare_forms.unites_id_id Request Method: POST Request URL: http://localhost:8000/admin/LocalManager/intensivecare_forms/add/ Django Version: 3.2.4 Exception Type: IntegrityError Exception Value: UNIQUE constraint failed: LocalManager_intensivecare_forms.unites_id_id Exception Location: /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py, line 423, in execute Python Executable: /Library/Frameworks/Python.framework/Versions/3.9/bin/python3 Python Version: 3.9.6