Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
drf-spectacular does not generate parameters in swagger-ui, which I provide in FilterSet class from django_filters
I am trying to implement some API by using GenericViewSet. I have also some FilterSet class with some custom fields. My issue is the generation of these custom fields in swagger-ui endpoint documentation. Generated schema just does not includes all these filtering parameters. Is there any method to solve this problem without using @extend_schema decorator with viewset actions? -
how to access context in serializer queryset
I'm looking for a way to access the context to filter by current user class RemovePermissionsSerializer(serializers.Serializer): user_permissions = serializers.PrimaryKeyRelatedField( many=True, queryset=Permission.objects.filter(user = context.get('request').user) ) I can't access context becuase it's undefined, neither self.context -
What is the best way to use the permission_classes combination in Django?
Writing 'permission_classes' for DRF project, help me decide what is the best way to write it: The DRF documentation describes two ways to write 'permission_classes': in a tuple and in a list. # first way, in a list permission_classes = [IsAuthenticated & IsUserWithAccess] # or in a tuple permission_classes = (IsAuthenticated, IsUserWithAccess) On one side, python is faster with tuples, but writing 'permission_classes' through a list allows you to use the logical '&' operator. Which do you think is the best way to use from a performance point of view? -
NoReverseMatch - Reverse for 'emotion-buttons' with arguments '(1,)' not found. 1 pattern(s) tried: ['student/emotion\\-buttons$']
I keep getting this error message "NoReverseMatch at /student/take-exam/1 Reverse for 'emotion-buttons' with arguments '(1,)' not found. 1 pattern(s) tried: ['student/emotion\-buttons$']'". I have been unable to figure out the problem with my code. When I link take_exam to start_exam it works fine, so the problem should be in linking emotion_buttons to start_exam. Here is what I have so far: urls.py from django.urls import path from student import views from django.contrib.auth.views import LoginView urlpatterns = [ path('student-exam', views.student_exam_view,name='student-exam'), path('take-exam/<int:pk>', views.take_exam_view,name='take-exam'), path('emotion-buttons', views.emotion_buttons_view,name='emotion-buttons'), path('start-exam/<int:pk>', views.start_exam_view,name='start-exam'), ] views.py @login_required(login_url='studentlogin') @user_passes_test(is_student) def take_exam_view(request,pk): course=QMODEL.Course.objects.get(id=pk) total_questions=QMODEL.Question.objects.all().filter(course=course).count() questions=QMODEL.Question.objects.all().filter(course=course) total_marks=0 for q in questions: total_marks=total_marks + q.marks return render(request,'student/take_exam.html',{'course':course,'total_questions':total_questions,'total_marks':total_marks}) @login_required(login_url='studentlogin') @user_passes_test(is_student) def start_exam_view(request,pk): course=QMODEL.Course.objects.get(id=pk) questions=QMODEL.Question.objects.all().filter(course=course) if request.method=='POST': pass response= render(request,'student/start_exam.html',{'course':course,'questions':questions}) response.set_cookie('course_id',course.id) return response @login_required(login_url='studentlogin') @user_passes_test(is_student) def emotion_buttons_view(request): courses=QMODEL.Course.objects.all() return render(request,'student/emotion_buttons.html',{'courses':courses}) take_exam.html <a href="{% url 'emotion-buttons' course.id %}" class="btn btn-info">Let's Start</a> emotion_buttons.html <a href="{% url 'start-exam' course.id %}" class="btn btn-info">End Session</a> Any help would be appreciated -
multiple values in a dropdown to be annotate, and then save in another table which is studentsession,.....Field 'id' expected a number but got ''
The error here, is i'm trying to get lecturersession from it table and then populate the studentsession, but i have multiple values for lecturersession, each lecturer has to registered it own session for student to get registered for session as well, please, am i doing the right thing or not, should i populate it directly from the source, where the session table my views.py class StudentSessionRegistration(View): def get(self, request, *args, **kwargs): student = Students.objects.get(admin=request.user) session = LecturerSession.objects.values('lecturersession'). annotate(Count('lecturersession')).order_by() context = { 'session': session } return render(request, 'superadmin/student/add-session.html', context) def post(self, request, *args, **kwargs): student = request.POST.get('student') student = Students.objects.get(admin=request.user.id) session = request.POST.get('studentsession') session = LecturerSession.objects.get(id=session) if StudentSession.objects.filter(student=student, studentsession=session).exists(): messages.error(request, f'Hello {request.user.username}! Your Session is already registered') return HttpResponseRedirect(reverse('emisapp:student-session-registration')) if not session: messages.error(request, 'Please select session') return HttpResponseRedirect(reverse('emisapp:student-session-registration')) try: StudentSession.objects.create(student=student, studentsession=session) messages.success(request, "Student Session Registration Successfully") return HttpResponseRedirect(reverse('emisapp:student-session-registration')) except: messages.error(request, "Error while saving Student Session Registration") return HttpResponseRedirect(reverse('emisapp:student-session-registration')) template <div class="form-group"> <label>Select Faculty</label> <select name="studentsession" id="studentsession" required class="form-control"> <option value="{{s.id}}">--Select a Session--</option> {% for s in session %} <option value="{{s.id}}">{{ s.slug }}</option> {% endfor %} </select> </div> Models.py class LecturerSession(models.Model): id = models.AutoField(primary_key=True) lecturer = models.ForeignKey('Lecturers', related_name='lecturersession',null=True, on_delete=models.CASCADE) lecturersession = models.ForeignKey(SessionYearModel, related_name='lecturersession',null=True, on_delete=models.CASCADE) slug = models.SlugField(null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = … -
How to change time in crontab in celery beat without explicitly refreshing celery beat from cmd,then how its possible to pass my new task in queue?
app.conf.beat_schedule = { 'send-mail-everyday': { 'task': 'pizza_order.tasks.sub_task', 'schedule': crontab(hour=d['hours'], minute=25), # day_of_month,month_of_year } } This is crontab part. I have implemented scheduling from here to my task. -
Djanjo with Rest Framework and Postgres search
I need to make search for looking some data from database and this search field should support some logical operations. Like AND, OR, NOT and so on. So I found that Postgres db has something that I need. Ad Django documentation saying to us we need to use SearchQuery with parameter search_type='websearch' And we have something like SearchQuery("'tomato' ('red' OR 'green')", search_type='websearch') # websearch operators When I'm tried to implement to my project I did something like that # views.py class DataSearch(generics.ListAPIView): serializer_class = DataSerializer def get_queryset(self): queryset = Data.objects.all() query = self.request.query_params.get('query') if query is not None: queryset = queryset.filter( search_vector = SearchQuery( query, search_type='websearch' ) ) return queryset But when I'm trying to run it I get Cannot resolve keyword 'search_vector' into field. Choices are: data, foo, foo_id So what I should do to make it work and to make API endpoint for this type of search? -
django Item matching query does not exist
I have an app that when someone saves an item it also save on item_transactionlog but when I try to run the code it's throwing an error api.models.Item.DoesNotExist: Item matching query does not exist. here's my models.py class Item(models.Model): cl_itemid = models.CharField(primary_key=True, max_length=20) studid = models.CharField(max_length=9, blank=True, null=True) office = models.ForeignKey('ClearingOffice', models.DO_NOTHING, blank=True, null=True) sem = models.CharField(max_length=1, blank=True, null=True) sy = models.CharField(max_length=9, blank=True, null=True) remarks = models.TextField(blank=True, null=True) resolution = models.TextField(blank=True, null=True) resolve = models.BooleanField(blank=True, null=True) resolve_date = models.DateField(blank=True, null=True) resolve_by = models.CharField(max_length=8, blank=True, null=True) recorded_by = models.CharField(max_length=8, blank=True, null=True) record_date = models.DateField(blank=True, null=True) class Meta: managed = False db_table = 'item' def save(self, *args, **kwargs): ItemTransactionLog.objects.create( cl_itemid=Item.objects.get(cl_itemid=self.cl_itemid), trans_desc='Add Clearance Item', trans_recorded=timezone.now() ) super(Item, self).save(*args, **kwargs) something is wrong in the cl_itemid=Item.objects.get(cl_itemid=self.cl_itemid) I just dont know how to fix it. hope someone can help -
How to Integrate Bitpay Payment Gateway with Django?
I am beginner developer and trying to integrate the Bitpay Payment gateway with django, I have created the transactions on Bitpay portal but unable to fetch them using the API. Currently i am using test account and getting the error invalid token or sometimes "error": "This endpoint does not support the pos facade". I am using this API endpoint. Please help me. -
First project of Django with mongodb getting django.db.utils.DatabaseError
I created my first with MongoDB with Django while during the setup I am getting this problem error Internal Server Error: /api/v1/device/ Traceback (most recent call last): File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/djongo/sql2mongo/query.py", line 856, in parse return handler(self, statement) File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/djongo/sql2mongo/query.py", line 928, in _insert query.execute() File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/djongo/sql2mongo/query.py", line 397, in execute res = self.db[self.left_table].insert_many(docs, ordered=False) File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/pymongo/collection.py", line 761, in insert_many blk.execute(write_concern, session=session) File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/pymongo/bulk.py", line 528, in execute return self.execute_command(generator, write_concern, session) File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/pymongo/bulk.py", line 363, in execute_command _raise_bulk_write_error(full_result) File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/pymongo/bulk.py", line 140, in _raise_bulk_write_error raise BulkWriteError(full_result) pymongo.errors.BulkWriteError: batch op errors occurred, full error: {'writeErrors': [{'index': 0, 'code': 11000, 'errmsg': 'E11000 duplicate key error collection: farmos.device index: __primary_key__ dup key: { id: null }', 'keyPattern': {'id': 1}, 'keyValue': {'id': None}, 'op': {'device_id': 2, 'device_name': None, 'device_status': 'new', 'device_actions': True, 'device_token': True, '_id': ObjectId('63182c4ee9afd58ca7855029')}}], 'writeConcernErrors': [], 'nInserted': 0, 'nUpserted': 0, 'nMatched': 0, 'nModified': 0, 'nRemoved': 0, 'upserted': []} The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/djongo/cursor.py", line 56, in execute params) File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/djongo/sql2mongo/query.py", line 783, in __init__ self._query = self.parse() File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/djongo/sql2mongo/query.py", line 868, in parse raise exe from e djongo.exceptions.SQLDecodeError: Keyword: None Sub SQL: None FAILED SQL: INSERT INTO "device" ("device_id", … -
RuntimeError: doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS - Django
The folder organization is like this: /project/ apps/ app1/ app2/ ........... core/ view.py ............ __init__.py manage.py settings.py urls.py But I get an error when I want to import a model "House" that I have in the folder "app2" to view.py, the import is the following "from apps.app2 import House" and the error I get is this: House does not declare an explicit app_label and is not in an app in INSTALLED_APPS. If you can help me with a solution, thanks in advance. -
how to plot two graph using plottly using dame function in django
I am trying to plot two graphs on my Django index page. If I call two different functions, then I function is working, but another one is not when I try using the same function, then I do not understand how to give context and call this function here. I am sharing my code sample. Maybe anyone can explain me. data_plots = go.Scatter(x=df2['MeterReading_DateTime'],y= df2['ACT_IMP_TOT'],marker = {'color' : '#335253'}) data_plots1 = go.Scatter(x=df3['MeterReading_DateTime'],y= df3['ACT_IMP_TOT'],marker = {'color' : '#335253'}) #data_plots = px.pie(values=random_x, names=names) layout = {'title': '','xaxis': {'title': 'Date and time'},'yaxis': {'title': 'Total Import(KWH)'},'plot_bgcolor':'#E8E8E8'} fig = {'data': data_plots, 'layout': layout} fig1 = {'data1': data_plots1, 'layout': layout} plot_div = offline.plot(fig, output_type='div') plot_div1 = offline.plot(fig1, output_type='div') return plot_div,plot_div1 def home(request): my_graph = homee(request) context={'graph1':my_graph,'plot_div1':my_graph} return render(request, "index.html", context) -
I can't verify email of user in django
I have django app with authentication and email verification in it. First, user enters credentials in form, then I send him an email with link to verification. And now I get an error. When user clicks on link in mail it says that token is not recognized. from .utils import generate_token class PersonalRegister(View): def post(self, request, *args, **kwargs): ... #get data from form using request.POST.get #sends email current_site = get_current_site(request) email_subject = 'Activate account | Zane' email_body = render_to_string('authentication/email/email_body.html', { 'user': models.PersonalUser, 'domain': current_site, 'uid': urlsafe_b64encode(force_bytes(user.pk)), 'token': generate_token.make_token(user) }) email = EmailMessage(subject=email_subject, body=email_body, from_email=settings.EMAIL_FROM_USER, to=[user.email]) email.send() ... def get(self, request, *args, **kwargs): return render(request, 'authentication/personal/personal_signup.html') From .utils I have imported that function: from time import time from django.contrib.auth.tokens import PasswordResetTokenGenerator import six class TokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return (six.text_type(user.pk)+six.text_type(timestamp)+six.text_type(user.is_email_verified)) generate_token = TokenGenerator() In render_to_string I have this file email_body.html {% autoescape off %} Hi {{mail}} Please use the link below to verify your account. http://{{domain}}{% url 'activate' uidb64=uid token=token %} {% endautoescape %} So when user clicks on this email it takes him to site which triggers another function: urls.py from django.urls import path from .views import ( Login, PersonalRegister, logout_user, activate_user ) urlpatterns = [ path('login/', Login.as_view(), name='login'), … -
How can I get number of input fields based on users selected number in django models?
So, you guys have seen we search and get for example "top 10 best horror films in hollywood". and these lists sometimes have 5/10/15 films reviews. so I wanted to do that in my project. but in models I have the "List" class. and here I want to set whenever someone creates a list (an instance of List model) they can first select how many movies they wanna put in. for example How many entries you wanna put : [ ], here we can add any int values for example 10. and then the user gets 10 input groups. each group contains (name, image, description) I am sorry if I'm terrible in my explanation . A bit jumbled up here! Thanks. -
Limit 1 after filter in django
SystemsV2.objects.filter(Q(sysname = 'DC_BW_SBX_S4H') | Q(sysname='DC_BW_DEV_S4H')).values('sysname') Executing the above command gives this output, <QuerySet [{'sysname': 'DC_BW_SBX_S4H'}, {'sysname': 'DC_BW_SBX_S4H'}, {'sysname': 'DC_BW_DEV_S4H'}]> How can we make it so that only one of each exists in the result. For example, <QuerySet [{'sysname': 'DC_BW_SBX_S4H'}, {'sysname': 'DC_BW_DEV_S4H'}]> -
Bootstrap navbar dropdown not working due to FlexStart css
I know this is a very common issue; however, this one is peculiar. When I use just the regular CSS style sheets (so without style.css), everything works fine, but as soon as I input in main.css, the dropdown stops working. I have no idea which specific part of the CSS is throwing off the dropdown so I am asking for help. I am using Django templates and if I include the style.css on just the home.html page then the dropdown only doesn't work there. I want to try and keep the FlexStart template so I would appreciate the help. base.html {% load static i18n %}<!DOCTYPE html> {% get_current_language as LANGUAGE_CODE %} {% load bootstrap_icons %} <html lang="{{ LANGUAGE_CODE }}"> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>{% block title %}Semiconnect{% endblock title %}</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="Behold My Awesome Project!"> <meta name="author" content="Dilreet Raju"> <link rel="icon" href="{%static 'images/favicons/favicon-32x32.png' %}"> {% block css %} {% load static %} <!-- Latest compiled and minified Bootstrap CSS --> <!-- Latest compiled and minified Bootstrap CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.3/css/bootstrap.min.css" integrity="sha512-GQGU0fMMi238uA+a/bdWJfpUGKUkBdgfFdgBm72SUQ6BeyWjoY/ton0tEjH+OSH9iP4Dfh+7HM0I9f5eR0L/4w==" crossorigin="anonymous" referrerpolicy="no-referrer" /> <!-- Your stuff: Third-party CSS libraries go here --> <!-- This file stores project-specific CSS --> <link href="{% … -
Why Django is not creating Foreign Key constraint on MySQL?
I'm not new to Python nor Django, but this is the first time I'm creating a completely new big project from scratch, and also the first time I'm actually creating the models for the whole database and I'm kinda confused here. Does Django does not really create the ForeignKey constraints on the Database to check if ID exists? It is just a logical python thing that works only when the server is running? Or is it a problem that happens on MySQL? Just to be clear what I'm talking about, the first thing I noticed because as a Laravel developer on PHP side, I'm used to always check the database diagram that PhpStorm/PyCharm generates by connecting to the database, and on Laravel migrated tables, we can see the arrows pointing to the respective foreign key tables relationships, but on the Django created database there is not a single arrow on the database diagram generated by the JetBrains IDE. So I went testing. For example, I have the following models: class Series(models.Model): class Meta: app_label = 'core' db_table = 'km_series' verbose_name_plural = 'series' # added this to avoid plural being "seriess" name = models.CharField(max_length=200) description = models.TextField(default=None, blank=True, null=True) cover_img = … -
Get data from another function to app callback
So I have this data in my views. py. and I’m passing the value to the iotData function that located in my Dash app called ph.py in my views.py from .overview import ph //this is my dash app// def overview(request): post_data = json.loads(request.body.decode("utf-8")) value = post_data.get('data') ph.iotData(value) //passing the data to this function// return render(request, 'html') ph.py def iotData(value): print(value) //printing the data that from my views.py// @app.callback(Output('graph-ph', 'figure'), [Input('interval-graph-update', 'n_intervals')], [State('graph-ph', 'figure')]) def update_extend_traces_traceselect(n_intervals, fig_raw): //I want to access iotData here so that I can use the data for my graph// how can I pass the data from iotData to my app.callback function -
Sum in query with F() return None instead zero if value is null
I have this query sq_edit = UsulanRekomposisiData.objects.filter(file=draft, prk=OuterRef('prk')) cols = ['edit_jan', 'edit_feb', 'edit_mar', 'edit_apr', 'edit_mei', 'edit_jun', 'edit_jul', 'edit_aug', 'edit_sep', 'edit_okt', 'edit_nov', 'edit_des'] expr = reduce(add, (F(col) for col in cols)) lrpa = monitoring. \ annotate( edit_jan = sq_edit.values('jan'),edit_feb = sq_edit.values('feb'),edit_mar = sq_edit.values('mar'),edit_apr = sq_edit.values('apr'), edit_mei = sq_edit.values('mei'),edit_jun = sq_edit.values('jun'),edit_jul = sq_edit.values('jul'),edit_aug = sq_edit.values('aug'), edit_sep = sq_edit.values('sep'),edit_okt = sq_edit.values('okt'),edit_nov = sq_edit.values('nov'),edit_des = sq_edit.values('des') ).annotate(sum_edit = expr) I want to annotate the sum of edit in each month but it always return None i guess because one of the month value is null. I want if the value is None the F return 0 or is there any other way to get the sum? -
Signal so that when someone follows someone a thread is created between them 2
I have this in models and I want to create a signal that when someone follows someone, a thread is automatically created between that person and the person they followed. The models are in 2 different apps, one from the social network and the other from the chat. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.CharField(default='Hola, este es mi Blooby!!!', max_length=100) image = models.ImageField(default='default.png') def __str__(self): return f'Perfil de {self.user.username}' def following(self): user_ids = Relationship.objects.filter(from_user=self.user)\ .values_list('to_user_id', flat=True) return User.objects.filter(id__in=user_ids) def followers(self): user_ids = Relationship.objects.filter(to_user=self.user)\ .values_list('from_user_id', flat=True) return User.objects.filter(id__in=user_ids) class Post(models.Model): timestamp = models.DateTimeField(default=timezone.now) content = models.TextField(max_length=300) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts') liked = models.ManyToManyField(User, default=None, blank=True) class Meta: ordering = ['-timestamp'] def __str__(self): return self.content @property def num_likes(self): return self.liked.all().count() LIKE_CHOICES = ( ('Like', 'Like'), ('Unlike', 'Unlike'), ) class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) value = models.CharField(choices=LIKE_CHOICES ,default='Like', max_length=10) class Relationship(models.Model): from_user = models.ForeignKey(User, related_name='relationships', on_delete=models.CASCADE) to_user = models.ForeignKey(User, related_name='related_to', on_delete=models.CASCADE) def __str__(self): return f'{self.from_user} to {self.to_user}' class Comment(models.Model): post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE) name = models.ForeignKey(User,related_name="user_name" , on_delete=models.CASCADE) body = models.TextField() timestamp = models.DateTimeField(default=timezone.now) The models of the app chat , here is the thread class ThreadManager(models.Manager): def by_user(self, **kwargs): user = kwargs.get('user') lookup … -
Pass data from views.py into the plotly dash callback function
I’m working with node js and Django data connection. I have this middleware using node js that can send data using post request. my node.js const payload = mydata; //POST payload to django var obj = { data: payload }; jsonobj = JSON.stringify(obj); var XMLHttpRequest = require("xhr2"); var xhr = new XMLHttpRequest(); xhr.open("POST", "http://127.0.0.1:8000/", true); xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); xhr.send(jsonobj); And I can access that data in my django project views.py using this following code. It’s printing the data that node js sent. from django.views.decorators.csrf import csrf_exempt import json @csrf_exempt def overview(request): if request.method == 'POST': post_data = json.loads(request.body.decode("utf-8")) value = post_data.get('data') print(value) return render(request, 'myhtml') how can I pass this data (value = post_data.get(‘data’)) into a Plotly dash callback function. I tried this function, but I think it's not recognized request @app.callback(Output('graph-ph', 'figure'), [Input('interval-graph-update', 'n_intervals')], [State('graph-ph', 'figure')]) def update_extend_traces_traceselect(n_intervals, fig_raw, request): if request.method == 'POST': post_data = json.loads(request.body.decode("utf-8")) value = post_data.get('data') print(value) in my template.html {% load plotly_dash %} {% plotly_app name='SimpleExample' ratio=1 %} -
How to solve "user.backend = backend AttributeError: 'NoneType' object has no attribute 'backend" in Django Tests
I'm new to django 3.6 and tried to write a test that involved the use of force_login. But anytime I run it, it gives me the error user.backend = backend AttributeError: 'NoneType' object has no attribute 'backend' even when my force_login backend parameter is already set to django.contrib.auth.backends.ModelBackend this is my test code def test_address_create_stores_user(self): user3 = models.User.objects.create_user('user3', 'pw432joij') post_data = { 'name':'john kercher', 'address1':'1 av st', 'address2':'', 'zip_code':'MA12GS', 'city':'Manchester', 'country':'uk', } self.client.force_login(user3, backend='django.contrib.auth.backends.ModelBackend') self.client.post(reverse('address_create', post_data)) self.assertTrue(models.Address.objects.filter(user=user3).exists()) and this is the error it gives *ERROR: test_address_create_stores_user (main.tests.tests_views.TestPage) Traceback (most recent call last): File "C:\Users\DD\Desktop\practical django\booktime\main\tests\tests_views.py", line 128, in test_address_create_stores_user self.client.force_login(user3, backend='hhh') File "C:\Users\DD.virtualenvs\practical_django-UtJdiNPl\lib\site-packages\django\test\client.py", line 600, in force_login user.backend = backend AttributeError: 'NoneType' object has no attribute 'backend'* -
Nginx support multiple hostnames
I am working on my django + nginx + docker-compose project I want to access my site via ip and mysite.com Problem -- ip url is working, but mysite.com returns error: 403 Forbidden Nginx My code - docker-compose.yml services: django: build: ./project # path to Dockerfile command: sh -c " sleep 3 && gunicorn --bind 0.0.0.0:8000 core_app.wsgi" ... expose: - 8000 env_file: - ./.env depends_on: - db nginx: image: nginx:1.19.8-alpine depends_on: - django env_file: - ./.env ports: - "80:80" volumes: - ./project/nginx-conf.d/:/etc/nginx/conf.d ... nginx-conf.d upstream app { server django:8000; } server { listen 80; server_name 127.0.0.1 mysite.com www.mysite.com; location / { proxy_pass http://django:8000; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { alias /var/www/html/static/; } } -
In Django, using urlpatterns, how do I match a url-encoded slash character as part of a parameter?
In a Django app — this one — I have a urlpatterns list that looks like this: urlpatterns = [ url(r'^$', schema_view, name='swagger'), url(r'^(?P<page_title>.+)/(?P<rev_id>[0-9]+)/$', WhoColorApiView.as_view(), name='wc_page_title_rev_id'), url(r'^(?P<page_title>.+)/$', WhoColorApiView.as_view(), name='wc_page_title'), ] The second entry will match a path like /en/whocolor/v1.0.0-beta/September_11_attacks/1108730659/?origin=* and the third will match a path like /en/whocolor/v1.0.0-beta/September_11_attacks/?origin=*. The idea is that it's matching a page_title parameter (a Wikipedia article title), and an optional integer rev_id (revision id) parameter. However, it does not work as intended for an article titled "Post-9/11", with path /en/whocolor/v1.0.0-beta/Post-9%2f11/?origin=*. I want this not to match the second pattern (which gets matched as page_title "Post-9" and rev_id 11), and instead match the third pattern. I understand why the second pattern should match if the path is /en/whocolor/v1.0.0-beta/Post-9/11/?origin=*, but when the title is url-encoded as "Post-9%2f11" it still matches the second pattern instead of continuing on to the third pattern. How can I make Django treat the url-encoded slash as part of the parameter instead of a path separator? -
"decouple" could not be resolved
I have uninstalled and reinstalled decouple several times, but my settings.py folder is still saying "decouple" could not be resolved. After uninstalling, I even search for it to make sure it's not hiding somewhere, but it says it's not installed. Then, I reinstall using pip install python-decouple Any idea what else can be done? Here's my settings code: import os from decouple import config from datetime import timedelta from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = config('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = config('DEBUG') ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'django_extensions', 'user', 'listing', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'core.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'core.wsgi.application' # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES = { 'default': {}, 'users': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'listings_users', 'USER': …