Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do i set attributes on a single option of a CheckboxSelectMultiple ChoiceWidget in django?
I have a django app with multiple choice questions and answers. The unanswered answers are stored as BooleanFields in a database table and rendered as a form to be answered by the user. When the user has answered the multiple choice question, the question with the given answers is to be displayed again to show if each single multiple choice option was correct or incorrect answered. Thus, we need to tag each single generated CheckboxWidget widget with a special css attribute so the correctness of the answer can be properly styled in the output html to give visual feedback to the user. models.py from django.db import models ... class SchulungsEinheitTestergebnis(models.Model): """ Schattentabelle eines Testergebnisses einer Frage eines Schulungseinheittestes """ id = models.AutoField('ID', primary_key=True, db_column='sete_id') schulungseinheittest = models.ForeignKey(SchulungsEinheitTest, db_column='set_id', on_delete=models.CASCADE, null=True, default=None, blank=True) frage = models.ForeignKey(Frage, db_column='frg_id', on_delete=models.SET_NULL, null=True, default=None, blank=True) antworten = models.ManyToManyField(Antwort, blank=True, help_text='Gegebene Antworten', related_name='set_set', forms.py from django import forms from django.forms.widgets import CheckboxSelectMultiple class TestErgebnisFormMehrfach(forms.ModelForm): class Meta: model = SchulungsEinheitTestergebnis fields = ('id', 'frage', 'antworten') widgets = { 'frage': FrageWidget, 'antworten': CheckboxSelectMultiple } def __init__(self, *args, **kwargs): super(TestErgebnisFormMehrfach, self).__init__(*args, **kwargs) if self.instance: if self.instance.frage: self.fields['antworten'].queryset = self.instance.frage.antwort_set.all() class TestErgebnisFormMehrfachErgebnis(TestErgebnisFormMehrfach): def __init__(self, *args, **kwargs): super(TestErgebnisFormMehrfachErgebnis, self).__init__(*args, **kwargs) self.fields['antworten'].disabled … -
IntegrityError at /join/join_create/ NOT NULL constraint failed: zeronine_join.product_code
I am a student who is studying Django for the first time. I am currently experiencing the same error as the title. How do I resolve these errors? If I press the join button, I want to save the product information in the DB, is there anything wrong with my code? I'd appreciate it if you could give me an answer. join/views.py def join_create(request): product = Product.objects.all() categories = Category.objects.all() if request.method == "POST": join = Join() join.product_code = request.GET.get('product_code') join.username = request.user join.part_date = request.GET.get('part_date') join.save() return render(request, 'zeronine/detail.html', {'product': product, 'categories':categories}) zeronine/views.py def product_in_category(request, category_slug=None): current_category = None categories = Category.objects.all() products = Product.objects.all() designated_object = Designated.objects.filter(rep_price='True') if category_slug: current_category = get_object_or_404(Category, slug=category_slug) products = products.filter(category_code=current_category) return render(request, 'zeronine/list.html', {'current_category': current_category, 'categories':categories, 'products':products, 'designated_object': designated_object}) def product_detail(request, id, product_slug=None): current_category = None categories = Category.objects.all() products = Product.objects.all() product = get_object_or_404(Product, product_code=id, slug=product_slug) options = Option.objects.all() values = Value.objects.all() designated_object = Designated.objects.filter(rep_price='True') return render(request, 'zeronine/detail.html', {'product':product, 'products':products, 'current_category': current_category, 'categories':categories, 'designated_object': designated_object, 'options':options, 'values':values}) join/urls.py from django.urls import path from .views import * urlpatterns = [ path('join_create/', join_create, name='join_create'), ] models.py class Join(models.Model): join_code = models.AutoField(primary_key=True) username = models.ForeignKey(Member, on_delete=models.CASCADE, db_column='username') product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code') part_date = … -
Django Oscar Image saved in cache folder but not showing
Could anyone point me the direction to solve the image not displaying properly, since the image was saved in cache folder with 500 error. I am not sure if it is to due to permission or something deeper? This is what I had configure but not sure if I doing it right. URLS.py: from django.apps import apps from django.urls import include, path from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from oscar.views import handler403, handler404, handler500 urlpatterns = [ path('admin/', admin.site.urls), path('', include(apps.get_app_config('oscar').urls[0])), ] if settings.DEBUG: import debug_toolbar # Server statics and uploaded media urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # Allow error pages to be tested urlpatterns += [ path('403', handler403, {'exception': Exception()}), path('404', handler404, {'exception': Exception()}), path('500', handler500), path('__debug__/', include(debug_toolbar.urls)), ] Setting.py: # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') MEDIA_ROOT = '/media/' MEDIA_URL = '/media/' THUMBNAIL_DEBUG = DEBUG THUMBNAIL_KEY_PREFIX = 'oscar-sandbox' THUMBNAIL_KVSTORE = env( 'THUMBNAIL_KVSTORE', default='sorl.thumbnail.kvstores.cached_db_kvstore.KVStore') THUMBNAIL_REDIS_URL = env('THUMBNAIL_REDIS_URL', default=None) STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) -
I am working on python django and have a registration form there are fields like username email password want to check if exists
I have a html form where there are fields like username, email, password I want to check individually if username exists or not by entering username also email exists or not by entering email in the html form also check both at same time if both exists or not the code I have written for this is not working for single field what I meant is if I enter only username it says username is taken also email is taken But I don't want that I want individually they exists or not and if I enter both existing email and username it should say email is taken and username is taken by displaying message. How can I modify the code to work like that This is my views.py code def Register(request): try: if request.method == 'POST': username = request.POST.get('username') email = request.POST.get('email') password = request.POST.get('password') try: email_taken = User.objects.filter(email=email).exists() username_taken = User.objects.filter(username=username).exists() if email_taken: messages.error(request,"Email is taken.") if username_taken: messages.error(request,"Username is taken.") if email_taken or username_taken: return redirect('/register/') user_obj = User(username = username , email = email) user_obj.set_password(password) user_obj.save() profile_obj = Profile.objects.create(user = user_obj ) profile_obj.save() return redirect('/login/') except Exception as e: print(e) except Exception as e: print(e) return render(request … -
How to use div for background in html
Hi I am trying to build a website, and I am trying to use particles.js as my background and display the content in overlaying manner. However, it is displaying it on top of the page instead of the background. When I set its position as absolute, its changes the format of my website. How can I set that div as the background? I have my background div id set as particles-js here is my code for base.html: <!DOCTYPE html> <html lang=en> {% load static %} {% static 'style.css' %} {% static 'particles.json' %} <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> </head> <body> {% include 'snippets/base_css.html' %} {% include 'snippets/header.html' %} <!-- Body --> <style type="text/css"> .main{ min-height: 100vh; height: 100%; } </style> <div class="main"> <div id="particles-js"></div> <script src="https://cdn.jsdelivr.net/particles.js/2.0.0/particles.min.js"></script> <script> particlesJS.load('particles-js', "{% static 'particles.json' %}", function(){ console.log('particles.json loaded...'); }); </script> {% block content %} {% endblock content %} </div> <!-- End Body --> {% include 'snippets/footer.html' %} </body> </html> this is my home.html: {% extends 'base.html' %} {% block content %} <style type="text/css"> @media (max-width: 768px) { .right-column{ margin-left: 0px; } } @media (min-width: 768px) { .right-column{ margin-left: 20px; } … -
labels are not showing in views cleaned_data
I am building a PollApp and I am stuck on a Problem. I am trying to add labels in cleaned_data in views.py BUT labels are not showing in browser. forms.py class PollAddForm(forms.ModelForm): choice1 = forms.CharField(label='Choice 1', max_length=100, min_length=2, widget=forms.TextInput(attrs={'class': 'form-control'})) choice2 = forms.CharField(label='Choice 2', max_length=100, min_length=2, widget=forms.TextInput(attrs={'class': 'form-control'})) class Meta: model = Poll fields = [ 'choice1', 'choice2'] labels = { 'choice1': "First Choice", 'choice2': "Second Choice", } views.py def polls_add(request): if request.user.has_perm('polls.add_poll'): if request.method == 'POST': form = PollAddForm(request.POST) if form.is_valid: poll = form.save(commit=False) poll.owner = request.user poll.save() new_choice1 = Choice(poll=poll,labels='First Choice', choice_text=form.cleaned_data['choice1']).save() new_choice2 = Choice(poll=poll,labels='Second Choice', choice_text=form.cleaned_data['choice2']).save() return redirect('home') else: form = PollAddForm() context = { 'form': form, } return render(request, 'add.html', context) else: return HttpResponse("Sorry") I have tried many times by adding labels forms and views but still not showing browser. Any help would be really Appreciated. Thank You in Advance. -
Get error messages in django_rest_framework in a json format
I want to get an error message { "phone": [ "user with this phone already exists." ] } in a JSON format like {"error": "user with this phone already exists."} from the response HTTP 400 Bad Request Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "phone": [ "user with this phone already exists." ] } but what I am getting is just VM8:1 POST http://127.0.0.1:8000/users/ 400 (Bad Request) Here is my code: Serializers.py class UserCreateSerializer(UserCreateSerializer): class Meta: model = User fields = ('id', 'first_name', 'last_name', 'email', 'phone', 'stream', 'school', "password", ) -
Update or create does not update and only creates
@require_http_methods(["POST"]) @login_required def edit_question(request): req = json.loads(request.body) question_no = req["question_no"] guided_answers=req["guided_answer"] for guided_answer in guided_answers: obj, created= models.ModelAnswer.objects.update_or_create( question_id=models.Questions.objects.get(pk=question_no), model_ans= guided_answer["model_ans"], answer_mark=guided_answer["answer_mark"], defaults={ 'answer_mark':guided_answer["answer_mark"], 'model_ans':guided_answer["model_ans"], } ) return success({"res": True}) What i am trying to do is update or create based off checking whether the model answer already exist or not in the database however everytime i try to update an existing model answer it creates it into a new one, i do not understand why it does not filter out if it exists or not,i do not know whether it is my filter or my defaults that is wrong -
How to solve POST http://127.0.0.1:8000/bkash/payment/create 403 (Forbidden) ?(Django + ajax)
I used "django-bkash-integration 0.3" https://pypi.org/project/django-bkash-integration/ with my project to integrate bkash payment gateway. Bkash also provide me BKASH_APP_KEY = // bkash app key BKASH_APP_SECRET = // bkash app secret BKASH_APP_USERNAME = // bkash app username BKASH_APP_PASSWORD = // bkash app password BKASH_APP_VERSION = // bkash app version BKASH_APP_BASE_URL = // bkash app base url According bKash Checkout Script https://developer.bka.sh/docs/bkash-checkout-script connect it from the frontend. template link: https://github.com/MdNazmul9/bkash-front-end-problem/blob/main/templates/bkash_index.html I always get POST http://127.0.0.1:8000/bkash/payment/create 403 (Forbidden). How can I solve it ? -
django argon2password hasher behaves weird
screenshot of pip list and error I have already installed argon2password hash in virtual environment and by pipenv list it shows that already there, also while re-installing it shows already have met the requirements. But while giving password for login it shows ValueError at /login/ Couldn't load 'Argon2PasswordHasher' algorithm library: No module named 'argon2' what's the actual problem?? I couldn't resolve it. -
Custom validation error message in django rest framework ImageField
I'm trying to create my custom validation error messages in django rest framework. I have a productSerializer like the below code: class ProductSerializer(serializers.ModelSerializer): # validation name = serializers.CharField(error_messages={'blank': 'Please fillout the product name!'}) price = serializers.FloatField(error_messages={'blank': 'Please fillout the product price!'}) slug = serializers.SlugField(error_messages={'blank': 'Please fillout the product slug!'}) size = serializers.CharField(error_messages={'blank': 'Please fillout the product size!'}) description = serializers.CharField(error_messages={'blank': 'Please fillout the description!'}) image = serializers.ImageField(error_messages={'blank': 'Please upload a photo image!'}) # validation category = serializers.StringRelatedField(read_only=False) productType = serializers.StringRelatedField() user = serializers.StringRelatedField() class Meta: model = Product fields = "__all__" and my views.py be like: class ProductsList(APIView): authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] def post(self, request): serializer = ProductSerializer(data=request.data) category = Category.objects.get(name=request.data['category']) productType = ProductType.objects.get(name=request.data['productType']) user = User.objects.get(username= request.user.username) if serializer.is_valid(): serializer.save(category=category, productType=productType, user=user) return Response("SUCCESS!!!!!!", status=200) else: return Response(serializer.errors, status=400) The problem: I want the image field error message to be what I've written, when it's blank. But I always face the message "No file was submitted." Question: How can I validate the image field being blank? -
How to change success url?
Url File. Here a red mark where I want to put my success url. what should change in my code ? views.py -
Django ipware environment variable for proxy_trusted_ips
I want to make an environment variable for a list of IP addresses for django-ipware's proxy_trusted_ips. I am testing on localhost before going to production. Whatever IP address I put inside of proxy_trusted_ips, it returns None plus the traceback below. Example change get_client_ip(request, proxy_trusted_ips=['177.139.233.133']) to get_client_ip(request, proxy_trusted_ips=settings.PROXY_TRUSTED_IPS) JSON file of environment variables: "PROXY_TRUSTED_IPS":"127.0.0.1,127.0.0.1", settings.py: PROXY_TRUSTED_IPS = config['PROXY_TRUSTED_IPS'].strip('"').split(',') views.py: ip, is_routable = get_client_ip(request, proxy_trusted_ips=settings.PROXY_TRUSTED_IPS) print(ip) if (ContactSpamModel.objects.filter(email=contact_email).exists() or ContactSpamModel.objects.filter(ip_address=ip).exists()) and ContactSpamModel.objects.filter(inserted__gt=timezone.now() - timezone.timedelta(seconds=int(settings.SPAM_TIMEOUT_SECONDS))): current_time = datetime.datetime.now() diff = current_time.timestamp() - time.mktime(datetime.datetime.fromisoformat(ContactSpamModel.objects.filter(ip_address=ip).values(result=Cast('inserted', TextField())).first()['result']).timetuple()) seconds_diff = divmod(diff, int(settings.SPAM_TIMEOUT_SECONDS)) x,seconds_remaining = divmod(diff, int(settings.SPAM_TIMEOUT_SECONDS)) remaining = (int(settings.SPAM_TIMEOUT_SECONDS) + 60 - seconds_remaining) // 60 if seconds_diff[0] < 1: if str(int(remaining)) == '1': messages.info(request, "We received a contact message from you recently. Please wait " + str(int(remaining)) + " minute and try again.") return HttpResponseRedirect(request.path_info) else: messages.info(request, "We received a contact message from you recently. Please wait " + str(int(remaining)) + " minutes and try again.") return HttpResponseRedirect(request.path_info) else: ContactSpamModel.objects.filter(inserted__lt=timezone.now() - timezone.timedelta(minutes=1)).delete() ContactSpamModel(email=contact_email,ip_address=ip).save() Models.py: class ContactSpamModel(models.Model): email = models.EmailField() inserted = models.DateTimeField(auto_now_add=True) ip_address = models. GenericIPAddressField() Traceback: Traceback (most recent call last): File "/home/name/.local/share/virtualenvs/project_name/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/home/name/.local/share/virtualenvs/project_name/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 423, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: NOT NULL … -
I am getting an error while using Django ManyToManyField
in view.py def watchlist(request, item_id): list=get_object_or_404(Listing, id=item_id) wc=WatchCount(user=request.user) if WatchCount.objects.filter(user=request.user, listing=list).exists(): wc.listing.remove(list) else: wc.listing.add(list) return HttpResponseRedirect(wc.get_absolute_url()) in models.py class WatchCount(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) listing = models.ManyToManyField(Listing, blank=True, related_name="watchcount") def __str__(self): return f"{self.user.username}" def count(self): return self.listing.count() def get_absolute_url(self): return reverse('list', kwargs={'item_id': self.pk}) ERROR: "<WatchCount: jeelen>" needs to have a value for field "id" before this many-to-many relationship can be used. -
How to set the time out in Django Rest Framework?
How to set the time out in Django Rest Framework. is it from the settings file. -
Token based authentication using Authentication header giving 403 forbidden error
I have the following code in my react app: I am sending an update request to rest backed which requires a user to be authenticated to perform PUT/POST/DELETE requests. const update = (e) => { e.preventDefault() const formData = new FormData(form.current); console.log('Token ' + localStorage.getItem("token")) // valid token const requestOptions = { method: 'PUT', headers : { // 'Authorization': 'Basic ' + btoa('user:password') // basic authentication works "Authorization": 'Token ' + localStorage.getItem("token"), }, body: formData }; fetch(url, requestOptions) .then(async response => { const data = await response.json(); if(!response.ok){ const error = (data && data.message ) || response.status; return Promise.reject(error) } alert('member updated') history.push("/members") }) .catch(error => console.error('Some error ', error)) } Unfortunately, I'm getting these in console logs: PUT http://localhost:8000/uskindia/56/ 403 (Forbidden) Some error 403 And this in backed logs: Forbidden: /uskindia/56/ [... *:*:*] "PUT /uskindia/56/ HTTP/1.1" 403 58 ``` Trying to solve this for the last 24 hours but not getting it right. -
How to add two more Columns in the USER model in djan
How to add these columns(dob, and one more) in User Model, and if we want to add one or more field like a phone number so can id add to the User model or not ?? views.py def register(request): if request.method == "POST": # Get the post parameters username = request.POST['username'] email = request.POST['email'] fname = request.POST['fname'] lname = request.POST['lname'] dob = request.POST['dob'] pass1 = request.POST['pass1'] pass2 = request.POST['pass2'] # check for errorneous input if User.objects.filter(username=username).exists(): messages.error(request, 'This Aadhaar is Already Used') return redirect('home') if User.objects.filter(email=email).exists(): messages.error(request, 'This Email is already Used') return redirect('home') if (pass1 != pass2): messages.error(request, " Passwords do not match") return redirect('home') # Create the user myuser = User.objects.create_user(username, email, pass1) myuser.first_name = fname myuser.last_name = lname myuser.dob = dob myuser.save() messages.success(request, "You are successfully registered") return redirect('home') else: return HttpResponse("404 - Not found") -
How to create a view for a model
How do I build a function for this model to display team.name for members in my team on page and list my teams.members for members in my team ? class Team(models.Model): name = models.CharField(max_length=255) members = models.ManyToManyField(User, related_name='teams') created_by = models.ForeignKey(User, related_name='created_teams', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) plan = models.ForeignKey(Plan, related_name='teams', on_delete=models.SET_NULL, null=True, blank=True) -
how to use OpenCV lib on a python host cpanel?
I have django project that I need to use OpenCV lib in it. I have no error or problem as long as I run the project on a localhost on my computer. However, when I push my project on a real host on internet (The host uses Linux as OS) I face some errors that I cannot solve them. at the first level this error shows up when I import cv2 (I have already installed numpy lib): OpenBLAS blas_thread_init: pthread_create failed for thread 30 of 46: Resource temporarily unavailable OpenBLAS blas_thread_init: RLIMIT_NPROC 35 current, 35 max OpenBLAS blas_thread_init: pthread_create failed for thread 31 of 46: Resource temporarily unavailable OpenBLAS blas_thread_init: RLIMIT_NPROC 35 current, 35 max OpenBLAS blas_thread_init: pthread_create failed for thread 32 of 46: Resource temporarily unavailable OpenBLAS blas_thread_init: RLIMIT_NPROC 35 current, 35 max OpenBLAS blas_thread_init: pthread_create failed for thread 33 of 46: Resource temporarily unavailable OpenBLAS blas_thread_init: RLIMIT_NPROC 35 current, 35 max OpenBLAS blas_thread_init: pthread_create failed for thread 34 of 46: Resource temporarily unavailable OpenBLAS blas_thread_init: RLIMIT_NPROC 35 current, 35 max OpenBLAS blas_thread_init: pthread_create failed for thread 35 of 46: Resource temporarily unavailable OpenBLAS blas_thread_init: RLIMIT_NPROC 35 current, 35 max OpenBLAS blas_thread_init: pthread_create failed for thread 36 of 46: … -
Why does this hacky way of specifying installed_apps in Django work, but not the proper way?
My file structure is like this: and the INSTALLED_APPS in settings.py looks like this: INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "nstv_fe", "django_tables2", ] With this setup, running a script that imports a model from nstv_fe (from nstv_fe.nstv_fe.models import Show), I get the following error: # If "not ready" is due to unconfigured settings, accessing # INSTALLED_APPS raises a more helpful ImproperlyConfigured # exception. settings.INSTALLED_APPS > raise AppRegistryNotReady("Apps aren't loaded yet.") E django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. ../../venv/lib/python3.8/site-packages/django/apps/registry.py:135: AppRegistryNotReady Most of the stackoverflow questions about this are answered by setting the DJANGO_SETTINGS_MODULE environment variable to the settings file - so I tried setting it to nstv_fe.nstv_fe.settings and nstv_fe.settings, but neither worked. What I find odd is that if I go into django/apps/registry.py and manually create a list: installed_apps = ['nstv_fe'] in the Apps class, it'll run the test for the script that imports the model no problem. But if I don't manually add that line, it'll give me the AppRegistryNotReady error. This leads me to believe that nstv_fe isn't getting picked up properly in the installed apps somehow, but I'm not sure where I'm going wrong because I have it in the INSTALLED_APPS list in settings.py. How can … -
How to give an object multiple ratings (on different aspects) with django-star-ratings app?
The django-star-ratings is a nice package that can add ratings to any Django model with just a few lines of code in an existing project. However, the default app only supports 1 rating on an object by a specific user. Considering giving multiple ratings to an object in various aspects, such as 1. Ease of use; 2. Value; 3. Quality etc., do anyone know what's the easiest way to accomplish this? -
Usar múltiplas database no DJANGO
Bem, comecei estudar django esse ano e veio uma dúvida e não consegui arrumar. O problema é que tenho várias database no mysql e algumas possuem relações entre elas. Quando quero mapear uma única database, por exemplo: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'DatabaseName1', 'USER': 'DatabaseUserName', 'PASSWORD': 'DatabaseUserpassword', 'HOST': 'localhost', 'PORT': '5432', }, é facinho, uso python manage.py inspectdb tab1 tab2 > my_app/models.py e vai. Ai tenho outra database que faz relação com essa DatabaseName1, mas já deu ruim :( kk Já tentei: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'DatabaseName1', 'USER': 'DatabaseUserName', 'PASSWORD': 'DatabaseUserpassword', 'HOST': 'localhost', 'PORT': '5432', }, 'segunda': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'DatabaseName2', 'USER': 'DatabaseUserName', 'PASSWORD': 'DatabaseUserpassword', 'HOST': 'localhost', 'PORT': '5432', } } O user, password, host e port são os mesmo, isso é possível? -
Wagtail upgrade from 2.12 to 2.13 -- migrations not applying
I have a Wagtail project using the following: Wagtail 2.12.4 Django 3.1.11 Python 3.8.5 Postgres 12.6 I tried to upgrade Wagtail to version 2.13. When I run python manage.py migrate after the upgrade, the migrations appear to complete successfully, and they show as having completed when I run python manage.py showmigrations. However, the database tables targeted by the migrations remain unchanged, and the migrations do not appear in the django_migrations table of the database. This problem persists even if I run the specific migration with python manage.py migrate wagtailusers 0010. I have looked online for similar issues, but I haven't been able to find anything. Any advice on how I can find what is causing this issue to happen? -
User account activation url not found in Django
I'm trying to activate a user account in django but I'm getting 404 error, and the error is due to the fact that django is unable to get the activation url. urls.py urlpatterns = [ path('activate/<slug:uidb64>/<slug:token>)/', views.account_activate, name='activate'), ] views.py def account_activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = UserBase.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, user.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() login(request, user) return redirect('account:dashboard') else: return render(request, 'account/registration/activation_invalid.html') template {% autoescape off %} Great {{ user.user_name }}! Please click on the link below to activate your account http://{{ domain }}{% url 'account:activate' uidb64=uid token=token %} {% endautoescape %} I have spent a couple of hours trying to figure out where my mistake is but I haven't been able. Please I want some insight on this. -
Stripe integration with Django rest and Angular/Cli
I want to create a stripe payment integration using Django Rest Framework as backend and Angular/Cli as frontend. And also I want to confirm the payment using stripe webhooks. I could not able to find Angular documentation just for the only frontend. And also the Stripe docs are generally has written for flask and not for the rest framework. Any help will be appreciated. Thank you in advance.