Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django custom user data `first_name` and `last_name` while signin
I'm not getting user first_name and last_name while i returning the data after user successfully signedin, but i'm getting other data except first_name and last_name. Any help would be appreciated. Thank you so mcuh in advance. serializers.py : class UserLoginSerializers(serializers.ModelSerializer): device_type = serializers.CharField(allow_blank=True) device_token = serializers.CharField(allow_blank=True) email = serializers.CharField(allow_blank=True) password = serializers.CharField(allow_blank=True,label='Password',style={'input_type':'password'},write_only=True) phone_number = serializers.CharField(allow_blank=True) token = serializers.CharField(allow_blank=True, read_only=True) country_code = serializers.CharField(allow_blank=True) isotp_verified = serializers.CharField(allow_blank=True,read_only=True) class Meta: model = User fields = ['phone_number','password','device_type','device_token','token','country_code','isotp_verified', 'email', ] def validate(self,data): email = data['email'] phone_number = data['phone_number'] password = data['password'] device_type = data['device_type'] device_token = data['device_token'] country_code = data['country_code'] if email: user_qs = User.objects.filter(email__iexact = email) if user_qs.exists() and user_qs.count() == 1: print('Count :',user_qs.count()) else: raise APIException400({ 'success' : 'False', 'message' : 'User with this email does not exist' }) user_obj = '' if user_qs.exists() and user_qs.count() == 1: user_obj = user_qs.first() if user_obj: if not user_obj.check_password(password): raise APIException400({ 'success' : 'False', 'message' : 'Wrong Password' }) payload = jwt_payload_handler(user_obj) token = jwt_encode_handler(payload) data['token'] = 'JWT '+str(token) data['email'] = user_obj.email data['username'] = user_obj.username data['user_id'] = user_obj.id data['phone_number'] = UserOtherInfo_obj.phone_number data['country_code'] = UserOtherInfo_obj.country_code data['isotp_verified'] = UserOtherInfo_obj.isotp_verified data['first_name'] = user_obj.first_name data['last_name'] = user_obj.last_name return data -
I want to reconstruct django view
view.py class ListDoctor(generics.ListCreateAPIView): queryset = DoctorList.objects.filter(h_code="h_0001") serializer_class = DoctorListSerializer def list(self, request): doctor = DoctorList.objects.values() return Response( { "doctor": doctor } ) data: "doctor": [ { "doctorname": "testname1", "position": "ST", "h_code_id": "h_0000", "d_code": "d_0000" }, { "doctorname": "testname2", "position": "CB", "h_code_id": "h_0000", "d_code": "d_0001" }, { "doctorname": "testname3", "position": "CM", "h_code_id": "h_0001", "d_code": "d_0002" }, { "doctorname": "testname4", "position": "GK", "h_code_id": "h_0001", "d_code": "d_0003" } ] I would like to change the above code like below. "h_0000" [ { "doctorname" : "testname1", "position" : "ST", "h_code_id: "h_0000", "d_code" : "d_0000" }, { "doctorname" : "testname2" "position" : "CB" "h_code_id: "h_0000", "d_code" : "d_0001" } "h_0001" [ { "doctorname" : "testname3", "position" : "CM", "h_code_id: "h_0001", "d_code" : "d_0002" }, { "doctorname" : "testname4" "position" : "GK", "h_code_id: "h_0001", "d_code" : "d_0003" } How can I change the data above to look like below? We sincerely appreciate those who respond. h_code_id(h_0001, h_0002, h_0003...) will increase gradually. Therefore, it cannot be manually created. -
Sharing static files in Django server with webpack-quasar
I have done a project with Django as backend and quasar as frontend. I want to publish the quasar-frontend side of the project in the Django server. So, I have build production on a quasar with webpack, and I get the necessary folders with production files such as CSS, js. And I have separated them into static files and index.html due to the Django framework structure. Django server shares the static files with extra folders like this example: '/static/somenestedfolder/'. So when the Django server shares the index.html file to the client, the client can not get the static js and CSS files with error 404 not found. For example, the client requests the address to get some js files: http://127.XX.XX.XX:8000/js/some.js, but the static files are located in http://127.XX.XX.XX:8000/static/js/some.js. So, I just want to add the '/static' (or some nested folder), when the webpack build production files. Or the sharing-static-files method is incorrect: a) Should I use the python webpack-loader module?; b) there are any methods to do it? c) Can I use it on production mode the Django too? -
'user' field keeps getting nulled
I want to create something where the current logged user can create 'posts'. Here's my codes: models.py from django.contrib.auth.models import User # Posts class Post(models.Model): user = models.ForeignKey(User) date = models.DateField(auto_now_add=True) content = models.TextField(max_length=500, blank=False) forms.py class PostForm(forms.ModelForm): class Meta: model = models.Post labels = { 'content': '' } widgets = { 'user': forms.HiddenInput() } fields = '__all__' # exclude = ('user',) views.py def my_profile(request): user = request.user profile_info = request.user.userprofileinfo if request.method == 'POST': post = forms.PostForm(data=request.POST) if post.is_valid(): post.save(commit=False) post.user = user post.save(commit=True) return HttpResponseRedirect(reverse('td_app:index')) else: print(post.errors) return HttpResponseRedirect(reverse('td_app:my_profile')) else: form = forms.PostForm data = { 'user': user, 'profile_info': profile_info, 'form': form } return render(request, 'td_app/my_profile.html', context=data) I have declared the 'user' field to be 'hidden' since we don't want users pretending to be someone else when they post - the 'user' field should automatically register the current logged user. However it keeps giving me this error: <ul class="errorlist"><li>user<ul class="errorlist"><li>This field is required.</li></ul></li></ul> When I do this instead: class PostForm(forms.ModelForm): class Meta: model = models.Post labels = { 'content': '' } # widgets = { # 'user': forms.HiddenInput() # } fields = '__all__' exclude = ('user',) It will now give me a null error: The above exception (null … -
Finding unique query values when using Django/Python
Hey guys I'm trying to print out a page with all the available categories of an auction site on it. Right now it's printing out every instance of whats in the table. For instance, there are multiple print outs of Animals as a category - but I just want it to show one. What's the best way to do this? I tried the "distinct" method but it doesn't seem to be doing anything. Below is my relevant code: views.py: def categories(request): query = NewPost.objects.all().distinct() return render(request, "auctions/categories.html", { "queries": query }) categories.html: {% extends "auctions/layout.html" %} {% block body %} <h2>Categories</h2> {% for query in queries %} <li><a href="/categories/{{ query.category }}">{{ query.category }}</a></li> {% endfor %} {% endblock %} -
'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte
I'm trying to mock an image for the test case scenario where a user uploads a photo. Upon trying to create it, I'm getting the error: UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte I have followed the following topics to do the very such thing but I'm still getting this error. Unit Testing a Django Form with a FileField Django testing model with ImageField. How can remedy this so that I get a working mock image for my test? class RedundantImageUpload(TestCase): @classmethod def setUpTestData(cls): f = BytesIO() image = Image.new("RGB", (100, 100)) image.save(f, 'png') f.seek(0) test_image = SimpleUploadedFile( "test_image.png", content=open(f.read(), 'rb'), content_type="image/png" ) user = User.objects.create_user("User") import pdb; pdb.set_trace() form = PhotoForm({'title': "Image Title"}, {'source': test_image}) instance = form.save(commit=False) instance.photographer = user instance.save() cls.submitted_form = PhotoForm( {'title': "Image Title"}, {'source': test_image} ) def test_image_upload_path_exists(self): print(self.submitted_form.errors) -
Django redirect to external link with parrameters
everyone. I have problem with redirection. I have urls: path('some/<int:pk>/', RedirectView.as_view(), name='redirect'), My target is: in RedirectView I have to get pk, take it and pass to 'url' variable inside view: class RedirectView(RedirectView): ? any_url = Model2.objects.filter(name='something') ? link = any_url.name ? any_url.save() ? url = link + <int:pk> ? redirect to url I mean, I have to take pk from url and attach it to external link, that I got from db. pk is id from Model_1. external url is any_url I take from Model_2, it was saved like CharField. Also, when I take url address from db I need resave this instance. I understand how it works if I make redirect inside project (thru pattern_name). Could you help me? -
Why DB dont save comment(Django)
The entered comments in the form are not saved in the database, and are not displayed anywhere. After clicking the save button, it simply redirects to another page and the comments are not displayed. I'm trying to make a form for entering comments directly from the site page, I have already configured it from the administration panel. Thanks! models.py class BarbersPage(ListView): model = Post template_name = 'main/barbers.html' context_object_name = 'posts' def post_new(request): post = get_object_or_404(Post) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): form.save() return redirect('barbers') else: form = CommentForm() return render(request, 'main/post_detail.html', {'form': form}) views.py class BarbersPage(ListView): model = Post template_name = 'main/barbers.html' context_object_name = 'posts' def post_new(request): post = get_object_or_404(Post) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): form.save() return redirect('barbers') else: form = CommentForm() return render(request, 'main/post_detail.html', {'form': form}) barbers.html {% for post in posts %} <img src="{{MEDIA_URL}}{{post.photo.url}}" width="800" /> <h3> {{ post.name_barber}} </h3> <p>{{ post.description}}</p> <h3> Comments.. </h3> {% if not post.comments.all %} no comments yet...<a href = "#">Add one</a> {% else %} {% for comment in post.comments.all %} <strong> {{ comment.name }} {{ comment.add_date }} </strong> <p>{{comment.body }}</p> {% endfor %} {% endif %} {% endfor %} post_detail.html <h1>New comment</h1> <form method="POST" class="post-form">{% … -
How to avoid the COUNT query Django's paginator does?
Paginator.page() causes the evaluation of the cached property count, which performs a COUNT query on the database. My problem is that the average query execution time for that COUNT is 1.06 seconds while the average time of the main query is 1.04 seconds. In effect I have a duplicated query. Is there a way to avoid that COUNT query? -
How can I include a python module in order to run a server on django?
I'm very new to coding python, and I'm following a tutorial on django for creating a simple website: < https://docs.djangoproject.com/en/3.1/intro/tutorial01/ > The problem I'm encountering is when I attempt to execute 'manage.py runserver'. I receive a "Module not found" error for my 'urls.py' file. This sort of makes sense as I created the file myself because I needed to, whereas the rest were automatically generated. Does anyone know of any way I can fix this error, and get the 'urls.py' file on the path or make it accessible? If any extra information is needed I can try to provide it. -
Comments aren't printing out on my Django Python site
Hey guys I'm making an auction site and I'm having trouble with the comments for some reason. I'm not getting an error when I add a new comment but when I try to print out the results, I'm getting nothing - no errors - just nothing. When I do a query in my view for Comments.objects.all() and try to print it to the terminal, I'm getting nothing printed out. I'm thinking perhaps it's something to do with the action in the form? Or the urls.py? Anyone see why? I provided relevant code - please let me know if you need any more. Thanks! urls.py: from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("auction", views.auction, name="auction"), path("watchlist/<str:username>", views.watchlist, name="watchlist"), path("categories", views.categories, name="categories"), path("post/<str:title><str:description><int:price><str:category>", views.post, name="post"), path("bid/<str:username>", views.bid, name="bid"), path("comment", views.post, name="comment"), path("closeAuction", views.closeAuction, name="closeAuction") ] views.py: def comment(request): username = request.POST.get("username") itemID = request.POST.get("itemID") comment = request.POST.get("comment") new = Comment.objects.create(username = username, comment = comment, itemID = itemID) new.save() commentQuery = Comment.objects.all() print(commentQuery) return render(request, "auctions/post.html", { "commentQuery": commentQuery}) models.py: class Comment(models.Model): username = models.CharField(max_length=64) comment = models.CharField(max_length=64) itemID = models.CharField(max_length=64) post.html: <form name="comment" action="/post/{{p.title}}{{p.price}}" method="post"> … -
Pythin Django - Disply result in html page one after each other
Python - Django def integration(request): 1. pushing config to the device 2. checking the config 3. update database with new status The function above run three tasks. How can I display the result in the html page after each result done. Now it work perfectly but I need to wait until all tasks done to see the result in the html page. Thanks, -
Adding a Condition in Payment System to include PayPal
I am trying to integrate PayPal to my E-commerce Project, so the flow of the checkout process is as following after adding items to cart: In the checkout page the user types the address and select the payment option through a radio button Now when the user selects the stripe it directs to core:payment in this template I am trying to add a condition so that if the selected payment option is paypal the paypal icons is appearing instead of the stripe payment form. Here is the models.py class Payment(models.Model): stripe_charge_id = models.CharField(max_length=50) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, blank=True, null=True) amount = models.FloatField() timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.user.username Here is the views.py class CheckoutView(View): def get(self, *args, **kwargs): try: order = Order.objects.get(user=self.request.user, ordered=False) form = CheckoutForm() context = { 'form': form, 'couponform': CouponForm(), 'order': order, 'DISPLAY_COUPON_FORM': True } -----------------Shipping address codes----------------------------- payment_option = form.cleaned_data.get('payment_option') if payment_option == 'S': return redirect('core:payment', payment_option='stripe') elif payment_option == 'P': return redirect('core:payment', payment_option='paypal') else: messages.warning( self.request, "Invalid payment option selected") return redirect('core:checkout') except ObjectDoesNotExist: messages.warning(self.request, "You do not have an active order") return redirect("core:order-summary") here is the url.py urlpatterns = [ path('payment/<payment_option>/', PaymentView.as_view(), name='payment'), here is the template <!------------Add an if statmenet if the … -
django-compressor Uncaught SyntaxError: import declarations may only appear at top level of a module
This is my JS structure: This is the beginning index.js import { elements } from './views/base'; const state = {}; const controlRandomPhrasal = async () => {} My base.js: export const elements = { searchFrom: document.querySelector('.search'), } I invoke the compressor like this: {% compress js %} <script src="{% static "phrasals/js/jquery.js" %}"></script> <script src="{% static "phrasals/js/index.js" %}"></script> {% endcompress %} How can I configure my project to avoid that error? Or can you suggest me an easier/better bundler? -
With Django, how do you update a value with the click of a button in a template?
In my app, "employees" can be assigned to different "supervisors". The html template for an individual employee page contains a list of all available supervisors. I want to put a button next to each supervisor in the list so that when you click the button, the employee.assigned_supervisor value is updated. Even once a supervisor is assigned, I'd like to be able to change which supervisor is assigned by clicking a button next to a different supervisor in the list. I've combed through the documentation and lots of other sites/examples, and all I've been able to find is examples of forms where you visit a separate page, complete/update the form, and submit. I want to update the value just by clicking the button. I'm using Django 3.1. models.py class Supervisor(models.Model): name = models.CharField(max_length=30) class Employee(models.Model): name = models.CharField(max_length=30) assigned_supervisor = models.ForeignKey(Supervisor) forms.py class EmployeeForm(forms.ModelForm): class Meta: model = Employee fields = ['name', 'assigned_supervisor'] views.py def new_employee(request): if request.method != 'POST': form = EmployeeForm() else: form = EmployeeForm(data=request.POST) if form.is_valid(): form.save() return redirect('my_app:employees') context = {'form': form} return render(request, 'schedules/new_employee.html', context) employee.html <p>Employee: {{ employee }}</p> <p>Available Supervisors:</p> <li> {% for supervisor in supervisors %} <li>{{ supervisor }}</li> <!-- Insert "Assign" button … -
AttributeError at / 'list' object has no attribute 'values'
I am new to django and trying to build social network system. Here in my view I am importing my friend list using profile variable. Now I want to show post only from my friends. but cant make the logic for how to filter through all the post. this is the view: @login_required def post_comment_create_and_list_view(request): profile = Profile.objects.select_related('user').get(user=request.user).get_all_friends_list() #profile contains list of the friends i have queryset = Post.objects.all_posts().filter(author__icontains=profile.values()) #post form post_form = PostModelForm() if 'submit_p_form' in request.POST: post_form = PostModelForm(request.POST or None, request.FILES or None) if post_form.is_valid(): instance = post_form.save(commit=False) instance.author = profile instance.save() post_form = PostModelForm() messages.success(request, 'Post published') return redirect('posts:main_post_list') #comment form comment_form = CommentModelForm() if 'submit_c_form' in request.POST: comment_form = CommentModelForm(request.POST or None) if comment_form.is_valid(): instance = comment_form.save(commit=False) instance.user = profile post_id = request.POST.get('post_id') instance.post = Post.objects.get(id=post_id) instance.save() comment_form = CommentModelForm() return redirect('posts:main_post_list') context = { 'queryset': queryset, 'profile': profile, 'post_form': post_form, 'comment_form': comment_form, } return render(request, 'posts/main.html', context) this is the post model: class PostManager(models.Manager): def all_posts(self): posts = Post.objects.prefetch_related('author',"comment_posted__user", "comment_posted__user__user",'likes') return posts class Post(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True, db_index=True) content = models.TextField(db_index=True) image = models.ImageField(upload_to='posts', validators=[FileExtensionValidator(['png', 'jpg', 'jpeg'])], blank=True) likes = models.ManyToManyField(Profile, blank=True, related_name='profile_liked') updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(Profile, on_delete=models.CASCADE, … -
Django: Integrating PayPal to payment options
Helloo, I need guidance on how to integrate PayPal radio buttons to replace my Django Radio buttons for the found in the below link https://developer.paypal.com/demo/checkout/#/pattern/radio I have set my payment options in the forms.py and I am stuck and don't know how to proceed The stripe payment method is working perfectly fine I just want to add the PayPal payment option. This is how my project is arranged: Forms.py PAYMENT_CHOICES = ( ('S', 'Stripe'), ('P', 'Paypal') ) class CheckoutForm(forms.Form): ----address related forms----------------------------------- payment_option = forms.ChoiceField( widget=forms.RadioSelect, choices=PAYMENT_CHOICES) Here is the checokout template <h3>Payment option</h3> <div class="d-block my-3"> {% for value, name in form.fields.payment_option.choices %} <div class="custom-control custom-radio"> <input id="{{ name }}" name="payment_option" value="{{ value }}" type="radio" class="custom-control-input" required> <label class="custom-control-label" for="{{ name }}">{{ name }}</label> </div> {% endfor %} </div> here is the views.py class CheckoutView(View): def get(self, *args, **kwargs): try: order = Order.objects.get(user=self.request.user, ordered=False) form = CheckoutForm() context = { 'form': form, 'couponform': CouponForm(), 'order': order, 'DISPLAY_COUPON_FORM': True } -----------------Shipping address codes----------------------------- payment_option = form.cleaned_data.get('payment_option') if payment_option == 'S': return redirect('core:payment', payment_option='stripe') elif payment_option == 'P': return redirect('core:payment', payment_option='paypal') else: messages.warning( self.request, "Invalid payment option selected") return redirect('core:checkout') except ObjectDoesNotExist: messages.warning(self.request, "You do not have an active order") return … -
Django (Password_change) doesn't work url
I'm learning Django book named by (Django for beginners) I have a problem with password _change Below my code from urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('',include('pages.urls')), path('admin/', admin.site.urls), path('users/', include('users.urls')), path('users/',include('django.contrib.auth.urls')), ] Next is password_change_form.html {% extends 'base.html' %} {% block title %} Password Change {% endblock %} {% block content %} <h1>Password change</h1> <p>Please enter your old password, for security's sake, and then enter your new password twice so we can verify you typed it in correctly.</p> <form method="POST"> {% csrf_token %} {{form.as_p}} <input type="submit" class="btn btn-success" value="Change my password"> </form> {% endblock %} my content does'nt linking to password_change_form.html Via versa linking to password_change from Django adminstration -
Change FileField in Django Model
I want to update the pre-created model field which is FileField; this file is stored in the server, not in request.FILES. My Model config is: class File(models.Model): fileID = models.AutoField(primary_key=True) apkToolFile = models.FileField(null=True,upload_to='{}'.format(join(getattr(settings,'FILES_BASE'),getattr(settings,'APKTOOL_DIR_BASE')))) apkFile = models.FileField(null=True,upload_to='{}'.format(join(getattr(settings,'FILES_BASE'),getattr(settings,'APK_DIR_BASE')))) appPackage = models.CharField(null=True, max_length=30) appName = models.CharField(null=True, max_length=30) appIcon = models.FileField(upload_to='{}'.format(join(getattr(settings,'FILES_BASE'),getattr(settings,'APP_ICON_DIR'))),null=True) appVersion = models.CharField(null=True, max_length=20) hashFile = models.CharField(null=True,max_length=64) jadxFile = models.FileField(null=True,upload_to='{}'.format(join(getattr(settings,'FILES_BASE'),getattr(settings,'JADX_DIR_BASE')))) def __str__(self): return "FileName: {apkFile} - HashFile: {hashFile}".format( apkFile = self.apkFile, hashFile=self.hashFile ) And my Model serilazer is: from rest_framework import serializers from .models import File class FileSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = File fields = [ 'fileID', 'apkToolFile', 'apkFile', 'appPackage', 'appName', 'appIcon', 'appVersion', 'hashFile', 'jadxFile' ] I want to update appIcon with the file which is stored in the server storage. How can i do this? Tank you -
FATAL: password authentication failed for user "siteadmin"
I am trying to run python manage.py makemigrations to initiliaze the data fields in my database, but I keep getting this error. Siteadmin is the user on my server, not even a user on my postgres database. I am trying to use the user "dbadmin" to create these datafields. local_settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'cramnation_prod', 'User': 'dbadmin', 'PASSWORD': 'abc123!', 'HOST': 'localhost', } } Dbadmin is a user in my postgres with sudo privileges and I have made sure that the passwords match. Why is it trying to use the name of my server user "siteadmin" instead of my postgres user "dbadmin"? -
User ModelForm not getting saved in database (Django)
I have a ModelForm that creates an instance of a custom user (AbstractUser model). Whenever I try to submit the form, nothing happens except a reload of the page (because of the action), and nothing is getting saved in the database. The code is as following: def sign_up(request): if request.method == 'POST': print("test") form = UserForm(request.POST) if form.is_valid(): form.save() data = form.cleaned_data user = authenticate( username=data['username'], password=data['password'] ) user_login(request, user) else: form = UserForm() return render(request, 'schedules/signup/signup.html', {'form':form}) class ClientUser(AbstractUser): classes = models.ManyToManyField(ScheduleClass) personal_changes = models.TextField(name="personal_changes", default="none") schedule = models.ManyToManyField(Schedule) def get_classes(self): return self.classes class UserForm(forms.ModelForm): class Meta: model = ClientUser fields = ['username', 'password', 'classes', 'schedule'] <form method="post" action="http://127.0.0.1:8000/"> {% csrf_token %} {{ form }} <input type="submit"> </form> For some reason, it's also not even printing the line I wrote on line 3 of the sign_up func, even when I post. Is there something I am doing wrong? -
How to use Django's session engine with subdomains?
I need to access a user's sessionid from within a subdomain on my site, so I can enable "single sign-on", but I can't seem to get it to work, despite changing SESSION_COOKIE_DOMAIN = '.localtest' in my settings. MRE You need to modify /etc/hosts to include localtest if you want to reproduce the error. Also note that this is only tested on macOS, so YMMV. urls.py: from django.contrib.auth import views from django.contrib.auth.decorators import login_required from django.urls import path @login_required def home_view(request): raise Exception('user was logged in') urlpatterns = [ path('login', views.LoginView.as_view(), name='login'), path('home', home_view, name='home'), ] settings.py: BASE_DOMAIN = 'localtest' SESSION_COOKIE_DOMAIN = '.' + BASE_DOMAIN LOGIN_URL = '/login' LOGIN_REDIRECT_URL = '/home' When I attempt to log a user in via the builtin LoginView, the login is successful, and the user is redirected to /home (which is on the same domain as the login). After the login redirect, the user's session gets dropped, and the login_required triggers, sending the user back to the login page. Why is this happening? Is this a bug, or am I missing something? If you want to reproduce this on your machine, here is a repo. The database has a test user set with the username root … -
How to create score from multiple choice site using Django, and then allow user to see their current/progressive score?
to programming and Django here. I'm creating a multiple choice quiz using Python and would like to calculate and keep track of the score. Also the user should be able view their current score from one question to the next (.html). Score to add 10 points for each correct answer selected. Total 10 questions, with each multiple choice question having 4 choices. What would be the best way to go about this? -
Django: Pass paramter to view funciton, but not in url
What I'm trying to do is allow my login page to be told whether to show an alert by through reverse without using the url from a redirect from another view function. My login view function looks like: def login(request, alert=False): ... context = generate_basic_context(request) if (alert): context['alert'] = { 'type': 'danger', 'text': 'You need to be logged in to do that!' } return render(request, 'login.html', context) My urls.py: urlpatterns = [ ... path('login/', views.login, {'alert': False}, name='login'), ... ] And my reverse (function is called from other view functions): def makeauthenticate(): return HttpResponseRedirect(reverse('login', kwargs={'alert': True'})) Error: django.urls.exceptions.NoReverseMatch: Reverse for 'login' with keyword arguments '{'alert': True}' not found. 1 pattern(s) tried: ['dashboard/login/$'] -
Things don't appear to be working at the moment. Please try again later. django-paystack
Im am getting this error; "Things don't appear to be working at the moment. Please try again later." It might be configuration settings but so far I don't what I'm missing, the documentation specifies 2 settings. django-paystack settings; I added the sendbox business email generated by paypal to PAYPAL_RECEIVER_EMAIL but I get the above error. PAYPAL_TEST = True PAYPAL_RECEIVER_EMAIL = '' Here is the views I'm testing out with. def process_payment(request): paypal_dict = { "cmd": "_xclick-subscriptions", "business": settings.PAYPAL_RECEIVER_EMAIL, "amount": "10000000.00", "item_name": "name of the item", "invoice": "unique-invoice-id", "notify_url": request.build_absolute_uri(reverse('paypal-ipn')), "return": request.build_absolute_uri(reverse('user_profile:success')), "cancel_return": request.build_absolute_uri(reverse('user_profile:cancelled')), # noqa "custom": "premium_plan", form = PayPalPaymentsForm(initial=paypal_dict, button_type="subscribe") return render(request, 'user_profile/process_payment.html', {'form': form}) }