Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-simple-history populate history when existing history present
After setting up history for a model using django-simple-history, I wanted to run populate_history to populate the history table based on the existing contents of the table. However, other users have already made a number of changes, causing the history table to be partially populated. Running populate_history --auto simply results in message Existing history found, skipping model. I wish to retain the existing history, but populate history for all records not currently stored in the history. Is there a way to do this? -
Why is my test failing on swapping to self.live_server_url() in Django?
so I'm doing a django calendar project with some TDD and running into an odd issue. I made a functional test using selenium that walks through logging in, adding an event to a calender and logging out. I had the test passing mostly but noticed I was adding items to my own database and figured I should use the LiveServerTestCase to avoid this. So I had the test inherit that and replaced self.browser.get('http://localhost:8000') with self.browser.get(self.live_server_url). The problem is that now the functional test fails part way through. This is the error that comes up: selenium.common.exceptions.ElementNotInteractableException: Message: Element <input id="id_title" class="event_name" name="title" type="text"> is not reachable by keyboard. This is happening because when a button is clicked, the JavaScript function I wrote doesn't change the form from style="visibility: hidden;" to style="visibility: visible;" I've confirmed in git the only line I'm changing is swapping from self.browser.get('http://localhost:8000') to self.browser.get(self.live_server_url). Why would swapping to the live server url cause this issue? Are there other ways I can delete objects after running the test? Any help is appreciated. -
when i submit email form it send back my own email Django python
class ProjectListAndFormView(SuccessMessageMixin, ListView, FormView): model = Project # data from database template_name = 'mainpage/main.html' context_object_name = 'list_projects' # name of the var in html template queryset = Project.objects.all().order_by("-pub_date")# list of all projects object_list = None form_class = ContactForm success_url = '/' # After submiting the form keep staying on the same url success_message = 'Your Form has been successfully submitted!' def form_valid(self, form): # This method is called when valid form data has been POSTed. cd = form.cleaned_data con = get_connection('django.core.mail.backends.console.EmailBackend') send_mail( cd['name'], cd['message'], cd.get('email', 'noreply@example.com'), ['22agrandon@gmail.com'], fail_silently=False ) return super(ProjectListAndFormView, self).form_valid(form) views.py im having trouble with a form page on my website. Whenever i enter a random email on the email form part on the website it sends a succesful mail but from my own emayil even if i put a random email. How do i fix this so when someone enters their email, it sucesfully sends me an email from their email? -
adding a url in django-template
i tried to add a url in django template which is supposedly to log out a user <div><a href="{% url 'accounts.views.user_logout' %}">logout</a></div> but it threw a NoReverseMatch the template: <header class="grid-header header"> <div class='logo-text'>Nitro fleet</div> <div class="profile-detail"> {% if user.is_authenticated %} <img class="profile-img" src="{{user.picture.url}}" /> <div> <div>{{user.username}}</div> <div><a href="{% url 'accounts.views.user_logout' %}">logout</a></div> </div> {%endif%} </div> </header> the url of the app (accounts) that has the logout view: from django.urls import path from . import views appname = 'accounts' urlpatterns = [ path('register', views.register_view , name='user_register'), path('login', views.user_login , name='user_login'), path('logout', views.user_logout , name='user_logout'), ] the view function: def user_logout(request): logout(request) return HttpResponseRedirect(request.path_info) the complete error log: NoReverseMatch at /maintenance/ Reverse for 'accounts.views.user_logout' not found. 'accounts.views.user_logout' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/maintenance/ Django Version: 3.2.9 Exception Type: NoReverseMatch Exception Value: Reverse for 'accounts.views.user_logout' not found. 'accounts.views.user_logout' is not a valid view function or pattern name. Exception Location: C:\Users\PC\AppData\Local\Programs\Python\Python310\lib\site-packages\django\urls\resolvers.py, line 694, in _reverse_with_prefix Python Executable: C:\Users\PC\AppData\Local\Programs\Python\Python310\python.exe Python Version: 3.10.0 Python Path: ['C:\\Users\\PC\\Desktop\\nitrofleet', 'C:\\Users\\PC\\AppData\\Local\\Programs\\Python\\Python310\\python310.zip', 'C:\\Users\\PC\\AppData\\Local\\Programs\\Python\\Python310\\DLLs', 'C:\\Users\\PC\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\Users\\PC\\AppData\\Local\\Programs\\Python\\Python310', 'C:\\Users\\PC\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages'] Server time: Mon, 31 Jan 2022 20:43:51 +0000 -
How do I run my DJANGORESTFRAMEWORK APP with SSL (https) on Hostinger VPS
(Front end - VUE) Installed SSL on the site via certbot, HTTPS website cannot send a request to http, therefore it makes https, and the DJANGORESTFRAMEWORK server works on http ( python3 manage.py runserver 0.0.0.0:668 ) certbot apparently does not allow making a certain port under SSL , How do I handle it? Please help me all day I’ve been sitting with this, I saw a decision to create a subdomain, but how can I put SSL there if apache wont be working becouse DRF will be (they conflict), and I can’t get to https DRF even after disabling apache and running DRF on 80 port HELP PLEASE! (UBUNTU 20) problem -
How to delete a form with django formset?
Is there a way to remove a form that dynamically appears in a formset from django and javascript? I tried it but when I click it returns me to the index and if I check my previous formset (which are on the same page) I get an error I've already done tests, I've reviewed the documentation and it's not a problem with my JS but with django. In this tutorial I found that it can be done, however I don't understand -
Django STMP with IONOS
Having an adress mail managed by IONOS, I'm struggling to set it up with Django to be able to send mails automatically. Here's my error: TimeoutError: [Errno 110] Connection timed out I personnalized the SMTP in my settings: DEFAULT_FROM_EMAIL="mymail" EMAIL_HOST = 'smtp.ionos.fr' EMAIL_HOST_USER = 'myusername' EMAIL_HOST_PASSWORD = 'mymdp' EMAIL_PORT = 25 EMAIL_USE_SSL = True and here's how I send mails: from django.core.mail import send_mail def send_forgotten_password_mail(self, request, pk=None): send_mail( 'Subject here', 'Here is the message.', None, ['tosend'], fail_silently=False, ) I'm not that used to send mails through SMTP with Django, so I might miss something. Thank you for your help. -
Save user who submitted form(django)
So I'm creating a reporting app for my organization I want to be able to save the user that submits the report. Problem is if I use the models.ForeignKey(User,on_delete=models.PROTECT) method on my model I get a drop down for all the users which is not what I want. models.py class Report(models.Model): id = models.UUIDField(primary_key=True,default=uuid.uuid1,editable=False) department = models.ForeignKey(Company,null=True,on_delete=models.SET_NULL) user= models.ForeignKey(User,on_delete=models.PROTECT) submission_date= models.DateField(auto_now=True) #invisible to user submission_time = models.TimeField(auto_now=True) #invisible to ,user date = models.DateField(default=now,blank=False) time = models.TimeField(default=now,blank=False,help_text="hh:mm:ss") location = PlainLocationField() building = models.ForeignKey(bld,null=True,on_delete=models.SET_NULL) size = models.PositiveIntegerField() notes = models.TextField(blank=True) def __str__(self): return f'{self.date} {self.time} ({self.company}) form.py from django.forms import ModelForm, fields from django.shortcuts import redirect from django.urls.conf import include from .models import Report from django import forms from location_field.forms.plain import PlainLocationField class ReportForm(forms.ModelForm): class Meta: model = Report fields = '__all__' location = PlainLocationField() def redirect(): return redirect("Report") views.py from django.forms import fields from django.forms.forms import Form from django.http import request from django.http.request import HttpRequest, validate_host from django.http.response import HttpResponse, HttpResponseRedirect from django.shortcuts import render,redirect from django.urls.base import reverse from django.views.generic.base import TemplateView from django.contrib.auth import authenticate, login from django.contrib.auth.mixins import LoginRequiredMixin # Create your views here. from .forms import ReportForm from .models import Report from django.views.generic.edit import CreateView, UpdateView, DeleteView … -
Validate CSV file while reading by headers python
I would like to validate CSV file with headers: name, last_name The idea is, if in uploaded csv file in the first line are name and last_name then continue, if not - raise an error. def write(): header = ['name', 'last_name'] buffer = io.StringIO() writer = csv.writer(buffer) writer.writerow(header) # after writing data from table def create(self, request, *args, **kwargs): serializer = CsvSerializer(data=request.data) if not serializer.is_valid(): return Response(serializer.errors, status=status.HTTP_422_UNPROCESSABLE_ENTITY) try: csv_file = serializer.validated_data['file'] file = csv_file.read().decode('utf-8') except: raise ValidationError('File cannot be parsed', code='parsing_issue') csv_fields = ['name', 'last_name'] csv_reader = csv.DictReader(io.StringIO(file), fieldnames=csv_fields) next(csv_reader) # skip headers from csv for processing the file -
Running SQL query in Django
We have four tables Including Category, Seller, Product, Product_Seller. Each product has one category. each seller can sell a product. Suppose you do not sell the same product multiple times and each seller sells each product at most once. We want to find products that have more than 5 sellers. and we want to find the second category that has the largest number of products. I want to run the SQL code in Django. But it has multiple errors. Please let me know how can I fix it. Thank you for your time and consideration. from django.db import models from django.db import connection class Category(models.Model): title = models.CharField(max_length=128) class Seller(models.Model): name = models.CharField(max_length=128) class Product(models.Model): category_id = models.ForeignKey(category), rate = models.IntegerField(blank=True, null=True) class Product_Seller(models.Model): product_id = models.ForeignKey(product), seller_id = models.ForeignKey(seller), price = models.IntegerField(blank=True, null=True) cursor = connection.cursor() cursor.execute( SELECT product_id FROM Product_Seller groupby product_id having Count(product_id) >5;) cursor.execute( SELECT category_id FROM Product groupby category_id having max(Count(category_id)) and NOT IN(SELECT category_id FROM Product groupby category_id having max(Count(category_id)));) -
django-filter checkbox ajax
I am trying to implement django-filters + ajax(jquery) after sending the request, the selected checkboxes "disappear" I have little experience yet, tell me how to fix it? I need to connect django-filter + ajax(jquery) ```filters.py class ItemFilter(django_filters.FilterSet): category__name = django_filters.ModelMultipleChoiceFilter(field_name='name', widget=forms.CheckboxSelectMultiple,queryset=Category.objects.all()) class Meta: model = Item fields = ['category__name'] views.py class CategoryList(View): template_name = 'category/store.html' def post(self, request): select_check = self.request.POST.getlist('checkBOX[]') categories = Category.objects.all().filter(id__in=select_check) filter_test = ItemFilter(self.request.POST, queryset=categories) ..... return render(request,template_name=self.template_name, context=context) store.html {% for c in filter_test.form %} <form method="post" id="filter-checkbox" class="myform"> {% csrf_token %} <div class="form-checkbox"> <p id="check_box_id" type="checkbox" name='check_box' >{{ c }}</p> </div> {% endfor %} <button type="submit" class="myform-submit">Submit</button> </form> </div>``` -
How to list separated result in Django Rest Framework
Currently I have four endpoints: /boards /boards/public_to_company /boards/my_collections /boards/shared_with_me the first endpoint retrieve all boards, and the next 3 are custom actions that aplly some filters. But I would like /boards returns what the three boards returns, but separated, something like this: { public_to_company_boards: Object { count: 8, boards: […] } shared_w_boards Object: { count: 1, boards: […] } user_boards Object:{ count: 2, boards: […] } } I'm not sure if I need to use anotate or something like that. my current model: class Board(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=200, blank=False, null=False) description = models.TextField(max_length=1000, blank=True, null=True) public_to_company = models.BooleanField(default=False) share_list = ArrayField(models.CharField(max_length=15), null=True, blank=True, default=list) last_update = models.DateTimeField(auto_now=True) owner = models.CharField(max_length=200, blank=False, null=False) deleted = models.BooleanField(default=False) history = HistoricalRecords() serializer: class BoardSerializerList(serializers.ModelSerializer): qtd_cards = serializers.SerializerMethodField() @staticmethod def get_qtd_cards(instance): return instance.cards.count() class Meta: model = Board fields = '__all__' read_only_fields = ['owner'] view: class BoardViewSet(ModelViewSet): queryset = Board.objects.exclude(deleted=True) serializer_class = BoardSerializerList permission_classes = [BoardPermission] authentication_classes = [TuriviusAuthentication] def destroy(self, request: Request, *args, **kwargs) -> Response: board = self.get_object() if not board.deleted: board.deleted = True board.save() return Response(status=status.HTTP_204_NO_CONTENT) return Response(status=status.HTTP_400_BAD_REQUEST) def get_serializer_class(self): if self.action == 'retrieve': return BoardSerializerRetrieve return super().get_serializer_class() @action(detail=True, methods=['get', 'post', 'delete'], serializer_class=CommentSerializer) def comments(self, request): … -
Number of format specifications in 'msgid' and 'msgstr' does not match msgfmt: found 1 fatal error
Django-Admin generates the following error: Execution of msgfmt failed: /home/djuka/project_app/locale/eng/LC_MESSAGES/django.po:49: number of format specifications in 'msgid' and 'msgstr' does not match msgfmt: found 1 fatal error CommandError: compilemessages generated one or more errors. I have the same number of strings in msgid and msgstr and i still get an error. Here is the code. #: reBankMini/templates/reBankMiniApp/index.html:135 #, python-format msgid "" "Leta 2020 je po svetu nastalo rekordnih 54 milijonov ton elektronskih " "odpadkov, kar je 21 odstotkov več kot v zadnjih petih letih. E-odpadki so " "najhitreje rastoči gospodinjski odpadki na svetu, ki jih povzročajo predvsem " "višje stopnje porabe električne in elektronske opreme, kratki življenjski " "cikli in malo možnosti za popravila. Le 17,4%% zavrženih e-odpadkov leta " "2020 je bilo recikliranih. Pri procesu recikliranju pride do številnih " "okolju nevarnih reakcij. Mi recikliramo drugače. Prizadevamo si za varne, " "trajnostne in popravljive izdelke, s katerimi bo vsak uporabnik aktivno " "vključen v reševanje okoljskih problemov." msgstr "" "In 2020, a record 54 million tons of electronic " "waste was generated worldwide, which is 21 percent more than in the last five years. E-waste is " "the fastest growing household waste in the world, caused mainly by " "higher … -
How to automatically update field in Django Admin (back end)
Imagine, that I have a model Ticket: class Ticket(models.Model): name= models.CharField(max_length=30, verbose_name='name') ticket_status = models.BooleanField(default=False, verbose_name='Is Active?') ticket_end = models.DateField(blank=True, verbose_name='Closing Date', null=True) class TicketAdmin(admin.ModelAdmin): list_display= ('name','ticket_status','ticket_end ') I can override save method: def save(self, *args, **kwargs): if self.dep_end > ## Expiration date here ##: self.dep_status = False super(Ticket, self).save(*args, **kwargs) And it's work in case when I am manually update object. But how realize automatically update in back end (in Django admin). Something like this: ticket_end = 1.02.2022, when the current date = 2.02.2022: update ticket_status = False. -
Django: App not compatible with buildpack
I am trying to deploy my Django app on Heroku and I am getting this error - error Based on the answers to this question, here is what I have tried so far - Adding the 'requirements.txt' file in the root directory of the project. Adding 'Procfile' in the root directory of my project. Made sure git is initialized in the root directory of my project. This is what my project structure looks like - Project Structure This is what my 'Procfile' looks like - web: gunicorn GameStudio.wsgi --log-file - Any suggestions/pointers will be highly appreciated. Thank you for your time! -
Django authentication jwt authentication
Can I use JWT(Json web token) in Django project which is not API? Or JWT is only used for API projects? If yes please recommend other alternatives -
Django Drf view AttributeError
I'm trying to get data that is related to the request.user but i'm doing something wrong. serializers.py class SchoolSerializerList(serializers.ModelSerializer): class Meta: model = School fields = ('name', 'zone', 'city', 'subCity', 'abbr', 'woreda', 'Schooltype', 'schoolemail', 'schoolphone', 'created_date') views.py class MySchoolsView(generics.ListAPIView): permission_classes = [IsSchoolOwner, ] serializer_class = SchoolSerializerList def get_queryset(request): try: queryset = School.objects.filter(owner=request.user) except ObjectDoesNotExist: return Response({"error": "Nothing found."}) return queryset the owner field in the school model is a foreignkey to the user i wanted to check if the current user has any schools by trying to match request.user with School.owner but this returns an attribute error saying 'MySchoolsView' object has no attribute 'user' -
How to use limit and order_by together in Django rest-framework?
I want to use limit on following as [1:10] data = GroupPostsModel.objects.filter( group_id=group_id) & GroupPostsModel.objects.filter(post_type=post_type).order_by('-time_stamp') I try this data = GroupPostsModel.objects.filter( group_id=group_id & GroupPostsModel.objects.filter(post_type=post_type)[1:10].order_by('-time_stamp') But did not work..! -
Django Admin Login 'CSRF cookie not set' when deployed, but works on localhost
I added several variations of the domain to CORS_ALLOWED_ORIGINS and CSRF_TRUSTED_ORIGINS, and ALLOWED_HOSTS. I added django.template.context_processors.csrf to context_processors. I had neither CSRF_COOKIE_SECURE nor SESSION_COOKIE_SECURE set to true (which I'm hoping I can change). I can't think of anything else I could do to get it to work on Django admin, and it only stopped working after I set up session authentication, (which included configuring csrf and session cookies). When I didn't have any authentication for the frontend, Django login worked fine, and even after, like I said, it was working fine on localhost. I would really appreciate any suggestions on something else I could try to fix this issue. -
Testing POST request throwing a KeyError in Postman
I am currently testing my POST request for the Tagging model. For this, I have tried to override the create() method. I am not so sure I have done this correctly but I tried everything I could think of. I even removed it and tried testing the POST request without overriding it. I keep getting this error while testing with Postman: KeyError at /api/tagging 'user' How can I get rid of this error? What is my create() method missing? serializers.py class TaggingSerializer(serializers.ModelSerializer): tag = StringRelatedField() resource = serializers.PrimaryKeyRelatedField(read_only=True) gameround = serializers.PrimaryKeyRelatedField(read_only=True) user = CustomUserSerializer(required=False, read_only=True) class Meta: model = Tagging fields = ('id', 'user', 'gameround', 'resource', 'tag', 'created', 'score', 'origin') def create(self, validated_data): """Create and return a new tagging""" tagging = Tagging( user=validated_data["user"], gameround=validated_data["gameround"], resource=validated_data["resource"], tag=validated_data["tag"], created=validated_data["created"], score=validated_data["score"], origin=validated_data["origin"] ) tagging.save() return tagging def to_representation(self, data): data = super().to_representation(data) return data This is my post request: def post(self, request, *args, **kwargs): tagging_serializer = TaggingSerializer(data=request.data) if tagging_serializer.is_valid(raise_exception=True): tagging_serializer.save(tagging=request.data) return Response({"status": "success", "data": tagging_serializer.data}, status=status.HTTP_200_OK) else: return Response({"status": "error", "data": tagging_serializer.errors}, status=status.HTTP_400_BAD_REQUEST) -
Django - vote system
I'm stuck with a simple problem. I want to create a voting system. I have a simple code that doesn't work properly. When I click UP it adds +1, when I click UP again, it removes -1. Same with the DOWN button. The problem is that when I click between the UP and DOWN buttons. The value increases or decreases (indefinitely) - it depends with the click of the button first. def vote_comment(request): comment = get_object_or_404(CommentsCode, id=request.POST.get('id')) is_voted = comment.is_voted.filter(id=request.user.id).exists() up = request.POST['name'] == "UP" down = request.POST['name'] == "DOWN" if up: if is_voted: comment.is_voted.remove(request.user) comment.vote -= 1 comment.save() else: comment.is_voted.add(request.user) comment.vote += 1 comment.save() elif down: if is_voted: comment.is_voted.remove(request.user) comment.vote += 1 comment.save() else: comment.is_voted.add(request.user) comment.vote -= 1 comment.save() -
How to validate that each wagtail page will have a unique slug?
I have several models that inherit from Page and I'd like to check that each page that is being added/edited has a unique slug. Also I'd like to avoid overriding the save method and do the validation there for each page. Is there another way to validate the slug uniqueness when creating/editing pages? -
formset not uploading pictures to the backend when user creates a new course?
When creating a new course all data in the formset get posted to the backend except the course cover image why is my formset not uploading the cover for a course, mean while i have added the field to OwnerCourseMixin and OwnerCourseEditMixin i see the cover field in my create formset, but it won't just save the cover image in my database. models.py class Course(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL,\ related_name='courses_created', on_delete=models.CASCADE) subject = models.ForeignKey(Subject,related_name='courses', on_delete=models.CASCADE) title = models.CharField(max_length=200) cover = models.ImageField(upload_to="course_pictures", blank=True,null=True) my view.py class OwnerMixin(object): def get_queryset(self): qs = super(OwnerMixin, self).get_queryset() return qs.filter(owner=self.request.user) class OwnerEditMixin(object): def form_valid(self, form): form.instance.owner = self.request.user return super(OwnerEditMixin, self).form_valid(form) class OwnerCourseMixin(OwnerMixin, LoginRequiredMixin): model = Course fields = ['subject', 'title', 'slug','overview','cover'] success_url = reverse_lazy('courses:manage_course_list') class OwnerCourseEditMixin(OwnerCourseMixin): fields = ['subject', 'title','slug', 'overview','cover'] success_url = reverse_lazy('courses:manage_course_list') template_name = 'manage/module/formset.html' class CourseCreateView(OwnerCourseEditMixin, OwnerEditMixin, CreateView, PermissionRequiredMixin): pass class CourseModuleUpdateView(TemplateResponseMixin, View): template_name = 'manage/module/formset.html' course = None def get_formset(self, data=None,): return ModuleFormSet(instance=self.course,data=data) def dispatch(self, request, pk): self.course = get_object_or_404(Course,id=pk,owner=request.user) return super(CourseModuleUpdateView, self).dispatch(request, pk) def get(self, request, *args, **kwargs): formset = self.get_formset() return self.render_to_response({'course':self.course, 'formset':formset,}) def post(self, request, *args, **kwargs): formset = self.get_formset(data=request.POST,) if formset.is_valid(): formset.save() return redirect('courses:manage_course_list') return self.render_to_response({'course': self.course, 'formset':formset}) -
How to use both Count() and Min/Max in sql
I have the following table: MyTable name | price |-------------------| | a | 10 | |-------------------| | b | 5 | |-------------------| | a | 7 | |-------------------| | a | 3 | |-------------------| | a | 12 | |-------------------| | b | 6 | |-------------------| | c | 2 | |-------------------| | c | 5 | |-------------------| I want to count the frequency of the name and need to get the max_price and min_price for each name. The expected output is: name | count | min_price | max_price |-------------------|----------------------| | a | 4 | 3 | 12 | |-------------------|----------------------| | b | 2 | 5 | 6 | |-------------------|----------------------| | c | 2 | 2 | 5 | |-------------------|----------------------| I would like to write Django ORM query. Please help me to achieve it. -
How to cast DurationField to second iin Django query
I have a model with a field defined like this: mask_label_ts = models.DurationField( default=timedelta ) In one of my query I'd like to multiply it by an integer, I aim at creating bill so I want to multiply the rate by hour by the nb of seconds. How can I cast my duration field into seconds ? I tried this: test=ExpressionWrapper(F('mask_label_ts') * F('mask__labeller__hour_rate'), output_field=FloatField()) But this is not working. Any ideas ? thanks