Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Question regarding queries over a junction table/intermediary model
my question concerns the many-to-many section of the django models docs: It is mentioned there that by using an intermediary model it is possible to query on the intermediary model's attributes like so: Person.objects.filter( group__name='The Beatles', membership__date_joined__gt=date(1961,1,1)) However for the other many-to-many model (Group) a similar query results in a FieldError: # which groups have a person name containing 'Paul'? Group.objects.filter(person__name__contains="Paul") Queries that reference the junction table explicity do work: Person.objects.filter(membership__group__name__contains="The Beatles") Group.objects.filter(membership__person__name__contains="Paul") Shouldn't Group therefore have access to Person via the junction model? -
how to create two table objects by one viewset django rest framework
Hi i am trying to save objects in reviews table from posts table filtered by type="R" i think i should override def create but i don't know how. please help me thanks. my posts table my reviews table this is my post model class Post(models.Model): """Model definition for Post.""" class Meta: db_table = 'posts' verbose_name = 'Post' verbose_name_plural = 'Posts' POST_TYPE = ( ('R', 'review'), ('C', 'clubpost'), ('A', 'advertisement'), ) title = models.CharField( max_length=20, null=False, verbose_name='제목' ) content = models.TextField( max_length=2000, null=False, verbose_name='내용' ) author = models.ForeignKey( User, on_delete=models.CASCADE, null=False, verbose_name='글쓴이', ) type = models.CharField( max_length=5, choices=POST_TYPE, null=True, verbose_name='글 종류', ) created_at = models.DateTimeField( auto_now_add=True, verbose_name='생성 일시', ) updated_at = models.DateTimeField( auto_now=True, verbose_name='수정 일시', ) review model class Review(models.Model): class Meta: db_table = 'reviews' verbose_name = 'Review' verbose_name_plural = 'Reviews' post = models.OneToOneField( Post, on_delete=models.CASCADE, related_name="review", ) post serializer class PostSerializer(ModelSerializer): author = UserAbstractSerializer(read_only=True) class Meta: model = Post fields = [ 'id', 'title', 'content', 'author', 'type', 'created_at', 'updated_at' ] extra_kwargs = { 'title': { 'error_messages': { 'required': '제목을 입력해주세요.', } }, 'content': { 'error_messages': { 'required': '내용을 입력해주세요.', } } } review serializer class ReviewSerializer(ModelSerializer): post_id = PostSerializer(read_only=True) class Meta: model = Post fields = [ 'id', 'post_id', ] … -
django rest framework nested categories
it is written in nested categories to categorize products. When we were working with Django itself, to display the nested categories in the navbar section, we used to display both the main and nested categories with the four loop twice. My question is that now that I want to write the code in django rest framework to display the nested categories, in addition to the code below, do I have to do anything else? In fact, the issue that is bothering me is how the nested category is called and displayed by the front-end programmer? my model : class Category(models.Model): name = models.CharField(max_length=200, null=True, blank=True) sub_category = models.ForeignKey('self', on_delete=models.CASCADE, related_name='sub') sub_cat = models.BooleanField(default=False) slug = models.SlugField(allow_unicode=True, unique=True, null=True, blank=True) class Product(models.Model): name = models.CharField(max_length=200, null=True, blank=True) category = models.ManyToManyField(Category, blank=True, related_name='cat_product') unit_price = models.IntegerField() my url : path('category/', views.CategoryListApi.as_view()), path('category/<slug:slug>/', views.CategoryProductsApi.as_view()), my view: class CategoryListApi(generics.ListAPIView): queryset = Category.objects.all() serializer_class = CategorySerializer class CategoryProductsApi(generics.ListAPIView): serializer_class = ProductSerializer def get_queryset(self): products = Product.objects.filter(category__slug=self.kwargs['slug']) return products my serializer: class ProductSerializer(serializers.ModelSerializer): category = serializers.SerializerMethodField() class Meta: model = Product fields = '__all__' def get_category(self, obj): return [cat.name for cat in obj.category.all()] class CategorySerializer(serializers.ModelSerializer): sub_category = serializers.SlugRelatedField(read_only=True, slug_field='name') class Meta: model = Category fields = … -
Trying to make a search/filter dropdown with select2 and ajax. my self defined is_ajax(request) function not working?
I am making a django project where there is a search/filter dropdown for a form. I am using select2 and ajax. It isn't working, and when I try to debug with print statements, it seems that the is_ajax(request) function is not returning true. I know the is_ajax() function was deprecated in JQuery, which is why I defined it myself. However, mine doesn't seem to work either. Here is the portion my view that filters objects: @login_required def job_application_create(request): form = JobApplicationForm() if is_ajax(request): print('TESTING TESTING TESTING TESTING TESTING TESTING TESTING TESTING ') term = request.GET.get('term') companies = Company.objects.filter(name__icontains=term) response_content = list(companies.values()) return JsonResponse(response_content, safe=False) and here is the is_ajax(request) definition: def is_ajax(request): return request.headers.get('x-requested-with') == 'XMLHttpRequest' Here is the JS in the page that has my form: <script> $(document).ready(function () { $('#id_company').select2({ ajax: { url: "{% url 'homepage' %}", dataType: 'json', processResults: function (data) { return { results: $.map(data, function (item) { return {id: item.id, text: item.name}; }) }; } }, minimumInputLength: 1 }); }); </script> -
Django Login Access with token
I am developing a Django project, I have created an API in the same project since other tools should be able to use functions from this project. This method is not working and I need someone who has done a similar thing to assist with a more refined and secured method or point out where am doing wrong. When a user is registered, I create an access token ( md5 has ) for this user and store it in a model, each token has a user foreign key. class AuthToken(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) token = models.TextField() created_date = models.DateField(auto_now_add=True) created_time = models.TimeField(auto_now=True) status = models.IntegerField(default=0) in the API, I have added a function to authenticate the user with the token. When the view to authenticate the user is invoked, what I do is. Check if the token exists. Get the user ( AuthToken.user.username ) Get user password ( AuthToken.user.password) Authenticate these details with Django authenticate I understand this will definitely fail since the password fetched from AuthToken.user.password with be an encrypted one, and passing the encrypted password to Django for authentication will encrypt that and compare again. Below is my API authentication view if module == 'auth': # authentication … -
Postgresql ignoring default value on bulk import
I have a postgres DB running in a docker container. I am trying to bulk import a csv full of postcodes. This is a Django project. As they all refer to the same state - "NSW". That column doesn't exist in the CSV. My Model (This is django) has the following definition for the State column: state = models.CharField(max_length=200, default="NSW", null=False, blank=False) But when I try and execute I get the following error: postgres=# \COPY datacollector_localities(name, postcode) FROM '/postcodes-nsw.csv' DELIMITER ',' CSV HEADER; ERROR: null value in column "state" of relation "datacollector_localities" violates not-null constraint DETAIL: Failing row contains (5, Condobolin, 2877, null). CONTEXT: COPY datacollector_localities, line 2: "Condobolin,2877" I assumed the leaving state out of the column_names list would make postgres use the default. What am I doing wrong? -
Is it possible to add a subquery table to a django queryset?
I am working on a query similar to the one below; I want to create this as a Django queryset for further filtering. select distinct on (id) id, title, weight from (select *, 3 + ts_rank_cd(to_tsvector(title), to_tsquery('sales'), 32) as weight from courses where to_tsvector(title) @@ to_tsquery('sales') union all select *, 2 + similarity(title, 'sales') as weight from courses where title % 'sales') as union_table order by id, weight desc I tried creating it as raw method, but that doesn't allow chaining additional filters and the extra method with the tables argument doesn't allow subqueries. Is there any solution other than using the raw SQL? -
Django - Connection refused mysql on ubuntu subsystem windows 10
I'm using xaamp for MySQL DB and I run my server on both cmd and ubuntu subsystem but my ubuntu says django.db.utils.OperationalError: (2003, 'Can't connect to MySQL server on '127.0.0.1' (111 "Connection refused")') -
How do I load django user data into user edit form in permission escalation safe environment
I am trying to create a profile edit form in django for Users in a way that they cannot set themselves as superuser or staff. This is my first learning project in django and so far I have followed https://docs.djangoproject.com/en/4.1/topics/forms/ to set everything up. in views.py @login_required def edit_profile(request): user = request.user if request.method == 'POST': form = edit_profile_form(request.POST) if form.is_valid(): if user.is_authenticated: try: user.first_name = form.cleaned_data['firstname'] user.last_name = form.cleaned_data['lastname'] user.email = form.cleaned_data['email'] user.username = form.cleaned_data['username'] user.save() except Exception as e: return HttpResponse(e) return render(request, 'index.html') else: #Get data ready for form data = {'firstname': user.first_name, 'lastname': user.last_name, 'email': user.email, 'username': user.username} form = edit_profile_form(data) return render(request, 'edit_profile.html', {'form': form} ) in forms.py from django import forms class edit_profile_form(forms.Form): firstname = forms.CharField(label='First name', max_length=100,) lastname = forms.CharField(label='Last name', max_length=100) email = forms.EmailField(label='Email', max_length=100) username = forms.CharField(label='Username', max_length=150) def __init__(self, *args, **kwargs): data = kwargs.get('data', None) super(edit_profile_form, self).__init__(*args, **kwargs) if data: self.fields['firstname'].initial = data['firstname'] self.fields['lastname'].initial = data['lastname'] self.fields['email'].initial = data['email'] self.fields['username'].initial = data['username'] in edit_profile.html {% extends 'base.html' %}{% load static %} {% block content %} <link href="{% static 'css/edit_profile.css' %}" rel="stylesheet" /> <main class="profile"> <form method='POST'> {% csrf_token %} <h1> Profile editor </h1> {{ form }} <input type='submit' value='Submit' class='btn … -
uploaded images not displayed in Django
I'm developping a django app but recently, I faced a challenge of images files uploaded in django admin that are not being displayed on pages, I tried every solution given here on the platform but none of it gave me a solution, plz does someone can help with this issue because it is been a while working on without a result. These are my models class House(models.Model): image_house = models.ImageField(upload_to='Images/', default='Images/house.png') # Cars property model class Car(models.Model): image_car = models.ImageField(upload_to='Images/', blank=True, default='Images/car.png') # Fields property model class Land(models.Model): image_land = models.ImageField(upload_to='Images/', blank=True, default='Images/land.png' ) and I set this in settings.py STATIC_URL = '/static/' # Media root and urls MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') And that' how I called the uploded picture from the model in Index.html <img src="{{ house.image.url }}" class="card-img-top" alt="..."> in my project urls I added urlpatterns = [ path('admin/', admin.site.urls), path('', include('realest_app.urls')), ] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) -
Reason given for failure: CSRF token from POST incorrect.?
Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: CSRF token from POST incorrect. In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django’s CSRF mechanism has not been used correctly. For POST forms, you need to ensure: Your browser is accepting cookies. The view function passes a request to the template’s render method. In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL. If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data. The form has a valid CSRF token. After logging in in another browser tab or hitting the back button after a login, you may need to reload the page with the form, because the token is rotated after a login. You’re seeing the help section of this page because you have DEBUG = True in your Django settings file. Change that to False, and only the initial error message will be displayed. You can customize this page using the CSRF_FAILURE_VIEW setting. please solve this? Reason given for … -
How do I use my coding skills for the greater good?
I am 17 year old African kid who knows HTML,CSS,JS(from freecodecamp) and currently learning django for making fullstack applications. I have no idea of what projects to make of them that will help my society and community. After solving the problem I want to write an essay about it when I apply to colleges and universities. something doable and takes few months to fully launch, since I am a senior I don't have much time in my hand. Please be specific don't give me only catagories. Ideas I got from my friends,family and internet: website for non-profit banking system government system school club websites -
Fixing "missing 1 required positional argument: 'id'" error when sending data from Django Form using Ajax
I have a Django Form where users inserts numeric values. I am sending the Ajax to a url but I keep receiving: TypeError: addlog() missing 1 required positional argument: 'id' I have tried to add the id in the url I got: Reverse for 'addlog' with arguments '(2,)' not found. 1 pattern(s) tried: ['workout/addlog/\\Z'] Here is the views: def addlog(request, id): workout = get_object_or_404(Workout, id=id) url = request.META.get('HTTP_REFERER') active_session = ActiveSession.objects.get(id=ActiveSession.objects.last().id) if request.headers.get('x-requested-with') == 'XMLHttpRequest' and request.method == 'POST': form = LogForm(request.POST) if form.is_valid(): data = Log() data.log_workout = request.POST.get('log_workout') data.save() context = { 'log_workout': data.log_workout, 'id': workout.id, } html = render_to_string('my_gym/log_form.html', context, request=request) return JsonResponse({'form': html}) else: print("The errors in addlog:",form.errors.as_data()) else: print("What happened??") return HttpResponseRedirect(url) Here is the form: <form class="review-form" action="{% url 'my_gym:addlog' object.id %}" method="post"> {% csrf_token %} </form> Here is the script: <script type="text/javascript"> $(document).ready(function(event){ $(document).on('click','#submitlog', function(event){ event.preventDefault(); var log_workout = $('#id_log_workout').val(); $.ajax({ type:'POST', url:'{% url 'my_gym:addlog' object.id %}', data:{'log_workout' : log_workout, csrfmiddlewaretoken':'{{csrf_token}}'}, dataType:'json', success:function(response){ $('#log_form').html(response['form']), console.log($('#log_form').html(response['form','div'])); }, error:function(rs, e){ console.log(rs.responseText); }, }); }); }); </script> Here is the url: path('workout/addlog/<int:id>', addlog, name='addlog'), My question How can I fix this error knowing that I tried changing the workout.id to object.id still same error. -
CSRF Failed | CSRF cookie not set
I'm using class based views to render a template. In that same class, I also have a post request to allow for the submission of a form. However, when I submit the form, I get the CSRF cookie not set error. I did use the {% csrf_token %} but still doesn't work. Here is my code: class SignIn(View): def get(self, request): # email = request.POST['email'] # password = request.POST['password'] template = loader.get_template('signin.html') logging.info(request) return HttpResponse(template.render()) def post(self, request): email = request.POST['email'] password1 = request.POST['password1'] password2 = request.POST['password2'] template = loader.get_template('signin.html') logging.info(request.__dict__) logging.info(password1) logging.info(email) if User.objects.filter(email=email).exists(): messages.info(request, 'E-mail Exists!') return redirect('signup') elif password1 != password2: messages.info(request, 'PASSWORD DOESNT MATCH') return redirect('signup') new_user = User.objects.create_user(email, email, password1) return HttpResponse(template.render()) This is my template: <html> <div> <p> Signup </p> <form method = "POST" action="/signup"> {% csrf_token %} username: <br/> <input type="text" name="email" /> <br/> Password: <br/> <input type="password" name="password1" /> <br/> confirm Password: <br/> <input type="password" name="password2" /> <br/> <input class ="btn btn-primary" type="submit" value= "signup" /> <br/> </form> </div> </html> My urls.py: from django import views from django.urls import path from .views import SignUp, SignIn, Index urlpatterns = [ path('', Index.as_view(), name='Index'), path('signup', SignUp.as_view(), name='SignUp'), path('signin/', SignIn.as_view(), name='SignIn') ] -
Django : FieldError at /editstu/121
Error : Cannot resolve keyword 'id' into field. Choices are: Age, Course_ID, DoB, Grade, Student_ID, Student_Name My function in views.py def Editstu(request,id): editstuobj = Student.objects.get(id=id) return render(request, 'editstu.html',{'Student':editstuobj}) My urls.py urlpatterns = [ path("admin/", admin.site.urls), path('',views.showStudent), path('InsertStudent',views.InsertStudent,name="InsertStudent"), path('Insertcour',views.InsertCourse,name="InsertCourse"), path('editstu/<int:id>',views.Editstu,name="Editstu"), path('editcour/<int:id>',views.Editcour,name="Editcour"), # path('Update/<int:id>',views.updateemp,name="updateemp"), path('Deletestu/<int:id>',views.Deletestu,name="Deletestu"), path('Deletecourse/<int:id>',views.Deletecourse,name="Deletecourse"), ] My Index.html <td><a href="editstu/{{result.Student_ID}}">Edit</a></td> <td><a href="Deletestu/{{result.Student_ID}}" onclick="return confirm ('Are you sure to delete the record?')">Delete</a></td> I checked the function if it is declared properly but no luck. I'm new to Django. It says error is 'id' but it should be fine. Please help if anyone can. -
'node with name "rabbit" is already running on host' even after killing the processes
Whenever I try to run a rabbit server, it meets me with this error: ERROR: node with name "rabbit" is already running on host "DESKTOP-BKRTA3R" I've read that I should kill the processes of rabbit by using rabbitmqctl stop But I still get the error, What else can I do I am on windows 10 Here is my full error 2022-11-11 16:46:03.015000-08:00 [error] <0.131.0> 2022-11-11 16:46:03.015000-08:00 [error] <0.131.0> BOOT FAILED 2022-11-11 16:46:03.015000-08:00 [error] <0.131.0> =========== 2022-11-11 16:46:03.015000-08:00 [error] <0.131.0> ERROR: node with name "rabbit" is already running on host "DESKTOP-BKRTA3R" 2022-11-11 16:46:03.015000-08:00 [error] <0.131.0> BOOT FAILED =========== ERROR: node with name "rabbit" is already running on host "DESKTOP-BKRTA3R" 2022-11-11 16:46:04.017000-08:00 [error] <0.131.0> supervisor: {local,rabbit_prelaunch_sup} 2022-11-11 16:46:04.017000-08:00 [error] <0.131.0> errorContext: start_error 2022-11-11 16:46:04.017000-08:00 [error] <0.131.0> reason: {duplicate_node_name,"rabbit","DESKTOP-BKRTA3R"} 2022-11-11 16:46:04.017000-08:00 [error] <0.131.0> offender: [{pid,undefined}, 2022-11-11 16:46:04.017000-08:00 [error] <0.131.0> {id,prelaunch}, 2022-11-11 16:46:04.017000-08:00 [error] <0.131.0> {mfargs,{rabbit_prelaunch,run_prelaunch_first_phase,[]}}, 2022-11-11 16:46:04.017000-08:00 [error] <0.131.0> {restart_type,transient}, 2022-11-11 16:46:04.017000-08:00 [error] <0.131.0> {significant,false}, 2022-11-11 16:46:04.017000-08:00 [error] <0.131.0> {shutdown,5000}, 2022-11-11 16:46:04.017000-08:00 [error] <0.131.0> {child_type,worker}] 2022-11-11 16:46:04.017000-08:00 [error] <0.131.0> 2022-11-11 16:46:04.017000-08:00 [error] <0.129.0> crasher: 2022-11-11 16:46:04.017000-08:00 [error] <0.129.0> initial call: application_master:init/4 2022-11-11 16:46:04.017000-08:00 [error] <0.129.0> pid: <0.129.0> 2022-11-11 16:46:04.017000-08:00 [error] <0.129.0> registered_name: [] 2022-11-11 16:46:04.017000-08:00 [error] <0.129.0> exception exit: {{shutdown, 2022-11-11 16:46:04.017000-08:00 [error] … -
Python Django: getting data from modal gives <built-in function id> error
I'm trying to get a value from a modal, that gets the value using jQuery from a list. Let's explain. I have a list of objects in an HTML page using a for loop, and in each row, there is a delete button. This delete button launches a confirmation Modal. To get the id of the row and use it in the Modal, I use jQuery: {% for a in objects %} [...] <td><button type="button" class="delete-button" data-name="{{ a.id }}" data-bs-toggle="modal" data-bs-target="#deleteModal">Delete</button></td> [...] {% endfor %} [...] <div class="modal fade" id="deleteModal"> [...] <form action="{% url 'delete_object' %}" method="post"> {% csrf_token %} <input type="hidden" name="object_id" name="object_field" /> <button type="submit">Delete</button> [...] <script> $('.delete-button').click(function() { $('#object_id').html($(this).data('name')) }) </script> Without explaining the urls.py part, let's get straight to the view, which is quite simple: def cancel_request(request): _id = request.POST.get("object_id") obj = Object.objects.get(id=id) obj.status = "Annulé" obj.save() return redirect("home") When I run the modal, I make sure I can see the id value getting in the modal, but when I try to put it in an input, I cannot see it anymore. If I put it in an h5 tag for example: <h5 class="modal-title" id="request_id" name="requestid_kw"></h5>, it shows on the modal, but still does not get … -
Post_save method in django
I've have stuck in a problem where if both the person follows the each other only then it should make them friends. I'm planning to use Django signal's post save method for this. But I'm not able to make any progression in it .Please help me on this .Thanks in advance and do refer the code below and sorry for bad coding. Models.py: class Follow(models.Model): Follower=models.ForeignKey(User, models.SET_NULL,null=True,related_name='from_user_followers',blank=True) Followe=models.ForeignKey(User,models.SET_NULL,null=True,related_name='to_user_followers',blank=True) created=models.DateTimeField(default=now) @receiver(post_save, sender=Follow) def create_friend(sender, instance, created, **kwargs): if created: see_followe_is_following_back = Follow.objects.filter(Followe=instance.Follower, Follower=instance.Followe) see_follower_is_following_back = Follow.objects.filter(Follower=instance.Followe, Followe=instance.Follower) try: if str(instance.Follower) == str(see_follower_is_following_back) and str(instance.Followe) == str(see_followe_is_following_back): create_friends= Friends.objects.update_or_create(from_user=instance.Followe , to_user=instance.Follower) return create_friends else: pass except Exception as e: return str(e) else: pass class Friends(models.Model): from_user=models.ForeignKey(User, models.SET_NULL,null=True,related_name='from_user_friends',blank=True) to_user=models.ForeignKey(User,models.SET_NULL,null=True,related_name='to_user_friends',blank=True) created=models.DateTimeField(default=now) -
In Heroku , python setup.py egg_info did not run successfully. error in troposphere setup command: use_2to3 is invalid
So, I am trying to deploy this django project on the Heroku platform and while making all the requirements running on the local server while this code is added to Heroku and it installs it on its server, It throws an error and didn't resolved, Even after lot of tries. Problem is with the setup.py installation and troposphere. I tried commands like:- pip install --upgrade setuptools. But this also didn't worked it gave the same error. For reference dropping my requirements:- argcomplete==1.12.3 asgiref==3.4.1 autopep8==1.5.7 awsebcli==3.20.3 boltons==21.0.0 boto3==1.18.16 botocore==1.23.54 cachetools==4.2.2 cement==2.8.2 certifi==2021.5.30 cfn-flip==1.2.3 charset-normalizer==2.0.4 click==8.0.1 colorama==0.4.3 dj-database-url==1.0.0 Django==3.2.6 django-cors-headers==3.7.0 djangorestframework==3.12.4 durationpy==0.5 factory-boy==3.2.0 Faker==8.11.0 future==0.16.0 google-api-core==2.0.1 google-auth==2.0.2 google-cloud-language==2.2.2 google-cloud-vision==2.4.2 googleapis-common-protos==1.53.0 grpcio==1.39.0 gunicorn==20.1.0 hjson==3.0.2 idna==3.2 jmespath==0.10.0 joblib==1.0.1 kappa==0.6.0 packaging==21.0 pathspec==0.9.0 pep517==0.11.0 pip-tools==6.2.0 placebo==0.9.0 proto-plus==1.19.0 protobuf==3.17.3 psycopg2==2.9.5 psycopg2-binary==2.8.4 pyasn1==0.4.8 pyasn1-modules==0.2.8 pycodestyle==2.7.0 pycountry==20.7.3 PyJWT==1.7.1 pyparsing==2.4.7 pypiwin32==223 python-dateutil==2.8.2 python-http-client==3.3.2 python-slugify==5.0.2 pytz==2021.1 pywin32==305 PyYAML==5.4.1 regex==2021.8.28 requests==2.26.0 rsa==4.7.2 s3transfer==0.5.0 semantic-version==2.8.5 sendgrid==6.8.1 sentry-sdk==1.10.1 six==1.14.0 sqlparse==0.4.1 starkbank-ecdsa==1.1.1 termcolor==1.1.0 text-unidecode==1.3 toml==0.10.2 tomli==1.2.1 tqdm==4.62.0 troposphere==2.7.1 twilio==6.63.1 urllib3==1.26.12 wcwidth==0.1.9 Werkzeug==0.16.1 whitenoise==6.2.0 wsgi-request-logger==0.4.6 zappa==0.53.0 -
Integrating a Django project with FreeRADIUS and Coovachilli
How do I integrate a django project with FreeRADIUS and Coovachilli? I have looked for any documentation that can help, but I can only find PHP guides. I also have checked out OpenWisp, but it does not fit my requirements (too complex). So is there any guide on integrating a django project with FreeRadius and Coovachilli? -
can't open file 'manager.py': [Errno 2] No such file or directory
I'm trying to creat an aplication usign python and django, but this error keeps happening. What I've already tried: put python path and script in environment variables reinstall python reinstall django close and open vscode (I thought it was an update issue) run the server inside setup - the application folder If anyone can help me, very much. -
Django redirect /D/<anything> to /d/<anything>
I'm looking for a way to redirect any url that start with /D/ to the same URL with lowercased /d/. /D/<anything_including_url_params> to /d/<anything_including_url_params> I literally only want to redirect urls that start with /D/ - not /DABC/ etc... The suffix can also be empty, eg. /D/ > /d/ Is there a way to do that in Django? It is for a third-party app with urls included in projects urls. The alternative is to use re_path and change: path("d/", include(...)) to re_path(r"^[dD]/$", include(...)) but I'd rather do a redirect instead of this. -
raise UndefinedValueError('{} not found. Declare it as envvar or define a default value.'.format(option))
I'm trying to deploy it on Railway. This error is coming. raise UndefinedValueError('{} not found. Declare it as envvar or define a default value.'.format(option)) Image of the error coming -
Django images not showing up in template
I've spent the whole day trying to find a solution for showing the images in the template but I couldn't find any solution to my case. This is my settings STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'DataCallGuide/static') ] My model class TroubleshootingSteps(models.Model): box_header = models.CharField(blank=True, null=True, max_length=250) box_content = models.CharField(blank=True, null=True, max_length=250) box_botton = models.CharField(blank=True, null=True, max_length=250) header = models.TextField(blank=True, null=True) sub_header = models.TextField(blank=True, null=True) text1 = models.TextField(blank=True, null=True) image1 = models.ImageField(blank=True, null=True, upload_to="images/") and the template {% extends 'base.html' %} {% load static %} {% block content %} <div class="container overflow-hidden"> <div class="text-center"> <h4 class="mt-5 mb-5">{{data.header}}</h4> </div> <h3 dir="rtl" class="rtlss">{{data.sub_header}}</h3> <img src="{{ data.image1.url }}"> </div> {% endblock%} Also when I click on the image link in admin pages it doesn't show the image and display page not found error with the below link http://127.0.0.1:8000/media/images/IMG-20220901-WA0009.jpg What is wrong please? -
Django IO bound performance drop with gunicorn + gevent
I have been working on an IO bound (only simple queries to database for getting info or updating it) application written in Django. As application is mostly db and redis queries, I decided to use gunicorn with async gevent worker class, but the weird part is that eventhough I'm running gunicorn with gevent (also monkey patched db for that purpose), I'm not seeing any performance gain by it, in fact, both requests/s and response time has dropped. Steps taken To do so, I have done the following: Installed greenlet, gevent & psycogreen as instructed in official docs. Patched postgres with psycogreen.gevent.patch_psycopg (tried wsgi.py, settings.py and post_fork in gunicorn) but to no avail. Tried running gevent's monkey.patch_all manually, also no use. This is my gunicorn.config.py: import gunicorn gunicorn.SERVER_SOFTWARE = "" gunicorn.SERVER = "" bind = "0.0.0.0:8000" worker_class = 'gevent' worker_connections = 1000 # Tested with different values keepalive = 2 # Tested with different values workers = 10 # Tested with different values loglevel = 'info' access_log_format = 'sport %(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s"' def post_fork(server, worker): # also tried pre_fork and on_starting from psycogreen.gevent import patch_psycopg patch_psycopg() Result But the app only got slower, also note …