Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django remove foreign relationship from model
I have two models. I want to remove the recommendation foreign field from the Document model and change it to many-to-many. class Recommendation(models.Model): name = models.TextField() question = models.ForeignKey(Question, on_delete=models.CASCADE) class Document(models.Model): name = models.TextField() recommendation = models.ForeignKey(Recommendation, on_delete=models.CASCADE) Inteded result: class Recommendation(models.Model): name = models.TextField() question = models.ForeignKey(Question, on_delete=models.CASCADE) documents = models.ManyToManyField('Document') class Document(models.Model): name = models.TextField() But there is an error when I run ./manage.py makemigrations <class 'questions.admin.DocumentInline'>: (admin.E202) 'questions.Document' has no ForeignKey to 'questions.Recommendation'. -
How do I pass the form to the get_context_data function?
How can I get the form variable here? def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = kwargs['form'] return context Comment model code: class Comment(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) text = models.TextField() date_posted = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.id) View class: class CommentCreate(LoginRequiredMixin, CreateView): model = Comment fields = ('text', ) template_name = 'post/details.html' def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = kwargs['form'] return context DetailView: class PostDetailView(DetailView): model = Post context_object_name = 'post' template_name = 'post/details.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context -
'User' object has no attribute 'user'
I have a User model class User(AbstractBaseUser): username = None first_name = models.CharField(max_length=100, null=True, blank=True) last_name = models.CharField(max_length=200, null=True, blank=True) phone_regex = RegexValidator(regex=r'^09(\d{9})$', message="Phone number must be entered in the format: '09111111111'") phone = models.CharField(validators=[phone_regex], max_length=11, unique=True) email = models.EmailField(max_length=255, null=True, blank=True) # cart_number = models.PositiveBigIntegerField(null=True, blank=True) # shomare cart banki birth_day = models.DateField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'phone' REQUIRED_FIELDS = [] def __str__(self): return self.phone def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.is_admin in view I want to have a class to get a User and update it class UserRetrieveUpdateView(generics.RetrieveUpdateAPIView): queryset = User.objects.filter(is_active=True) serializer_class = UserSerializer permission_classes = (IsOwner,) when I want to test it with post man I give this error: AttributeError at /account/1/ 'User' object has no attribute 'user' this is my url: path('<int:pk>/', views.UserRetrieveUpdateView.as_view(), name='dashboard'), -
How I can display the video after uploaded from fileInput in the website using ajax
I working on uploading video with progress bar using ajax and I need to display the video after upload it in the video element, instead of image. I using the Django backend, How I can display the video file which I will choose in the website from fileInput to display it in specific video html element The Html (Template) <video src="<!--here I need to display the video-->" autoplay> </video> <!-- Form --> {% if request.user.is_authenticated %} <div id="alert-box"></div> <div id="image-box"> </div> <br> <form id="upload-form" action="." method="post" enctype="multipart/form-data"> {% csrf_token %} {{V_form.as_p}} <button class="btn btn-primary btn-block mt-5" name="submit_v_form"> <i class="icon-upload icon-white " name="submit_v_form"></i> Upload </button> </form> {% endif %} <br> <br> <div id="progress-box" class="d-none">progress</div> <div id="cancel-box" class="d-none"> <button id="cancel-btn" class="btn btn-danger">Cancel</button> </div> </div> <hr> </div> </div> The javaScript file success: function(response) { console.log(response) // imageBox.innerHTML = `<img src="${url}" width="300px">` imageBox.innerHTML = `<video src="${url}" width="300px">` alertBox.innerHTML = `<div class="alert alert-success" role="alert">Successfully uploaded the image below!</div>` }, -
Problem with Django project. AttributeError at / 'Product' object has no attribute 'Category'
Hello I was wondering could anyone help me with an issue I've ran into while working on a Django project. I've tried a few different things but cant seem to get it working a screenshot of the error is attached. -
When this code in views.py is run, there is a duplicate row in the Excel spreadsheet for each record in the table
The following code exports to an Excel file, but when this code in views.py is run, there is a duplicate row in the Excel spreadsheet for each record in the table def export(request): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="persons.xls"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('Person Data') # this will make a sheet named Person Data # Sheet header, first row row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['first_name', 'last_name', 'middle_name', 'email', 'country', 'phone_country_code', 'area_code', 'phone_number', 'time_zone', 'select_languages', 'team', 'experience', 'ref_name', 'ref_email', 'contemplative_inq', 'start_date', 'hours_month', 'hear_about', 'linked_in_url', 'web_site_url', 'employment', 'resume_sent', 'resume', 'picture', ] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) # at 0 row 0 column # Sheet body, remaining rows font_style = xlwt.XFStyle() rows = Person.objects.all().values_list('first_name', 'last_name', 'middle_name', 'email', 'country', 'phone_country_code', 'area_code', 'phone_number', 'time_zone', 'select_languages', 'team', 'experience', 'ref_name', 'ref_email', 'contemplative_inq', 'start_date', 'hours_month', 'hear_about', 'linked_in_url', 'web_site_url', 'employment', 'resume_sent', 'resume', 'picture') for row in rows: row_num += 1 for col_num in range(len(row)): ws.write(row_num, col_num, row[col_num], font_style) wb.save(response) return response -
Django pass data from HTML table to database model
I am creating a student attendance system using django. I am fetching all students name from student database into a HTML table and updating information about student to django model. This is my view.py to get data def attendanceFill (request, subject): context = '' ad_standard = request.session.get('standardO') subjects = CustomStudent.objects.filter(className__name__contains = ad_standard, subjectName__subjects__contains = subject) # attendanceForm = Attendance(request.POST or None, instance=subjects) print(ad_standard) print(subject) print(subjects) context = {'subjects' : subjects} if request.method == 'POST': student = request.POST print(student) return render(request, 'teacher/attendance_fill.html', context) This is my HTML template for data handling. <div class="container"> <div class= "row mt-4"> <form action="" method="POST"> {% csrf_token %} <table> {% for student in subjects %} <tr> <td name= 'student'><p class="student-name" id="student-name">{{ student.sname }}</p></td> <td> <input type="checkbox" name="attendance" id="attendance"> </td> </tr> {% endfor %} <tr> <td> <button type="button" name="checked" id = "checked" class="btn btn-outline-dark mb-4 shadow" style="border-radius:25px;">Submit</button> </td> <td></td> </tr> </table> </form> </div> </div> This is jquery function I am using to capture data. var formData = new FormData() $(document).ready(function(){ $("#checked").click('click', function(){ $students = document.getElementsByClassName('student-name').textContent; $attendance = $('#attendance').val() console.log($students) console.log($attendance) }) }) I have tried $('student-name').val() to get value for all students but it returns blank. Nothing is captured with this method. I wish capture all data … -
How to detect if user is still online with django session
I use Django 2.2 and trying to detect if user is still connected when the user close his browser without logging out I tried to use some Django packages like qsessions but it need to replace 'django.contrib.sessions.middleware.SessionMiddleware', with qsession middleware but it makes another error django.contrib.sessions.middleware.SessionMiddleware not found I need your help to get every user session separately. -
Django request should run in background?
When user submit request, the request should run in background so that user should not wait for the request complete and update to user via email/slack channel? i have a request to ssh and performs the task, so some commands/tasks will take longer time to completed, that's why i'm looking this option What is the better way to achieve? -
Django Weasyprint Timeout error for loading images in log
and I made a project that takes some pictures and converts them to pdf using weasyprint library. everything is alright in localhost but when I deployed it in python anywhere it generates the pdf but pictures that supposed to be in it dosent display and just the replace string of them is in the pdf please help me -
What is easiest way to do "Featured comments " in Django?
I have an requirement in Django , If mark a comment has Featured , it should be displayed in top of the home page (or any page), for next 24 hrs. And after 24 hrs it should go to normal state. i.e I will be flagging a comment has featured with a FLAG and the flag should automatically reset after 24 hrs. I am already showing the recent comments in the home page by descending date's , now the flagged comment should appear on top of it. is there any Django specific library available to achieve this (instead of going to redis) -
Django jwt token error. "Given token not valid for any token type, token_not_valid"
I am using Django Rest Framework for authentication and Axios in the frontend. When I pass the token to an axios.get method directly it fetches the API endpoint (getUserInfo) correctly, but when I use a variable (string) and pass it dynamically it fails and it gives the error described above. First case: (succeeds) const config = { headers: { Authorization: 'Bearer <token string>' }, }; await axios.get(URLS.FETCH_USER, config) Second case: (fails) const config = { headers: { Authorization: `Bearer ${accessToken}` }, }; await axios.get(URLS.FETCH_USER, config).etc Note that the token is fresh and taken directly from a postman login request. -
how to set custom sqlalchemy logging parameters?
I am using sqlalchemy for connecting to database in a django based python application. In settings.py I have configured logging like this: settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'simple': { 'format':'%(asctime)s - %(name)s - %(levelname)s - %(message)s' }, }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'simple' } }, 'loggers': { 'app1': { 'handlers': ['console'], 'level': 'DEBUG', }, 'sqlalchemy.engine': { 'handlers': ['console'], 'level': 'INFO', }, } In views.py sqlogger=logging.getLogger("sqlalchemy.engine") logs are getting printed like this: 2021-02-23 16:32:35,741 - sqlalchemy.engine.base.Engine - INFO - SELECT `info`.`name` AS `info_name`, `info`.`open from `info` I want to input the logged in user variable which i store it in session request.session["username"]="Designer" so that the logs are getting printed like this with the logged in user: 2021-02-23 16:32:35,741 - sqlalchemy.engine.base.Engine - Designer- INFO - SELECT `info`.`name` AS `info_name`, `info`.`open from `info` Sqlalchemy automatically emits log statements, so I am not sure , how to pass this customization of user to the sqlalchemy engine. Can anyone please help? Thanks -
Django migrate won't run new migration when migration exists
I'm working on adding a foreign relation into an existing model. I created the foreign model with no issues and implemented the foreign key into my existing model. I ran makemigrations which created the migration file. However, when I run migrate, the migration is not applied and I receive the message that there were no new migrations to apply - even though there is one. I'm not too sure what else to try at this point. I've removed my newly created migration and tried rerunning makemigrations before migrating, but this has not helped at all. I double-checked to ensure that the migration file has all the correct information and is based of the directly previous migration. I've also made sure that I am in the correct spot in the project directory with my virtual environment running and docker running. I additionally tried specifying the migration file and the app it is in when running migrate, but this did not work either. I'm brand new to docker and so I'm not sure if this is what is causing the issue. I looked at this stackoverflow post which I thought might help but after looking at it, I don't really know if … -
Accessing APi'S on a different computer in react native on the same network
I have a django rest framework running on a different computer than the computer running my react native app. Both computers are running Kali Linux. I want my react native to access the endpoint's on the other computer. I have tried setting up my endpoint using both local and external IP address but it is not workingconst BASE_URL="http://MY_IP/api / const BASE_URL="https://MY_IP/api". Any help will be appreciated -
Unsure of approach for Django custom user groups and permissions
I am creating my first Django (ver 3.1) website which is simply a blog with a home page and store page. I want to create custom user groups that define specific roles (with unique permissions) for my blog. These groups are: Reader - anonymous viewers and new accounts; has read permission for all content only Author - login required; has read and create permissions; edit and delete permissions for own content only Moderator - login required; has all CRUD permissions for all content Admin - login required, has all permissions (superuser) All new users by default are in the Reader group. Author would either be assigned manually or eventually by an online form application to determine eligibility. Moderator and Admin would of course be manually assigned. I am approaching this with possible future development, such as allowing user groups to be easily extended to other website pages. For example, a 5% discount for Author users applied to all store items, etc. Which approach to creating user groups would be best for my situation? I have seen it done within the Django Admin Panel and by creating custom User Models via extending the AbstractBaseUser and UserBaseManager classes. -
Django: linking from one API view to another API view
I am currently trying to develop a plugin for the Netbox software. For this I am trying to add an additional API endpoint. Since the total amount of data is very large, I want to split up the endpoints a bit. My current state is something like this: "results": [ {"cg": clusterGroup1: {cluster1, devices: [{},{},{},] vms: [{},{},{},] },{cluster2, devices: [{},{},{},] vms: [{},{},{},] } }, {"cg": clusterGroup2: {cluster1, devices: [{},{},{},] vms: [{},{},{},] } ] Sorry for the not totaly correct JSON but I just wanted to show the Structure of the JSON. One respons containse around 40 cluster groups and each of them containes multiple clusters with devices and virtual machines. Because of the amount of data, one API call takes roughly a minute. Now I would like to split the cluster groups for enhanced performance. To do this I would put all cluster groups into one list but without the additonal data of clusters, devices and virtual machines. This List shut containe a Link to the detailed view of a cluster group. The link in the following JSON shut refer to the view seen in the first JSON data but just for one specific cluster group rather then all. "results":[{ … -
OrderAddView is missing a QuerySet. Python Django
Why such a mistake? OrderAddView is missing a QuerySet. Define OrderAddView.model, OrderAddView.queryset, or override OrderAddView.get_queryset(). urls from django.urls import path from .views import * urlpatterns = [ path('add/<str:tag>', OrderAddView.as_view(), name='order_add'), ] view class OrderAddView(CreateView): from_class = FastOrdersForm template_name = 'orders/order_add.html' def get_context_data(self, *, object_list=None, **kwargs): context = super().get_context_data(**kwargs) context['tag'] = self.kwargs['tag'] print('tag ', context['tag']) return context form class FastOrdersForm(forms.ModelForm): class Meta: model = Orders fields = ['device', 'serial', 'comment', 'status'] widgets = { 'device': forms.TextInput(attrs={'class': 'form-control'}), 'serial': forms.TextInput(attrs={'class': 'form-control'}), 'comment': forms.Textarea(attrs={'class': 'form-control', 'rows': 5}), } -
While deploying my python2.7 code to production my pip==8.1.1 version gets changed to the latest version automatically to pip==20.0.3
While deploying my python2.7 code to production my pip==8.1.1 version gets changed to the latest version automatically to pip==20.0.3 can anyone help me on this? -
Django DRF Token authentication over https/ssl
I'm trying to implement Djangos' rest framework token authentication working over https. It works great over http but I can't get it working over https. On http I login, get my token and I can use that token for authentication with valid response. over https I can login, get back token successfully, However when I try to use that token for authenticate api requests over https, I get 401 unauthorized status code and response is "detail": "Authentication credentials were not provided." I followed this tutorial for http https://www.pythondecoders.com/2021/01/token-authentication-in-drf-django-rest.html#comment-form and http works fine. I have been trying to look for answers but didn't see anything anywhere. Is there any extra settings changes I need to make to make it work? -
Create a foreign key for a django model with specialized accessors
I'd like workers to be able to supervise other workers. A worker does not need a supervisor. They cannot supervise themself. (I don't care about loops) I'm not sure about the most django standard way to go about this. I can create a custom setter function, but I notice that the model still has supervisor and supervisor_id, which can be written to directly, circumventing the requirements I have in place. Here's what I have, but it's telling me "AttributeError: 'ForeignKey' object has no attribute 'setter'" class Worker(models.Model): supervisor = models.ForeignKey(Worker, blank=True, null=True, on_delete=models.CASCADE) @supervisor.setter def assign_supervisor(self, s_id): if s_id == self.id: raise Error("can't supervise yourself!") self.supervisor_id = s_id self.save() -
What would make django remove a trailing slash?
I need to make sure all of my urls are ending with a slash. Most off them are adding the slash to the end of a request, but I have a few that are removing the slash if I explicitly add it to the url. For example: http://127.0.0.1/about/testing/ will redirect to http://127.0.0.1/about/testing I am using 'django.middleware.common.CommonMiddleware' and APPEND_SLASH=True in my base.py, there are no overrides in my other settings.py. In urls.py the regex that catches this request is urlpatterns += [url(r'^.+/', nav_views.default), ], if I comment this line I will get a 404, but the trailing slash still gets removed. I know there is something that is missing, what possible way could the slash be getting removed? -
issue when running django site on IIS server
I am new to django. I am facing an unusual error. When I am running my site on localhost it is running smoothly. but when I run the same site via IIS server I am sometimes getting "Query doesn't exist issue". It is same query when I run on localhost it always give a correct result but when run via IIS (1 out of 5 times) it give "query doesn't exist issue". I have used try and except for the "query doesn't exist issue ". but can someone tell me why I am getting this issue. what should I add to the site. I am not sure of what code to present. so please let me know and I will share the code. Also I am using django modelforms to save the data. Thanks in advance. -
Partial Updating MongoDB Document - Mongoengine
I want to update part of my mongodb document in Django using Mongoengine rest framework. But the documentation is sadly really bad when it comes to updating a dict in a list of dicts. Both options are yet not working. Sample MongoDB document { delivery: "One", sequences: [ { "_id": "503505f14548f73d20ae067a", "name": "Sequence_1", "name_short_form": "IGI", "sequence_number": "050", "descriptions": "Description_1", "active": true }, { "_id": "191526f14548f73d20ae067a", "name": "Sequence_2", "name_short_form": "IGP", "sequence_number": "060", "descriptions": "Description_2", "active": true } ] } Update MongoDB Document in Django sequence_id = "191526f14548f73d20ae067a" # Fields I want to update (only replace given fields) new_sequence_data = { "name": "Sequence_2", "name_short_form": "PGP", "sequence_number": "070", "descriptions": "Description_2_Updated", "active": true } # Mongoengine set sequence data (option 1) document.update(set__sequences={{"_id": sequence_id}, new_sequence_data }) # Mongoengine set sequence data raw (option 2) document.update(__raw__=({"sequences.id": shot_id}, {"$set": { new_sequence_data }) # Save full document document.save() return Response(status=status.HTTP_200_OK) -
when an order is placed the quantity of products should be decremet
I am working on ecommerce site. Where I want when order is placed , The product quantity should be decrement by 1. I guess thee change should be done in orders models.py. But what should be the change I do not know here is my product models.py file: class Product(models.Model): title = models.CharField(max_length=110) slug = models.SlugField(blank=True, unique=True) status = models.CharField(choices=CATEGORY_CHOICES, max_length=10) price = models.DecimalField(decimal_places=2, max_digits=6) quantity=models.IntegerField(default=1) discount_price=models.FloatField(blank=True, null=True) size = models.CharField(choices=SIZE_CHOICES, max_length=20) color = models.CharField(max_length=20, blank=True, null=True) image = models.ImageField(upload_to=upload_image_path) description = RichTextField(max_length=1000) featured = models.BooleanField(default=False) author = models.ForeignKey(User, on_delete=models.CASCADE) time_stamp = models.DateTimeField(auto_now_add=True) my orders models.py is : class OrderManager(models.Manager): def new_or_get(self , billing_profile , cart_obj): created = False qs = self.get_queryset().filter(billing_profile=billing_profile, cart=cart_obj, active=True,) if qs.count() == 1: obj = qs.first() else: obj = self.model.objects.create(billing_profile=billing_profile, cart=cart_obj) created = True return obj , created class Order(models.Model): billing_profile = models.ForeignKey(BillingProfile, null=True , blank=True , on_delete=models.CASCADE) order_id = models.CharField(max_length=120 , blank=True) shipping_address = models.ForeignKey(Address, related_name="shipping_address" ,null=True , blank=True , on_delete=models.CASCADE) billing_aaddress = models.ForeignKey(Address, related_name="billing_address" ,null=True , blank=True , on_delete=models.CASCADE) cart = models.ForeignKey(Cart, on_delete=models.CASCADE) status = models.CharField(max_length=120 , default='created', choices=ORDER_STATUS_CHOICES) shipping_total = models.DecimalField(default=5.99, max_digits=100 , decimal_places=2) total = models.DecimalField(default=0.00, max_digits=100 , decimal_places=2) active = models.BooleanField(default=True) def __str__(self): return self.order_id objects = OrderManager() def update_total(self): …