Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Run function only if all tests passed in Django
I was looking for a way how can I run a function ONLY if all of the tests are passed. I have looked around the documentation, unfortunately, I cannot see any way how can I check are all tests passing(not all tests in each class, but all tests overall), or how to run a function after all tests(same, not TearDown in each class, just one function after all of the tests ;)). Any idea how I can achieve that? Thank you in advance ;) -
Querying the sum of fields based on the same value fields in different class model (annotate)
I got 3 different models: class Buyer(models.Model): name = models.CharField(max_length=200, blank=True) description = models.CharField(max_length=200, blank=True) class Sell(models.Model): buyer = models.ForeignKey(Buyer, related_name='sell', on_delete=models.CASCADE) total_paid = models.DecimalField(max_digits=6, decimal_places=2) class Payment(models.Model): name = models.ForeignKey(Buyer, related_name='payment', on_delete=models.CASCADE) value = models.DecimalField(max_digits=6, decimal_places=2) I'm trying to sum the fields Sell.total_paid and Payment.value based on the Sell.buyer.name, which has the same values as the Payment.name I've tried the code below in my views.py but it's not working properly: def debtor(request): debtors = Sell.objects.values('buyer__name').\ annotate(total_paid=Sum('total_paid'), other=Sum('buyer__payment__value'), debit=F('total_paid')-F('other')) context = {'debtors': debtors} return render(request, 'debtor.html', context) Thank you! -
Messages not appearing after creating an app for it in Django
I created an app called marketing app which customizes messages to be written on top of website page. My problem is that these messages are not showing when everything is configured and I don't know why is that This is the model of the Marketing App class MarketingMessage(models.Model): message = models.CharField(max_length=120) active = models.BooleanField(default=False) featured = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) start_date = models.DateTimeField( auto_now_add=False, auto_now=False, null=True, blank=True) end = models.DateTimeField( auto_now_add=False, auto_now=False, null=True, blank=True) def __str__(self): return str(self.message[:12]) this is the views for the core app from marketing.models import MarketingMessage class HomeView(ListView): model = Item paginate_by = 10 template_name = "home.html" marketing_message = MarketingMessage.objects.all()[0] this is the template {% if marketing_message %} <div class="alert alert-light alert-top-message" role="alert"style="margin-bottom: 0px; border-radius: 0px; text-align: center;padding-top:80px"> <div class="container"> <h3>{{ marketing_message.message }}</h3> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> </div> {% endif %} This is the admin.py of marketing from django.contrib import admin from .models import MarketingMessage # Register your models here. class MarketingMessageAdmin(admin.ModelAdmin): class Meta: model = MarketingMessage admin.site.register(MarketingMessage, MarketingMessageAdmin) -
Django template: Displaying parent and child from the same model
I am creating a django blog and I have a Comments model that looks like this: class Comment(models.Model): content = models.TextField('Comment', blank=False, help_text='Comment * Required', max_length=500) post = models.ForeignKey('Post', on_delete=models.CASCADE, blank=False, related_name='comments') parent = models.ForeignKey('self', null=True, on_delete=models.SET_NULL, related_name='replies') I am attempting to display the replies below the comment using the code below in the template: {% for comment in comments %} {{ comment.content }} {% for reply in comment.replies.all %} {{ reply.content }} {% endfor %} {% endfor %} However, the result of this is the replies get displayed twice. Below the comment they're related to and again by themselves. What am I doing wrong? Why are the replies getting displayed twice. Also, the replies only go one level i.e. there can't be a reply to a reply only a reply to a comment. -
IOS safari ans Chrome block my websocket django Channels
I’m having a problem developping my web app with django channels. On laptop, the websocket works perfectly: data are well received end sent. But on all iPhone, it does not work. Thanks to web inspector I caught the error: the connexion is blocked because it is not secure(ws). Same problem with IOS Chrome but Ecosia works. The app works fine on Android. How can i prevent IOS safari (and Chrome) from blocking the connexion ? Thx. -
Django server running but cant hit url
I am on windows 10. I have a django server running which said the following: python manage.py runserver Watching for file changes with StatReloader This is the DRF tutorial. When I go to http://127.0.0.1:8000/users/, I get the screen you get when your internet is down: This site can’t be reached 127.0.0.1 refused to connect. Every time I hit the URL, the server doesn't register anything. Usually a new line would print showing the request and either 200 or an error. I have never seen this happen after running a django server. I also don't usually do python on windows I prefer linux. I'm assuming this is a windows issue. Any help appreciated -
Django deleting and re-creating model instead of rename
class ModelA: pass class ModelB: model_a = ForeignKey(ModelA) If I want to rename ModelA to ModelANew here is the strategy Django Follows: Migration 1: Create ModelANew Migration 2: Remove field model_a from ModelB. Add field model_a_new to ModelB Migration 3: Delete ModelA The obvious downside of this is that the information in the table modela is lost. Can this be done with renaming the model? Django obviously did not ask if this was a rename. Is it possible to inform or make it go that route? If not, what would be a strategy to manually code the migration. -
Wrong upload path in Django
I have configured Django3.0 / Ubuntu 18 / NginX Media root in URL.py: if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and in Nginx: server { listen 80; server_name XXXXX.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/user/proj; } location /media/ { root /home/user/proj; } location / { include proxy_params; proxy_pass http://unix:/run/proj_gunicorn.sock; } } and in models, I have some FileField and ImageField with 'upload_to ' attribute. When I upload something through admin, everything is okay and files will be uploaded in sub-folders (eg. media/2020/avatar/1.jpg) but when I do that through forms, files will be uploaded in right sub-directories but the image (or file) URL shows the root of media (eg. media/1.jpg) and when I click on URL, it returns 404. I can not figure out why this is happening, I've used this config in dozens of web sites and they work like a charm. Any ideas? -
Django - Chained Dropdown - Display a value based on two dropdown options
I want to display data in a dropdown based on two values selected in their respective dropdown menus. Here is the form which provides mapping between elements, number_service_location, country and did_number - class DID_Definition_Model_Form(forms.ModelForm): class Meta: model = DID_Definition_Model fields = ('did_number','country','number_service_location') labels = { 'country' : 'Country', 'number_service_location' : 'Number Service Location', } This above definition is later used for in another model and made available as dropdown class DID_Number_Assignment_Model_Form(forms.ModelForm): class Meta: model = DID_Number_Assignment_Model fields = ('country','number_service_location','did_selector', 'usage_assignment', 'employee_fullname', 'employee_email', 'subscriber_department' ) labels = { 'country' : 'Country', 'number_service_location' : 'Number Service Location', 'did_selector' : 'DID Selector' } So when both country and number_service_location are selected, corresponding did_selector value displays. To further add, country and number_service_location fields are independent. Any guidance will be helpful... -
App crashed error heroku deploying django
I deployed django app on heroku and got an error - h10 app crashed, but didn't get any info about reason of this error: -
Django Forms connect two forms as one where one is a FK to the other
I have two classes. Types and Materials. I need to create a form for the UNIQUE types only. It will create a type and this type is going to be directly a FK to the Material that is being created on the same time with the type. class Type(models.Model): TYPE_GENERIC = 'generic' TYPE_UNIQUE = 'unique' TYPE_CHOICES = ( (TYPE_GENERIC, 'generic'), (TYPE_UNIQUE, 'unique'), ) material_type = models.CharField(max_length=250, choices=TYPE_CHOICES, default=TYPE_GENERIC) name_type = models.CharField(max_length=250) description = models.TextField(blank=True) creation_date_type = models.DateTimeField(auto_now_add=True) class Material(models.Model): name = models.CharField(max_length=250) barcode = models.CharField(max_length=50) #id=barcode creation_date_mat = models.DateTimeField(auto_now_add=True) slug = models.SlugField(max_length=250, null=True, blank=True) material_picture = models.ImageField(blank=True, upload_to='media/', default='None/no-img.jpg', null=True) type = models.ForeignKey(Type, on_delete=models.CASCADE) These are my forms: # Formulaire d'Ajout Des Type De Materiels class formType(forms.ModelForm): class Meta: model = Type exclude = ['creation_date_type', 'material_type'] # Formulaire d'Ajout De Materiels Uniqrues class formUnique(forms.ModelForm): class Meta: model = Material fields = ['name','barcode', 'material_picture'] My views??? def addMaterial(request): if not request.user.is_authenticated: return redirect("../../accounts/login") else: if request.method == 'POST': form = formMaterial(request.POST, request.FILES) form_type = formType(request.POST) form_unique = formUnique(request.POST) if form.is_valid(): form.save() form = formMaterial() messages.success(request, f"New Material created") return redirect("homepage") else: form = formMaterial() form_type = formType() form_unique = formUnique() return render(request, 'siteWeb/addMaterial.html', {'form': form, 'form_type': form_type, 'form_unique': form_unique}) And my … -
Django doesn't use its upload_to path, and also won't validate its form?
I have a django model for storing images related to profiles. Its a pretty simple system, I'll show the model here: def image_path(instance: "Image", filename: str) -> str: return f"profiles/{instance.profile_id}/images/{instance.type}/{filename}" class Image(models.Model): """ The 'Image' model holds all images related to a profile. Most types ('logo', 'benefits_and_perks' etc) are expected to have one of each type per profile 'gallery' images will have a variable number and must maintain their order with the 'order' field """ profile = models.ForeignKey( "profiles.Profile", on_delete=models.CASCADE, related_name="images", help_text="Profile that this image is associated with." ) file = PrivateFileField( upload_to=image_path, content_types=("image/jpeg", "image/png"), help_text="Image file that the model represents." ) type = models.CharField( max_length=100, choices=IMAGE_TYPES, help_text="The type image which defines where it belongs in the profile." ) order = models.IntegerField(null=True) class Meta: ordering = ["order"] Pretty simple, however, we are doing uploads with ajax. That way, users can go through the flow, upload & crop an image, and it'll appear on the front end without a refresh. If I manually create a new Image model and save the file to it, it'll work, but it doesn't seem to actually use the upload_to path. Also, I can't get a form class to validate. Heres some relevant view code file … -
Django error : OSError: [WinError 126] module could not be found
I run locally a Django application on Windows. Everything works well until I add django-debug-toolbar. I then get the following error : OSError: [WinError 126] module could not be found I suspect the issue is coming from geodjango incompatibilities. The app is based on Python 3.6.10, Django 2.2.12, GDAL 2.3.3. Database is Postgresql 11.7.4 with Postgis 2.5.2. I created a virtual environment with miniconda3, I installed gdal within miniconda (conda install gdal=2.3.3) and then installed the requirements with pip (pip install -r requirements.txt) The database and production version of the app are stored on render.com. Here is the remote database configuration : DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'pcadb5', 'USER': 'pcadb5_user', 'PASSWORD': os.environ['DBPASSWORD'], 'HOST': 'dpg-xxxxxxx', 'PORT': '5432', } } Any clue ? -
TemplateDoesNotExist in Class Based Views. Django Not loading the template in CBV's
Hi I am Newbie to Django. I am trying to learn class based views. I tried to load one list view in my django. But its showing TemplateDoesNotExist Error The above is my app structure. I have two URls.py one is template level and another one at app level basic_app/urls.py from django.urls import path from basic_app import views app_name = "basic_app" urlpatterns = [ path('',views.SchoolListView.as_view(),name = "list") ] project level urls.py from django.contrib import admin from django.urls import path,include from basic_app import views urlpatterns = [ path('admin/', admin.site.urls), path('',views.IndexView.as_view()), path('basic_app/',include('basic_app.urls')) ] I am not sure whether I need to add something in settings. I tried many combinations but its showing TemplateDownNotExistError """ Django settings for advcbv project. Generated by 'django-admin startproject' using Django 3.0.6. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR,'template') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 's8yp$(4x%&t^l)sq1r%e&eu56*%hgf=bq4dkwmvmk5n0h44pi*' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = … -
Please How can I fix 'npm ERR! missing script: build-assets'
I was trying to setup saleor ecommerce software using the standard guide for windows (https://docs.saleor.io/docs/getting-started/installation-windows/). On reaching step 9,Prepare front-end assets, and running the command npm run build-assets I got the following error. npm ERR! missing script: build-assets npm ERR! npm ERR! Did you mean one of these? npm ERR! build-schema npm ERR! build-emails npm ERR! A complete log of this run can be found in: The complete log is pasted below: 0 info it worked if it ends with ok 1 verbose cli [ 1 verbose cli 'C:\\Program Files\\nodejs\\node.exe', 1 verbose cli 'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js', 1 verbose cli 'run', 1 verbose cli 'build-assets' 1 verbose cli ] 2 info using npm@6.14.4 3 info using node@v12.16.2 4 verbose stack Error: missing script: build-assets 4 verbose stack 4 verbose stack Did you mean one of these? 4 verbose stack build-schema 4 verbose stack build-emails 4 verbose stack at run (C:\Program Files\nodejs\node_modules\npm\lib\run-script.js:155:19) 4 verbose stack at C:\Program Files\nodejs\node_modules\npm\lib\run-script.js:63:5 4 verbose stack at C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:116:5 4 verbose stack at C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:436:5 4 verbose stack at checkBinReferences_ (C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:391:45) 4 verbose stack at final (C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:434:3) 4 verbose stack at then (C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:161:5) 4 verbose stack at C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:382:12 4 verbose stack at C:\Program Files\nodejs\node_modules\npm\node_modules\graceful-fs\graceful-fs.js:115:16 … -
How to Login without using Django default login form?
I have create my own login page and i want to know how can i login into that. I have tried this. Login.html <form action="{% url 'success' %}" id="Myform"> {% csrf_token %} <label>Username: <input type="text" placeholder="Enter Your Username" id="input" name="userUsername"> </label><br> <label>Password: <input type="password" placeholder="Enter Your Password" id="input" name="userPassword"> </label><br> <a href="{% url 'register' %}" style="float: right;">Didn't Have Account?</a><br><br> <button class="btn-success" id="button">Log In</button> </form> View.py def registerUser(request): username = request.POST['username'] #this LOC is generating the error email = request.POST['email'] password = request.POST['password'] salt = os.urandom(32) key = hashlib.pbkdf2_hmac( 'sha256', password.encode('utf-8'), salt, 100000) hashPassword = salt + key context = { 'username': username } if request.method == 'POST': user = User(username=username, email=email, password=password, hashedPassword=hashPassword) user.save() return render(request, "success.html", context) else: return HttpResponse("Username already Exists") def loginCredentials(request): username = request.POST["userUsername"] password = request.POST['userPassword'] salt = os.urandom(32) key = hashlib.pbkdf2_hmac( 'sha256', password.encode('utf-8'), salt, 100000) hashPassword = salt + key checkUsername = User.objects.get(username=username) checkPassword = User.objects.get(hashedPassword=hashPassword) if checkUsername and checkPassword: return render(request, "success.html") else: return render(request, "login.html") after running the app i am getting this Error django.utils.datastructures.MultiValueDictKeyError: 'username' [09/May/2020 17:03:27] "GET/success/?csrfmiddlewaretoken=ORQBKajE1Ezzk0PeoWkUMxc3nUBbJ8g29I6MsMElyXbT8C8CjA2uoi9wdR7Z6hpd&userUsername=harshashra&userPassword=qwerty HTTP/1.1" 500 79237 So, what i wanna know is that how can i solve this error and login through my custom login form -
Django ORM subquery in annotate to get correct calculation
These are my models: class Consume(models.Model): amount = models.FloatField(default=1) entry_for = models.ForeignKey( Person, on_delete=models.SET_NULL, related_name='consume_entry_for', ) class Purchase(models.Model): amount = models.DecimalField( max_digits=6, decimal_places=2, default=0.00 ) entry_for = models.ForeignKey( Person, on_delete=models.CASCADE, related_name='ledger_entry_for', ) and this is current my query but it is returning wrong calculation: person_wise_total = Person.objects.annotate( total_purchase=Coalesce(Sum('ledger_entry_for__amount'), Value(0)), total_consume=Coalesce(Sum('consume_entry_for__amount'), Value(0)), difference=Coalesce(Sum('ledger_entry_for__amount'), Value(0)) - Coalesce(Sum('consume_entry_for__amount'), Value(0)) ) For example, I have an entry in Purchase amount: 2, entry_for: jhon, amount: 3, entry_for: smith amount: 5, entry_for: jhon, amount: 1, entry_for: jhon, and consume entry: amount: 1, entry_for: jhon, amount: 2, entry_for: smith, According to above data, my query Sum should return total_consume for jhon is 1, but it is returning 3 for jhon in total_consume and smith total_consume is 2, here smith result is expected but jhon result is unexpected. I discover, the problem/ wrong calculation occurring because of jhon has 3 entry in the Purchase table, so it is multiplying with the total entry of person's purchase and total consume amount. here is django official explains the reason yield the wrong calculation I heard of Subquery and Outerref that i can get my calculation result properly, i have read django subquery and outerRef documentation but i couldn't do it. … -
How can I export the data from Django database to excel in a way I classified below?
In the models.py I have this codebase: class Person(models.Model): sex_choices = ( ('Male', 'Male'), ('Female', 'Female') ) martial_choices = ( ('Single', 'Single'), ('Married', 'Married'), ('Divorce', 'Divorce'), ('Widowed', 'Widowed') ) education_choices = ( ('Below Matric', 'Below Matric'), ('Matriculate', 'Matriculate'), ('12 Pass', '12 Pass'), ('Graduate', 'Graduate'), ('PG', 'PG'), ('Ph.D', 'Ph.D'), ) occupation_choices = ( ('Student', 'Student'), ('Govt. Employee', 'Govt. Employee'), ('Unemployed', 'Unemployed'), ('Self-Employed', 'Self-Employed'), ('Cultivator', 'Cultivator'), ('Pvt. Employee', 'Pvt. Employee'), ('Minial Job', 'Minial Job'), ('Others', 'Others') ) income_choices = ( ('Nill', 'Nill'), ('Below ₹10k', 'Below ₹10k'), ('₹10k to ₹25k', '₹10k to ₹25k'), ('₹25k to ₹50k', '₹25k to ₹50k'), ('Above ₹50k', 'Above ₹50k') ) name = models.CharField(max_length=200) sex = models.CharField(choices=sex_choices, max_length=50) martial_status = models.CharField(choices=martial_choices, max_length=50) age = models.IntegerField() education_level = models.CharField(choices=education_choices, max_length=50) occupation_status = models.CharField(choices=occupation_choices, max_length=50) income = models.CharField(choices=income_choices, max_length=50) "Government Documents:" registered_voter = models.BooleanField(default=False) procured_certificate_available = models.BooleanField(default=False) aadhar_card_available = models.BooleanField(default=False) bank_account_available = models.BooleanField(default=False) "Details of Education Qualification" def __str__(self): return self.name class DetailsOfEducationQualification(models.Model): #for age 3-23 type_choice = ( ("Government", "Government"), ("Private", "Private"), ("Anganwadi Center", "Anganwadi Center"), ) education_proximity_choice = ( ("0-5", '0-5km'), ('5-10', '5-10km'), ('10+', 'Above 10km'), ('Outside the state', 'Outside the state'), ) person = models.ForeignKey(Person, on_delete=models.CASCADE) course_class = models.CharField(max_length=50, blank=True) type_of_education_sector = models.CharField(choices=type_choice, max_length=50, blank=True) education_facility_proximity = models.CharField(choices=education_proximity_choice, max_length=50, … -
NoReverseMatch at /update Reverse for 'update_profile' with arguments '('',)' not found. 1 pattern(s) tried: ['updateprofile/(?P<profile_pk>[^/]+)$']
views.py def form_demo_update(request,profile_pk): profile = get_object_or_404(Createdemo,pk=profile_pk) if request.method == "POST": form = Form_demo(request.POST or None, instance=profile) # success_url = reverse_lazy('profile_update') #success_msg = 'Ok' if form.is_valid(): #instance=form.save(commit=False) form.save() return redirect('/') context={ 'form':form, 'profile':profile, } return render(request,'travel_form.html',context) urls.py path('updateprofile/<profile_pk>',views.form_demo_update,name='update_profile'), update.html <form action="{%url 'update_profile' profile.pk %}" method="post"> {% csrf_token %} {{form}} <input type="submit" value="Update" /> </form> -
Django: 'ManyRelatedManager' object has no attribute 'pk'
am working on project where the driver adds a price to the user post...and the user has the ability to accept the offer and reject it. but when the user click on remove button it show above error This is models.py (price model added by the driver) class price(models.Model): my_post = models.ManyToManyField(Loader_post, related_name='prices') user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, default='') driver_price = models.CharField(max_length=150, null=True) driver_name = models.CharField(max_length=150, null=True) approved_price = models.BooleanField(default=False) status = models.BooleanField(default=False) this is my views.py to remove price @login_required def booking_remove(request, pk): cs = get_object_or_404(price, pk=pk) post_pk = cs.my_post.pk cs.delete() return redirect('Loader:offer', pk=post_pk) here is urls.py path('remove/<int:pk>', views.booking_remove, name="booking_remove"), and html page of where directly cancel the offer {% for loader_post in request.user.Loader.all %} {% for price in loader_post.prices.all %} <p>{{ price.driver_name }}</p> <p>{{ price.driver_price }}</p> <p>{{loader_post.sender_name }}</p> <a href="{% url 'Loader:booking_remove' pk=price.pk %}">cancel</a> {% endfor %} {% endfor %} -
I can’t send the desired url to the address bar
I need to do so that I can open the news from the main page. But I ran into a problem, the interpreter throws the error "ValueError: Field 'id' expected a number but got 'news1' (I add the Traceback and code below). I understand that it expects a number, but receives a string, but I can’t figure out how to fix it Who knows, please help Traceback: Internal Server Error: /news1/ Traceback (most recent call last): File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\db\models\fields\__init__.py", line 1772, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: 'news1' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\views\generic\base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "C:\Users\dadi2\Desktop\church\website\views.py", line 18, in get posts = Blog.objects.get(id=slug) File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\db\models\query.py", line 404, in get clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs) File "C:\Users\dadi2\Desktop\church\venv\lib\site-packages\django\db\models\query.py", line 904, in filter return self._filter_or_exclude(False, … -
How to fix "there was an error in a CGI script. Error 500" when I'm hosting Python django with xampp on Mac OS?
I'm trying to host Python Django project with xampp but I've got this error I config exactly which on windows and it run ok. But when i run it on MacOS, it doesn't. How can i fix this. -
how to use paginate by this is not working
views.py paginate_by is not working, is there any alternative for this. class PostListView(ListView): template_name = 'all_users/doctor/main.html' model = Post context_object_name = 'posts' paginate_by = 3 def get(self, request, **kwargs): query = self.request.user post = Post.objects.filter(author=User.objects.get(username=query)).order_by('-date_posted') context = { 'posts': post, } return render(request, self.template_name, context) -
Is there any Django App to auth using phone number such as django-allauth?
I am building a backend where user's identifier is phone_number. So, is there any simple and beauty app, that provides auth staff using phone_number like django-allauth, django-registration using email? -
django allauth missing context login page
Requesting /accounts/login/ work fine but if I enable any social account provider,when login template is rendering I get the following error: Exception has occurred: VariableDoesNotExist Failed lookup for key [scope] It happens rendering this line: href="{% provider_login_url provider.id process=process scope=scope auth_params=auth_params %}">{{provider.name}}</a> Here is my settings: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', 'allauth.socialaccount.providers.google', 'game', ] SITE_ID = 1 # Provider specific settings SOCIALACCOUNT_PROVIDERS = { 'facebook': { 'METHOD': 'oauth2', 'SCOPE': ['email',], }, 'google': { 'SCOPE': [ 'profile', 'email', ], 'AUTH_PARAMS': { 'access_type': 'online', } } } Also, I have defined two social apps (facebook and google) and the site (I have tested with name "1" and "localhost") It's configured as the documentation shows and all examples I have followed. It only happens with any social login that I add. Why the context is not including scope to the template?