Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get full url or parts to settings in model (wagtail 4.2)
@register_setting class NavigationMenuSetting(BaseSiteSetting): ... def get_url_to_admin_setting: {code} return 'admin/settings/navigation/navigationmenusetting/2/' Need solution if it's possible to do. -
backend function in AUTHENTICATION_BACKENDS is not called
I am using python-ldap What I want to do is, 1.Access LDAP Server and check there is username or not/ 2.If not exist in LDAP, then check local DB. So I set AUTHENTICATION_BACKENDS like this below in settins.py AUTHENTICATION_BACKENDS = [ "defapp.backends.MyLDAPBackend", "defapp.backends.MyAuthBackend" ] Then my source code is here. from django.contrib.auth.backends import ModelBackend from django.contrib.auth.models import User from django_auth_ldap.backend import LDAPBackend class MyAuthBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): print("My auth back end is called") try: print(username) user = User.objects.get(username=username) print(user) except User.DoesNotExist: print("user can not found") return None else: if user.check_password(password) and self.user_can_authenticate(user): return user class MyLDAPBackend(LDAPBackend): def authenticate(self, username, password): print("try ldap auth") user = LDAPBackend.authenticate(self, username, password) if user: user.set_password(password) user.save() return user When I try to login the account which is exist in Ldap server, However message is like this, My auth back end is called It seems like MyLDAPBackend is not called. I suppose, class in AUTHENTICATION_BACKENDS is called in order. However dose it not work? -
'User' has no attribute 'DoseNotExist' [closed]
from django.contrib.auth.models import User class MyAuthBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): try: user = User.objects.get(username=username) except User.DoseNotExist: return None It shows AttributeError: type object 'User' has no attribute 'DoseNotExist' In my understanding Model returns the DoseNotExist, however it doesn't happen in my case. I am using Django4 Where am I wrong? -
Django or Flask or Pyscript? [closed]
I am making a website which uses some python code. For example my python code includes searching a file and some other python stuff also. So now I am confused how should I use my python file with my HTML, CSS and JS. whether I should use Django or flask or use Py script . Also I want a second answer what would be better if my deployment is on AWS and the website has 4-5 users at a time. -
<TemplateResponse> object does not have attribute data in Unit test in django
Hi guys im trying to run some unit testing based on this view here in django but it gives me the error AttributeError: 'TemplateResponse' object has no attribute 'data'. I tried to print the content or context from the TemplateResponse object but it does not retrieve the object date in order to assertEqual (compare) the data. I also tried to return a response object in the view but still getting the same error. class PostList(generics.ListAPIView): permission_classes = [IsAuthenticated] serializer_class = JobPostSerializer def get_queryset(self): user = self.request.user if user.is_superuser: return JobPost.objects.all() else: return JobPost.objects.filter(author=user) This is the unit test snippet code. class PostListTestCase(APITestCase): def setUp(self): self.author = NewUser.objects.create_user( email='testuser@testuser.com', user_name='test11', first_name="test11", password='Family123!') self.superuser = NewUser.objects.create_superuser( email='admin@admin.com', user_name='admin', first_name="admin", password='Family123!') self.post1 = JobPost.objects.create(title="Job Post 1", place="Test Place 1", description="Test description 1", job_date="2023-05-20", status="undone", slug="job-post-1", reward=1, author=self.author,) self.post2 = JobPost.objects.create( title="Job Post 2", place="Test Place 2", description="Test description 2", job_date="2023-05-22", status="done", slug="job-post-2", reward=1, author=self.superuser,) def test_get_queryset_superuser(self): self.client.login(email='testuser@testuser.com', password='Family123!') response = self.client.get('') self.assertEqual(response.status_code, status.HTTP_200_OK) queryset = JobPost.objects.all() serializer = JobPostSerializer(queryset, many=True) self.assertEqual(response.data, serializer.data) def test_get_queryset_author(self): self.client.login(email='admin@admin.com', password='Family123!') response = self.client.get('') print(response) self.assertEqual(response.status_code, status.HTTP_200_OK) queryset = JobPost.objects.filter(author=self.author) serializer = JobPostSerializer(queryset, many=True) self.assertEqual(response.data, serializer.data) -
Should I set a maximum length for journal content in the database?
I am using Django and PostgreSQL to do a Journal Application. What I'm thinking of is not limiting the length of the journal context so that the user can write as much as they want. What will happen if I don't set a maximum length? Should I set a maximum length for journal content in the database? -
Visual Studio 2022 and Django
I've just installed Visual Studio 2022 and created an empty Django project. When I run the server, Django is installed. But I can see that the editor highlights some warnings such as, in apps.py from django.apps import AppConfig I have reportMissingModuleSource Import "django.apps" could not be resolved from source I opened the file in Visual Code Studio and everything looks good. Has anyone an idea of what wrong with Visual Studio 2022? Or what I did wrong, even I just followed the steps of the MS tutorial (https://learn.microsoft.com/fr-fr/visualstudio/python/learn-django-in-visual-studio-step-01-project-and-solution?view=vs-2022). Having "wrong" warning is VS 2023 will very quickly be confusing... -
Binary data of Image as HttpResponse error in Django
I am trying to send the binary data of the image as a HttpResponse for the post request generated by python request lib. My view function is as follows : def view(request): print("--------------------------------------------") print("type of request:", request.method) if request.method =="POST": print( "line 55 EPD, content of POST:", request.body) print( "META", request.META) print( "FILES", request.FILES) print( "headers", request.headers) print( "all", request) print("Content_params",request.content_params) print("COOKIES", request.COOKIES) print("accepts", request.accepts("application/octet-stream")) print("session:", request.session) with open(r"C:\....\main\image.bin", mode='rb') as p: Image=p.read() print(type(Image)) return HttpResponse( Image, headers={'Content-Type': 'application/octet-stream'} ) and my unit test for generating request is as follows: def make_request(): import requests url = 'http://localhost:8000/view/' print("before sending the POST") print("sending") parameters = ( { 'Size':0, 'length':1, }) postresponse = requests.post(url,json=parameters,stream=True, headers= {'Content-Type':'application/json; charset=utf-8'}, timeout=10) print(postresponse.status_code) print("Now print Response") print("headers:", postresponse.headers) print("encoding:", postresponse.encoding) print("raw:",postresponse.raw) print("content:", postresponse.content) make_request() When my server is running, I receive the successful transfer of the response, but in the unit test code terminal, I receive the error as below: C:...\requests\models.py", line 899, in content self._content = b"".join(self.iter_content(CONTENT_CHUNK_SIZE)) or b"" I receive the output until postresponse.raw but unable to output postresponse.content. Any suggestion is highly appreciated. I tried using JsonResponse as return but I get an error message stating byte objects is not serializible. -
500 internal server problem in Django issued from an inexistent favicon
I am a newbie in the Django world, and I am trying to start a new Django project but in vain! first of all, I have an old favicon from another project that appears. I don't have any referred favicon in this new project even I tried to add one it was the same problem. During the handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/user/.local/lib/python3.8/site-packages/django/template/base.py", line 470, in parse compile_func = self.tags[command] KeyError: 'endif' During the handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3.8/wsgiref/handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "/home/jihan/.local/lib/python3.8/site-packages/django/contrib/staticfiles/handlers.py", line 76, in __call__ return self.application(environ, start_response) File "/home/user/.local/lib/python3.8/site-packages/django/core/handlers/wsgi.py", line 133, in __call__ response = self.get_response(request) File "/home/user/.local/lib/python3.8/site-packages/django/core/handlers/base.py", line 128, in get_response response = self._middleware_chain(request) File "/home/user/.local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 49, in inner response = response_for_exception(request, exc) File "/home/user/.local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 103, in response_for_exception response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) File "/home/user/.local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 138, in handle_uncaught_exception return debug.technical_500_response(request, *exc_info) File "/home/user/.local/lib/python3.8/site-packages/django/views/debug.py", line 52, in technical_500_response html = reporter.get_traceback_html() File "/home/user/.local/lib/python3.8/site-packages/django/views/debug.py", line 329, in get_traceback_html t = DEBUG_ENGINE.from_string(fh.read()) File "/home/user/.local/lib/python3.8/site-packages/django/template/engine.py", line 136, in from_string return Template(template_code, engine=self) File "/home/user/.local/lib/python3.8/site-packages/django/template/base.py", line 155, in __init__ self.nodelist = self.compile_nodelist() File … -
Docker container Losing all file when start from cache
I am trying to create a Dockerfile for developing Django backend. However, when I finished my Dockerfile and tried to build it, a very strange error occurred. When my container was successfully built and automatically started, all the files I had copied into it were lost. Container build log Container log I try to change the CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] to CMD ["python"] and used ls check the file, its empty. file check Then I found the last cache and used it to generate a container, and found that the process worked perfectly fine, which was the most peculiar part. Container from cache working fine Environment I'm using: Windows 11 Docker for windows v4.17.1 PyCharm 2023.1 (Professional Edition) Configuration setting Docker setting configuration setting I don't know if this is a problem with my Dockerfile or a bug with Docker, but since I need to provide my team with a Docker to complete our task, I hope to solve this problem and enable my team to build containers correctly from the Dockerfile. -
How to create django registration with email conformation code
Someone has a guide mb or tutorial about how can i make instant email verification by code like i want to register user and after he typed his email username and password in registerForm send him code on email NOT link and check that code and create user if everything is good with code And i also searching for way to do the same with drf -
Django update_or_create() from JSON when key may or may not exist
So i am create a function where data is being pushed to models from the JSON file. There is a possibility that my JSON may or may not have the desired key. but i am not sure how can i pass default value such as N/A if key not existed. Sample JSON: Here 1st object have title key and 2nd does not h {"timestamp":"2023-04-20T15:45:53.085646251+05:30","status_code":200,"content_length":17620,"failed":false, "title":Test Website} {"timestamp":"2023-04-20T15:45:53.085646251+05:30","status_code":200,"content_length":17620,"failed":false} Django view: data = [] for line in open(results.json', 'r'): data.append(json.loads(line)) for item in data: obj, created = http.objects.update_or_create(asset=item['input'], defaults={ 'status_code':item['status_code'], 'title':item['title'], 'last_added':datetime.now()},) This gives me KeyError('title') Can I add default value to be added only if key not existed? -
ERROR 404 (Page not found) in POST Method with Django
I'm creating a Django project, and I've just implemented the functions for creating, editing, listing, and deleting an instance (object) through the front-end. See below: The view to create an instance(add_category.py): def add_category(request): template_name = 'tasks/add_category.html' context = {} if request.method == 'POST': form = CategoryForm(request.POST) if form.is_valid(): f = form.save(commit=False) f.owner = request.user f.save() messages.success(request, 'Categoria adicionada com sucesso') form = CategoryForm() context['form'] = form return render(request, template_name, context) The template add_category.html: {% extends 'base.html' %} {% load widget_tweaks} {% block title %} Adicionar Categoria - {{ block.super }} {% endblock title %} {% block body %} <div class="container"> <h1>Categoria</h1> {% include 'partials/messages.html' %} <div class="row"> <div class="col-md-12"> <form action="." method="post"> {% csrf_token %} <div class="form-group"> <label for="{{ form.name.id_for_label }}">Nome</label> {{ form.name }} </div> <div class="form-group"> <label for="{{ form.description.id_for_label }}">Descrição</label> {{ form.description}} </div> <button class="btn btn-lg btn-primary btn-block mt-5" type="submit" >Salvar</button> </form> </div> </div> </div> {% endblock body %} The Url's: from django.urls import path from . import views app_name = 'tasks' urlpatterns = [ path('categorias/', views.list_categories, name='list_categories'), path('categorias/adicionar/', views.add_category, name = 'add_category' ), path('categorias/editar/<int:id_category>', views.edit_category, name = 'edit_category' ), path('categorias/excluir/<int:id_category>', views.delete_category, name = 'delete_category' ), ] so far it's working normally. See it: The template Save de object … -
Django can't show Bokeh plot's through CloudFlare tunnel
Have a **Django **website that was accessed through port forwaring in the router. Django lives in an Windows server and in a happy companion with a Bokeh server. Accessing the server ip to a dedicated port gave respons and Django got nice graphics from Bokeh. So I bought a domain and accessed the Django site via a Cloudflare Tunnel, and the Django website can’t get any grapics from Bokeh anymore. How should this be configured and what is best practic for this to work well through Cloudflare. I'am stretching my skills a bit here. Anybody who can help me solve this puzzle? Best regards Jon Helge Thougth in the beginning that the problem were in Bokeh, so installed SSL to solve communication between DJango and Bokeh. Did not solve the problem Tried to find out how Django and Bokeh communicates with each other but still not seen a drawing for how exchenge of data is done between them. But if we go localhost again all is functioning again. A bit stuck om how to go further. -
django-admin returns - zsh: [PATH] no such file or directory
I read through similar posts and learned the Path may be an issue. When I request my path I get the following: (env) Josevv@Eye-C-You env % echo $PATH /Users/Shared/codeproj/env/bin:/opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Apple/usr/bin I see a lot of repetition here. Does anything seem extraordinary here? -
Setting log factory logic from outside settings.py
I have a Django application where I want to update the standard logging to structured JSON format. I can get this working fine by adding my logging config and some business logic into settings.py, but I want to keep the business logic separate. Is there any Django built-in file (akin to the settings.py) that allows you to add some logic that Django will pick up, or can I load a file with this additional logic from settings.py? Here is what I have: settings.py LOGGING = { 'version': 1, 'formatters': { 'structured': { 'format':'%(json_structured)s', 'datefmt': "%H:%M:%S" } }, 'handlers': { ... }, 'loggers': { ... } } # Below is what I want to move from settings.py class JsonDateTimeEncoder(JsonStringFallbackEncoder): def default(self, obj): if isinstance(obj, datetime): return obj.strftime('%Y-%m-%dT%H:%M:%S%z') else: return super().default(obj) std_record_factory = logging.getLogRecordFactory() def structured_log_record_factory(*args, **kwargs) -> logging.LogRecord: record = std_record_factory(*args, **kwargs) record.json_structured = json.dumps( { 'level': record.levelname, ... }, cls=JsonDateTimeEncoder, ) return record logging.setLogRecordFactory(structured_log_record_factory) I know I can load the LOGGING config from file, but not sure how best to achieve this with the additional logic. -
Annotate a QuerySet with Exists instead of Count
I have a model which contains a ManyToManyField: class UserHasProduct(Model): user = ForeignKey(User, on_delete=CASCADE) products = ManyToManyField(Product) class Product(Model): is_nfr = BooleanField(default=False) I want to annotate my queryset with a simple is_nfr value that returns True if any of the products have is_nfr set to True. The best I could come up with is this: UserHasProduct.objects.filter(user=self.request.user).annotate( is_nfr=Count("license_code_products", filter=Q(products__is_nfr=True)) ) That works, but instead of a boolean it returns an integer. Not a huge deal, but I am still wondering if it's possible to return a boolean, and if that would help with query performance in any way (i.e. it can stop as soon as it finds the first match, no idea if it works like that). -
Django CSRF verification failed after setting SSL with Certbot
I'm currently working on a Django project that utilizes Docker, and I recently set up an SSL certificate using a containerized version of Certbot in order to secure my Django app through HTTPS. However, after implementing the SSL certificate and updating my nginx configuration, I began to experience the 'CSRF verification failed' error, which was not an issue before the setup. Previously, I was able to log into my Django app when it was using HTTP. What could be the cause of this problem? My Django setting. # settings.py ALLOWED_HOSTS = ["*"] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "corsheaders.middleware.CorsMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] if DEBUG: CORS_ALLOW_ALL_ORIGINS = True else: CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = [ 'https://example.ph', ] My previous nginx configuration. upstream api { server sinag_app:8000; } server { listen 80; location / { proxy_pass http://api; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { alias /static/; } } My new nginx configuration with SSL certificate. upstream api { server sinag_app:8000; } server { listen 80; server_name ${DOMAIN}; location /.well-known/acme-challenge/ { root /vol/www; } location / { return 301 https://$host$request_uri; } } server { listen 443 ssl; server_name ${DOMAIN}; ssl_certificate /etc/letsencrypt/live/${DOMAIN}/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/${DOMAIN}/privkey.pem; include /etc/nginx/options-ssl-nginx.conf; ssl_dhparam … -
Django show TypeError'>' not supported between instances of 'NoneType' and 'float'
I try to compare value from get with value in database. First, I get input from url as f1, f2. Then, if alert_field = 1 set f1 as f , if alert_field = 2 set f2 as f . Then, if alert_symbol = 1 compare f with alert_value using = ,if alert_symbol = 2 compare f with alert_value using >. def test(request): key = request.GET.get('key') f1 = request.GET.get('f1') f2 = request.GET.get('f2') f1 = float(f1) if f1 is not None and is_float(f1) else None f2 = float(f2) if f2 is not None and is_float(f2) else None if Key.objects.filter(api_key=key).exists(): # Alert dv = Device.objects.filter(api_key=dv_key) for dv in dv: # get all condition # Check if alert_field=1 then use f1 value to compare, if alert_field=2 then use f2 value to compare if(dv.alert_field==1): f = f1 fname = rcv_set.field1_name elif(dv.alert_field==2): f = f2 fname = rcv_set.field2_name if(dv.alert_symbol==1): # Check if alert_symbol=1 then compare with = if(f==dv.alert_value): msg = "=" lineAlert(dv_key.line_api, msg) elif(dv.alert_symbol==2): # Check if alert_symbol=2 then compare with > if(f>dv.alert_value): msg = ">" lineAlert(dv_key.line_api, msg) In database I set alert_symbol=2. I send data to get is 50 it show error like this. '>' not supported between instances of 'NoneType' and 'float' Error at … -
Django migrations - opertions to perfrom
i am building a django project and i migrate i get this message: Operations to perform: Apply all migrations: app1, app2, admin, app3, auth, authtoken, contenttypes, sessions Running migrations: No migrations to apply. when i see thae tables in the admin page i can see the changes i am doing but i dont understand how the changes are made but im getting the messgae Operations to perform if someone can please explain to me that would be halpful thanks -
Django migrations - opertions to perfrom
i am building a django project and i migrate i get this message: Operations to perform: Apply all migrations: app1, app2, admin, app3, auth, authtoken, contenttypes, sessions Running migrations: No migrations to apply. when i see thae tables in the admin page i can see the changes i am doing but i dont understand how the changes are made but im getting the messgae Operations to perform if someone can please explain to me that would be halpful thanks -
TemplateDoesNotExist at /app/search_flights/ in Django
I'm making a web app that lets a user login, logout, search a flight, book a flight and view the bookings made. For some reason the 'search_flights/html' is not being rendered or Django's not being able to find it. I spent a lot of time trying to debug it but with no luck. Project directory (I've included search_flights.html both in the root templates folder as well as the app templates folder as of now to see if changing anything will work, but it didn't) flight └─ flight_booking ├─ app │ ├─ admin.py │ ├─ apps.py │ ├─ migrations │ │ ├─ 0001_initial.py │ │ ├─ __init__.py │ │ └─ __pycache__ │ │ ├─ 0001_initial.cpython-39.pyc │ │ └─ __init__.cpython-39.pyc │ ├─ models.py │ ├─ templates │ │ ├─ app │ │ │ ├─ book_flight.html │ │ │ └─ search_fights.html │ │ └─ base.html │ ├─ tests.py │ ├─ urls.py │ ├─ views.py │ ├─ __init__.py │ └─ __pycache__ │ ├─ admin.cpython-39.pyc │ ├─ apps.cpython-39.pyc │ ├─ forms.cpython-39.pyc │ ├─ models.cpython-39.pyc │ ├─ urls.cpython-39.pyc │ ├─ views.cpython-39.pyc │ └─ __init__.cpython-39.pyc ├─ db.sqlite3 ├─ flight_booking │ ├─ asgi.py │ ├─ settings.py │ ├─ urls.py │ ├─ views.py │ ├─ wsgi.py │ ├─ __init__.py … -
Uploading file in django but in data base it just save its nome and didnot found any file in media folder
I am new in Django I am working on a project where user will able to add file name and its file file can be **doc, img, pdf, csv ** i want that to be saved but when i upload them they didn't get saved here is my code **model.py** class Resources(models.Model): resource_name = models.CharField(max_length=255) rec_file = models.FileField(upload_to = "resources/", max_length=10000, null=True, default=None) created_at = models.DateField(auto_now=True) **view.py** def add_resources(request): title="Add Resources" requesturl = request.get_full_path title = 'Create Clinic' if request.method == "POST": resource_name = request.POST.get('resource_name') resource_file = request.POST.get('resource_file') resource_instances = Resources.objects.create( resource_name = resource_name, rec_file = resource_file ) resource_instances.save() return render(request, 'add_resources.html',{'title':title, 'requesturl':requesturl}) **setting.py** MEDIA_ROOT = BASE_DIR/"media" MEDIA_URL = "/media/" **url.py** from django.conf import settings from django.conf.urls.static import static if settings.DEBUG: urlpatterns+=static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) when i upload the file it just save the file name and nothing is saved in the media folder please help thank you -
How to count row from backref in template?
I have a question. I need to count MemePositiveRating for Meme in template. I try meme.memeratingpositive|length but not working. There is any idea to do it with Abstract layer in models ? home.html <a class="mr-2" href="#">{{ meme.memeratingpositive|length }}</a> models.py class Meme(models.Model): title = models.CharField(max_length=100) meme = models.ImageField(upload_to='memes') creation_date = models.DateField(default=timezone.now) profile = models.ForeignKey(Profile, on_delete=models.CASCADE) def __str__(self): return f'Meme id: {self.id}' class MemeRating(models.Model): meme = models.ForeignKey(Meme, on_delete=models.CASCADE, related_name = 'ratings', blank = True, null = True) profile = models.ForeignKey(Profile, on_delete=models.CASCADE) class Meta: abstract: True class MemeRatingPositive(MemeRating): pass class MemeRatingNegative(MemeRating): pass views.py class HomeView(ListView): template_name = 'meme/home.html' model = Meme context_object_name = 'memes' def get_queryset(self): return Meme.objects.filter(memestatus__is_in_moderating_room=False, memestatus__is_in_waiting_room=False) -
SELECT app_product.id FROM app_product left JOIN app_order ON app_product.id = app_order.product_id GROUP BY app_product.id
this is sql quary how to convert in django orm please given this problem solution