Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Heroku Django get error 500 when Debug = False
None of the answers from the similar questions helped me. Hello guys i will dump a bunch of the log items from "heroku logs" because i dont have enough knowladge to filter it I tried my best in finding for myself the response but i didnt get it 2022-04-11T01:38:21.468915+00:00 app[api]: Release v23 created by user kaynanrodrigues.nt@gmail.com 2022-04-11T01:38:21.894310+00:00 heroku[web.1]: Restarting 2022-04-11T01:38:22.078216+00:00 heroku[web.1]: State changed from up to starting 2022-04-11T01:38:23.440307+00:00 heroku[web.1]: Stopping all processes with SIGTERM 2022-04-11T01:38:23.902672+00:00 heroku[web.1]: Process exited with status 0 2022-04-11T01:38:33.564199+00:00 heroku[web.1]: State changed from starting to up 2022-04-11T01:39:19.769086+00:00 heroku[router]: at=info method=GET path="/" host=quiet-ravine-74023.herokuapp.com request_id=2a1e2ccb-5923-4a73-9b51-4f172c653ccf fwd="177.124.150.24" dyno=web.1 connect=0ms service=428ms status=500 bytes=451 protocol=https 2022-04-11T01:39:19.770060+00:00 app[web.1]: 10.1.55.102 - - [10/Apr/2022:22:39:19 -0300] "GET / HTTP/1.1" 500 145 "-" "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Mobile Safari/537.36" 2022-04-11T02:13:35.839258+00:00 heroku[web.1]: Idling 2022-04-11T02:13:35.841484+00:00 heroku[web.1]: State changed from up to down 2022-04-11T02:13:36.656264+00:00 heroku[web.1]: Stopping all processes with SIGTERM 2022-04-11T02:13:37.856205+00:00 heroku[web.1]: Process exited with status 0 2022-04-11T02:29:07.000000+00:00 app[api]: Build started by user kaynanrodrigues.nt@gmail.com 2022-04-11T02:29:47.486991+00:00 app[api]: Deploy 436002d8 by user kaynanrodrigues.nt@gmail.com 2022-04-11T02:29:47.486991+00:00 app[api]: Running release v24 commands by user kaynanrodrigues.nt@gmail.com 2022-04-11T02:29:48.066613+00:00 app[api]: Starting process with command `/bin/sh -c 'if curl $HEROKU_RELEASE_LOG_STREAM --silent --connect-timeout 10 --retry 3 --retry-delay 1 >/tmp/log-stream; then 2022-04-11T02:29:48.066613+00:00 app[api]: … -
Get the encrypted value in django-fernet-fields
I use the django-fernet-fields library: class RoutePoint(models.Model): username = models.CharField(max_length=30) password = EncryptedCharField(max_length=30, null=True) When I access an encrypted field, the value of the field is automatically decrypted. p = RoutePoint.objects.all()[0] print(p.password) > mypass Is there any way I can get the encrypted value that is actually stored in the database? -
Reverse for 'user_page' with keyword arguments '{'pk': ''}' not found. I beleive my decorators are causing the issue
So my login view takes the user to the home.view but first checks user is logged in and then checks if the user is an admin or not through the decorator 'admin_only'. My user will prove to be false for this scenario (which is expected). The user is then redirected to the user_page view to which first goes through the decorator allowed_users (which will be true) and then the user_page view. My aim is to pass the primary key at login_user view to user_page view but the middle men decorators I believe are causing me problems. views.py @unauthenticated_user def login_user (request): user = None if request.method == 'POST': temp_username = request.POST.get('username') temp_password = request.POST.get('password') user = authenticate(request, username=temp_username, password=temp_password) if user is not None: login(request, user) context = {'user':user} print ('Primary key in login view = ', user.id) return redirect('home', context) else: messages.info(request, "Username or Password is incorrect!") context = {'user':user } return render(request, 'login.html', context) @login_required(login_url='login') @admin_only def home(request, pk): user = User.objects.get(id=pk) context = {'user':user} return render(request,'home.html',context) @login_required(login_url='login') @allowed_users(allowed_roles=['customer']) def user_page(request,pk): user = User.objects.get(id=pk) context = {'user':user} return render(request, 'user.html', context) urls.py #url.py path('user/<int:pk>/', views.user_page, name='user_page') path('', views.home, name='home'), decorators.py def allowed_users(allowed_roles=[]): def decorator(allow_users_view_function): def wrapper_function(request, *args, **kwargs): … -
How to store a Keras .h5 file in a Django database?
I have several Keras .h5 files that I want to store using a Django model. In the Django docs there is no model field designed for .h5 files. Is there and way I can convert it to a json and store it as that or is there another go to way for doing this? -
Qual os conhecimentos indispensáveis para um back-end pleno em python?
Qual os conhecimento indispensável para um back-end python pleno, e qual o legal saber? -
Can't create links to any Django admin templates beside index.html?
I'm trying to create a link to Django's admin/auth/user/add/ to let users create an account to login with. This is when I ran into the problem that even though setting href="{% url 'admin:index' %}" works for linking to the admin's index.html, replacing index with any other template's name doesn't work. So, I have no way of adding new accounts. -
ValueError: Field 'id' expected a number but got '<built-in function id>'; POST request redirect
When a User successfully makes a POST request to edit their own question, they are redirected to a detail page for the same question. When a subsequent GET request is sent to the PostedQuestionPage view after editing a question, the following ValueError is raised when trying retrieve an instance with get_object_or_404(): ValueError: Field 'id' expected a number but got '<built-in function id>' Why is PostedQuestionPage being passed '<built-in function id>' and not a value that is suppose to represent a question instance id? > c:\..\posts\views.py(137)get() -> question = get_object_or_404(Question, id=question_id) (Pdb) ll 134 def get(self, request, question_id): 135 import pdb; pdb.set_trace() 136 context = self.get_context_data() 137 -> question = get_object_or_404(Question, id=question_id) 138 context['question'] = question 139 return self.render_to_response(context) (Pdb) question_id '<built-in function id>' (Pdb) n ValueError: Field 'id' expected a number but got '<built-in function id>'. > c:\..\posts\views.py(137)get() -> question = get_object_or_404(Question, id=question_id) (Pdb) n --Return-- > c:\..\posts\views.py(137)get()->None -> question = get_object_or_404(Question, id=question_id) class TestPostEditQuestionPage(TestCase): '''Verify that a message is displayed to the user in the event that some aspect of the previous posted question was edited.''' @classmethod def setUpTestData(cls): cls.user = get_user_model().objects.create_user( username="OneAndOnly", password="passcoderule" ) profile = Profile.objects.create(user=cls.user) tag = Tag.objects.create(name="TagZ") question = Question.objects.create( title="This is Question Infinity", body="The … -
Django form not showing up in template
My problem is not showing up form in the Django template. I'm using python 3.7.6 Django 3.2 Here is my code .................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................... forms.py from django import forms from tasks.models import Task, TaskType class TaskForm(forms.ModelForm): name = forms.CharField(max_length=100, required=True, widget=forms.TextInput(attrs={'class': 'form-control'})) input_image = forms.ImageField(widget=forms.FileInput( attrs={'class': 'form-control-file'})) task_type = forms.ModelChoiceField(queryset=TaskType.objects.name.all(), widget=forms.Select( attrs={'class': 'form-control'})) class Meta: model = Task fields = ['name', 'input_image', 'task_type'] view.py from django.shortcuts import render, redirect from tasks.forms import TaskForm def create_task(request): if request.method == 'POST' and 'submit-task' in request.POST: task_form = TaskForm(request.POST, request.FILES, instance=request.user) if task_form.is_valid(): task_form.save() return redirect(to='dashboard') return render(request, 'users/dashboard.html', {'task_form': task_form}) dashboard.html <form method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="modal fade" id="myModal"> <div class="modal-dialog modal-fullscreen-lg-down"> <div class="modal-content"> <!-- Modal Header --> <div class="modal-header"> <h4 class="modal-title">Upload your image</h4> <button type="button" class="btn-close" data-dismiss="modal" ></button> </div> <!-- Modal body --> <div class="modal-body"> <div class="form-group"> <label class="">Task name</label> {{task_form.name}} <div class="input-group"> <select class="custom-select" id="inputGroupSelect04"> <option selected>Choose your model</option> {{task_form.task_type}} </select> <span class="input-group-btn"> <span class="btn btn-outline-dark btn-file"> Browse… {{task_form.image_input}} </span> </span> <input type="text" class="form-control" readonly /> </div> <img id="img-upload" /> </div> </div> <!-- Modal footer --> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal" > Close </button> <button type="button" class="btn btn-primary" name="submit-task"> Save changes </button> </div> </div> </div> </div> </form> So, … -
Failed to load resource: net::ERR_INCOMPLETE_CHUNKED_ENCODING in Django deployed to Heroku
How to fix this error? I have set a server-sent event that sends data only if there is new data in the database to the frontend. but every minute it keeps on sending data even though there is no new data in the database. This problem is not present during development, but when deployed to Heroku this error shows. views.py def event_stream(): initial_data = "" while True: deposit_records = Deposit.objects.filter().values('date').order_by( '-id').annotate(bottles=Sum('number_of_bottles'), credits=Sum('credits_earned'), not_bottle=Sum('not_bottle')) bottle = Deposit.objects.aggregate(Sum('number_of_bottles'))[ 'number_of_bottles__sum'] # deposit_records = Deposit.objects.order_by( # "-id").values("number_of_bottles", "credits_earned", "date") data = json.dumps(list(deposit_records) + list(str(bottle)), cls=DjangoJSONEncoder) # print(data) if not initial_data == data: yield "\ndata: {}\n\n".format(data) initial_data = data time.sleep(1) def stream(request): response = StreamingHttpResponse(event_stream()) response['Content-Type'] = 'text/event-stream' return response JS var eventSource = new EventSource("{% url 'stream' %}") eventSource.onopen = function(){ console.log('yay its open'); } eventSource.onmessage = function(e){ if(!e){ eventSource.end() } else{ console.log(e) var final_data = JSON.parse(e.data) } eventSource.onerror = function(e) { console.log(`error ${e}`); } -
InvalidArgument when calling the PutObject operation: None
i try to use boto3 and django-storages for media storage when i try to upload image its throws me an error like this: ClientError at /admin/myschool/secondary/add/ An error occurred (InvalidArgument) when calling the PutObject operation: None even in my admin panel. i'm a begineer i don't know how this work this is my first time using AWS after i switch from cloudinary to aws S3. i have setup everything as you can see here in my settings.py file: AWS_ACCESS_KEY_ID = '' AWS_SECRET_ACCESS_KEY '' AWS_STORAGE_BUCKET_NAME '' AWS_S3_FILE_OVERWRITE = 'False' AWS_DEFAULT_ACL = 'None' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' this is my Cross-origin resource sharing (CORS): [ { "AllowedHeaders": [ "*" ], "AllowedMethods": [ "GET", "HEAD" ], "AllowedOrigins": [ "*" ], "ExposeHeaders": [], "MaxAgeSeconds": 3000 } ] Access control list (ACL): Grantee Objects Bucket ACL Bucket owner (your AWS account) Canonical ID: '' List Write Read Write Edit Object Ownership ACLs disabled (recommended) is anybody who can help me please ? -
Django Can't CSS / customize image
I want to center an image and it doesn't work. I cant customize the image at all with my CSS files. home.html {% load static %} <link rel="stylesheet" href="{% static 'stylehome.css' %}"> <div class="testimage"> <img src="{% static 'images/bottrade.jpg'%}" alt="erar"> </div> stylehome.css .testimage { display: block; margin-left: auto; margin-right: auto; width: 50%; } -
Hello, I am completely lost with this error: ModuleNotFoundError: No module named 'django.contrib.authpolls'
I know that this is not really how stackoverflow is supposed to be used and I apologize if I wasted your time with this question. But I keep getting this error when I try to run my django applications on pythonanywhere and I do not have any idea why. I do not recall using such thing as django.contrib.authpolls or at least I cannot find it anywhere in my settings.py or any other file. I found, that a missing comma in the INSTALLED APPS in the settings.py file could be the source of this issue, but i checked it and thats not my case. So please could you guys help me out. Thank you so much in advance. Traceback (most recent call last): File "/home/jaca2288/django_projects/mysite/manage.py", line 22, in <module> main() File "/home/jaca2288/django_projects/mysite/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/jaca2288/.local/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/jaca2288/.local/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/home/jaca2288/.local/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/jaca2288/.local/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/jaca2288/.local/lib/python3.9/site-packages/django/apps/config.py", line 212, in create mod = import_module(mod_path) File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File … -
Django + mod_wsgi + apache2 : Module not found
im trying to host my django webapp on a VPS where I have root access. I followed the official django mod_wsgi apache tutorial and its almost working.. but my virtual env don't work because wsgi can't find django module. I've done a lot a research on this topic but my soul is slowly dying right now. help. I don't understand why it don't work, I've tested my venv at /home/env by doing an import django and it works... Here is my apache virtualHost conf file : ServerAdmin admin@elytrasfr.localhost ServerName 127.0.1.1 ServerAlias localhost DocumentRoot /var/www/elytras ErrorLog /var/www/elytras/error.log CustomLog /var/www/elytras/access.log combined Alias /static /var/www/elytras/static <Directory /var/www/elytras/ecommerce> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /var/www/elytras/ecommerce/wsgi.py process-group=elytras WSGIDaemonProcess elytras python-home=/home/env python-path=/var/www/elytras WSGIProcessGroup elytras </VirtualHost> The error I got (on firefox): Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator at admin@elytrasfr.localhost to inform them of the time this error occurred, and the actions you performed just before this error. More information about this error may be available in the server error log. my logs : [Sun Apr 10 22:04:45.615774 2022] [wsgi:info] [pid 1088:tid 139742691768064] [remote 92.154.56.19:60814] mod_wsgi (pid=1088, … -
assertRedirects(response) triggers NoReverseMatch error;
I'm testing a scenario where a User successfully edits an answer in response to a question. Once the answer is edited, the user is redirected to a listing page with the question and all answers posted. The problem being encountered is that the user is not being redirected; a NoReverseMatch error is being raised: Reverse for 'question' with keyword arguments '{'id': 1}' not found. 1 pattern(s) tried: ['questions/(?P<question_id>[^/]+)/$'] self.assertRedirects() is trigger this error within in the test. Yet, I cannot pinpoint why it's being raised when question_id is being passed into the reverse("posts:question", kwargs={"question_id": answer.question.id}) call of assertRedirects()? It's saying that the key is 'id'? class TestEditInstanceAnswerPage(TestCase): '''Verify that a User who has posted an Answer to a given Question has the ability to edit their answer.''' @classmethod def setUpTestData(cls): cls.user = get_user_model().objects.create_user("TestUser") cls.profile = Profile.objects.create(user=cls.user) cls.answer_user = get_user_model().objects.create_user("TheAnswer") cls.answer_profile = Profile.objects.create(user=cls.answer_user) cls.tag = Tag.objects.create(name="Tag1") cls.question = Question.objects.create( title="How do I get an answer to my post", body="This is the content that elaborates on the title that the user provided", profile=cls.profile ) cls.question.tags.add(cls.tag) cls.answer = Answer.objects.create( body="This is an answer in response to 'How do I get an answer to my post'", question=cls.question, profile=cls.answer_profile ) cls.data = { "body": "This … -
django-elasticsearch-dsl Object of type 'AttrList' is not JSON serializable
I have a Django application where I need to implement a search system, for this application, elasticsearch seems to be the most suitable, but I came across a problem that I can't solve. I have in postgres a table with a column of type jsonb similar to this: [ { "act": 1900, "max": 2850, "min": 2850, "tgt": 2850, "desc": "L - Durchsatz (kg/h)", "name": "L - Durchsatz (kg/h)", "unit": "kg/h", "color": "red", "ordering": 1, "monitoring": true }, { "act": 283, "max": 425, "min": 425, "tgt": 425, "desc": "L - Siebbandgeschwindigkeit (m/min)", "name": "L - Siebbandgeschwindigkeit (m/min)", "unit": "m/min", "color": "red", "ordering": 2, "monitoring": true }, ... ] Django Model: class Collect(models.Model): recipe = models.ForeignKey(RecipeSentHistory, on_delete=models.CASCADE, null=True, default='1') general_info = models.JSONField(default=dict) record = models.JSONField(default=dict) justify = models.CharField(max_length=255, default='*') automatic = models.BooleanField(default=False) user = models.CharField(max_length=255, default='*') user_job_position = models.CharField(max_length=255, default='*') timestamp = models.DateTimeField(default=timezone.now) def __str__(self): return self.recipe.machine.name My serializer: class MyCollectSerializer(serializers.ModelSerializer): class Meta: model = Collect fields = [ 'justify', 'record', 'user', 'user_job_position', 'timestamp', 'automatic', 'recipe_id', 'general_info', ] read_only = True My documents.py: from django_elasticsearch_dsl import Document, fields from django_elasticsearch_dsl.registries import registry from mpa.models import Collect @registry.register_document class CollectDocument(Document): general_info = fields.ObjectField( properties={ 'batch': fields.TextField(), 'machine': fields.TextField(), 'recipe_cep': fields.TextField(), 'recipe_mpa': fields.TextField(), 'fabrication_order': … -
Django: How to store certain objects of a model in another model
I am currently trying to create a user profile that will contain the courses that the user chose. Currently, the user profile model is UserProfile and the courses are objects of Course. I've tried using the ManyToMany field but that just results in UserProfile storing all courses in Course. The two models are stored in different apps. models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default="default.jpg", upload_to="profile_pics") courses = models.ManyToManyField("course.Course", blank=True, default=None, related_name = "courses") def __str__(self): return f"{self.user.username} Profile" Any help is appreciated. Thanks. -
How can I get the total objects returned in Django queryset within my aggregation?
If I have a model: class Book(models.Model): name = models.CharField(max_length=100) ... And I do a query: Book.objects.filter(name__icontains="The").aggregate(number_of_books=Count("*"), ...) Here, I'm filtering the books to only return ones that contain the The substring, and doing an aggregation. I want the resulting dict to tell me, among other things, how many items were in my queryset. This should be the same as if I did Book.objects.filter(name__icontainers="The").count(). What will get me the total number of items (Books) in my queryset? Count("*") was just a guess, but it seems to work. Is that correct? -
How to create an API using django
I need to create an API using django. My api should call a query that I have created . Here is the code of my query : import pymongo from pymongo import MongoClient client = MongoClient("mongodb://localhost:27017/") db = client['db3']['aliex3'] dbColumn = db["comments"] query = { "Feedback.country": "MA" } docs = dbColumn.find(query) for x in docs: print(x) My query select from my mongodb database comments that are from country x. My API takes as imput this country and give as output list of comments with this country. This is my database schema : { "_id": { "$oid": "624718162b554a6ec1efb625" }, "Title": "Original TWS Y50 Fone Bluetooth Headphones Sports Outdoor Wireless Earphones Touch Control Headset with Charging Box Y50 Earbuds ", "Price": "37.69", "Currency": "MAD", "Stars": "4.7", "Orders": "1066 sold", "Shipcost": "Free Shipping", "Supplier": "Shop5524084 Store", "Productlinks": "https://www.aliexpress.com/item/1005003705651241.html?algo_pvid=c95de82c-2500-44f3-998b-ddd2c220d3fa&algo_exp_id=c95de82c-2500-44f3-998b-ddd2c220d3fa-0&pdp_ext_f=%7B%22sku_id%22%3A%2212000026872977176%22%7D&pdp_pi=-1%3B37.69%3B-1%3B-1%40salePrice%3BMAD%3Bsearch-mainSearch", "Feedback": [ { "country": "LK", "comment": "ok", "images": [] }, { "country": "PK", "comment": "order received on the time, with great quality.", "images": [ "https://ae01.alicdn.com/kf/Uc5faae18cdd34cba9d4e26d46ae3291eg.jpg" ] }, { "country": "CL", "comment": "excellent", "images": [] }, { "country": "BR", "comment": "Very good", "images": [] }, { "country": "UA", "comment": "Згідно опису. Працює задовільно", "images": [] }, { "country": "BY", "comment": "They work well, they end up … -
JS addEventListener "input" automatically extract what the user typed, I can not reach user Input
Im trying connect JS inside my Django project I got message in console "InputEvent" but I would like to get currency name thats in my wallet I dont know why In this part of code "calculate" I got 2 values curr1 and a1 with out any problems c1[i].addEventListener("change", function() { calculate(curr1,a1); }, false); amount1[i].addEventListener("input", function() { calculate(curr1,a1); }, false); but here c1[i].addEventListener("change", function() { calculate2(curr1); }, false); I received only InputEvent without currency name and also when I use amountAmount.addEventListener("input", calculate2); it works live what the amount put as a input immediately it changes but in here c1[i].addEventListener("change", function() { calculate(curr1,a1); }, false); amount1[i].addEventListener("input", function() { calculate(curr1,a1); }, false); It does not works if I change the amount, nothing happens HERE HOW ITS LOOKS LIKE IN MY WEB BROWSER https://i.stack.imgur.com/BkEEm.png here is the part of html {% extends "web/layout.html" %} {% block body %} <br><br><br> <div id="jumbotron" class="jumbotron" style="text-align: center; margin-top:-50px"> <h1 id="devise" class="display-5">Devise </h1> <h5>Exchange Rate Converter</h5> <img src="image.jpg" class="image" style="width:100px; margin-bottom:-50px; " > </div> <div class="container"> <div class="page-header" id="banner"> <div class="row"> <div class="col-sm-15"> <h1 style="align-content: center;"> </h1> <p class="lead" style="margin-left:280px; font-size:2rem"> </p> </div> </div> </div> <div class="row"> {% for item in buttons %} {% for money_purchased in user_purchased_currencies … -
Django Filter not working with user choosen place
in the code the product is assigned with place, so the products should be come with user choosen place. But now i am getting all the products name with user choosen place also those products are not assigned with any country. def formfield_for_manytomany(self, db_field, request, **kwargs): if db_field.name == ("places","coffee"): kwargs["queryset"] = models.Region.objects.filter( country=request._user_places, ) return super().formfield_for_manytomany(db_field, request, **kwargs) -
heroku python error ' at=error code=H14 desc="No web processes running'
I made a simply website using django and am trying to deploy to Heroku. But I get the following error message when i try to open the web page: Application error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command heroku logs --tail And this is what i find in the logs: 2022-04-10T18:53:57.509376+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=safe-earth-20673.herokuapp.com request_id=fdb90caf-8174- 4ca3-9871-2046f928c959 fwd="62.163.104.251" dyno= connect= service= status=503 bytes= protocol=https If I use the 'heroku local web' command i get this error: [WARN] ENOENT: no such file or directory, open 'Procfile' [FAIL] No Procfile and no package.json file found in Current Directory - See run-foreman.js -- help And this is what is in my Procfile: web: gunicorn ullie_diary.wsgi --log-file - My Procfile is in the same directory as manage.py. I also have the requirements.txt and runtime.txt files in the same directory. I tried this solution: web: gunicorn ullie_diary.wsgi --log-file - But it doesn't work. I've checked out other questions with the same problem on Stack overflow but can't figure out what the … -
NoReverseMatch at /blog/redirect2
I'm new to django and I've been trying to test the URLs redirection methods I've tried two options but the return render() keeps giving me this error of no reverse match this is my urls.py code : app_name = 'blog' urlpatterns = [ # path('about', views.about, name = 'about'), path('about.html', views.about, name='about'), path('home.html', views.home, name='home'), # path('home', views.home, name ="home") path('redirect', views.redirect_view), path('redirection_fct',views.redirection_fct, name='redir_fct'), #redirection par la fonction as_view path('redirect1', RedirectView.as_view(url='http://127.0.0.1:8000/blog/redirection_fct')), path('redirect2', views.redirect_view1), ] and this is my views file : def about(request): return render(request, 'about.html', {}) def home(request): return render(request, 'home.html', {}) #redirection par HttpResponseRedirect def redirect_view(request): return HttpResponseRedirect("redirection_fct") def redirect_view1(request): return redirect('redir_fct') def redirection_fct(request): return render(request, 'redirection.html', {}) Is there something wrong with my URLs pattern or it is the render one? -
How to check if a relation exists? M2M
I have models: class User(models.Model): ... group = models.ManyToManyField( Group, related_name="users_group", ) class Group(models.Model): .... How to check in serializer is the Group empty (there is no relationship with User) My version is : class GroupSerializer(serializers.ModelSerializer): empty = serializers.SerializerMethodField() class Meta: ... def get_empty(self, obj): return not User.objects.filter(group=obj).exists() But maybe there is an even better way. -
I got an error when installing django-pyqt library
I tried to install the django-pyqt library using the following command PS C:\Windows\system32> py "C:\Users\mehdi\Desktop\myfiles\python\git hub\django-pyqt-master\django-pyqt-master\setup.py" but i got this Error PermissionError: [WinError 5] Access is denied: 'C:\Users\mehdi\.django-pyqt\drivers\etc\hosts' I followed the installation method exactly from the site and I will put the link below https://github.com/ZedObaia/django-pyqt -
Unable to read environment variables in Django using django_configurations package
I was using django-environ to manage env variables, everything was working fine, recently I moved to django-configurations. My settings inherit configurations.Configuration but I am having trouble getting values from .env file. For example, while retrieving DATABASE_NAME it gives the following error: TypeError: object of type 'Value' has no len() I know the below code return's a value.Value instance instead of a string, but I am not sure why is that behaviour. The same is the case with every other env variable: My .env. file is as follows: DEBUG=True DATABASE_NAME='portfolio_v1' SECRET_KEY='your-secrete-key' settings.py file is as follows ... from configurations import Configuration, values DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': values.Value("DATABASE_NAME", environ=True), ... I have verified that my `.env' file exists and is on the valid path. Any help would be appreciated.