Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to access an api in react js with axios on same server like django + react js
I have connected the frontend(ReactJS) with backend(python) using Django and axios. How can i post an Api on the Django app using axios from React JS? -
Django OTP TOTP - how to display QR code in template
I have successfully implemented two-factor-auth package to my web app however I would like to display QR code to a template when a user is logged in but am unable to do so as it stands. This package uses wizard forms and when a user is prompted to setup two factor the QR code is displayed during setup for them to scan on their chosen device but not sure how to use the QR code for later use in another template. I found the follwing piece of code from the wizard template which I tried to use but says page not found: <div class="d-flex justify-content-center"> <p><img src="{{ QR_URL }}" alt="QR Code" /></p> </div> Page not found error Using the URLconf defined in wfi_workflow.urls, Django tried these URL patterns, in this order: admin/ account/login/ [name='login'] account/two_factor/setup/ [name='setup'] account/two_factor/qrcode/ [name='qr'] The current path, account/two_factor/qrcode/, matched the last one. But I can view the QR code for users via Admin panel under: Otp_Totp TOTP devices Click on user and QRCode link is at the bottom of page Anyone know how to go about displaying the QR code only in another template? If more info is required do let me know. Thanks -
Django User Manager Not Checking Model Validators
I'm using a custom django user model. I have created everything and all seems perfect until I try to call the create_user from a registration page on the template. It is creating the user without taking the validators I have placed in the models into consideration. The validators are working just fine until I try to use the create_user action. def validate_reg(value): try: x = SignUpAccess.objects.get(reg_key=value) if x.is_used == True: raise ValidationError( message='Your validation number is used already', ) except SignUpAccess.DoesNotExist: raise ValidationError( message='Your validation number does not exist', ) class User(AbstractUser): username = None email = models.EmailField( unique=True, max_length=75, # db_index=True, primary_key=True, verbose_name='email address' ) reg_number = models.CharField( max_length=12, unique=True, null=True, validators=[validate_reg] ) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) date_joined = models.DateTimeField(default=timezone.now) REQUIRED_FIELDS = [] USERNAME_FIELD = 'email' objects = UserManager() As seen above I have added a validator in the registration number to make sure only those with a valid registration number can create an account on the site. This works perfectly when I try to create a user from admin (which is really pointless). As with custom user models, I have a user manager class UserManager(BaseUserManager): def create_user(self, … -
Cannot store user instance in the related model in django?
views.py def become_vendor(request): # vendorform = VendorCreationForm() vendordetailform = VendorAdminDetailsForm() if request.method == 'POST': # vendorform = VendorCreationForm(request.POST) vendordetailform = VendorAdminDetailsForm(request.POST, request.FILES) if vendordetailform.is_valid(): # if vendorform.is_valid(): # new_user = vendorform.save() print("hello") vendordetailform.instance.vendoruser = request.user print("hello1") request.user=vendordetailform.save() print("hello2") request.user.is_active = False request.user.save() user_details = CustomUser.objects.filter(id=request.user.id) vendor_details = user_details[0].vendor_details.all() return render(request,'vendor/preview.html', {'user_details':user_details, 'vendor_details':vendor_details}) else: # vendorform = VendorCreationForm() vendordetailform = VendorAdminDetailsForm() Here I save the user store details in the foreign key related model after the user logged in. Here I face issue in the line vendordetailform.instance.vendoruser = request.user. The user instance is not stored and user.is_active=False is not happening. the error is Cannot assign "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x00000158FEFB15B0>>": "VendorDetails.vendoruser" must be a "CustomUser" instance. -
JavaScript POST non-API request with repeated keys in payload
Javascript. POST request. It is not an API request (axios or fetch), but the old classical request. I need a payload like ...&_selected_action=5&_selected_action=10. So I think I cannot use a form submitting technique here. With a single occurence ...&_selected_action=5 I am able to do it, everything works well. For the repeated value I can create the string by hand or by URLSearchParams().toString() but I am not able to send it. Any idea? More details. I need create this request in Django+Vue application which partially replaces the old school Django Admin. The ListView is replaced using Vue and now I want to reuse the actions where Django Admin uses Post request formatted as above. So with single selected row in list I am able to do it, but with 2+ selected rows I cannot find a good way how to do it. -
Unauthorized: /auth/users/
i am using react in the frontend and Django in the backed and am trying to register user, but when I try creating new user I get error Unauthorized: /auth/users/ [02/Dec/2021 12:29:27] "OPTIONS /auth/users/ HTTP/1.1" 401 58 The frontend looks somewhat like this export const signup = (first_name, last_name, email, password, re_password) => async dispatch => { const config = { headers: { 'Content-Type': 'application/json' } }; const body = JSON.stringify({ first_name, last_name, email, password, re_password }); try { const res = await axios.post(`${process.env.REACT_APP_API_URL}/auth/users/`, body, config); dispatch({ type: SIGNUP_SUCCESS, payload: res.data }); } catch (err) { dispatch({ type: SIGNUP_FAIL }) } }; -
How to add a timepicker only in my django project?
I am new to django and web development. I want to implement a timepicker only for my website. I don't know how to add it to my models and forms? and how should I implement the timepicker whether using bootstrap or jquery. Is there any easy way to do that? forms.py from django import forms from .models import Post class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'content','chamber','address','fees','days','hours'] widgets = { 'hours':forms.DateField(widget=forms.DateInput(attrs={'class':'timepicker'})) } models.py class Post(models.Model): author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField('Doctor\'s Name',max_length=200) content = models.CharField('Specialty',max_length=200) chamber = models.CharField('Chamber\'s Name',max_length=200) address = models.CharField('Address',max_length=100) fees = models.IntegerField(default=0) days = myFields.DayOfTheWeekField() hours = models.DateField('Visiting Hours') liked = models.ManyToManyField( settings.AUTH_USER_MODEL, blank=True, related_name='liked') date_posted = models.DateTimeField(default=timezone.now) objects = PostManager() class Meta: ordering = ('-date_posted', ) def __str__(self): return self.title def get_absolute_url(self): return reverse('post_detail', kwargs={'pk': self.pk}) I want to add a timepicker in the hours fields and post it to the models too. Don't know what models.field should I use and what form since I am at the very beginning level of django The timepicker should look somewhat similar like this. -
User profile update using dj-rest-auth + allauth
I'm trying to implement authentication using dj-rest-auth library, Everything works fine up to now but when i try to update user it says user with same name exist. user/ is my url which give me a view with PUT and PATCH method. But bot are not working and if i change my username it updates. urls.py urlpatterns = [ # path('', views.login, name="login"), path('login/', LoginView.as_view()), path('logout/', LogoutView.as_view()), path('register/', RegisterView.as_view()), path('verify-email/', VerifyEmailView.as_view(), name='rest_verify_email'), path('account-confirm-email/', VerifyEmailView.as_view(), name='account_email_verification_sent'), path('account-confirm-email/<str:key>/', ConfirmEmailView.as_view()), re_path(r'^account-confirm-email/(?P<key>[-:\w]+)/$', VerifyEmailView.as_view(), name='account_confirm_email'), path('user/', UserDetailsView.as_view()), path('google/connect/', GoogleLogin.as_view(), name='google_connect') ] models.py USER_TYPE_CHOICE = ( ('admin', 'admin'), ('student', 'student'), ('instructor', 'instructor'), ) class CustomUser(AbstractUser): phone = models.CharField(max_length=12) user_type = models.CharField(max_length=20, choices=USER_TYPE_CHOICE, default='student') # class UserProfile(models.Model): # user = models.OneToOneField(CustomUser, related_name='userprofile', on_delete=models.CASCADE) # # custom fields for user # full_name = models.CharField(max_length=100) # profile_pic = models.ImageField() serializers.py from dj_rest_auth.serializers import UserDetailsSerializer, PasswordResetSerializer from rest_framework import serializers from django.conf import settings from allauth.account.adapter import get_adapter from allauth.account.utils import setup_user_email from dj_rest_auth.registration.serializers import RegisterSerializer from .models import * from allauth.account.forms import ResetPasswordForm, ResetPasswordKeyForm class CustomRegisterSerializer(RegisterSerializer): phone = serializers.CharField(required=True, max_length=100) def get_cleaned_data(self): data_dict = super().get_cleaned_data() data_dict['phone'] = self.validated_data.get('phone', '') data_dict['user_type'] = self.validated_data.get('user_type', '') return data_dict class CustomUserDetailsSerializer(UserDetailsSerializer): class Meta(UserDetailsSerializer.Meta): fields = UserDetailsSerializer.Meta.fields + \ ('phone', 'user_type', ) class CustomPasswordResetSerializer(PasswordResetSerializer): … -
Django rest framework - serializer for dictionary structured payload
I'm trying to create a Serializer for a payload that looks something like this - { "2fd08845-9b21-4972-87ed-2e7fd03448c5": { "operation": "Create", "operationId": "356f6501-a117-4c8d-98ce-dcb4344d481b", "user": "superuser", "immediate": "true" }, "fe6d0c85-0021-431e-9955-e8e1b1ebc414": { "operation": "Create", "operationId": "adcedb2f-c751-441f-8108-2c29667ea9cf", "user": "employee", "immediate": "false" } } I thought of using DictField, but my problem is that there isn't a field name. it's only a dictionary of keys and values. I tried something like: class UserOperationSerializer(serializers.Serializer): operation = serializers.ChoiceField(choices=["Create", "Delete"]) operationId = serializers.UUIDField() user = serializers.CharField() immediate = serializers.BooleanField() class UserOperationsSerializer(serializers.Serializer): test = serializers.DictField(child=RelationshipAuthorizeObjectSerializer()) But again, there isn't a 'test' field. -
Connecting mysql to django project [closed]
I am displaying some chart values through js file in the django project statically. I want my js to fetch it from mysql. What should I do? Thanks. -
Django: Renaming Models, M2M Table not renamed
TLDR: Models moved to a new app. After migrating M2M relation refers to table that does not exist. Previous M2M table was not renamed. Django Version: 3.2.3 Scenario: I am refactoring a Django application. In this process I have moved some models to a new app. To do so, I renamed the tables as described by Haki Benita, using SeparateDatabaseAndState. One of the models Studentsin the new app has a field with Many2Many relationship to another model Teachers (which I also moved to the new app). oldapp/migrations/000X_auto_XXX.py operations = [ ... migrations.SeparateDatabaseAndState( state_operations=[ migrations.DeleteModel( name='Students', ) ], database_operations=[ migrations.AlterModelTable( name='Students', table='newapp_students' ) ] ), migrations.SeparateDatabaseAndState( state_operations=[ migrations.DeleteModel( name='Teachers', ) ], database_operations=[ migrations.AlterModelTable( name='Teachers', table='newapp_Teachers' ) ] ), ... ] newapp/migrations/0001_initial.py operations = [ ... migrations.SeparateDatabaseAndState( state_operations=[ migrations.CreateModel( name='Teacher', fields=[...], options={...}, ) ], database_operations=[] ), migrations.SeparateDatabaseAndState( state_operations=[ migrations.CreateModel( name='Students', fields=[ ... ('teachers', models.ManyToManyField(blank=True,related_name='students', to='newapp.Teachers')), ... ], options={...}, ) ], database_operations=[] ), ... ] After running python manage.py migrate all the Models got renamed (so far so good).. Problem: The automatically generated table for Many2Many was not renamed (oldapp_students_teachers). However, the model in the new app refers to a table in the new app (newapp_students_teachers) that does not exist. I did some … -
Why is my static CSS file working fine but not javascipt in Django?
I'm new to Django. I'm trying to add a javascript for my navbar. Browser is reading static CSS file properly. But it looks like browser is ignoring my static javascript file. Here is my code: Settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] Index.html <html lang="en"> {% load static %} <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel='stylesheet' type='text/css' href="{% static 'style.css' %}"> <script type='text/javascript' src="{% static 'style.js' %}"></script> <title>{% block title %}{% endblock title %}</title> </head> To check whether javascript is working properly I have only put a alert box. But still it is not showing alert box. Config.js alert("Checking"); -
Static files from AWS not served when they contain a Django {{variable}}
I have a Django App, deployed on Heroku with AWS S3. All static and dynamic files are being served, except when the static file name contains a Django variable. <div class="sibling" id="left"> <a href="{% url 'showtree' sibling_left_id %}"> <img src="{%static '/img/siblingsLeftFrame'%}{{no_siblings_left}}.png"> </a> </div> The generated URL should be (for example): ...amazonaws.com/img/siblingsLeftFrame02.png But looks like this: ...amazonaws.com/img/siblingsLeftFrame?X-Amz-Algortihm=AWS-4-etc.(credentials, date etc.).png Locally it works, but on Heroku/AWS I get a 403 Response. Is this a CORS problem? Here are the settings: INSTALLED_APPS = [ ... "corsheaders", ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', ... ] CORS_ALLOW_ALL_ORIGINS = True -
Module not found un uwsgi.ini when setting up Django and Docker
I'm getting a weird error when trying to run a Django server in Docker with uWSGI, for some reason the configuration file can't pick up the path to Django's wSGI file. I've run the app with just the regular "runserver" and things work fine, so I'ts not t an issue with the Django app, rather with the configuration file and how it accesses the directories in the Docker environment. I've also tried running: docker system prune -a --volumes To make sure that there isn't a problem with a redundant structure of volumes that got into the way. The error message: web_container | Traceback (most recent call last): web_container | File "/code/./docker/projectile/projectile/wsgi.py", line 16, in <module> web_container | application = get_wsgi_application() web_container | File "/usr/local/lib/python3.9/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application web_container | django.setup(set_prefix=False) web_container | File "/usr/local/lib/python3.9/site-packages/django/__init__.py", line 19, in setup web_container | configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) web_container | File "/usr/local/lib/python3.9/site-packages/django/conf/__init__.py", line 82, in __getattr__ web_container | self._setup(name) web_container | File "/usr/local/lib/python3.9/site-packages/django/conf/__init__.py", line 69, in _setup web_container | self._wrapped = Settings(settings_module) web_container | File "/usr/local/lib/python3.9/site-packages/django/conf/__init__.py", line 170, in __init__ web_container | mod = importlib.import_module(self.SETTINGS_MODULE) web_container | File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module web_container | return _bootstrap._gcd_import(name[level:], package, level) web_container | ModuleNotFoundError: No module named … -
Django and DRF - checks for constraint before ID
In my Django project I use DRF. One of my models, Type, has a constraint; the name field should be unique. Another model, Project, relation to Type; a project always has a type. The serializer for Project has another relationship that I'd like to write in. For this purpose, ProjectSerializer implements WritableNestedModelSerializer from this package. Here's the problem: when making a new Project, one shouldn't also (be able to) create a new Type at the same time. However, it seems that Django does check if this would be allowed. This leads to an error, because when sending a Project object in a POST, it checks if the Type object given is allowed to be created before checking if it contains and ID field, indicating that it's using an already existing type. Because of this, I get an error that says the name field for the Type already exists, and I can't create the new project. How do I indicate that this isn't what I want? I could just remove the constraint on the name field in Type, but I do kind of want it there. Here is relevant code: class ProjectType(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=50, unique=True) is_active = … -
Django webpack Loader / webpack5 / vue3 cannot render main.js in production
I am trying to deploy my simple application with Django 3 backend and Vue 3 frontend. I am using webpack-loader and webpack5 but i am not able to get main.js file produced in vue3 by webpack. in Django settings CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = ("http://localhost:8080",) WEBPACK_LOADER = { 'DEFAULT': { 'CACHE': not DEBUG, 'BUNDLE_DIR_NAME': 'dist/', # must end with slash 'STATS_FILE': '/home/ytsejam/public_html/medtourism/medtourism/frontend/webpack-stats.json', 'POLL_INTERVAL': 0.1, 'TIMEOUT': None, 'IGNORE': [r'.+\.hot-update.js', r'.+\.map'], 'LOADER_CLASS': 'webpack_loader.loader.WebpackLoader', } } in webpack.config.json: module.exports = (env = {}) => { return { mode: 'production', devtool: 'source-map', entry: path.resolve(__dirname, './src/main.ts'), output: { path: path.resolve(__dirname, './dist/'), filename: "main.js", clean: true }, module: { rules: [ ... ] }, resolve: { ... }, plugins: [ new VueLoaderPlugin(), new BundleTracker({ filename: './webpack-stats.json', publicPath: 'http://localhost:8080/' }), new HtmlWebpackPlugin({ title: 'Production', }), ], devServer: { headers: { "Access-Control-Allow-Origin":"\*" }, hot: true, https: true, client: { overlay: true, }, } }; } In developer tools the request response is: Request URL: http://localhost:8080/main.js Referrer Policy: no-referrer-when-downgrade I have read all the documents, could not find a solution. can you help me ? Thanks -
can we get prefetch_related result in same queryset?
I don't want to query again from Model_B, can I get that result from same queryset? queryset = Model_A.objects.prefetch_related('Model_B') -
How to optimize creation of huge amount of objects in Django Models
I am trying to read a csv of 200k data and create Django models and save them using bulk_create but the model creations code (i.e. users_list.append(User(phone_number=phone_number) ) is taking too much time to create all the models, is there anyway to make it fast. -
File get closed once rest api return response
I am using threading to upload multiple files on S3 server but I am getting error I/o operation on closed file after my API returns the response, I don't want my API to wait for files to upload, I want to know why the file gets closed once it returns the response import threading class NewClass(APIView): def post(self, request): # doing_something threading.Thread(target=uploadDocs, args=(docList)).start() #docList eg. list of <InMemoryUploadedFile: file-sample_100kB.doc (application/msword)> return response({'status':True}) def uploadDocs(docList): for file in docList: print(file.closed) #prints false # suppose now api returns the response print(file.closed) #prints true S3_upload_doc(file) #fails to upload gives me error I/o operation on closed file -
List from django view past to template is not showing any elements
I have a problem in Django. I made the following view passing a list of errors and a length of the error list. The list of errors consists of strings. Output from printing it before passing it can be seen below. In my template I have the following code. But for some reason, the ordered list has no instances when rendering the page. I'm probably doing something wrong but cannot seem to figure out what. Any help would be really appreciated! -
How can I solve Django Heroku Deploy Issue?
I am trying to deploy my application on Heroku. Previously I tried with another application and it worked perfectly. But now it showing me an application error. I tried heroku logs --tail --app <my_app> and It shows my all log. This is my application Logs 2021-12-02T10:06:41.545537+00:00 app[web.1]: [2021-12-02 10:06:41 +0000] [9] [INFO] Worker exiting (pid: 9) 2021-12-02T10:06:41.724277+00:00 app[web.1]: [2021-12-02 10:06:41 +0000] [4] [WARNING] Worker with pid 9 was terminated due to signal 15 2021-12-02T10:06:41.738864+00:00 app[web.1]: [2021-12-02 10:06:41 +0000] [4] [INFO] Shutting down: Master 2021-12-02T10:06:41.738922+00:00 app[web.1]: [2021-12-02 10:06:41 +0000] [4] [INFO] Reason: Worker failed to boot. 2021-12-02T10:06:41.992312+00:00 heroku[web.1]: Process exited with status 3 2021-12-02T10:06:42.068312+00:00 heroku[web.1]: State changed from up to crashed 2021-12-02T10:06:45.375408+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=lproperty.herokuapp.com request_id=6e428a90-ba38-4d3f-8b0a-a469458e7dde fwd="13.213.118.202" dyno= connect= service= status=503 bytes= protocol=https 2021-12-02T10:06:45.754499+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=lproperty.herokuapp.com request_id=48a6a475-2745-45e1-844c-a6be90aef873 fwd="13.213.118.202" dyno= connect= service= status=503 bytes= protocol=https 2021-12-02T10:08:17.684518+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=lproperty.herokuapp.com request_id=f9b3efb8-2c1d-40d3-895a-5cc46994e8db fwd="13.213.118.202" dyno= connect= service= status=503 bytes= protocol=https 2021-12-02T10:08:18.110957+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=lproperty.herokuapp.com request_id=72825948-e67a-4e88-80a4-0672100e450f fwd="13.213.118.202" dyno= connect= service= status=503 bytes= protocol=https How can I solve this issue? -
How to sort data with depth-first processing pre order from django model in python?
I have a data in the database, if you convert to json the data would be like this: [{ 'id': 27, 'has_sub_topic': 1, 'name': '123123', 'xml_name': '123123', 'validated': 1, 'created_at': '2021-12-02 02:19:44.962043', 'updated_at': '2021-12-02 02:19:44.962043', 'last_editor_id': 2, 'parent_id': None, 'subject_module_level_id': 25, 'order': 1 }, { 'id': 34, 'has_sub_topic': 0, 'name': 'nosub', 'xml_name': 'nosub', 'validated': 1, 'created_at': '2021-12-02 02:19:44.962043', 'updated_at': '2021-12-02 02:19:44.962043', 'last_editor_id': 2, 'parent_id': None, 'subject_module_level_id': 25, 'order': 2 }, { 'id': 31, 'has_sub_topic': 1, 'name': 'asdasda', 'xml_name': 'asdasda', 'validated': 1, 'created_at': '2021-12-02 02:19:44.962043', 'updated_at': '2021-12-02 02:19:44.962043', 'last_editor_id': 2, 'parent_id': None, 'subject_module_level_id': 25, 'order': 3 }, { 'id': 28, 'has_sub_topic': 0, 'name': '11111', 'xml_name': '11111', 'validated': 1, 'created_at': '2021-12-02 02:19:44.962043', 'updated_at': '2021-12-02 02:19:44.962043', 'last_editor_id': 2, 'parent_id': 27, 'subject_module_level_id': 25, 'order': 1 }, { 'id': 29, 'has_sub_topic': 0, 'name': '2222', 'xml_name': '2222', 'validated': 1, 'created_at': '2021-12-02 02:19:44.962043', 'updated_at': '2021-12-02 02:19:44.962043', 'last_editor_id': 2, 'parent_id': 27, 'subject_module_level_id': 25, 'order': 2 }, { 'id': 32, 'has_sub_topic': 0, 'name': 'qweqwe', 'xml_name': 'qweqwe', 'validated': 1, 'created_at': '2021-12-02 02:19:44.962043', 'updated_at': '2021-12-02 02:19:44.962043', 'last_editor_id': 2, 'parent_id': 31, 'subject_module_level_id': 25, 'order': 1 }, { 'id': 33, 'has_sub_topic': 0, 'name': 'zxczxcz', 'xml_name': 'zxczxcz', 'validated': 1, 'created_at': '2021-12-02 02:19:44.962043', 'updated_at': '2021-12-02 02:19:44.962043', 'last_editor_id': 2, 'parent_id': 31, 'subject_module_level_id': 25, 'order': 2 }] … -
Social network failure apple signing
i have set up the apple signin in Django using SocialLoginView settings.py SOCIALACCOUNT_PROVIDERS = { "apple": { "APP": { # Your service identifier. "client_id": "com.test.web", # The Key ID (visible in the "View Key Details" page). "secret": "login with apple test", # Member ID/App ID Prefix -- you can find it below your name # at the top right corner of the page, or it’s your App ID # Prefix in your App ID. "key": "CCCDDDFAKE", "certificate_key": """-----BEGIN PRIVATE KEY----- dfdfdfddfdfjsdhfksdjfkljsdkfjsdlkfjksdlfjkdsjfkdjsfjdfkjdjfkjkdf MjqvQmfIotaSSRy/SkS9Kfagv/dkjfkjdfkjdfkjdkfjdkfjkdjfkjdfkjdfkjdf/s /Kd41Y03f1mDR8D5/dfdfdfdf+dfdfdfdfdf R3iwdyjH -----END PRIVATE KEY-----""" } } } views.py from allauth.socialaccount.providers.apple.views import AppleOAuth2Adapter,AppleOAuth2Client,AppleProvider from dj_rest_auth.registration.views import SocialLoginView as AppleLoginView class AppleLogin(AppleLoginView): adapter_class = AppleOAuth2Adapter callback_url = 'https://testssite.com/accounts/apple/login/callback' client_class = AppleOAuth2Client urls.py from django.urls import path, include from . import views urlpatterns = [ path('accounts/', include('allauth.urls')), path('login/', views.AppleLogin.as_view()), path("", views.index, name="index"), ] So far so good, if i go to mysite/accounts/apple/login i can provide my apple id. But then i get the message Social Network Login Failure Iam stuck with this, and dont know what is missing. -
How to change moderation in Django comments-xtd library
I have implemented comments xtd library in my blog however I am struggling with changing the moderation behavior. In order to see the page with comments, users must be logged in and I want to moderate all comments, also for logged-in users. For now, I see in the admin panel that is_public is by default True if the user posts a comment. How to change to False by default so the moderator has to accept the comment before publishing it? -
How to retrieve object with lookup field in Django Rest through React?
I am using the Django Rest framework as an API and React for front-end. I have everything configured to display React through Django. And everything works in development. However when using the production build I run in to an issue when trying to retrieve a single object from the database using 'slug' as the lookup field. For example I can make a call using the id field axiosInstance .get('/articles/1') which targets this view class ArticleViewSet(viewsets.ModelViewSet): ... and returns the desired article. However when I change the lookup field to 'slug' # views.py class ArticleViewSet(viewsets.ModelViewSet): lookup_field = 'slug' ... # serializers.py class ArticleSerializer(serializers.Serializer): class Meta: ... lookup_field = 'slug' and the axios call to console.log(slug) # Logs "article-1" as it should axiosInstance .get(`/articles/${slug}`) # This results in /articles/article-1 Then the index.html file is returned to me. The ArticleViewSet's retrieve method never even gets called. What's more strange is that I can still view the article using a slug by going directly to the api with, for example "localhost:8000/articles/article-1" in my browser. This returns the desired article. How can I call the retrieve method using a slug with the production build? Any help is much appreciated, thank you.