Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Css is correctly working on Local but not on server Django?
CSS is Loading perfectly on local but not on the server. Also, I am trying using static_root and collectstatic method but that way the CSS is loading totally. -
How do you access the primary key from a generic list view?
I am trying to access the primary key of the url from a generic list view. Let me explain. So, I currently have a simple page with a list of student instances from the model student. Each row is dedicated to one student, such as the name, age, email, etc. Now, I want to add a link to each row so that I can view each student's calendar once I clicked it. Right now, the calendar view is a generic ListView like below. class CalendarView(LoginRequiredMixin, generic.ListView): model = Class template_name = 'leads/calendar.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # use today's date for the calendar d = get_date(self.request.GET.get('month', None)) # Instantiate our calendar class with today's year and date cal = Calendar(d.year, d.month) # Call the formatmonth method, which returns our calendar as a table html_cal = cal.formatmonth(withyear=True) context['calendar'] = mark_safe(html_cal) context['prev_month'] = prev_month(d) context['next_month'] = next_month(d) return context However, I want the calendar to show only information related to the student I clicked on. In order to do this, I need to be able to use the primary key(or ID) of the student in my calendar view. Of course, I can embed the primary key in the url, but … -
Django possible circular import
I'm setting up a new "Game" website. I have started a new app Games, set up the games/models.py with the code (below). After makemigrations game and migrate, I was able to log into Admin and add entries. Then I set to create the URLs, views, one template. After creating them, when I runserver, I get the following error: url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'games.urls' from '/home/mackley/PycharmProjects/alphabet/games/urls.py'>' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. The first thing I noticed is that the top line (from django.conf import settings) of games/models.py (using PyCharm) is greyed out. I don't know if that has anything to do with the error: Can anyone spot where I have made a mistake? Here is the relevant code. # games/models.py from django.conf import settings from django.contrib.auth import get_user_model from django.db import models from django.urls import reverse class Game(models.Model): title = models.CharField(max_length=255) date_create = models.DateTimeField(auto_now_add=True) date_start = models.DateTimeField(auto_now_add=False) body = models.TextField() author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) answer_one = models.CharField(max_length=1) answer_two = models.CharField(max_length=1) answer_three = models.CharField(max_length=1) answer_four = models.CharField(max_length=1) answer_five = models.CharField(max_length=1) answer_six = … -
m2m_changed signal not firing when an instance is in an m2m relationship is deleted? How can I trigger updates in other models when this happens
I have an app that has a 'real-time data' frontend by using django signals and webhooks. It works when a relationship is removed, or added, but if a relationship instance is deleted, m2m_changed isn't fired so the frontend isn't updated. Is m2m_changed meant to be fired in this situation though? The parent model has an m2m field which stores 'subscribed to' child models. I also have a property function that shows all possible child models to subscribe to (I have both subscribed and unsubscribed fields so i can have an on/off switch on the frontend): class Parent(models.model): subscribed_to = m2mField(Child) @property def potential_subscriptions(self): return Child.objects.all() # not sure if this is bad practice My signal looks like this: @receiver(m2m_changed, sender=Parent.subscribed_to.through) def signal(sender, instance, action, reverse, **kwargs): from .api.serializers import ParentSerializer if action == "post_add" or action == "post_remove" or action == "post_clear": serializer = ParentSerializer(instance) websocket.send(f"parent_{instance.id}", "parent_update", serializer.data) So it works when child instances are added or removed, but if a child instance is deleted it doesn't fire, so my websocket doesnt update the frontend. As a work around I tried to create a pre_delete signal for the Child object, and within the signal I clear it's relationship before it … -
Hello! I have a model with DateField that contains null = True, blanck = True and when I use it somewhere, i got errors below:
begin_date= models.DateField(verbose_name=_("Begin date"),null=True, blank=True) errors: [{loc: ["begin_date"], msg: "none is not an allowed value", type: "type_error.none.not_allowed"}] 0: {loc: ["begin_date"], msg: "none is not an allowed value", type: "type_error.none.not_allowed"} I use ValidationError from Pydantic, it also triggers because of that I know that there's a way like set allow_none to True but I have no clue how to write it correctly. I'm completely new to programming and English is not my native so sorry for mistakes. -
django display message issue after POST form submit?
Whenever I am using messages function, I get an error File "D:\Django Project\ta2\practice\views.py", line 60, in changepassword messages.SUCCESS(request,'your password has been updated') TypeError: 'int' object is not callable Here is my views.py def register(request): if request.method == 'POST': fm = new_registration_form(request.POST) if fm.is_valid(): fm.save() messages.add_message(request, messages.SUCCESS, 'Thanks for the registration') else: fm = new_registration_form() return render(request,'register.html',{'form':fm}) Here is my register.html part containing messages information div class="alert-info">{% if messages %} {% for message in messages %} {{message}} {% endfor %} {% endif %}</div> -
How to change the order of the form field when it is sorted in Django?
I am trying to change the order of the form field in the table when the user sorts it in the dropdown menu. Basically, it will be in the uppermost left of the table when the user sorted it the original table: the table will look like this when the user sorted it in name field: in my forms.py i have the field in order of: class myForm(forms.ModelForm): class Meta: model = myModel fields = [ "email", "name", "order", ] and in my models.py: class myModel(models.Model): name = models.CharField(max_length=100, null=True) email = models.CharField(max_length=100, null=True) role = models.CharField(max_length=100, null=True) in my views.py i tried: qs = myModel.objects.all().order_by("name") but it is just sorting the items inside the name field. how can I make it so that the name field will appear at the uppermost left part of the table? -
Run django on background for action
I'm trying to test my react app with yarn using Github Actions, I need to have Django running for some tests, however Django has the Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). October 15, 2021 - 03:32:25 Django version 3.2.6, using settings 'controller.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. message which locks bash, any ideas how I can start Django inside the action so that the action continues to run? This is currently my action name: CI on: push: branches: [ main ] pull_request: branches: [ main ] workflow_dispatch: jobs: tests: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Installing dependecies run: ./install.sh shell: bash - name: Testing backend run: ./backend-test.sh shell: bash - name: Starting backend run: ./backend.sh > /dev/null 2>&1 shell: bash - name: Testing frontend run: ./frontend-test.sh shell: bash And backend.sh does this # Backend test script cd backend/ && \ sudo service postgresql start && \ source .venv/bin/activate && \ python3 manage.py test -
Using same database table with two different projects Django
I'm a beginner in Django. I would like to know how to configure two different projects to share the same database table in Django. The database I'm using is MySQL. Let's say there's two projects, project A and project B. In project A, I already created a custom user model in it. And in project B, I want to use the custom user table from database created in project A just for the login. Means that in project A, there's registration and login for the custom user model. In project B, there's login only that will be using the same custom user data in the database. Do I have to redefine the same custom user model from project A in project B? What are the configuration settings that need to be done? Thanks in advance. -
Implementing Django user roles and group with Django REST framework
I have been following a django REST api and reactjs tutorial online on building a website. But the tutorial didn't cover the part for user roles and group for creating new users, admin or other roles which I wanted to implement it to extend the project. So far the django REST api can authenticate a user with the simplejwt, but I wanted it to authenticate different types of users. So anyone can enlighten me what and how should I do next? I am quite confuse when looking at other tutorials explaining this topic. -
How do I submit a Django form and print the result without redirecting the page?
Hello how are you? Hope someone can help me! I read a bunch of answers here on stack overflow, but none of them worked. I have an application that is a "social network". In the Divs of the logged user's own posts, there is an "Edit" button, which replaces the post content with a Djago form for the user to edit the content. The logic works, but I want that when the user saves the changes, the div itself is changed, without refreshing the page, how can I do that? My views.py: @login_required def edit_post(request, id): # Query the post try: post = Post.objects.get(id=id) except Post.DoesNotExist: return HttpResponse("Error: The post does not exist.") # Check if the user is the post's author. if request.user.id != post.author.id: return HttpResponse("Error: You can't edit this post.") # If request method is POST, modify the post if request.method == "POST": form = editPostForm(request.POST, instance=post) if form.is_valid(): form.save() return render(request, "network/postDiv.html", {"post": functions.getPost(id)}, content_type='application/xml') # If request method is GET: return the form form = editPostForm(instance=post) return render(request, "network/editPostForm.html", {"form": form, "id": id}) My urls.py: urlpatterns = [ path("", views.index, name="index"), path("following", views.following, name="following"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("u/<str:username>",views.profile, name="profile"), … -
Save users cookies langauge code in model field, When user login
I am using i18n in my django app. I give users the ability to change the language before and after login. When user changes their language without login then that language takes effect only for that session. if the user login and changes language after login it will be saved in the user model's lang field. If the user changes language without login and login after that then the language changed before login should be saved in the user model's lang field. If the user doesn't change their language before login we should continue with their profile language. thank you. -
How to make users automatically connected to specific rooms they chose even after they leave the site
I'm using Django and python-socket.io for the server side. I'm pretty new to socket.io, and I am wondering how to keep track of who is in which rooms even after the client is disconnected (closed tab of my site) so that the client automatically connect to the rooms they have decided to belong before leaving my site. I'm trying to do something like this: socketio.enter_room(django_user_object, "room1") # Instead of sid, I want to add the user. Thank you. -
How to pass user information to utils.py in django
I am trying to pass in user information to utils.py, but don't know how. Here is a part of the utils.py I am having trouble with: class Calendar(HTMLCalendar): def formatmonth(self, withyear=True): events = Class.objects.filter(date__year=self.year, date__month=self.month).exclude(student=None) cal = f'<table border="0" cellpadding="0" cellspacing="0" class="calendar">\n' cal += f'{self.formatmonthname(self.year, self.month, withyear=withyear)}\n' cal += f'{self.formatweekheader()}\n' for week in self.monthdays2calendar(self.year, self.month): cal += f'{self.formatweek(week, events)}\n' return cal The problem is the queryset events. I want to do something like below for it: if self.request.user.is_student: events = Class.objects.filter(date__year=self.year, date__month=self.month).exclude(student=None) if self.request.user.is_teacher: events = Class.objects.exclude(student=None) Basically, I want to change the queryset depending on what user is using the website. That is why I need to use something like self.request.user in the utils.py. I tried to do def get_queryset(self) in the views.py, but it doesn't seem to work. I hope you could help, and give me any questions that you have. -
Django - Create multiple different objects with relations in single Django endpoint
Is there a way to create a endpoint that creates multiple objects? what I've been doing instead is taking in request data and creating the objects one at a time and if one fails then delete the previously created entities, this seems really really hacky and there has to be a better way to create multiple objects. So essentially all Post need to be associated with a Goal so when a request comes it it'll be accompanied with post related data and goal related data in request.data. So it should create the Goal first then the Post associated with it. Is there a way to do this in one go? My assumption is creating a custom serializer to handle this, but not sure how to eloquently handle the case of when if Post fails to create I should delete Goal. model.py class Goal(AbstractBaseModel): creator_uuid = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, related_name="goal_creator_uuid") goal_category = models.ForeignKey(GoalCategory, on_delete=models.CASCADE) description = models.CharField(max_length=150, validators=[MinLengthValidator(5)]) class Post(AbstractBaseModel): creator_uuid = models.ForeignKey( User, on_delete=models.CASCADE, related_name="post_creator_uuid") goal_uuid = models.ForeignKey(Goal, on_delete=models.CASCADE) body = post_body view.py def post(request): """ POST endpoint for current user creating a goal update post """ goal_serializer = GoalSerializer(data=request.data) if goal_serializer.is_valid(): goal_obj = goal_serializer.save() else: # return Error … -
In drf, url address does not pass validation
I'm studying DRF through realworld github. I got some problem about validation. Using python(3.8.0), django(3.2.8), drf(3.12.4), Postman. I'm trying to update "image_url" through Postman request. But my serializer cannot receive "image_url". I think that "image_url" does not pass validation.. before update serializer.. because when I printed "serializer_data", I was able to take "image_url" like first line in picture 4. but when I printed "validated_data", I was not able to take "imgae_url" like second line in picture 4. I wanna update "Image_url" from "" to "https://stackoverflow.com/questions/ask". How can I solve this problem? Thank you. 1. views.py 2. serializers.py 3. Postman 4. print(serializers.py) in views.py and print(validated_data) in serializers.py first line: print(serializers.py) in views.py second line: print(validated_data) in serializers.py -
Is this the right way to get item of specific status in django?
I'm doing a to-do list in Django, I gave a model 'Todo' 3 status, which are 'todo''in_progress' and 'done', now I want to change a task's status from 'todo' to 'in_progress' and render this task, below codes seems not to work, any help would be appreciated. views.py ''' def add_to_progress(request, todo_id, project_id): todo = Todo.objects.get(id=todo_id) project = Project.objects.get(id=project_id) if request.method != 'POST': form = dragTodoForm() else: form = dragTodoForm(request.POST) if form.is_valid(): form.save() Todo.objects.filter(id=todo_id).update(status='in_progress') progress = Todo.objects.filter(status='in_progress') context = {'form', form, 'todo', todo, 'project', project, 'progress', progress} return render(request, 'todo_lists/new_progress.html', context) ''' project.html ''' </div> <form method="post" action="{% url 'todo_lists: add_to_progress' todo.id project.id %}"> {% csrf_token %} {{ form.as_p }} <button type="submit">Doing</button> </form> </div> ''' -
Save date to db with difference timezone
faced with a problem, that Django save a datetime with difference time: my local time and time from Django settings. My current timezone + 3 hours ahead, than utc time. And for example i tried save date to Django: 2021-01-01 08:00, but to database will be saved like 2021-01-01 11:00. After receive date from db, DateTime field will be serialized, and will be showed like 2021-01-01 08:00. But there is one bigger problem. With one database, can work two Django app, where local timezone on VPS can has a different value: +6 time, ahead utc. And after serialization, we will has different time in Django apps, but we use one DB and has same TZ in Django settings. How can solve this moment? Thanks -
False commit | Django
my code is working perfectly but I'd like to make some changes and NOT save anymore the uploaded filename in SQLite database. My code: # false commit to get upload file name upload = form.save(commit=False) upload.save() uploadFile = upload.file.name.split('/')[-1] As I said, I don't need right now to save this form in database. I tried to comment out the line upload.save() but the code is not working, displaying the error message below: Exception Type: com_error Exception Value: it's possible that the file may be removed, renamed or trashed. Thank you! -
Pytest hangs indefinitely running tests after Selenium image update
A day ago selenium updated their standalone-images (https://hub.docker.com/search?q=selenium&type=image) and at the same time selenium 4.0.0 was released on pypi (https://pypi.org/project/selenium/#history) I am using pytest and selenium to test my frontend of my django app and everything was working perfectly fine until yesterday when the release came out. What happens now is that when I run pytest (in PyCharm) the test just runs indefinitely without throwing an error or anything. It just never stops running. I very sure that the release is the problem, because when I pull the chrome-debug image, which was updated 15 days ago (in comparison to the chrome-standalone yesterday), my test-suite runs just fine again. I also tried pulling the standalone-firefox image to check if it may be a problem with only the standalone-chrome image, but I get the same result. Now, an intermediate solution is of course to use the chrome-debug image, but I am afraid that they will update this one soon too which will break my test-suite yet again, plus the standalone images are more lightweight. I have absolutely no clue what's going on. A minimal example of my test suite: Docker-compose: selenium: image: selenium/standalone-chrome ports: - 4444:4444 - 5900:5900 Docker-file; FROM python:3.9-alpine3.14 .... … -
Django+Postgres DB constraint errof
I have 2 models: class YouTubeCurrentChannelStat(models.Model): blogger = models.ForeignKey( BloggerProfile, on_delete=models.CASCADE, related_name='youtube_channel_stat' ) channel_id = models.CharField(primary_key=True, max_length=100) blog_theme = models.TextField(max_length=150, blank=True) channel_title = models.CharField(max_length=200, default='') subscribers = models.PositiveIntegerField() views = models.PositiveIntegerField() videos_count = models.PositiveIntegerField(null=True) description = models.TextField(max_length=5000) published_date = models.DateTimeField() last_updated = models.DateTimeField(blank=True, null=True, default='') and: class YouTubeVideoItemsCurrentStat(models.Model): channel = models.ForeignKey(YouTubeCurrentChannelStat, on_delete=models.CASCADE, related_name='videos_data') video_id = models.CharField(primary_key=True, max_length=100) stat_data = models.JSONField() # Updated daily with a Celery Task last_updated = models.DateTimeField(blank=True, null=True, default='') Second is related to first as FK. I use create_or_update method of Django ORM. When i create Postgres DB record for the first time - it creates without any issues. But when I want to update it I get this error: django.db.utils.IntegrityError: duplicate key value violates unique constraint "socials_youtubecurrentchannelstat_pkey" DETAIL: Key (channel_id)=(UCd3rBmH-OiF7tp3pye9LJIg) already exists My create task looks like: def update_videos_db_records(channel_id, response, video_id): YouTubeVideoItemsCurrentStat.objects.update_or_create( video_id=video_id, channel_id=channel_id, stat_data=dict( title=response.get('title', ''), likes=response.get('likes', 0), views=response.get('views', 0), thumbnail=response.get('thumb_url', ''), comments=response.get('comments', 0), dislikes=response.get('dislikes', 0), favourites=response.get('favourite', 0) ), last_updated=datetime.datetime.now() ) Also I tried it this way: def update_videos_db_records(channel_id, response, video_id): YouTubeVideoItemsCurrentStat.objects.filter( video_id=video_id, channel_id=channel_id).update( stat_data=dict( title=response.get('title', ''), likes=response.get('likes', 0), views=response.get('views', 0), thumbnail=response.get('thumb_url', ''), comments=response.get('comments', 0), dislikes=response.get('dislikes', 0), favourites=response.get('favourite', 0) ), last_updated=datetime.datetime.now() ) But it raised the same error. Method description on Django docs says: Like … -
NameError SERVER is not Defined Django
I am getting an error I don't understand with django: NameError at / name 'SERVER' is not defined My View: class RobotDetail(UpdateView): model = models.Robot form_class = RobotUpdateForm template_name = 'dashboard-home/robotdetail.html' robo = Robot.objects.get(pk=pk) PORT = robo.port SERVER = robo.server My Model: port = models.IntegerField() server = models.CharField(max_length=200, default='10.10.19', blank=True, null=True) -
Extension of an issue about Uploading multiple files from the Django admin
folks! I'm beginner in Django and I've seen this answer How to upload multiple files from the Django admin? about uploading multiple files from django admin, but I'd like to know how to validate a such field in admin main form based only if the upload field located at its child Inline form has a file selected already? Thanks in advance. -
New Written Django Manager is not working in the template
I have a simple todolist app where each task has a Booleanfield called is_deleted. in my list template, I only want to show the tasks with is_deleted=False . I know I can use Task.objects.all().filter(is_deleted=False) in my view; but I want to do it with managers in my template. here is my manager: class TaskManager(models.Manager): def available(self): return self.filter(is_deleted=False) . . objects = TaskManager() here is my view: class TaskList(ListView): model = models.Task context_object_name="tasks" template_name = "home/list.html" paginate_by=5 and here is the the condition in my template: {% if tasks.available%} ... -
Model Field with only year or full date using Django
how can i get ModelField in which i would once add full date in format like "2016-07-04" and once only a year like 1997, so i would have two items one with only a year, and one with full date, and then i could sort them by year?