Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i make my first form with a selected field prepopulate that field in a second form in Django
I'm new to Django, started learning it this week. I have made my models.py like so: class EmployeeTrack(models.Model): time = models.DateTimeField(default=datetime.now(), blank=False) eid = models.ForeignKey('Employee', on_delete=models.CASCADE, null=True, blank=False, verbose_name = 'Employee') tmp = models.DecimalField(max_digits=3, decimal_places=1, verbose_name='temperature') class Meta: verbose_name_plural='Employee Tracking' class Employee(models.Model): first_name= models.CharField(max_length=100, blank=False) last_name= models.CharField(max_length=100, blank=False) email= models.CharField(max_length=100, blank=False) My question now is how can I make a form, with one input field like for example id, and then enter a user id, transfer that user id to the form for the model EmployeeTrack and populate the eid field based on my previous input in the first form? -
Is there a way to delete the datas from django on a particular time when user is not using the website [duplicate]
I'm trying to delete the datas on Bangladesh time 10:00 PM with django. And i searched for it but there is no result. I'm thinking that i can solve it by datetime module, But I'm lost in this and I can't understand anything about it. I tried by this, x = datetime.datetime.now() # times = x.split(' ', 1) print(x) # I'm lost now How can i solve it? -
Listen failure while using wesocket in django says winerror 10048
Listen failure: Couldn't listen on 127.0.0.1:8000: [WinError 10048] Only one usage of each socket address (protocol/network address/port) is normally permitted. While using websocket in Django I am having above error. Not sure why it is happening. Please help me if you can. -
How to override M2M field names and models in Django with an existing database?
I'm using Django 3.1.3 and working with an existing postgresql database. Most of the models and fields names of this DB are badly chosen and/or way too long. Most of the time its easy to change them with some handy Django options like so : class NewModelName(models.Models): new_field_name = models.CharField(max_length=50, db_column='old_field_name') class Meta: managed=False db_table='database_old_table_name' But let say I want to change a M2M field name and the corresponding model name. I'd like to have something like : class Foo(models.Models): new_m2m_field_name = models.ManyToManyField('RelatedModel', blank=True, db_column='old_m2m_field_name') class Meta: managed=False db_table='foo_old_table_name' class RelatedModel(models.Models): name = models.CharField(max_length=50) class Meta: managed=False db_table='related_model_old_table_name' But if I do that, Django will throw an error stating django.db.utils.ProgrammingError: relation "foo_new_m2m_field_name" does not exist. It is like it is ignoring the db_column option. Any idea how I could get to a similar result ? Thanks! -
Where in Django can I run startup to load data?
I have a django application that loads a huge array into memory after django is started for further processing. What I do now is , after loading a specific view, I execute the code to load the array as follows: try: load_model = load_model_func() except: #Some exception The code is now very bad. I want to create a class to load this model once after starting django and I want to be able to get this model in all other this model in all other methods of the application So, is there a good practice for loading data into memory after Django starts? -
How to Access Digital Oceans private file on Django
I can upload files but how can i download a file from Digital Oceans Spaces which is private on Django? A public file can be accessed by the path below. https://"Project".ams3.digitaloceanspaces.com/"Project path"/"File name" Accessing a private path would however require an AWS3 signature using Boto3 AWS_S3_REGION_NAME = 'xxxx', AWS_S3_ENDPOINT_URL = 'xxxxxxxxxx', AWS_ACCESS_KEY_ID ='xxxxxxxxx', AWS_SECRET_ACCESS_KEY ='xxxxxxxxxxxxxxxxxxxxxxxxx') But how do you actually implement this to download a file from spaces? Any help would be appreciated -
Field 'id' expected a number but got '-'
I'm basically new to the Django and got such ValueError. I have a basic user model inheriting from AbstractUser class. Also I have Profile model (in separate app), which also contain OneToOneField refering to my User model. First of all, lets take a look on my Profile model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') country = models.ForeignKey('Country', on_delete=models.SET_DEFAULT, default='-') full_name = models.CharField(max_length=32, default='-') about = models.TextField(max_length=1000, default="User don't set any information about") register_date = models.DateField(auto_now=True) image = models.ImageField(upload_to='images/', default='images/no_avatar.png') active = models.BooleanField(default=False) website = models.URLField(default='-') github = models.URLField(default='-') twitter = models.URLField(default='-') instagram = models.URLField(default='-') facebook = models.URLField(default='-') Secondly when I create a new User I have to also create his own profile (model instance refering to the user instance). Let's look on my view.py where I creating a new user. class SignupView(View): def get(self, request): """ :param request: :return: Register page """ return render(request, "login/register.html", { 'form': SignupForm() }) def post(self, request): """ Tests data validity,creating user if everything is ok. :param request: :return: Particular user page if data is valid, otherwise it will return couple of mistake messages """ form = SignupForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] email = form.cleaned_data['email'] password1 = form.cleaned_data['password'] password2 = form.cleaned_data['confirm_password'] if password1 … -
Admin register CustomUser model gives error in Django
I'm trying to register my CustomUser model that I've created and it gives me this error but I verified the files for many times and I don't understand why I'm getting this error @admin.register(CustomUser) class CustomUserAdmin(UserAdmin): model = CustomUser add_form = CustomUserCreationForm fieldsets = ( *UserAdmin.fieldsets, ( 'Mobile Phone', { 'fields': ( 'mobile_phone' ) }, 'Email Status', { 'fields': ( 'do_not_marketing_email', 'email_verified' ) } ) ) error: <class 'users.admin.CustomUserAdmin'>: (admin.E009) The value of 'fieldsets[4]' must be of length 2. -
what is the use of request.META.get('HTTP_REFERER', '/') in django
My question is plain and simple,i just want to know what it does. What does it mean if i return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/')) in one of my views in django?? -
Best theorically way to integrate some standalone apps into a web environment?
I've developed some python standalone apps that now I want to integrate into a web environment in order to make them more user friendly for my workmates, whom aren't used to CLI and the command shell. I've thought in remaking those apps as Django apps, using the Django REST framework, but I'm not sure if that way is the theoretically correct given the REST API meaning. For giving some examples, one of my apps takes some geometries from a geopackage, which is a kind of compact format for transferring geospatial information that could acts as a database for itself, and does some QA processes in order to ensure the geometries and data quality. Another of my apps takes some more geometries from the same geopackage and converts them into shapefiles or CAD files. In brief, my question is that it is theoretically correct to remake those apps as Django apps, using the Django REST framework, or maybe exists another options or framework that are more suitable to what I want to approach. -
This field is required. Dajngo rest framework
I'm trying to send put request on my Django rest API server. but my rest API server is giving me this exception again and again {'user': ['This field is required.']} what should i do? Django rest framework serializer.py class UserProfileSerializer(CountryFieldMixin, serializers.ModelSerializer): user = UserSerializer() avatar = AvatarSerializer(read_only=True) class Meta: model = Profile fields = "__all__" read_only_fields = ("username",) def update(self, instance, validated_data): user_validated_data = validated_data.pop('user') profile = Profile.objects.filter(id=instance.id).update(**validated_data) user = User.objects.filter(id=instance.user.id).update(**user_validated_data) return Profile.objects.filter(id=instance.id).first() django rest framework views.py class UserProfileRetrieveUpdateAPIView(RetrieveUpdateAPIView): serializer_class = UserProfileSerializer def get_user_or_404(self): return get_object_or_404(User, id=self.request.user.id) def get_object(self): obj = get_object_or_404(Profile, user=self.get_user_or_404()) return obj function that is sending put request. def edit_specific_profile(request, form): token = request.session.get('access') data = { "id": None, "user": { "email": form.cleaned_data.get("email"), "first_name": form.cleaned_data.get("first_name"), "last_name": form.cleaned_data.get("last_name") }, "headline": form.cleaned_data.get("headline"), "maiden_name": form.cleaned_data.get("maiden_name"), "company_name": form.cleaned_data.get("company_name"), "proposal_comments": form.cleaned_data.get("proposal_comments"), "associations": form.cleaned_data.get("associations"), "interests": form.cleaned_data.get("interests"), "website": form.cleaned_data.get("website"), "location": form.cleaned_data.get("location"), "bio": form.cleaned_data.get("bio"), "state": form.cleaned_data.get("state"), "country": form.cleaned_data.get("country"), "date_of_birth": form.cleaned_data.get("date_of_birth"), } print(data) url = settings.AUTHENTICATION_HOST + "accounts/profile/" response = requests.put(url, data = data, headers = {"Authorization": f"Bearer {token}"}) print(response.json()) and in Django rest framework web interference in raw data Django rest framework is expecting { "user": { "username": "admin", "email": "itshamzamirchi@gmail.com", "first_name": "Hamza2", "last_name": "Lachi" }, "headline": "Test", "maiden_name": "test", "company_name": "t", "proposal_comments": "", "associations": … -
Migrating data to a ManyToMany Field in django
There already exists a model called Team and an email field users. Later it is converted to a ManyToMany Field. Is it possible to migrate the data from the email field to the ManyToMany field by scripts. Currently the users list is saved in the string format. After converting it to the list format and then adding it to the ManyToMany field is possible? class User(models.Model): email = model.EmailField() class Team(models.Model): users = models.EmailField() members = models.ManyToManyField(User, related_name='teams') And I tried with the following code to restore the data, but it is not getting restored def team_member_update(apps, schema_editor): team_list = Team.objects.all() for team in team_list: list_users = team.users # converting to list for user in list_users: team_user = User.objects.create(email=list_users) team.members.add(team_user) team.save() -
Why does Django test fail if user is authenticated
I am trying to test a Django view that requires that the user be logged in urls.py path('', BooksListView.as_view(), name='book_list'), views.py from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import ListView from .models import Book class BooksListView(LoginRequiredMixin, ListView): model = Book template_name = 'books/book_list.html' login_url = 'account_login' tests.py class BooksTests(TestCase): def setUp(self): self.user = get_user_model().objects.create_user( username='reviewuser', email='reviewuser@email.com', password='testpass123' ) def test_book_list_view_for_logged_in_user(self): self.client.login(email='reviewuser@email.com', password='testpass123') response = self.client.get(reverse('book_list')) print(self.user.username, self.user.is_authenticated, response.status_code) self.assertEqual(response.status_code, 200) This fails because response.status_code returns 302 The output of the print statement is reviewuser True 302 In testing the web site a logged in user is able to access the page Where does the 302 come from? -
how to pass variable from views in one app to another app in django?
The app in my project have the following views(view1.py) def check(req): userid = req.POST['userid'] pwd = req.POST['password'] return render(req, 'success.html', {'username': username}) I need to use the same username variable in the views in another app of same project(view2.py) def edit_parameter_view(req): return render(req, 'edit_parameter.html',username) Both views are in different apps of the same project -
How to include a Django logging.FileHanler with Celery on ElasticBeanstalk
If I do not include logging I have an Django application with Celery working fine on ElasticBeanstalk using AWS SQS. When I include logging with a 'logging.FileHandler' celery gets permission denied error because it doesn't have permission rights for my log files. This is my error ValueError: Unable to configure handler 'celery_file': [Errno 13] Permission denied: '/opt/python/log/django.log' This is my logging setup LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'handlers': { 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler' }, 'file': { 'level': log_level, 'class': 'logging.FileHandler', #'filters': ['require_debug_false'], 'filename': os.environ.get('LOG_FILE_PATH', LOG_FILE_PATH + '/var/log/django.log') }, 'mail_admins': { 'level': 'ERROR', #'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' }, 'cqc_file' :{ 'level': log_level, 'class': 'logging.FileHandler', #'filters': ['require_debug_false'], 'filename': os.environ.get('LOG_FILE_PATH', LOG_FILE_PATH + '/var/log/cqc.log') }, 'null': { 'class': 'logging.NullHandler', }, 'celery_file': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': os.environ.get('LOG_FILE_PATH', LOG_FILE_PATH + '/var/log/celery.log'), } }, 'loggers': { '': { 'level': 'WARNING', 'handlers': ['file'], }, 'debug' : { 'level': log_level, 'handlers': ['file'], }, 'django.security.DisallowedHost': { 'handlers': ['null'], 'level' : 'CRITICAL', 'propagate': False, }, 'django.request': { 'handlers': ['file','mail_admins'], 'level': 'DEBUG', 'propagate': True, }, 'cqc_report' : { 'level' : 'INFO', 'handlers' : ['cqc_file'] }, 'celery.task' : { 'handlers': ['console', 'celery_file'], 'level': 'INFO', 'propagate': True, } } } … -
Uncaught reference error when calling a javascript function
I am trying to run a javascript function when control comes out of a field(AWSID). Getting the following error: Uncaught ReferenceError: getCustomerName is not defined at HTMLInputElement.onblur (ipwhitelistindex:12) onblur @ ipwhitelistindex:12 Please help me out. {% extends 'base.html' %} <html> <body> <script type ="text/javascript"> function getCustomerName() { alert('get customer name called....'); } </script> {% block content %} <h1>IP Whitelisting</h1> <form name = "ipwhitelistindex" action = 'ipwhitelisting' method = "post"> {% csrf_token %} <center> <table> <tr><td>Enter AWS Account Id </td><td>:</td><td><input type = 'text' name = AWSID onblur="getCustomerName()"></td></tr> <tr><td>Customer Name </td><td>:</td><td><input type = 'text' name = CUSTNAME style = "background-color : lightgrey" readonly></td></tr> <tr><td>Enter list of IPS seperated with(,) </td><td>:</td><td><input type = 'text' name = IPS></td></tr> <tr><td>Enter description </td><td>:</td><td><input type = 'text' name = DESC></td></tr> </table><br> <input type = 'submit' value = 'submit'> </center> </form> {% endblock %} </body> </html> -
How to create field in Django model that refers to another field in the same model
I want to create field in my Model that refers to another field (in the same model) and modifies it. My code: class Result(models.Model): score = models.IntegerField(default=10) rank = models.IntegerField(score/2) // how to point to score from the same model (Result)? -
Best and simplest way of deploying django app?
I would like to ask few questions. I finally got to deploying my app, but it's even bigger headache than building the app itself.. Apparently, I would need virtual server, so my first question is does the location of provider matter for SEO? Should I find a local provider? Also, do you maybe have any step by step tutorial on how to deploy django app? I have searched and they are all just different and too complicated for my current skill level. Thanks -
How to automaticly flag stings for makemessage translation file in django
I'm creating a signal that sends messages to multiple users, and each message should be translated to the receiver's language. this is a simplified example of that the alert handler does: def alert_handler(**kwargs): t_message = kwargs.pop("message", None) context = kwargs.pop("context", None) for recipient in recipients: activate(recipient.language) message = _(t_message, context) new_alert = Alert(recipient=recipient, message=message) This works as intended but the makemessages command doesn't recognize the sting passed in the kwargs as a translatable string. Is it possible to flag a string to be picked up by the makemessages command? -
Django UpdateView
I am using the generic Django Views for creating CreateViews and UpdateViews in my views.py - where the field 'Author' is a ForeignKeyField in the model: class BookCreate(CreateView): model = Book fields = ['title', 'author'] The generically rendered Creation-Form supplies a DropDown-List where I can choose the Author - so far so good. My question: How can I sort that dropdown alphabetically? Thanks in advance for your help!! -
django object has no id, or is at least not passing any id
I'm trying to get my template to pass an object's id to the relevant url, but I'm having no luck. In my template, I'm trying to pass "player.id". The template's name is "show.html" Like this... <tr> <td>{{ QB }} <a href="{% url 'delete_player' player.id %}">Delete</a> </td> </tr> The url I'm trying it pass it to is this... path('show/<int:id>',views.show, name="show") The url needs an id but isn't getting one. The problem seems to be coming from the relevant views.py function that I'm trying to link to "delete_player" def delete_player(request, id): player = Player.objects.get(id=id) player.delete() return redirect('show') show.html is being rendered by show() def show(request, id): player = Player.objects.all(id=Player.id) print(player) user = request.user if user.is_authenticated: try: QB = Quarterback.objects.values_list('name', flat="True")[0] except IndexError: QB = 'empty' try: RB = Runningback.objects.values_list('name', flat="True")[0] except IndexError: RB = 'empty' try: WR = Widereceiver.objects.values_list('name', flat="True")[0] except IndexError: WR = 'empty' try: TE = Tightend.objects.values_list('name', flat="True")[0] except IndexError: TE = 'empty' try: K = Kicker.objects.values_list('name', flat="True")[0] except IndexError: K = 'empty' print(player) context = { 'QB': QB[0:], 'RB': RB[0:], 'WR': WR[0:], 'TE': TE[0:], 'K': K[0:], 'player': player } return render(request,"game/show.html", context) when I try to access http://127.0.0.1:8000/game/show, I keep getting a 404 because there is no id to … -
Django Queryset: sum of interval field converted to seconds with group by (annotate)
in the contact table I keep the contact logs between some devices. # select * from contact; node | contact | start_time | end_time | duration | alert | id -----------+-----------+---------------------+---------------------+----------+-------+---- DEVI-C533 | DEVI-DEC2 | 2020-11-19 16:44:34 | 2020-11-19 16:44:34 | 00:00:00 | f | 1 DEVI-DEC2 | DEVI-E720 | 2020-11-20 08:57:26 | 2020-11-20 08:57:26 | 00:00:00 | f | 2 DEVI-D1BC | DEVI-F382 | 2020-11-20 09:06:15 | 2020-11-20 09:07:51 | 00:01:36 | f | 3 DEVI-E720 | DEVI-F382 | 2020-11-20 08:57:27 | 2020-11-20 08:57:27 | 00:00:00 | f | 4 DEVI-D1BC | DEVI-E720 | 2020-11-20 09:07:26 | 2020-11-20 09:07:32 | 00:00:06 | f | 5 DEVI-E720 | DEVI-F35E | 2020-11-13 12:19:33 | 2020-11-13 14:51:06 | 02:31:33 | f | 9 DEVI-DEC2 | DEVI-E44F | 2020-11-19 16:45:10 | 2020-11-19 16:45:10 | 00:00:00 | f | 11 DEVI-D1BC | DEVI-DF5C | 2020-11-19 16:44:44 | 2020-11-19 16:46:13 | 00:01:29 | f | 12 DEVI-D1BC | DEVI-DEC2 | 2020-11-19 16:40:36 | 2020-11-19 16:46:13 | 00:05:37 | f | 13 DEVI-D1BC | DEVI-F35E | 2020-11-19 16:44:07 | 2020-11-19 16:44:19 | 00:00:12 | f | 14 ... I need to return the grouped values as in the following query QUERY select node, contact, sum(duration) as … -
request.POST.getlist() returns empty list
I am not able to access my inputs thorugh request.POST.getlist() method, and when I run my program, all other fields are okay and I can see the result but when it comes to choices it return empty list. views.py if request.method == 'POST': teacher_get = request.POST.get('teacher') department_get = request.POST.get('department') subject_get = request.POST.get('subject') answer_list = [] print(teacher_get) print(department_get) print(subject_get) answer = request.POST.getlist("question_{{question.id}}") print(answer) OUTPUT: Ahmad Software Engineering Programming [] [26/Nov/2020 15:48:12] "POST / HTTP/1.1" 200 2353 INDEX.HTML <form action="{% url 'index'%}" method="POST"> {% csrf_token %} <select name="teacher"> {% for question in question %} <ol>{{ question.question }}</ol> {% for choice in rating_choices %} <input type="radio" name="question_{{question.id}}" value="{{choice.0}}">{{choice.1}} {% endfor %} {% endfor %} <br> <input type="submit" value="Vote"> -
How to fix Python Django TypeError
I have a simple model class which I want to return the the value for a field in my Django Admin. Error Logs from terminal TypeError: __str__ returned non-string (type NoneType) models.py class Solution(models.Model): description = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) user = models.ForeignKey(User, on_delete=models.CASCADE) error = models.ForeignKey(Error, on_delete=models.CASCADE) def __str__(self): return self.error + " fixed by " + self.user -
Make soap request with certificate
I'm facing problem with making soap request. I've got three certificates .key, .csr and .pfx. With openssl i've changed .pfx to .pem certificate and try to add in session. This is the code: session = Session() session.cert = BASE_DIR + '/cert.pem' transport = Transport(session=session) transport.session.headers = self.headers client = Client(WSDL, transport=transport) self.service = client.create_service('{http://tempuri.org/}', self.endpoint) What i'm facing is error (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1122)'))) The .pfx certificate is protected by password, but I've tried making .pem file without password, so what I'm doing wrong? I've tested .pfx file with ReadyAPI and after adding certificate everything is working perfectly.