Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Post method not working, only get request
I have a form like this: <form method="post"> {% csrf_token %} <div class="mb-3"> <input type="hidden" class="form-control" id="url" name="delete-id" value="{{ url.id }}"> </div> <div class="mb-3"> <button type="submit" class="btn btn-primary mb-3">Delete</button> </div> </form> This form is embedded in a cell of a table. I make a post request in the form but when I'm testing the request.method, it always gives me the GET answer. if request.method == 'post': Url.objects.get(id=request.POST.get['delete-id']).delete() Here request.method is always GET and I don't understand why. -
Django treebeard count on each child
I'm using django-treebeard to create tree of Structures (some kind of folders). Each Structure could contain a Resource. When I list my Structures I need to know how many Resources are in current Structure and it's children. Is there a way to Sum them with aggregation? Example: - RootStructure - ChildStructure - Resource1 - Resource2 return Structure.get_root_nodes().annotate(resources_number=Count("resource")) resources_number = 0 (i want to get 2 because ChildStructure have 2 Resources) return parent_obj.get_children().annotate(resources_number=Count("resource")) resources_number = 2 when parent_obj is RootStructure Here are my models: class Structure(MP_Node): objects = StructureManager() name = models.CharField(max_length=100) description = models.CharField(max_length=500, blank=True, default="") class Meta(MP_Node.Meta): ordering = ("path",) class StructureResource(models.Model): resource_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) structure = models.ForeignKey( Structure, on_delete=models.CASCADE, related_name="resource" ) resource_id = models.IntegerField() resource_object = GenericForeignKey("resource_type", "resource_id") -
Docker - Media volume not storing data
I have a Django project in which I have a media volume that contains all the files that are uploaded. Some of those files are the objects of a Script model. However, there must be something in my definition/use of the volume as I get a No such file or directory: 'path_of_the_file' error when trying to access to my files. I tried different approaches, and discovered that when creating an object through the admin panel, the file was accessible until the container's next restart. I tried checking what was inside of my volume using this answer but I get a The specified path does not exist when trying to cd into the mountpoint. Here is the inspection result : C:\Users\stephane.bernardelli\Documents\TestApp\src>docker volume inspect testapp_media [ { "CreatedAt": "2022-07-21T14:34:17Z", "Driver": "local", "Labels": { "com.docker.compose.project": "testapp", "com.docker.compose.version": "2.6.1", "com.docker.compose.volume": "media" }, "Mountpoint": "/var/lib/docker/volumes/testapp_media/_data", "Name": "testapp_media", "Options": null, "Scope": "local" } ] And here is my docker-compose.yml: version: '3.8' services: rabbitmq3: image: rabbitmq:3-alpine ports: - 5672:5672 networks: - main postgres: container_name: postgres hostname: postgres image: postgres:latest env_file: - env environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} - POSTGRES_DB=Scripts Application networks: - main ports: - "5432:5432" restart: on-failure volumes: - postgresql-data:/var/lib/postgresql/data django_gunicorn: volumes: - static:/static - media:/media … -
Send HttpResponse as Attachment in emails in django
I have a class in which I am creating a downloadable excel file like the following: response = HttpResponse(content_type='application/vnd.openxmlformats- officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename=Scanned Data_{}.xlsx '.format(time.strftime("%d-%m-%Y %H:%M")) writer = ExcelWriter(response) . . . writer.save() Now I want to send this response as an attachment to the mail for which I am using Mimemultipart() like the following: recipient_list = ['xxx@yyy.com',] message = MIMEMultipart() message['Subject'] = 'Results' message['From'] = 'xxx@yyyy.com' body_content = "foo" message.attach(MIMEApplication(response)) message.attach(MIMEText(body_content, "html")) msg_body = message.as_string() server = SMTP('email-smtp.ap-south-1.amazonaws.com', 587) server.starttls() server.login('xxxx', 'xxx+x') server.sendmail(message['From'], recipient_list, msg_body) for which I am getting: TypeError: expected bytes-like object, not HttpResponse How do I attach this to file ? Should I convert it to the file and save it locally and then read it and send email and then delete it ? (This doesn't seem the right way to do this) -
How do I create an embed HTML link for a favicon generator?
I'm working on a favicon generating web app that displays a embed HTML code for linking the favicon. I am using Django for the development of this web. I'm out of ideas on what approach to use for this function. Are there possibly any python libraries or modules that I can use? -
How to update event time in Django model?
I have the following code. The expect outcome would be: If the event does not exist, then the admin form shows only created_at time, the updated_at field is empty. If the event exists: a. if there is no updated_at, the field would be filled with time now. b. if updated_at exists, the field time should be updated. My code does not work, how should I change it? Thank you. from django.db import models from django.utils.timezone import now import uuid class Venue (models.Model): class Types(models.TextChoices): LPN='LPN', RN ='RN' type = models.CharField( max_length=3, choices=Types.choices, default=Types.RN ) venue_id= models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created_at = models.DateTimeField(default=now, editable=True,null=True, blank=True) if venue_id is True: updated_at = models.DateTimeField(default=now, editable=True,null=True, blank=True) updated_at.update() else: updated_at = models.DateTimeField(default=None, editable=True,null=True, blank=True) place_text=models.CharField(max_length=200) date = models.DateField ('Date') start_time = models.DateTimeField ('start time') finish_time= models.DateTimeField ('finish time') details= models.CharField (max_length=500) def _str_(self): return self.venue_text please refer to the attached screenshot. -
Decentralized Login System
I have to build a decentralized system in which a WebApp appears, with which the user interacts to: Registration phase: in which he enters his data (username, email and password) and an API, which receives the data in clear text, encrypts them, and sends them back to the WebApp, which stores them in the database. Login phase: in which he enters his data, the API encrypts them and sends them back, and they are compared with those present in the database. I am using Django, and the Django-Restful frameworks, how can I establish this connection between the two applications? Is there any useful library? Here you can view the Django-project structure. -
session_id in cookie is changing when redirecting from one page to another resulting in switching between two profile and some times login out
So we have this very weird problem. Will appreciate a lot if anyone could help us out. I built a notification service using django and redis. When I click on the post notification link, it redirects me to the post detail page. Everything works fine. It redirects to the page. However when it redirects to another page, "sometimes" it switches the profile. For example if i was logged in as user1 (previously logged in as user2), when i get redirected to the post detail page, i get the post detail page but i am now logged in as user 2. So after thorough debugging we found out that this happens because in browser cookies, the session_id changes sometimes. And sometimes, session_id is missing, and in that case it is redirected to log in page as @login decorater is used in post detail page. The code is absolutely fine as we do not get this bug in local or in test server. It only happens in production server which is hosted in aws server. So i wanted to know why exactly the session_id is changing in first place? Does it have anything to do with server configuration? or too much load … -
__init__() takes from 1 to 2 positional arguments but 5 were given - Django Error
I'm trying to add an email verification app to my Django Project. However when I try to run it, it throws an error: TypeError at /register __ init __() takes from 1 to 2 positional arguments but 5 were given My views.py function: def register_user(request): if request.method == "POST": form = RegisterUserForm(request.POST) if form.is_valid(): myuser = User.objects.create_user( username=form.cleaned_data['username'], first_name=form.cleaned_data['first_name'], last_name=form.cleaned_data['last_name'], email=form.cleaned_data['email'], password=form.cleaned_data['password1'], ) myuser.is_active = False myuser.save() # Welcome Email subject = "Welcome To ---" body = " ... " #message from_email = settings.EMAIL_HOST_USER to_list = [myuser.email] send_mail(subject, body, from_email, to_list, fail_silently=True) # Confirm Email current_site = get_current_site(request) email_subject = "Confirm Your Email - ---" email_message = render_to_string('email_confirmation.html', { 'name': myuser.first_name, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(myuser.pk)), 'token': generate_token.make_token(myuser), }) email = EmailMessage( email_subject, email_message, settings.EMAIL_HOST_USER, [myuser.email], ) email.fail_silently=True email.send() messages.success(request, ("Registration: Successful!")) return redirect('confirm-address-page') else: form = RegisterUserForm() I have imported all the necessary modules and checked the names of the URLs and template names. Everything is correct. -
Gunicorn not starting anymore after adding PostgreSQL in Docker
I have a Django project that I'm trying to dockerize. I successfully added Django with gunicorn and nginx to Docker. However, when trying to add PostgreSQL, I encountered an issue. My Postgres container starts, but my gunicorn one doesn't start anymore, and I get this error in the logs, so it indeed seems like it comes from Postgres : C:\Users\stephane.bernardelli>docker logs testapp-django_gunicorn-1 Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/django/db/backends/base/base.py", line 244, in ensure_connection self.connect() File "/usr/local/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.10/site-packages/django/db/backends/base/base.py", line 225, in connect self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.10/site-packages/django/db/backends/postgresql/base.py", line 203, in get_new_connection connection = Database.connect(**conn_params) File "/usr/local/lib/python3.10/site-packages/psycopg2/__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: connection to server at "127.0.0.1", port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 460, in … -
How can I find a way to display the comment object and TV data at the same time?
I do what I want to do I want to display user comment and data that is searched by tv_id in comment object. Each comment objects has tv_id. I want to get data by TV_id of each comment object and display it in HTML with the comment. However, I can't find a way to display the comment object and TV data at the same time. How can I do this? Current state class TV(models.Model): id = models.CharField(primary_key=True, editable=False, validators=[alphanumeric],max_length = 9999) stars = models.FloatField( blank=False, null=False, default=0, validators=[MinValueValidator(0.0), MaxValueValidator(10.0)] ) def get_comments(self): return Comment_tv.objects.filter(tv_id=self.id) def average_stars(self): comments = self.get_comments() n_comments = comments.count() if n_comments: self.stars = sum([comment.stars for comment in comments]) / n_comments else: self.stars = 0 return self.stars class Comment_tv(models.Model): class Meta: unique_together = ('user', 'tv',) comment = models.TextField(max_length=1000) stars = models.FloatField( blank=False, null=False, default=0, validators=[MinValueValidator(0.0), MaxValueValidator(10.0)] ) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) tv = models.ForeignKey(TV, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: unique_together = ('user', 'tv') indexes = [ models.Index(fields=['user', 'tv']), ] data = requests.get(f"https://api.themoviedb.org/3/tv/{tv_id}?api_key={TMDB_API_KEY}&language=en-US") class Comment_List_TV(ListView): template_name = 'account/user_comment_list_tv.html' def get_queryset(self): Comment_list_query = Comment_tv.objects.none() if self.request.user.is_authenticated: Comment_list_query = Comment_tv.objects.filter(user=self.request.user) return Comment_list_query -
How to embed a dynamic matplotlib 3d cluster chart in an HTML page?
I am working on Django based UI. Here I have created a matplotlib cluster chart which looks like this: As you can see, I can scroll this image to rotate this graph from different angles and also there are multiple options below to work like zoom, save, scroll etc. I want to bring this graph in my UI as it is. Right now I am using it as an image and displaying it with html tag. But its just a static image. I tried iframe but not able to save this figure as html or any other form. Kindly help me on how to bring this on UI so I can do scrolling and all in my UI. Thank you. -
how make unique list of all month with days in the year
how make this by Django 1-Create another endpoint to get the number of days in which he entered any thing in one month period (the current month for the current year) 2-create another endpoint to get the month which has the highest number of days which have entries in the current year -
How to create Public URL for Django Localhost to access in Other Machines
I'm working Django Project. How to create a Public IP permanently for Localhost(127.0.0.1:8000) IP in Django Project. After Creating Public URL, how to allow access for Other users without Source Code when I run python manage.py runserver x.x.x.x:8088 in command prompt it is generating a URL with specified IP address. But when I share/open this URL with others it is not working Can any one help me to configure this issue. Thanks in advance. -
no such table: two_factor_phonedevice when using django-two-factor-auth==1.14.0 and --nomigrations
I have a 2.2 Django project with django-otp==0.8.0, django-two-factor-auth[phonenumbers]==1.14.0, and an app two_factor_auth that makes use of these two libraries. When tests are run with migrations, they pass. $ ./manage.py test two_factor_auth Applying two_factor.0001_initial... OK Applying two_factor.0002_auto_20150110_0810... OK Applying two_factor.0003_auto_20150817_1733... OK Applying two_factor.0004_auto_20160205_1827... OK Applying two_factor.0005_auto_20160224_0450... OK Applying two_factor.0006_phonedevice_key_default... OK Applying two_factor.0007_auto_20201201_1019... OK ---------------------------------------------------------------------- Ran 13 tests in 5.549s OK Note that these migrations are the ones from the django-two-factor-auth package as the two-factor-auth app has no migrations. However, when tests are run without migrations (as is done in CI and local environments because our project has hundreds of migrations), they fail. $ ./manage.py test two_factor_auth --nomigrations Traceback (most recent call last): File "/opt/miniconda3/lib/python3.8/site-packages/two_factor/views/profile.py", line 38, in get_context_data 'default_device': default_device(self.request.user), File "/opt/miniconda3/lib/python3.8/site-packages/two_factor/utils.py", line 16, in default_device for device in devices_for_user(user): File "/opt/miniconda3/lib/python3.8/site-packages/django_otp/__init__.py", line 80, in devices_for_user for device in model.objects.devices_for_user(user, confirmed=confirmed): File "/opt/miniconda3/lib/python3.8/site-packages/django/db/models/query.py", line 274, in __iter__ self._fetch_all() ... File "/opt/miniconda3/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 383, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: two_factor_phonedevice I can confirm that this issue no longer appears if I go back to using django-otp==0.7.5 and django-two-factor-auth==1.9.1. What could be the problem? -
csv report From filtered Data in django
i have a search field in my django app and filtering Data work well . when i want get csv report , whole of record will be print in csv not filtered data . thank you for help me . qs=EventkindofProblem.object.all() MyFilter=eventfilter(request.GET,queryset=qs) return djqscsv.render_to_csv_response(myFilter.qs,append_data_stamp=True)``` -
Django filter by date gives wrong results
I am trying to filter data retrieved from a postgresSQL table using django filter method. Below is the code I am using for that and I am giving "2022-7-13" as the filter_date in the query. The database has 62 entries for the date "2022-7-13" but, the API gives 23 as the result. I have set USE_TZ = True in my django settings.py file and I am using pendulum.timezone('America/Los_Angeles') as the timezone in django settings file. Can anyone help to resolve this issue. def get_runs(self, obj): """ drf serializer method field """ runs = 0 date = self.context.get('request').query_params.get('filter_date', None) if date is not None: filter_date = datetime.strptime(date, '%Y-%m-%d')\ .replace(tzinfo=pendulum.timezone('America/Los_Angeles')).date() runs = obj.runs.filter(created_on__date=filter_date).count() else: runs = obj.runs.count() return runs -
Why isn't the current directory in sys.path for a django application
To my understanding, the sys.path has the current directory (the directory the module is in) as its first index, yet this seems inconsistent with django. I have a project structure: In my_file_1.py, printing sys.path gives me: In my_file_2.py, printing sys.path gives me: These two sys.path prints makes sense since that red underline is the directory the modules are in (their respective current directory). However, in my django app with the following project structure: When printing sys.path in urls.py, I get: Which is the root directory of the project, instead of the current directory of urls.py which should be c:\\Users\\5403\\Desktop\\tutorial\\tutorial Could someone explain this inconsistency and correct me if I have any misconceptions, thanks. -
How to check data exist in database or not while uploading large dataset using django
I am going to make a scripts that load excelsheet which contain 17000 rows to django model. But, I don't get idea to check given data already exist or not in database efficiently. in models.py # no fields value are unquie here, class Student(models.Model): name=models.CharField(max_length=100) address=models.CharField(max_length=100) age=models.CharField(max_length=100) rollno=models.CharField(max_length=100) in views.py def upload_script(request): wb = openpyxl.load_workbook(excel_file) worksheet = wb["All DMAs"] for row in worksheet.iter_rows(): datacollection=row[0:9] name=datacollection[0] address=datacollection[1] rollno=datacollection[2] age=datacollection[3] # everytime this call the database which load more time if(Student.objects.filter(name=name,address=address,rollno=rollno,age=age).first(): continue student_obj=Student( name=name, address=address, rollno=rollno, age=age ) student_list.append(student_obj) if len(student_list)>1000: Student.objects.bulk_create(student_list) student_list=[] Student.objects.bulk_create(student_list) -
Getting user input from a input field in Django
So what I am trying to do is grab the users input, and then it append it to the HTML, I am making an attempt to make a chatbot system, I have the modules wrote I am just having trouble getting the users input. I have been looking around and I thought something like this would work but I am receiving back this: {'rawText': None} I will take the input, and pass it to the python module I wrote, and then append the results also to the HTML, like a messenger, still new to python, and django so confused as to why I am not getting any text back in console. views.py: from django.shortcuts import redirect, render from django.shortcuts import HttpResponse from .forms import messageForm from .main import get_weather, take_user_input def home(request): form = messageForm() # Get the message to display to view. if request.method == "POST": rawText = request.GET.get('textInput') context = {'rawText': rawText} print(context) return render(request, 'home.html', {'form': form}) forms.py: from django import forms class messageForm(forms.Form): message = forms.CharField(max_length=1000) home.html: {% extends 'base.html'%} {% load static %} {% block content %} <h2>Blue's Chatbot</h2> <div> <div id="chatbox"> <p class="botText"><span>Hi! Let's get to chatting.</span></p> </div> <div id="userInput"> <form type="text" id="textInput" action="" … -
How to customize showing query parameter with DRF filtering (ManyToManyfield)
I hope my question is not a duplicated.. I'm building a rest API with DRF, now I'm trying to do filtering hashtag. The url I want is article/list?hashtags=dobi BUT I got id, like article/list?hashtags=13 How can I override? Here is models.py: class Article(AbstractTimeStamp): user = models.ForeignKey('users.User', on_delete=models.CASCADE) title = models.CharField(max_length=300,blank=False) content = models.TextField(max_length=1000) hashtags = models.ManyToManyField('Hashtag', max_length=200, related_name='articles', blank=True) class Hashtag(models.Model): hashtag = models.CharField(max_length=200, unique=True, blank=True) Here is my serializers.py: class ListSerializer(serializers.ModelSerializer): hashtags = HashtagsSerializer(many=True) class Meta: model = Article fields = ['id','title','hashtags'] Here is my views.py: class ArticleListAPIView(generics.ListAPIView): queryset = Article.objects.all() serializer_class = ListSerializer filter_backends = [filters.SearchFilter,DjangoFilterBackend] search_fields = ['title'] filterset_fields = ['hashtags'] -
Django Error: from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django'
I'm using django and virtual environment "virtualenv", activate it, try to run the server in the project folder like this: python manage.py runserver, but I get this error: from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django'. what could be happening? if someone can help, thank you in advance -
In django whenever I try to run the server, I want to see the login page first, but I am seeing the index page?
I am attaching my code in views and urls.py. Whenever the server runs, I want to see the login page first, but I am seeing an error that this page is not working. def loginPage(request): if request.user.is_authenticated: return redirect('/') else: if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('/') else: messages.info(request, 'Username OR password is incorrect') context = {} return render(request, 'accounts/login.html', context) urlpatterns = [ path('', views.loginPage, name="login"), path('index/',views.index,name="index"), -
DJANGO custom user model: create_superuser() missing 1 required positional argument: 'username'
I have the following User model which uses email as USERNAME_FIELD and leave the actual username unused. All authentication features work fine, but I just realized I cannot create superuser with manage.py because of the error: create_superuser() missing 1 required positional argument: 'username' Can anyone help me debug this error? users/models.py class User(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) username = None first_name = models.CharField(max_length=100, default="unknown") last_name = models.CharField(max_length=100, default="unknown") profile_pic = models.CharField(max_length=200, default="unknown") premium = models.BooleanField(default=False) email = models.EmailField(unique=True, db_index=True) secret_key = models.CharField(max_length=255, default=get_random_secret_key) USERNAME_FIELD = "email" REQUIRED_FIELDS = [] class Meta: swappable = "AUTH_USER_MODEL" users/services.py def user_create(email, password=None, **extra_fields) -> User: extra_fields = {"is_staff": False, "is_superuser": False, **extra_fields} user = User(email=email, **extra_fields) if password: user.set_password(password) else: user.set_unusable_password() user.full_clean() user.save() return user def user_create_superuser(email, password=None, **extra_fields) -> User: extra_fields = {**extra_fields, "is_staff": True, "is_superuser": True} user = user_create(email=email, password=password, **extra_fields) return user @transaction.atomic def user_get_or_create( *, email: str, first_name: str, last_name: str, profile_pic: str ) -> Tuple[User, bool]: user = User.objects.filter(email=email).first() if user: return user, False return ( user_create( email=email, first_name=first_name, last_name=last_name, profile_pic=profile_pic, ), True, ) Full error log ❯ docker-compose run --rm web ./manage.py createsuperuser ─╯ Email: example@email.com Password: Password (again): Traceback (most recent call last): File "./manage.py", line … -
for loop in django template returning blank list items
I'm looping through the field of joined for my Group model and returning the list of joined members in my GroupDetail template: class Group(models.Model): leader = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=55) description = models.TextField() joined = models.ManyToManyField(User, blank=True) Each member in the for loop relates to a User (or username) that has joined the Group: <ul> {% for member in joined_members %} <li>{{ member }}<li> {% endfor %} </ul> There are four members in the Group, and all members are being returned, however four empty list items are also being returned as such (via chrome dev tools): <ul style="display: block;"> <li>joe</li> <li></li> <li>johnny</li> <li></li> <li>ralph</li> <li>/li> <li>mike</li> <li></li> </ul> There are only four members (Users) joined to this particular group, so I don't understand what's happening. I assume the issue is from how I passed the data into the template from my view: class GroupDetail(DetailView): model = Group template_name = 'group_details.html' def get_context_data(self, *args, **kwargs): group = get_object_or_404(Group, id=self.kwargs['pk']) joined_members = group.joined.all() context = super(GroupDetail, self).get_context_data() context["joined_members"] = joined_members return context There are no actual errors, just these four empty list items. Is the issue with my for loop? Or is it with how I'm passing my context?