Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can i direct a form to specific user with Django?
Hello I have created a model for a form that asks for the recipient, title, content of the message. I want that message to be viewed by the recipient only how can i do that? -
How to display a text, from a python program, to a HTML form in Django?
I am new to Django and web programming and HTML. I am trying to create a webpage using Django, with following functionality: When the page is browsed for the first time, it should invoke a program rules.py and display a text output from rules.py to a paragraph in the page. The page contains a form with label as 'name'. The user will look at the message displayed from rules.py and enter a name in the form and click on 'submit' On clicking submit, the page should POST the request, alongwith the 'name' entered and execute program validate.py, that returns a numeric code (0: success, 1: invalid), and a text (next instruction if success, error message is failure). This text should be displayed back to my page, in the same place where the output from rules.py was displayed earlier. Then based on the message displayed, user will enter another name, and same process will repeat. How to display a text in the form that is output from a python program? I am able to display the output in the label of the input name field, using code below. But I don't want to change the label, I want a paragraph / … -
I can't connect to minio service from another service in docker-compose
I have my minio setup in docker compose like this : service: minio: image: minio/minio:RELEASE.2020-09-21T22-31-59Z container_name: backend-minio volumes: - minio:/data environment: MINIO_ACCESS_KEY: minio MINIO_SECRET_KEY: minio123 expose: - 9000 command: server /data volumes: minio: I want to connect to the minio from another app I use minio:9000 or localhost:9000 as the url I get this error for both : urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='minio', port=9000): Max retries exceeded with url: /django?location= (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fb222a79810>: Failed to establish a new connection: [Errno 111] Connection refused')) what's wrong with the minio config in the docker compose I also checked and all env variables are set any idea? -
Django URLS Slugs Multiple Paths
I am working on a website with Django that has one template for a model class that has two items in the database, categoryone and categorytwo, but I need the index.html template to link to different urls for each item of the model class, so one url path for categoryone and another for categorytwo, as they are both different sections of a website with the same index template, how can I do this using only one template? Thank you! models.py class PostSection(models.Model): section_heading = models.CharField(max_length=30) section_desc = models.CharField(max_length=300, blank=True, null=True) class Meta: ordering = ['section_heading'] verbose_name_plural = 'Content Section' def __str__(self): return f"{self.section_heading}" class Post(models.Model): post_section = models.ForeignKey(PostSection, on_delete=models.CASCADE, related_name="posts") post_heading = models.CharField(max_length=30, unique=True) post_desc = models.CharField(max_length=300, blank=True, null=True) post_img = models.ImageField(upload_to= 'media', blank=True, null=True) post_highlight_img = models.ImageField(upload_to= 'highlights', blank=True, null=True) post_highlight_desc = models.CharField(max_length=300, blank=True, null=True) post_date = models.DateField(null=True, blank=True) featured = models.BooleanField(default=False) order = models.IntegerField(blank = True, null = True) tag = models.ManyToManyField(Tag, help_text="sth", blank=True, null=True) slug = models.SlugField(null=False, blank=False, unique=True) def __str__(self): return self.slug class Meta: ordering = ('order', 'post_date') def display_tag(self): return ', '.join([ tag.name for tag in self.tag.all()[:8] ]) display_tag.short_description = 'Tag' def save(sender, instance, *args, **kwargs): instance.slug = slugify(instance.post_heading) def get_absolute_url(self): return reverse("architecture", kwargs={"slug": self.slug}) … -
'admin-chat' is not a registered namespace
Whenever I click the button this error showup I have no idea why is this happening. error NoReverseMatch at /admin-chat-list/ 'admin-chat' is not a registered namespace html file <form mthod="POST" action="{% url 'admin-chat:{{data.email}}' %}"> <input type="submit" value="CHAT"> </form> urls.py path('admin-chat/<str:merchant_email>/', views.admin_chat, name='admin-chat'), views.py def admin_chat(request, merchant_email): print(merchant_email) if request.method == 'POST': msg = request.POST['message'] Message.objects.create(sender=request.user, receiver=merchant_email, message=msg) return redirect('admin-chat') return render(request, 'dashboard/admin/chat.html') -
Need help in final year project urgently
Any web developer who knows Django and JavaScript well . Need help urgently. Please someone willing to help via zoom meeting? -
How to use function TruncDay(or another one like TruncMonth) to sum results from two or more models?
for example I'm using this query to get counts by month: Item1.objects .annotate(month=TruncMonth('timestamp')) .values('month') .annotate(c=Count('id')) .values('month', 'c') now to every month I want to sum every month of the second model (Item2) Item2.objects .annotate(month=TruncMonth('timestamp')) .values('month') .annotate(c=Count('id')) .values('month', 'c') Can i do this with the ORM instead programatically? i know that i can iterate the results and sum if the month match, but i don't want to do that. -
Django model based on an SQL table-valued function using MyModel.objects.raw()
If it's relevant I'm using Django with Django Rest Framework, django-mssql-backend and pyodbc I am building some read only models of a legacy database using fairly complex queries and Django's MyModel.objects.raw() functionality. Initially I was executing the query as a Select query which was working well, however I received a request to try and do the same thing but with a table-valued function from within the database. Executing this: MyModel.objects.raw(select * from dbo.f_mytablefunction) Gives the error: Invalid object name 'myapp_mymodel'. Looking deeper into the local variables at time of error it looks like this SQL is generated: 'SELECT [myapp_mymodel].[Field1], ' '[myapp_mymodel].[Field2] FROM ' '[myapp_mymodel] WHERE ' '[myapp_mymodel].[Field1] = %s' The model itself is mapped properly to the query as executing the equivalent: MyModel.objects.raw(select * from dbo.mytable) Returns data as expected, and dbo.f_mytablefunction is defined as: CREATE FUNCTION dbo.f_mytablefunction ( @param1 = NULL etc etc ) RETURNS TABLE AS RETURN ( SELECT field1, field2 etc etc FROM dbo.mytable ) If anyone has any explanation as to why these two modes of operation are treated substantially differently then I would be very pleased to find out. -
Django forms - create a form for each object in model, and then save to the corresponding PK
I'm new to django (and programming in general). Sorry if I used the wrong vocabulary (and please correct me). This is what i'm trying to do: I have this model: Class A(models.Model): name = models.CharField(max_length=100, null=True, default='John') first_number = models.FloatField(blank=True, default=1) second_number = models.FloatField(blank=True, default=2) third_number = models.FloatField(blank=True, default=3) And I have this form: class Numbers(ModelForm): class Meta: model = A fields = ['first_number', 'second_number'] In my template, I created a for for x in a (given that 'a' is A.objects.all()): {% for x in a %} {{form}} {% endfor %} When I submit the form, though, I cant get the corresponding numbers. I only saves the last number I enter in both 'first_number' and 'second_number' for the both objects that I created. How can I save the correct values? -
Automatically configuring settings to local or production depending on the IP address
I have 4 settings files - __init__.py (which controls the other 3 files) base.py (which has settings needed when running the site locally or in production mode) local2.py (which has settings needed for running the site locally) production.py (which has settings needed for running the site in production) In __init__.py I want to identify the ip address which would then dictate if we need to use local2.py or producction.py. My problem is a lot of the ways I know to capture ip address only work with request. Which from what I gather is something you pass to views. Therefore these methods do not work in my settings __init__.py file. Does anyone know a way of capturing the ip address via the setting file? I looked at Django: Get remote IP address inside settings.py but it did not help me. -
Django calculate models total field
I want to return rate, but got this error in admin unsupported operand type(s) for +: 'NoneType' and 'NoneType' class SomeModel(models.Model): code_style_rate = models.DecimalField(max_digits=4, decimal_places=2) decision_rate = models.DecimalField(max_digits=4, decimal_places=2) severity_rate = models.DecimalField(max_digits=4, decimal_places=2) @property def rate(self): return (self.code_style_rate + self.decision_rate + self.severity_rate) / 3 def __str__(self): return self.rate -
Django server returning HTML instead of JSON when using fetch()
I'm trying to fetch data from an API in my own Django server but for some reason, it is returning HTML instead of a JSON object Here's the API route Im tring to fetch from: path("emails/<str:mailbox>", views.mailbox, name="mailbox") Here's the mailbox function in views.py: @login_required def mailbox(request, mailbox): # Filter emails returned based on mailbox if mailbox == "inbox": emails = Email.objects.filter( user=request.user, recipients=request.user, archived=False ) elif mailbox == "sent": emails = Email.objects.filter( user=request.user, sender=request.user ) elif mailbox == "archive": emails = Email.objects.filter( user=request.user, recipients=request.user, archived=True ) else: return JsonResponse({"error": "Invalid mailbox."}, status=400) # Return emails in reverse chronologial order emails = emails.order_by("-timestamp").all() return JsonResponse([email.serialize() for email in emails], safe=False) Here's the model i'm trying to fetch from: class Email(models.Model): user = models.ForeignKey("User", on_delete=models.CASCADE, related_name="emails") sender = models.ForeignKey("User", on_delete=models.PROTECT, related_name="emails_sent") recipients = models.ManyToManyField("User", related_name="emails_received") subject = models.CharField(max_length=255) body = models.TextField(blank=True) timestamp = models.DateTimeField(auto_now_add=True) read = models.BooleanField(default=False) archived = models.BooleanField(default=False) def serialize(self): return { "id": self.id, "sender": self.sender.email, "recipients": [user.email for user in self.recipients.all()], "subject": self.subject, "body": self.body, "timestamp": self.timestamp.strftime("%b %-d %Y, %-I:%M %p"), "read": self.read, "archived": self.archived } Here's the JS code: if(document.querySelector('h3').innerHTML === 'Inbox'){ fetch('/emails/inbox') .then(response => response.json()) .then(emails => { console.log(emails); }); Finally, here's my console output no … -
How to serialize foreignkey in Django Rest Framwork?
I have jobs model and categories model and they have one to many relationship. so I want to get the details of category as well when i pull the job model. Abstract Job Model class JobAbstractModel(models.Model): title = models.CharField(max_length=150) no_of_vacancy = models.PositiveIntegerField() offered_salary = models.CharField(max_length=200) deadline = models.DateTimeField() education_level = models.CharField(max_length=200) description = models.TextField(blank=True) description_points = models.TextField(blank=True) skills = models.TextField() other_specification = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) updated_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='+') is_active = models.BooleanField(default=1) class Meta: abstract = True Job Model class Job(JobAbstractModel): category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='categories') job_level = models.CharField(max_length=50, choices=JOB_LEVEL_CHOICES, default='Mid') employment_type = models.CharField(max_length=50, choices=EMPLOYEMENT_TYPE_CHOICES, default='Full') experienced_required = models.FloatField() created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='jobs_created_by') def __str__(self): return self.title Category Model class Category(models.Model): name = models.CharField(max_length=150) is_active = models.BooleanField(default=1) image = models.ImageField(upload_to='categories_images/') def __str__(self): return self.id + ":"+self.name Serializers.py class CategorySerializer(serializers.ModelSerializer): image = serializers.SerializerMethodField() class Meta: model = Category fields = "__all__" def get_image(self, category): request = self.context.get('request') image_url = category.image.url return request.build_absolute_uri(image_url) class JobOverViewSerializer(serializers.ModelSerializer): #category = serializers.CharField(source='category.name', read_only=True) categories = CategorySerializer(read_only=True, many=True) class Meta: model = Job fields = ['id', 'no_of_vacancy', 'employment_type', 'experienced_required', 'categories'] jobs.py class JobCategoriesView(APIView): def get(self, request): categories = Category.objects.all() serializer = CategorySerializer(categories, many=True, context={'request': request}) return Response(serializer.data) class JobOverView(APIView): def get(self, … -
Django separate settings and .env files (python-decouple): the specified path was not found for static files
I have developed a Django Project and try to manage different configuration (dev and prod) and .env using python-decouple. Below my project architecture and different config files. Maybe I misunderstand but in my comprehension : I have differents settings.py files (dev and prod) that inherit from my "base" settings.py Some variables must be kept secret: these variable are store in .env files that will not be share (.gitignore) In production, these secret variables are read from .env in settings files I run python manage.py migrate --settings=core.settings.dev python manage.py runserver --settings=core.settings.dev and got an error FileNotFoundError: [WinError 3] The specified path was not found: 'D:\Users\xx\DevSpace\PROJECT_FOLDER\core\static' That right because static folder is at the same level as core app. But how to configure this path? - PROJECT_FOLDER |_ core |_ wsqi.py |_ settings |_ __init__.py |_ .env |_ base.py |_ dev.py |_ prod.py |_ manage.py |_ static |_ css |_ images |_ db.sqlite3 .env SECRET_KEY=rqps9azjw7i0@_(qxirwr!@0w3f)$prsky9l7bt8t-(y)_tiuj base.py from decouple import config STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR,'static'), os.path.join(BASE_DIR,'randomization/static'), os.path.join(BASE_DIR,'unblind/static'), os.path.join(BASE_DIR,'pharmacy/static'), ) dev.py from .base import * SECRET_KEY = 'f!hap7sff#f@8$1iix@(%d4f=88swwetxkhbq=%^x)ga2eowbs' DEBUG = True prod.py from .base import * SECRET_KEY = config("SECRET_KEY", default="unsafe-secret-key") DEBUG = False -
Static CSS not being applied to django-allauth templates
My templates do not seem to be able to access static css files. The project using all-auth for authentication. My file structure is as follow: Project Folder App 1 App 2 Static CSS style.css Templates Account login.html signup.html base.html home.html base.html is as follow: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>Shuffle</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href='{% static "css/style.css" %}' rel="stylesheet"> </head> <body> <div id="card"> {% block content %} {% endblock %} </div> <!--card --> </body> </html> The rest of the templates extend from base.html. On inspecting the rendered page, all the html are correct but the styling is missing. Please help! :) -
Multiple nginx instances = gateway time-out; each instance works fine if addressed directly
This was working yesterday, but I made some changes which I have now reverted, and now it seems to be broken, and I can't find out why. I desperately need some tips on how to debug this. Background I've made multiple applications that move around quite a bit. In each app's repository, I've included nginx and docker configurations for two scenarios: Running as the only application on a server, and running alongside other applications. Because I want each repository to be "complete", I don't want any of the applications to assume whether or not they will be served by a "main" nginx instance in front. They should be capable of running using their "default", "standalone" configuration, and of existing alongside any number of other applications that also listen on the same ports, etc. Of course, running multiple web servers or APIs, for example, alongside one another would cause port allocation conflicts (and other problems), so there is some manual setup involved when running multiple apps on the same server. Almost all these applications consist of a Django REST framework server, a postgres database and an nginx reverse proxy. I made a separate repository with template files and instructions for running … -
Django custom auth model
Not sure how to name this problem, let me elaborate. I have very old django project, been migrating it since django 1.5 or so. It has always had class Member, extending User and has been practically used as authentication model for the app. AUTH_USER_MODEL was never changed, however SOCIAL_AUTH_USER_MODEL is set to custom auth model (and it works that way). Currently I am migrating to django 3.x and I am ran into trouble with django-registration - it used to work with Member set as model, but now it checks it against AUTH_USER_MODEL. Bottom line is, I want to make it the "right" way and set proper custom model and make sure I do it right before I dig deep into it as I expect it not to be too easy. When I simply set AUTH_USER_MODEL to custom model, I get error members.Member.user_ptr: (fields.E301) Field defines a relation with the model 'auth.User', which has been swapped out. When I make Member extend AbstractUser instead of User, I am missing id and fields as django then expects all data in single table (rather than having 2 one-to-one relationship tables). I could somehow manually merge data into this single table, but I am … -
Django REST API update view returns http 405
I'm trying to build a single page app (Vue) with a django backend. It's a very simple app to practice Vue + Django Rest Framework. The app allows the user to creating, delete and view (list) stories (just a title, datetime and content (simply text)) and this works fine. I'm now trying to also implement editing capabilities, but I get an error with regards to CORS headers. My backend code is very simple. Settings.py # relevant parts of settings.py INSTALLED_APPS = [ ..., 'rest_framework', 'corsheaders' ] MIDDLEWARE = [ ..., 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ] CORS_ALLOWED_ORIGINS = [ "http://localhost:8080", ] CORS_ALLOW_METHODS = ( 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS' ) urls.py: urlpatterns = [ path('', views.StoryList.as_view(), name='stories'), path('<int:pk>/', views.StoryDetail.as_view(), name='story'), path('delete/<int:pk>/', views.StoryDetail.as_view(), name='delete_story'), path('update/<int:pk>/', views.StoryDetail.as_view(), name='update_story') ] views.py: from django.shortcuts import render from django.http import HttpResponse, Http404 from rest_framework import generics from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from .models import Story from .serializers import StorySerializer class StoryList(APIView): def get(self, request, format=None): stories = Story.objects.all() serializer = StorySerializer(stories, many=True) return Response(serializer.data) def post(self, request, format=None): serializer = StorySerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.data, status=status.HTTP_400_BAD_REQUEST) class StoryDetail(APIView): def get_object(self, pk): try: return Story.objects.get(pk=pk) except Story.DoesNotExist: … -
Django: substitute unique_together with UniqueConstraint
I am trying to enforce a constraint upon a Vote model in my Django application, namely that a user cannot vote more than once the same object. To do so I am using unique_together: class Vote(models.Model): vote = models.SmallIntegerField(choices=VOTES, null=True, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user_votes") definition = models.ForeignKey(Definition, on_delete=models.CASCADE, related_name="definition_votes") class Meta: # Ensure user cannot vote more than once. unique_together = ["user", "definition"] This works, I think. However, in Django's documentation for unique_together it is noted that UniqueConstraint provides more functionality than unique_together. unique_together may be deprecated in the future. How can I substitute the above code using unique_together with code using UniqueConstraint? -
Validate Unique email django rest framework serializer
I have a model where Email field is unique. I thought it would make every email lowercase as it has normalize_email() method on User instance. However, it normalizes domain part only so Company@gmail.com is considered to be unique if company@gmail.com exists. So I decided to create validate_email() in my serializer to always return a lowercase email. It is a field validation and it is described in docs. def validate_email(self, value): return value.lower() However, looks like this method returns the value after the serializer has checked if the value exists in the database. Here is an example: if I try to create a user with user@gmail.com and it already exists, it will return "user already exists" which is expected. However, if I run with User@gmail.com it will run a SQL request first and check User@gmail.com != user@gmail.com and after that it'll try to create a new instance with user@gmail.com because it is returned from validate_email() and IntegrityError will be raised because it becomes user@gmail.com which is already in DB! I could do something like def validate_email(self, value): norm_email = value.lower() if User.objects.filter(email=norm_email).exists(): raise serializers.ValidationError("Not unique email") return norm_email but this is another request to DB and I don't want it. So … -
Django F expression seems to be case-insensitive with TextField on mariadb
Suppose I have the following model definition: class ExampleModel(models.Model): a = models.TextField(blank=True, null=False) b = models.TextField(blank=True, null=False) Django's F expression seems to lower text from b field when I want all objects where value from field a equals value from field b to be excluded from the queryset. ExampleModel.objects.create(a='sentence', b='Sentence') # should be 1 since 'sentence' != 'Sentence' assert ExampleModel.objects.exclude(a=F('b')).count() == 0 # 'Sentece' is what should be under F('b') but apparently it is not assert ExampleModel.objects.exclude(a='Sentence').count() == 1 I'm using mariadb with Django 2.1.15 What is the cause of this behaviour? -
get report of all tasks done on every week of day
Hi I have a model like : class Task(models.Model): todo_list = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100, blank=True) description = models.CharField(max_length=1024, blank=True) completion_date_time = models.DateTimeField(blank=True, null=True) now I want to get that on every week day how much task were completed . Like on {'Monday':2, 'tuesday':3 , 'Wednesday':2, 'Thrusday':1, 'Friday':2, 'Saturday':0, 'Sunday':0} -
How to add Django model method to serializer without explicit defining the fields?
model class Doctor(models.Model): ...tons of fields def no_of_ratings(self): ratings = Rating.objects.filter(doctor=self) return len(ratings) serializer class DoctorSerializer(serializers.ModelSerializer): class Meta: model = Doctor fields = ('__all__') # this will NOT show method fields = ('id', 'first_name', 'no_of_ratings') # this works I don't think this is a duplicate of this as my question explicit mentions model methods. -
Django: unsure how to access this jinja variable because of '@' in dictionary key
The output shows the url tag of the enclosure containing a file that needs to be retrieved is '@url' instead of the usual 'url'. Can't use '{{item.enclosure.url}}' nor '{{item.enclosure.@url}}' How can I retrieve this url as a Jinja variable? Reading RSS feed with Jinja The output of the HTML with Jinja -
Creating war file of django project?
I have created a sample Django project and want to convert a Django project into a war file. I have followed the step given in https://pythonhosted.org/django-jython/war-deployment.html creating .war of Django project but got an error in the manage.py file. Please help me to create a war file of the Django project.