Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to log to STDOUT in django
settings.py LOG_LEVEL = "DEBUG" LOGGING = { "version": 1, "disable_existing_loggers": False, "handlers": { "console": { "level": LOG_LEVEL, "class": "logging.StreamHandler", "stream": sys.stdout, "formatter": "console", }, "rq_console": { "level": LOG_LEVEL, "class": "rq.utils.ColorizingStreamHandler", "formatter": "rq_console", "exclude": ["%(asctime)s"], }, }, "formatters": { "rq_console": { "format": "%(asctime)s | %(name)s | %(levelname)s | %(message)s", "datefmt": "%Y-%m-%d %H:%M:%S", }, "console": { "format": "%(asctime)s | %(name)s | %(levelname)s | %(message)s", "datefmt": "%Y-%m-%d %H:%M:%S", }, }, "loggers": { "": { "handlers": ["console"], "level": LOG_LEVEL, "propagate": True, }, "django": { "handlers": ["console"], "level": "INFO", "propagate": True, }, "rq.worker": { "handlers": ["rq_console"], "level": LOG_LEVEL, }, }, "root": { "handlers": ["console"], "level": LOG_LEVEL, }, } some/api.py logger.info("Got some info") logger.debug("Got some debug") logger.warning("Got some warning") logger.error("Got some error") I'm running Django in debug mode using python manage.py runserver and none of the log statements are logging the console. The API is working just fine. And this is the code path it is taking, I ensured it by intentionally breaking the API using a break. However, I'm unable to get the logging working for some reason! At the start of the some/api.py file I've tried using all the below loggers, and none of them are printing the logs to the console logger = … -
Settting up virtual environment
i installed django on my virtual environment but when i deactivate the env and check my local machine, django is showing on my machine without installing django on it, please what can cause this? steps i used to installed django on my virtual environment i installed virtual env create virtual environment with "virtualenv env" 3 i activate the env by using source env/bin/activate then i installed django i used django-admin to create my first project so as i want to work on my second project i create new environment activate it but to my own suprise when i "pip freeze" to check whats inside the new Environment, it showing django and some other libraries i installed on the previous environment please guys is this normal? -
How to handle the user field in Django when making a Post request to a model that is accessed using an API key?
models.py: class Hosts (models.Model) : host_label = models.CharField (max_length=64, verbose_name = "Host Label" ) host_activation_request = models.CharField (max_length = 400, verbose_name = 'Activation Request', blank=True, null=True) host_developer_email = models.CharField (max_length = 400, verbose_name = 'Developer Email', blank=True, null=True) class Meta: verbose_name = "Available Host" unique_together = [['host_label', 'host_developer_email']] serializers.py: class HostSerializer(serializers.ModelSerializer): class Meta: model = Hosts fields = ('host_label','host_activation_request') views.py: class CreateHost(CreateAPIView): serializer_class = HostSerializer def generate_activation_request(self, feature, customer_ref="Isode"): config = get_active_config() #this function has been imported at the top command_list = [os.path.join(config.generate_activation_binary_directory, "generate_activation_request")] import subprocess proc = subprocess.run(command_list, universal_newlines=True, capture_output=True) self.result = proc.stdout def post(self, request, *args, **kwargs): print(request.data) self.generate_activation_request(feature=request.data["feature"]) request.data['host_activation_request'] = self.result return self.create(request, *args, **kwargs) A user can login to the website and make a Host in there and the host_developer_email field will be their email and the other two fields will be whatever they input in the form, as host_developer_email has been set to be a hidden field. Now, I have created an endpoint called /api/host which I can send a post request to in order to create a Host instance, but I have implemented the djangorestframework-api-key library. So my request from Insomnia (can use Postman too I guess) looks like this: The Header has the … -
docker-compose, reload server each time I make changes to code
I am dockerizing my Django app and I have the following docker-compose.yml file: version: '3' services: # other services as db etc. web: container_name: web build: context: . dockerfile: Dockerfile.web restart: 'always' env_file: - csgo.env ports: - '8000:8000' volumes: - web:/code depends_on: - db volumes: web: App logs: System check identified no issues (0 silenced). web | September 15, 2022 - 01:38:47 web | Django version 4.0.7, using settings 'csgo.settings' web | Starting development server at http://0.0.0.0:8000/ web | Quit the server with CONTROL-C. I want my container (or the app, idk) to reload whenever I let's say make changes to my models or functions etc. For now, I add some functionality to my app, edit some html views, but no changes appears and the app logs doesn't say that it's reloading. I have to rebuild and up my compose again to see my changes. How to do live-reload composing up? How to send changes to docker? Thanks! -
MUI with django framework
Is it possible to use mui with a django framework? I would like to keep it server-side using django. I know typically mui is built with client side rendering by using a react library. I did find a cdn library in muicss.com but i'm afraid this library is outdated. I would like to use the current version 5.0 and all of it's classes/components. Any ideas? -
How can I access my virtual environment created 1 week ago using ubuntu? I just know the name of the virtual environment but idk how access| PYTHON
I installed my first virtual environment using this commands below Commands used: apt-get update -y apt-get install -y python3-venv mkdir awesome_python_project cd awesome_python_project python3 -m venv awesome_venv source awesome_venv/bin/activate but I can't access it again, does anyone knows why? -
What's the real use of the management/commands directory in the Django Application?
In the documentation, it is written that it can be used for writing custom Django-admin commands. But my question is why do we need to write custom Django admin commands? The given example in the official documentation is a bit dry to me. I would be really grateful if someone give real-world examples from which I can connect its real-life use. Django doc on management/commands:https://docs.djangoproject.com/en/2.2/howto/custom-management-commands/ -
Using Default UserCreationForm does not show error if the passwords do not match
Using Default UserCreationForm from django.contrib.auth.forms does not show error if the passwords do not match. I do not want to create a custom model. Here is the code from my views.py file from django.contrib.auth.forms import UserCreationForm from django.shortcuts import render # Create your views here. def register(response): if response.method == "POST": print(response.POST) form = UserCreationForm(response.POST) if form.is_valid(): form.save() else: print(form.errors) form = UserCreationForm() return render(response,"register/register.html",{"form":form}) register.html code <html> <head> <title>Register </title> </head> <body> <h1>This is the Registration page</h1> <form method="post"> {% csrf_token %} {{form.as_p}} <button type="submit">Submit</button> </form> </body> </html> I thought the message would be automatically displayed. Am I missing something? Edit: None of the error message are being displayed like password length < 8, all numeric passwords, etc. -
Can't access to public IP of django docker container
I can access the container with these curl commands: curl http://localhost:8000/api/health/ curl http://127.0.0.1:8000/api/health/ But I can't access it with public IP address: curl http://xx.xxx.xxx.xxx:8000/api/health/ curl: (7) Failed to connect to xx.xx.xxx.xxx port 8000 after 0 ms: Connection refused I used this command to run the container: docker container run -d --network=host -p 8000:8000 my-central-api Dockerfile has this line: CMD [ "python3", "manage.py", "runserver", "0.0.0.0:8000"] I am running this container on an EC2 instance. I set up the security group and NACL. So I think it is related to docker configuration. Why I can't access to port 8000 with public IP? -
When I make migrations I get this error, what could be the reason?
I cloned the repository. Then I added several fields to the model and wanted to add them to an existing database. I ran the makemigrations command and got this error -
Heroku adds whitespace characters to django template javascript code
I'm trying to combine python and javascript code in django template to update page after every keyup event (like in a browser). I have a list of teachers with name and surname which I want to display if it matches pattern given by the user. While everything is fine on localhost, after deploying on heroku there is a syntax error: Uncaught SyntaxError: Invalid or unexpected token Here is a fragment of my teacher.html file, where python teachers is QuerySet passed from views.py during rendering and str is a pattern taken from entry, earlier in javascript function get_names(str){ let teachers = []; {% for teacher in teachers %} var name = "{{teacher.name}}"; if (name.includes(str)) { teachers.push("{{teacher|safe}}"); } {% endfor %} return teachers; } Here is output of my localhost js code var name = "John"; if (name.includes(str)) { teachers.push("John Kowalski"); } And here is output of heroku server var name = "John"; if (name.includes(str)){ teachers.push("John Kowalski <-- Error occurs here "); } More interesting is the fact, that for some names it works, but mostly it doesn't. I needed to reset the database and uploaded the same data once again using heroku run python manage.py shell. Before that everything was fine, … -
How to add two form fields (one shown and one not) to a model field
I have a Spent model class that holds the name of where the user spent money at, how much, the reason as to why they spent, and a total amount spent. The total amount spent does not show up on the form in the template just the name, place and how much was spent (no need for the total amount to be shown). I'm having trouble figuring out how to update the total amount spent. I would like to have the total amount spent keep track of how much the user has spent in total. modles.py from django.db import models from django.contrib.auth.models import User class Bills(models.Model): name = models.CharField(max_length=25) amount = models.FloatField() due_date = models.DateField() user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name class Budget(models.Model): income = models.FloatField(default=0.00) budget = models.FloatField(default=0.00) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.user.username class Spent(models.Model): name = models.CharField(max_length=25) amount = models.FloatField(default=0.00) reason = models.TextField(default="") total_spent = models.FloatField(default=0.00) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.user.username forms.py from django import forms from .models import Bills, Budget, Spent class DateInput(forms.DateInput): input_type = 'date' class AddBillForm(forms.ModelForm): class Meta: model = Bills fields = ['name', 'amount', 'due_date'] widgets = { 'name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter bill name'}), 'amount': … -
Django User does not update when saved?
I cannot get the default User model or my created Agent model to update. Below is my admin.py, forms.py, models.py, urls.py, views.py, and my edit_profile.html. I know it must be silly, but I've got three good days working on this. The HTML page tries to edit both the "EditProfileForm" and the "MoreInfoForm." The EditProfileForm uses the built-in User model, while the MoreInfoForm is my model that extends the built-in User model. As a note, the MoreInfoForm also contains an Image that I want to be able to update. When I submit the form, I get a POST request, but when I view the profile, it doesn't contain any changes. admin.py class AgentInline(admin.StackedInline): model = Agent can_delete = False verbose_name_plural = 'agent' class UserAdmin(BaseUserAdmin): inlines = (AgentInline,) admin.site.unregister(User) admin.site.register(User, UserAdmin) forms.py class RegisterUserForm(UserCreationForm): email = forms.EmailField(widget=forms.EmailInput(attrs={'class': 'form-control'})) first_name = forms.CharField(max_length=50, widget=forms.TextInput(attrs={'class': 'form-control'})) last_name = forms.CharField(max_length=50, widget=forms.TextInput(attrs={'class': 'form-control'})) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2',) def __init__(self, *args, **kwargs): super(RegisterUserForm, self).__init__(*args, **kwargs) self.fields['username'].widget.attrs['class'] = 'form-control' self.fields['password1'].widget.attrs['class'] = 'form-control' self.fields['password2'].widget.attrs['class'] = 'form-control' class MoreInfoForm(forms.ModelForm): agent_phone_num = forms.CharField(max_length=10, required=True, help_text='Enter a 10 digit # without spaces or dashes', widget=forms.TextInput( attrs={'class': 'form-control'})) agent_mls = forms.CharField(max_length=6, required=True, help_text='Enter your 6 … -
Django - "return render(...)" doesn't work in a view that interacts with an ajax request
I want to solve this task: I click a button on the first page and after that my view creates a chat room and redirects me to the chat page. I decided to use ajax request for this task, but I have a problem, my view works until line return render(request, 'chat/chatroom.html'), the chat room is created, but the chat/chatroom.html page doesn't open, I don't understand why. I have no errors, the return render(request, 'chat/chatroom.html') line does nothing. My code: html <button type="submit" id="chat-button" value="{{advertisement.author.id}}">Write to the author</button> <script> $(document).on('click', '#chat-button', function (e) { e.preventDefault(); $.ajax({ type: 'POST', url: '{% url "main_app:create-chat" %}', data: { send_to_id: $('#chat-button').val(), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), action: 'post' }, success: function (json) { }, error: function (xhr, errmsg, err) { } }); }) </script> views.py from django.contrib.auth import get_user_model from django.shortcuts import render, redirect, get_object_or_404 from django.db.models import Q from django.utils.decorators import method_decorator from django.views import View from django.views.decorators.csrf import csrf_exempt from chat.models import Thread User = get_user_model() @method_decorator(csrf_exempt, name='dispatch') class CreateChat(View): def post(self, request): send_to_id = int(request.POST.get('send_to_id')) send_to = User.objects.get(id=send_to_id) auth_user = request.user final_q = Q(Q(first_person=send_to) & Q(second_person=auth_user)) \ | Q(Q(first_person=auth_user) & Q(second_person=send_to)) thread = Thread.objects.filter(final_q) if not thread: Thread.objects.create(first_person=auth_user, second_person=send_to) return render(request, 'chat/chatroom.html') urls.py app_name … -
How do I can implement Follow/Unfollow system with CBV in Django?
I did a lot of attempts to create a following system. Who can describe in details how to implement this? My code shows a lot of errors. In AddFollower() and Remove follower() I get a profile I'm on and a current profile (my) and add or remove in database. But these functions don't work. Help me to find a solution, please urls.py path('add-follower/<int:id>/', AddFollower.as_view(), name='add_follower'), path('remove-follower/<int:id>/', RemoveFollower.as_view(), name='remove_follower') views.py class AddFollower(LoginRequiredMixin, View): def post(self, request, *args, **kwargs): user = self.kwargs.get('user') profile = Profile.objects.get(user=user) profile.subscribers.add(request.user) return redirect('user-posts', id=profile.id) class RemoveFollower(LoginRequiredMixin, View): def post(self, request, *args, **kwargs): user = self.kwargs.get('user') profile = Profile.objects.get(user=user) profile.subscribers.remove(request.user) return redirect('user-posts', id=profile.id) class GetUserProfile(ListView): model = Question template_name = 'blog/profile.html' queryset = Question.objects.all() def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Question.objects.filter(user=user) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) user = get_object_or_404(User, username=self.kwargs.get('username')) profile = Profile.objects.get(user=user) followers = profile.subscribers.all() if self.request.user in followers: is_following = True else: is_following = False context['question_count'] = Question.objects.filter(user=user) context['post_count'] = Post.objects.filter(author=user) context['answer_count'] = Answer.objects.filter(user=user) context['profile_user'] = User.objects.get(username=user) context['is_following'] = is_following return context profile.html {% if profile_user.id == request.user.id %} <div class="buttons mt-3"> <a class="btn btn-dark px-4 ms-3" href="{% url 'profile' %}">Редактировать</a> </div> {% else %} {% if is_following %} <form action="{% url 'remove_follower' user.id … -
Django DateTimeField default not affecting Time
I am following an online tutorial on Django. Below is my Models script: from django.db import models from datetime import datetime class Tutorial(models.Model): tutorial_title = models.CharField(max_length=200) tutorial_content = models.TextField() tutorial_published = models.DateTimeField('date published', default=datetime.now) def __str__(self): return self.tutorial_title and here is my admin script: from django.contrib import admin from .models import Tutorial # Register your models here. class TutorialAdmin(admin.ModelAdmin): fieldsets = [ ("Title/date",{"fields":["tutorial_title","tutorial_published"]}), ("Content", {"fields":['tutorial_content']}) ] admin.site.register(Tutorial, TutorialAdmin) My issue is that DateTimeField(default=) is just not working. I am absolutely unable to change the default time in tutorial published. No matter what I put in default, nothing changes. It's always 16:39:02. This isn't a time zone difference. I have no clue what is causing this. Any help would be greatly appreciated. -
random "relation "client_machine" does not exist" message
I have a big issue with my Django application. The application return an error 500 randomly. ProgrammingError at /dashboard/ relation "client_machine" does not exist LINE 1: ...t", "client_machine"."receive_publicity" FROM "client_ma... ^ I can spam any request, sometimes it's works, sometimes not. -
Forbidden (CSRF token missing or incorrect.) how to send CSRF token from frontend to backend?
I have a Django project, where I need to send a date string from frontend to backend. At frontend I am using the javascript fetch method async function getCustomerInDeliveryDate(deliveryDate : String) { const response = await fetch('getCustomerInTripDate', { method : 'POST', headers : { 'Content-Type' : 'application/json', }, body: JSON.stringify({ deliveryDate : deliveryDate }), }); return response } From Django backend I currently implemented a simple method that returns a string back to frontend class GetCustomerInTripDate(LoginRequiredMixin, View): def post(self, request, *args, **kwargs): print('Backend received call from front end!!!!!!!!!!!!!') return JsonResponse({'data': ['hello', 'world']}, status = 200) The error that I receive when I try to send to backend is Forbidden (CSRF token missing or incorrect.): /staff/getCustomerInTripDate I am not sure how to send the csrf token. The research I have done so far all indicated that credentials should be set as "same-origin", and I have tried it but still get the same error. -
How do I create a user area system in Django? [closed]
I want to create a user area system so that each person can add a certain amount of users to their collection by purchasing a plan. For example, a user can add 10 people to their collection by purchasing a $10 plan. The user has the ability to display the people in his group -
custom pagination of limit and page in Django Rest Framework
I wanted to create custom paginations for this get_queryset. get_queryset = Comments.objects.filter(language_post_id=post_in_lang_id,is_post_comment=True).order_by('-created_on')[offset:offset+limit] I want to change the offset value whenever the page_no updates. Suppose someone enters page_no=1, so offset must be 0, and when enters 2, so offset should be 10, and so on. Every time page_no updates, it should update the offset value accordingly. like ?page_no=3: get_queryset = Comments.objects.filter(language_post_id=post_in_lang_id,is_post_comment=True).order_by('-created_on')[offset:offset+limit] # [ 20 : 20 + 10 ] -
How to display image file from sftp remote server in django template?
We have 2 servers. One of them is for media files and the other one is for django project server(ngnx+gunicorne). Our media server is local(internal). We want to access to media server from inside the project with sftp storage package which includes paramiko. we don't want to access media server via URL (http,https). HttpResponse(file, content_type=type) can display the image file as a big picture but we want to pass the image file to django template for display in html file like <a href="{{ course.get_absolute_url }}"><img src="{{images}}" alt=""></a> We know HttpResponse is not a good solution but we use it below code for explained our problem. # view def coursesPageView(request): courses = Course.objects.filter(is_published=True) image_data =[imageRespone(data) for data in courses] data = { 'published_courses_list':courses, 'images' : image_data } return render(request, 'pages/course2.html', data) def imageRespone(valid_image): if sfs.exists(valid_image.image.name): file = sfs._read(valid_image.image.name) type, encoding = mimetypes.guess_type(valid_image.image.name) response = HttpResponse(file, content_type=type) return response else: return HttpResponse('404 Not Found') #course2.html <a href="{{ course.get_absolute_url }}"><img src="{{images}}" alt=""></a> -
Python was not found cmd
!one day before python manage.py runserver command successfully executed & give the IP address of Server]1 -
How can you omit empty django-filter params in url?
I am using django-filters to filter my queryset, I am wondering whether it is possible for the library to omit empty fields when generating a filtered URl. My URl would look like this: /?price=&producer=&price__gte=4&price__lte=&producer__name=&category__name=&o=-price And I want to achieve a cleaner one, using only non-empty filters: /?price__gte=4&o=-price filters.py class ProductFilter(django_filters.FilterSet): # price = django_filters.NumberFilter() price__gte = django_filters.NumberFilter(field_name="price", lookup_expr="gte") price__lte = django_filters.NumberFilter(field_name="price", lookup_expr="lte") vendor__name = django_filters.CharFilter(lookup_expr="icontains") category__name = django_filters.CharFilter(lookup_expr="icontains") o = django_filters.OrderingFilter( # tuple-mapping retains order fields=(("price", "price"),), # labels do not need to retain order ) class Meta: model = Product fields = ["price", "category", "vendor"] views.py class ProductListView(LoginRequiredMixin, ListView): model = Product ordering = ["-created_at"] def get_ordering(self): ordering = self.request.GET.get("ordering", "-created_at") return ordering def get_queryset(self, **kwargs): qs = Product.objects.exclude(status="HID").all() return qs def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) f = ProductFilter(self.request.GET, queryset=self.get_queryset()) context["filter"] = f return context -
Trying to restrict items to a specific user in a Django Class Based View query set
I have the following models: class AccountManager(models.Model): account_manager = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) def __str__(self): return str(self.account_manager) class Client(models.Model): account_manager = models.ForeignKey(AccountManager, on_delete=models.CASCADE, related_name='account_manager_clients') client = models.CharField(max_length=255) def __str__(self): return self.client class Contract(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='client_contracts') site_name = models.CharField(max_length=255) def __str__(self): return self.site_name I can restrict the clients to the specific account managers by using the following view class ClientListView(LoginRequiredMixin, ListView): model = Client template_name = "clients/list.html" def get_queryset(self, *args, **kwargs): return ( super() .get_queryset(*args, **kwargs) .filter(account_manager__account_manager=self.request.user) ) However I can't seem to restrict the contracts to the account manager with the following view: class AMContractDetailView(LoginRequiredMixin, DetailView): model = Contract template_name = 'contracts/am_contract_detail.html' def get_queryset(self, *args, **kwargs): return ( super() .get_queryset(*args, **kwargs) .filter(client__account_manager=self.request.user.id) ) This allows account managers to see all the clients not just their own. I know I am doing something fundamentally wrong but have got a bit lost! Any help would be appreciated. -
Run local NGINX web app on HTTPS without domain name
I'm developing a django web app which runs on a gunicorn-nginx local server. I've followed this digitalocean guide to setup the web app but I don't understand how to create a ssl certificate and use it without having a domain name. I've found a lot of guides but none of them specify how to enable HTTPS without a domain and using a local IP. How can I make this happen?