Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
The virtual environment is not activated in the pycharm terminal
I use pycharm, but my power shell does not recognize the virtual environment? What do you think I should do so that he can recognize the virtual environment? And that this happened after I moved my django project folder to another folder terminal setting : And that my virtual environment is recognized by pycharm and the application runs, but when testing the terminal, it does not recognize my virtual environment. -
using selenium I get some errors: TypeError: expected str, bytes or os.PathLike object, not NoneType
When I run a test case python3.9 manage.py test in django webapp I get some errors. System check identified no issues (0 silenced). test_login (pygiustizia.tests.test_views_topics.ViewsTopicsTestCase) ... nel costruttore model Users Traceback (most recent call last): Traceback (most recent call last): Traceback (most recent call last): File "/usr/lib/python3.9/wsgiref/handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "/home/nicola/.local/lib/python3.9/site-packages/django/test/testcases.py", line 1662, in __call__ return super().__call__(environ, start_response) Traceback (most recent call last): File "/usr/lib/python3.9/wsgiref/handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "/usr/lib/python3.9/wsgiref/handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "/home/nicola/.local/lib/python3.9/site-packages/django/test/testcases.py", line 1662, in __call__ return super().__call__(environ, start_response) File "/home/nicola/.local/lib/python3.9/site-packages/django/core/handlers/wsgi.py", line 132, in __call__ response = self.get_response(request) File "/home/nicola/.local/lib/python3.9/site-packages/django/test/testcases.py", line 1662, in __call__ return super().__call__(environ, start_response) File "/home/nicola/.local/lib/python3.9/site-packages/django/core/handlers/wsgi.py", line 132, in __call__ response = self.get_response(request) File "/home/nicola/.local/lib/python3.9/site-packages/django/test/testcases.py", line 1645, in get_response return self.serve(request) File "/usr/lib/python3.9/wsgiref/handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "/home/nicola/.local/lib/python3.9/site-packages/django/core/handlers/wsgi.py", line 132, in __call__ response = self.get_response(request) File "/home/nicola/.local/lib/python3.9/site-packages/django/test/testcases.py", line 1645, in get_response return self.serve(request) File "/home/nicola/.local/lib/python3.9/site-packages/django/test/testcases.py", line 1657, in serve return serve(request, final_rel_path, document_root=self.get_base_dir()) File "/home/nicola/.local/lib/python3.9/site-packages/django/test/testcases.py", line 1657, in serve return serve(request, final_rel_path, document_root=self.get_base_dir()) File "/home/nicola/.local/lib/python3.9/site-packages/django/test/testcases.py", line 1645, in get_response return self.serve(request) File "/home/nicola/.local/lib/python3.9/site-packages/django/test/testcases.py", line 1657, in serve return serve(request, final_rel_path, document_root=self.get_base_dir()) File "/home/nicola/.local/lib/python3.9/site-packages/django/views/static.py", … -
NameError: name '_mysql' is not defined on Mac A1 Monterey
I am trying to include mysql into my django and face the error of in <module> version_info, _mysql.version_info, _mysql.__file__ NameError: name '_mysql' is not defined I think this might be an error due to the new M1 chip and mac OS system, but I can't figure out how to fix it. (I am using mac Monterey with M1 chip.) Here is the package version: mysql-connector-python 8.0.29 mysqlclient 2.1.1 mysql Ver 8.0.29 for macos12.2 on x86_64 (Homebrew) Python 3.8.9 I've read it somewhere about my python needs to be at the homebrew directory, but not sure how to do it. which python3 /usr/bin/python3 I've also seen other solution of using arch -x86_64 brew install mysql It didnt work for me. here is my .zshrc file now export PATH="/usr/local/opt/python/libexec/bin:$PATH" export PATH="/usr/local/opt/mysql-client/bin:$PATH" export DYLD_LIBRARY_PATH="/usr/local/mysql/lib:$PATH" export PATH="/usr/local/opt/python@3.8/bin:$PATH" and here is my bash_profile export PATH="/usr/local/opt/python/libexec/bin:$PATH" export PATH="/Applications/Sublime Text.app/Contents/SharedSupport/bin:$PATH" export PATH="/usr/local/opt/mysql-client/bin:$PATH" -
How to send email list over django using model's ArrayField
I habe a Group model: 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) email_list = ArrayField( models.CharField(max_length=255, blank=True), blank=True, default=list, ) When Users join or leave Groups, I have their email either added or removed from the email_list via this view: def join_group(request, pk): id_user = request.user.id group = Group.objects.get(id=request.POST.get('group_id')) account = Account.objects.get(user_id=id_user) if group.joined.filter(id=request.user.id).exists(): group.joined.remove(request.user) account.joined_groups.remove(group) group.email_list.remove(account.user.email) else: group.joined.add(request.user) account.joined_groups.add(group) group.email_list.append(account.user.email) return HttpResponseRedirect(reverse('group_detail', args=[str(pk)])) And this works to the best of my knowledge. The issue comes when I want to send a mass email out to everyone in the mailing list. I have a url path('group/<int:pk>/notifications/', notifications, name='send_notifications'), that I access from my GroupDetail view: <a href="{% url 'send_notifications' group.pk %}">SEND NOTIFICATIONS</a> But I get this error when trying to render my notifications view: Group matching query does not exist. The reason I didn't ask about this error is because I believe I know where the issue is coming from -- the first line in my notifications view: def notifications(request, pk): group = Group.objects.get(id=request.POST.get('group_id')) if request.method == 'POST': subject = request.POST['subject'] message = request.POST['message'] recipients = group.email_list for recipient in recipients: send_mail ( subject, message, NOTIFICATION_EMAIL, [recipient], fail_silently=False ) return render(request, … -
Test a data migration ManyToMany in Django
I tried to add a field to my ManyToMany relationship models in Django. So step by step, I created the new model and apply makemigrations and migrate. I checked I have the new table in my postgresql database. Now before I will add the through keyword in the ManyToMany field I want to write a function in the migration file that will copy the old data of the previous ManyToMany table to the new one with the additional field. I followed a solution explained here: Django migration error :you cannot alter to or from M2M fields, or add or remove through= on M2M fields I want to test the function that will migrate the data in a test function but I don't understand to do. here my code: survey/models: class Survey(BaseModel): name = models.CharField(max_length=256, help_text='Survey name') user = models.ManyToManyField(User, blank=True, help_text='patient') survey/models: class SurveyStatus(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) survey = models.ForeignKey(Survey, on_delete=models.CASCADE) survey_status = models.CharField(max_length=10, blank=True, null=True, choices=STATUS_SURVEY_CHOICES, ) The function I wrote that need to copy the data from the previous M2M to the new one is the following one: def create_through_relations(apps, schema_editor): Survey = apps.get_model('survey', 'Survey') SurveyStatus = apps.get_model('survey', 'SurveyStatus') for survey in Survey.objects.all(): for user in survey.user.all(): … -
How do I get all the commented TV and movie scores in descending order?
What we want to achieve I want to display stars (SCORE) in descending order on my Movie and TV models. Current state I have been retrieving data from TMDB to get movie and TV data. Then when the user puts in comments and scores, that movie or TV gets its own Model created. Questions to ask I choose the opition score in the html select Then when the score is chosen, data = requests.get (f "https://api.themoviedb.org/3/tv/{tv_id}?api_key={TMDB_API_KEY}&language=en-US") or data = requests.get (f "https://api.themoviedb.org/3/movie/{movie_id}?api_key={TMDB_API_KEY}&language=en-US") for IDs stored in your own Movie and TV models Search. How can I sort those movies and TVs in descending order of stars (score) and display them in html? important point If you choose another option in select, movies and TV will be displayed as described in javascirt. current code def index(request): # Render the template query = request.POST.get('media_type') print(query) return render(request, 'Movie/index.html') class Movie(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_movie.objects.filter(movie_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 TV(models.Model): id = models.CharField(primary_key=True, editable=False, validators=[alphanumeric],max_length … -
Celery configuration on uwsgi not working
I have a Django project that I'm trying to move on my production VM. I'm using uWSGI and nginx and I succeeded in configuring it so that my website is available. Now I'm trying to start my Celery worker which is also needed. I saw on uWSGI docs that in order to configure Celery, the following should be added to the configuration file : [uwsgi] master = true socket = :3031 smart-attach-daemon = /tmp/celery.pid celery -A tasks worker --pidfile=/tmp/celery.pid I then ended up with this : [uwsgi] chdir = /home/xxx/ScriptsApp/src/ module = main.wsgi home = /home/xxx/ScriptsApp/venv master = true processes = 10 socket = /home/xxx/ScriptsApp/src/scriptsApp.sock chmod-socket = 666 vacuum = true daemonize = /home/xxx/uwsgi-emperor.log # Celery smart-attach-daemon = %(chdir)tmp/celery.pid celery -A main worker --pidfile=%(chdir)tmp/celery.pid However, when running it, Celery isn't running, while if I run celery -A main worker in my virtual environment, Celery is correctly running. I've just started using linux/uwsgi so I may have messed up somewhere in the process but I'm unable to find where, even though I've tried every possible solutions that I found. Thanks in advance for your help ! -
Way to deploy django with webpack loader with vue.js
while I was working on a project in django integrated with vue js via webpack. https://github.com/django-webpack/django-webpack-loader I had a doubt about the deployment. Are there any services that allow this? For django I have always used pythonanywhere as hosting but in this case is it possible? Are there any hosting services that allow django to easily deploy with the webpack loader with vuejs? -
ERROR: No matching distribution found for whitenoise-6.2.0
While trying to push to heroku I get this error: ERROR: No matching distribution found for whitenoise-6.2.0 Heroku is currently on Python 3.10. Locally I have 3.9, but this is within the scope mentioned in the whitenoise docs. http://whitenoise.evans.io/en/stable/index.html#compatibility When this error says no 'matching distribution' - matching what? Python? Django? Some other dependency? Heroku? Please advise. Thx. -
Which Django field should I use for longitude and latitude?
I am saving longitude and latitude as FloatField. But when I tried to use them on JS in the array I figured out that FloatField separates with a comma instead of a dot as should be on latitude or longitude. So it acts like four different elements in js. js: map.on('load', () => { 'coordinates': [ [{{tour.departure.city.longitude}},{{tour.departure.city.latitude}}], [{{tour.arrival.city.longitude}},{{tour.arrival.city.latitude}}], // it will be like [ 23, 0534 , 42, 1534] // but should be like [ 23.0534 , 42.1534] ] }); models.py class Tour(models.Model): latitude = models.FloatField(blank=True, null=True, verbose_name=_("Latitude")) longitude= models.FloatField(blank=True, null=True, verbose_name=_("Longitude")) I tried to save with dot but Django converted it to the comma. -
Not rendering the Messahe in Django
I am trying to create message before submitting the page, but i do not know why the message not rendering , can anyone help me to correct it. form.py class NameForm(forms.ModelForm): translated_names = TranslationField() class Meta: fields = "__all__" model = models.Name admin.py class NameAdmin(MasterDataBaseAdmin): form = forms.NameForm inlines = [AddressInline, RegistrationTypeInline] queryset = models.Name.objects.prefetch_related( "names", "name__id", "registrationstype") views.py class NameViewSet(viewsets.ReadOnlyModelViewSet): queryset = models.Name.objects.supported().prefetch_related("names", "registrationstype") serializer_class = serializers.NameSerializer def nametype(request): form = Form(request.POST) if form.is_valid(): return render(request, 'templates\ view2.html', form) view2.html {% extends "admin/base_site.html" %} -
Show all comments from a specific user in django
I am trying to consolidate all the comments, on various products, from the logged in user in an "Account" page. My initial plan was to request all comments from the user id. Because I created a Profile model, I thought the right way to approach this was to link it to the profile id, and not directly to the use id. Obviously, it's not working. Am I close to it? or should I think of it completely differently? (new to programming, as you can see on the code) Starting with my models.py class ReviewRating(models.Model): user = models.ForeignKey(User,blank=True, on_delete=models.CASCADE) product=models.ForeignKey(Product,related_name="comments", on_delete=models.CASCADE) review=models.TextField(max_length=250) def __str__(self): return '%s - %s - %s'%(self.user, self.product, self.date_added) class Profile(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) general_reviews = models.ForeignKey(ReviewRating,null=True, on_delete=models.CASCADE) def str(self): return str(self.user) Views.py def account(response, profile_id): generalreviews_list = Profile.general_reviews.objects.all(pk=profile_id) return render(response,"main/account.html", {'generalreviews_list':generalreviews_list}) URLS path("account/<profile_id>/", views.account, name="account"), -
Django Post method not showing form to fill fields
The post method does not bring a form to enter the field details. I am able to enter data using json format. I followed the Django documentation to create the API This is my serializer code: from rest_framework import serializers from .models import Tasks # converting objects into datatypes understandable by javaScript and frontend frameworks class TasksSerializers(serializers.ModelSerializer): class Meta: model = Tasks fields = "__all__" views.py @api_view(['GET', 'POST']) def task_list(request, format=None): serializer_class = TasksSerializers if request.method == 'GET': tasks = Tasks.objects.all() serializer = TasksSerializers(tasks, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = TasksSerializers(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) print(request.method) return Response(serializer.data, status=status.HTTP_201_CREATED) models.py class Tasks(models.Model): task_id = models.AutoField(db_column="task_id", primary_key=True, unique="true") task_description = models.TextField(db_column="task_description", null=True) task_status= models.CharField(max_length=399, db_column="task_status", default="Not started" ) task_priority = models.CharField(max_length=399, db_column="task_priority", default="Low priority") asignee_name = models.TextField(db_column="asignee_name", blank=False, null=False) deadline = models.DateField(db_column="deadline", blank=False, null=False) emp = models.ForeignKey(Employee,on_delete=models.CASCADE,default='') # metadata for the table class Meta: db_table = "Tasks" What have I done wrong? -
Django admin login redirects to admin login with a 302
I have a new django 4 app, and when I try to login to the admin, I am redirected to the login page. This is in development, so localhost, with no SSL. I have checked the following: Allowed hosts is ["*"] Authentication definitely succeeds, user is returned from auth backend Django sessions app and middleware are in settings.py Django sets 2 browser cookies, one for csrf and one for session id django_sessions table contains sessions Session id on browser cookie matches session id in database table. I'm a bit lost, it's a very opaque error, just an infinite loop of 302s back to login. -
Why Django form didn check unique of form field?
Method is_valid didnt check unique of form and when i try to create new item its just do nothing. models.py from django.db import models from django.contrib.auth.models import User class Links(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='Пользователь') long_url = models.CharField('Длинная ссылка', max_length=300) short_url = models.SlugField('Сокращенная ссылка', max_length=50, unique=True) title = models.CharField('Название для ссылки', max_length=80) def __str__(self): return self.title field short_url have unique=True views.py from django.shortcuts import render, redirect from django.views.generic import ListView from .models import Links from .forms import AddLinkForm def links(request): return render(request, 'main/main_page.html') class LinksList(ListView): model = Links template_name = 'links/links.html' ordering = ['-id'] def get_context_data(self, *, object_list=None, **kwargs): ctx = super(LinksList, self).get_context_data(**kwargs) user = self.request.user links = Links.objects.filter(user=user) form = AddLinkForm ctx['form'] = form ctx['links'] = links return ctx def post(self, request, *agrs, **kwargs): post = request.POST.copy() post['user'] = request.user request.POST = post form = AddLinkForm(request.POST) if form.is_valid(): form.save() return redirect('links') i try to use is_valid but when im testing it form let me entry not unic word, i press add it but page reload.It shoud work but i cant understand what is wrong forms.py from django import forms from .models import Links class AddLinkForm(forms.ModelForm): long_url = forms.CharField( required=True, label='Длинная ссылка', widget=forms.TextInput(attrs={'placeholder': 'Введите длинную ссылку'}) ) short_url = forms.SlugField( … -
django access same attribute on different model dynamically
I have different models which has following format. class Company(models.Model): pass class ModelA(models.Model): company = models.ForeignKey(Company, models.CASCADE) class ModelB(models.Model): company = models.ForeignKey(Company, models.CASCADE) class ModelC(models.Model): modelb = models.ForeginKey(ModelC) I want to write generic display field by the use of mixin in django admin for ModelA, ModelC as: class FieldMixin: @display(description='field') def my_field(self, obj): # normal solution would be this if object is ModelA and object.company.is_active: return 'active' if object is ModelC and object.modelb.company.is_active return 'active' # i wanted something like this instead of above. It will be easier if object has immediate attribute but object can have same field in nested object as well. object._meta.get_fields('company').is_active -
Changing a ForeignKey to a be the parent class/model
I have a situation where there are various entities, with ForeignKeys to models that are subclasses of another model. I need to update these FKs to point to the parent, so that any of the various subclasses could be linked. For example, the code might be: class School(Model): ... class University(School): ... class Student(Model): university = ForeignKey(University) ... and I need to change that FK from Student to University, to be an FK to School. I think that all Universities will have the same ID as the School that is in the database for that university. So is it safe/reliable to define the Student: class Student(Model): university = ForeignKey(University) school = ForeignKey(School) Then make a migration that creates the new school attribute, and uses RunPython to copy the id from university into school, then delete the university attribute and makemigrations for that? Is it ever possible that this method would break, or produce bad data? -
Why cleaned_data is None in BaseInlineFormSet?
Why when I want to get cleaned data in my custom forms, I get cleaned data is None? class AbstractRangeForm(BaseInlineFormSet): def __init__(self, *args, **kwargs): super(AbstractRangeForm, self).__init__(*args, **kwargs) def clean(self): cleaned_data = super(AbstractRangeForm, self).clean() #cleaned_data = None -
I want to know about the exact need of using @tracer.wrap() decorator in django
@tracer.wrap() - I have seen this decorator, above various methods in classes. I want to know about its use case. It is imported from ddtrace like "from ddtrace import tracer" -
Django: How to get the first time a user logged in within 24 hours in django
In Django, we can get the time a user last logged in by using Auth.User.last_login. That is only updated when the user logs in using his username/password. This would be useful for queries such as getting the number of new records since the last visit. Users can log out and also login multiple times in a day, now I want to get the first time a user logged in, in a day and store it in a model in the db. How do I achieve this functionality? -
Can't identify elements after ajax insert
There is a data in Django DB, when html page loaded it sends request to db and create html block in Django template, and at last it insert to html by id. This part works, checkboxes creates and all is good, but there is no elements is I try to find them by id after ajax insert. How to to get access them? html: <div id="fill-statuses" status-table-url="{% url 'ajax_status_data' %}"></div> Django template: {% for status in statuses %} <label class="toggle"> <input class="toggle__input" type="checkbox" id="{{ status.status_new }}_status_check_box"> <span class="toggle__label"> <span class="toggle__text">{{ status.status_new }}</span> </span> </label> {% endfor %} view.py: def fill_status_check_boxes(request): statuses = TaskStatus.objects.values('status_new').distinct return render(request, 'persons/statuses_for_filter.html', {'statuses': statuses}) And now js block, with comments: function fill_status_check_boxes() { const url = $("#fill-statuses").attr('status-table-url') $.ajax({ url: url, success: function (data) { $('#fill-statuses').html(data) }, complete: function () { console.log(document.querySelectorAll("[id*='status_check_box']")) //return array with elements, that's why I thought that all works, when tested it } }) console.log(document.querySelectorAll("[id*='status_check_box']")) //but here return empty array [] } fill_status_check_boxes() console.log(document.querySelectorAll("[id*='status_check_box']")) //and here also return empty array [] -
bulk create in django with foreign key
Models: class Author(Base): name = models.CharField(max_length=100, unique=True) class Book(Base): name = models.CharField(max_length=100, unique=True) class AuthorBookAssn(Base): author = models.ForeignKey(Author) book = models.ForeignKey(Book) I have an api to create a book, and along with the book data we would also get a list of author ids. Now for each book we need to create one/more records (depending on the author ids provided) in the AuthorBookAssn table. What is the best way to do this and can the create be done in bulk. Currently the approach is to get the author objects for each of the ids in the list and then call AuthorBookAssn.objects.create(book=book_instance,author=author_instance) -
Get user group's permission from request.user in dajngo?
I had created a group with certain permission, and added a user to that group. Now, with the request.user can we able to get the group's permission and grant permission to the respective view class.? For user permission we can do this, request.user.has_perm("app_label.code_name") For user group's permission? -
Test whether a Django migration has been applied to a DB
I have a django project, and I wish to update a MySQL database from a previous version of the codebase to be compatible with the current version. I have all of the migrations for the project, but I do not know which was the last one applied to this alternate database. I can try and determine this manually, but I was wondering if there was an easier automated way of finding which the first unapplied migration is. -
Django Keep connection with route through standalone frontend
I am working on a chatbot and want to deploy it in Django but I am using a standalone frontend. I have little to no knowledge about JavaScript and copied this Script from somewhere: onSendButton(chatbox) { var textField=chatbox.querySelector('input'); let text1=textField.value if(text1==="") { return; } let msg1={name: "User", message: text1} this.messages.push(msg1); this.updateChatText(chatbox) textField.value='' fetch('http://localhost:8000/chat', { method: 'POST', body: JSON.stringify({message: text1}), mode: 'cors', headers: { 'Content-Type': 'application/json' }, }) .then(r => r.json()) .then(r => { console.log(r) let msg2={name: "CareAll", message: r.answer}; this.messages.push(msg2); if("follow_up" in r) { let msg3={name: "CareAll", message: r.follow_up}; this.messages.push(msg3) } this.updateChatText(chatbox) textField.value='' }).catch((error) => { console.error('Error:', error); this.updateChatText(chatbox) textField.value='' }); } This function is for /chat route def chat_bot_response(request): if request.method == "POST": u_msg = json.loads(request.body)["message"] ints = predict_class(u_msg, cb_model) resp = {"answer": getResponse(ints, intents)} maxConf = max(ints, key=lambda x: x["probability"]) if maxConf["intent"] not in [ "greeting", "farewell", "about_self", "about_self_function", "question", "unknown", "yes_to_symptom", "no_to_symptom", ]: RESP_LIST.append(resp["answer"]) resp["answer"] = "Do You Have other symptoms?" if maxConf["intent"] == "yes_to_symptom": print(RESP_LIST) elif maxConf["intent"] == "no_to_symptom": resp["answer"] = RESP_LIST[0] return JsonResponse(resp) What I am trying to do is, I want to stay in this function when the chatbox is opened until the user leaves the page. Will I need to improve JavaScript? use …