Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Save() method thread safe or not in django
Is django's save method thread safe or not. Meaning that if i have multiple threads then will the save() method interfere with the data sent to each of the save() method ? Have faced this problem while running the save() method on multiple threads. I noticed that some of the fields values are interchanged meaning that the field value of one thread's save method has gone to the field value of the other thread. Is there a way to tackle with this situation? -
import data django-import-export does not create objects in celery task
I've created celery task in project for asinc create objects in my model using django-import-export. Task run and everything okey on local machine, but on server objects doesn't create. There is my code: signals.py: @receiver(post_save, sender=BuildingProductUploadFile) def building_product_upload_file(instance, sender, **kwargs): if kwargs.get('created'): if instance.status == BuildingProductUploadFile.NEED_PROCESSING: transaction.on_commit(import_building_product.s(instance.pk).delay) signal.py: @celery.task(bind=True) def import_data(self, dataset, building, resource): logger.info(f'start import') return resource.import_data( dataset, building=building, use_transactions=True, ) @celery.task(bind=True) def import_building_product(self, upload_id): logger.info(f'start task: {self.name}') dataset = Dataset() product_resource = ImportProductBuildingResource() upload_file = BuildingProductUploadFile.objects.get(id=upload_id) logger.info(f'get file id: {upload_file.id}') try: with open(upload_file.file.path, 'rb') as file: dataset.xls = file.read() result = import_data( dataset, building=upload_file.building, resource=product_resource ).delay() logger.info(f'result: {result.rows}') upload_file.log_journal['info']['totally_rows'] = result.total_rows # upload_file.log_journal['total'] = result.total upload_file.status = BuildingProductUploadFile.COMPLETE error_list = [] for num_row, row in enumerate(result.rows): if row.import_type == row.IMPORT_TYPE_ERROR: upload_file.status = BuildingProductUploadFile.COMPLETE_WITH_ERRORS logger.info(f'error in row task: {num_row}') # errors = [element.error for element in row.errors] # error_list.append(formatting( # num=num_row, # row=row.errors[0].row, # errors=errors, # debug_mode=settings.DEBUG_UPLOAD_GEAR # )) upload_file.log_journal['error_log'] = error_list logger.info(f'error list task: {error_list}') except XLRDError: upload_file.log_journal['error_log'].append("Для загрузки требуется файл формата xlsx или xls.") except Exception as err: upload_file.log_journal['error_log'].append(err.__repr__()) finally: self.update_state( state="COMPLETED" ) logger.info(f'file status: {upload_file.status}') if upload_file.status == BuildingProductUploadFile.NEED_PROCESSING: upload_file.status = BuildingProductUploadFile.COMPLETE upload_file.save() logger.info(f'file status after save: {upload_file.status}') logger.info(f'end task: {self.name}') import_utils.py: from decimal import InvalidOperation … -
How to put two decimals in cell with type of percent in .xls format
Recently I spent some time solving this issue. If you face same problem this might be helpful and you will get a clue how to solve the problem. I have openpyxl version 2.2.2 I need to write percent value with 2 digits after dot into a cell. Value should be seen in Excel as '3.14%' - type of percentage, two decimals digits after dot Here is my first attempt: from messytables import XLSTableSet table_set = XLSTableSet(request.FILES['file'], **kwargs) row_set = table_set.tables[0] for row in row_set: row_data = [] is_row_null = True for cell in row: value = cell.value print valueenter image description here -
How to get a request user query without hitting DB each time in django?
I built some Blog API but I've got an issue. In the serializer, there is a method field that returns request user has liked the post or not. The problem is this field hits the user DB every single time. How can I avoid this? this is serializer class DashboardSerializer(serializers.ModelSerializer): image = serializers.ImageField(allow_null=True, use_url=True) likes_count = serializers.SerializerMethodField(read_only=True) tags = TagSerializer(many=True, read_only=True) user_has_liked = serializers.SerializerMethodField(read_only=True) owner = UserField(read_only=True) comments = CommentsField(read_only=True, many=True, source='two_latest_comments') comments_count = serializers.SerializerMethodField() class Meta: model = Blog fields = ['id', 'title', 'owner', 'likes_count', 'user_has_liked', 'image', 'video', 'tags', 'get_elapsed_time_after_created', 'comments', 'comments_count'] ordering = ['created_at'] def get_likes_count(self, instance): return instance.likes.count() def get_user_has_liked(self, instance): request = self.context.get('request') ***return instance.likes.filter(pk=request.user.pk).exists()*** *******request.user.pk hits the DB.********* def get_comments_count(self, instance): return instance.comments.count() Thank you in advance. -
How to Uninstall Django from Window10?
I command I deleted Django using "pip uninstall django". But it did not install again. The error message is: C:\Django>python -m pip install -U pip Requirement already up-to-date: pip in c:\python\lib\site-packages (19.2.3) I don't know which command to use to completely remove and reinstall. -
Django /JQuery - Disabling certain dates on JQuery Date Picker
As a part of a task, I created an "apartment listings" website. I managed to get that done, but now I need to make a "reservation system" for it. The basic idea is that a logged in user can select an apartment from the listed apartments, pick a "start_date" and an "end_date" (if the apartment already isn't booked ) and book the apartment. When the user clicks on the date input field, a jquery datepicker pops up and he can then pick the date via the calendar, same for end date. Once he goes through with the booking, I want the dates to be "disabled" in the calendar so no one else can pick them. This is the datepicker that I'm using: https://jqueryui.com/datepicker/ and the code: <script> $(function () { $("#datepicker").datepicker(); }); </script> Im a total Django / web development newbie, and need some pointers in order to start somewhere with this task, I know some JS but jquery is new to me, that's why I'd like some help. I have an Apartment model which contains all of the Apartments info that I use to print everything out with the template. I have an Reservation model which saves the start … -
Genre for models in DJango
I am creating a site with Django, and I encounter a problem with the administration site. When I create a new model, I can assign a verbose_name for the singular and plural in the meta class, but I don't find any option that allows me to assign what gender that model is, that is, whether it is feminine (female) or masculine (male). For example, I have the city model, which in Spanish would be "Ciudad" and would be feminine. Then when on the admin site I add a new record, the legend "Se añadió con éxito el ciudad" appears, when the right thing would be "Se añadió con éxito la ciudad". I know this could be a translation issue, but I suppose something should indicate to the translations that the model should put "el" or "la" as the case may be. Can anybody help me? -
Getting type-error using custom middleware in specific view
This is my middleware class HasAccessMiddleware(object): def __init__(self, get_response): print("init") self.get_response = get_response def __call__(self, request): allowed_ips = WebSettings.get_allowed_ip() ip = request.META.get('REMOTE_ADDR') # Get client IP if ip not in allowed_ips: return HttpResponse("false", status.HTTP_401_UNAUTHORIZED) print("call") return self.get_response(request) this is my setting MIDDLEWARE = ( 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'tools.middleware.HasAccessMiddleware', ) and this is my view @decorator_from_middleware(HasAccessMiddleware) def json_backup(request): pass I am getting this error TypeError: __init__() takes exactly 2 arguments (1 given) Would you help me find what is wrong? Thanks -
Django update all objects on html rows via save button
As per the below image I want to create a form where I can update the edited values. So far I can get the data from the request._post and loop thru the values and update them. Is there a better / simpler way of doing this ? ######################## MODEL ##################### class sampleModel(models.Model): primaryKey = models.CharField(max_length=100,primary_key=True) text = models.TextField(null=True,blank=True) ######################## VIEW ##################### def sampleModel_list_view(request): if request.method == 'POST': pass #DO SOMTHING objs = sampleModel.objects.all() context={'objs':objs,'title':'List of all objects'} return render(request,'sampleModel_list.html',context) ######################## HTML ##################### <form method='POST' action='.' enctype='multipart/form-data'> {% csrf_token %} {% for obj in objs %} <div class='card'> <div class='card-body'> <input type='text' name='primaryKey' placeholder='' value='{{obj.primaryKey}}' /> <input type='text' name='text' placeholder='' value='{{obj.text}}' /> </div> </div> {% endfor%} <input type='submit' class="btn btn-success" value='Save'/> -
At the time of registering a user, the username is automatically changed to a different username
I am creating two types of user using flags(is_grievant,is_department) The problem I am facing is that when I am registering a user, the username is automatically changed to a different username. What I mean to say is as you can see here, under the user model it is registered with the correct username(Asad) User Model, shown inside the Admin View but in the grievants model it is showing with the username(Raju). Raju is the username of a department model. Grievant Model, shown inside the Admin View view.py @method_decorator([login_required, grievant_required], name='dispatch') class GrievantComplaintListView(ListView): login_url = '/login/' model = Complaint context_object_name = 'complaint_list' template_name = 'grievant_complaint_list.html' def get_queryset(self): student = Grievant.objects.get(student=self.request.user) complaint_list = Complaint.objects.filter(grievant=student) return complaint_list @method_decorator([login_required, grievant_required], name='dispatch') class CreateComplaintView(CreateView): login_url = '/login/' redirect_field_name = 'complaint_detail.html' template_name = 'create_complaint.html' form_class = ComplaintForm model = Complaint def form_valid(self, form): student = Grievant.objects.get(student=self.request.user) form.instance.grievant = student return super().form_valid(form) class ComplaintDetailView(LoginRequiredMixin,DetailView): login_url = '/login/' model = Complaint template_name = 'complaint_detail.html' def grievant_register(request): registered = False if request.method == 'POST': if Grievant.objects.filter(Registeration=request.POST['Registeration']).count() >0: response = {} response['error'] = 'This Registeration Number already exists' return render(request,'student_register.html',response) user_form = SignUpForm(data=request.POST) profile_form = GrievantProfileForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save(commit=False) user.set_password(user.password) user.is_grievant = True user.save() profile = … -
WebSocket handshake: Unexpected response code
(index):12 WebSocket connection to 'ws://app.quicktreatment4u.com/ws/chat/fsdfds/' failed: Error during WebSocket handshake: Unexpected response code: 404 -
Move http to https in Django
my website have SSL certificate. But when I scan by using ScreamingFrog, inlinks exist http. So, How can I move all http to https quickly instead remove each link in my post. Thanks. -
Django: How can I have two different ModelChoiceFields return to the same Model Field?
I want the user to be able to see which categories they are a part of, which would come from the Private_Users model. I also want them to be able to see which Private_Category they have created. First issue: private_category2 only returns the object from the Private_User. I want it to return the object from the Private_Category. Second issue: I want private_category2 to be entered into the same model field as private_category if private_category was never filled out. Is there any way to get these things done without creating a new field in Private_Category? forms.py class PostForm(forms.ModelForm): ... private_category = forms.ModelChoiceField(queryset = None, widget=forms.Select( attrs={ 'style':'width:33%;' }), required=False) private_category2 = MyModelChoiceField(queryset = None, widget=forms.Select( attrs={ 'style':'width:33%;' }), required=False) def __init__(self, user, *args, **kwargs): super(PostForm, self).__init__(*args, **kwargs) self.fields['private_category'].queryset = Private_Category.objects.all().filter(owner=user) self.fields['private_category2'].queryset = Private_Users.objects.all().filter(name=user) models.py class Private_Category(models.Model): owner = models.ForeignKey(User, related_name='privateowner', on_delete=models.CASCADE, null=True) category_password = models.CharField(max_length=50) title = models.CharField(max_length=200, unique = True) description = models.CharField(max_length=500) image = ProcessedImageField(upload_to='category_photo', processors=[ResizeToFill(500, 500)], format='JPEG', options={'quality': 100}) def __str__(self): return self.title class Private_Users(models.Model): name = models.CharField(max_length=50, null=True) category = models.ForeignKey(Private_Category, null=False, on_delete=models.CASCADE, default=None) def __str__(self): return self.name -
Check if a Model is already linked to its related Model via render_change_form
I have an admin form for adding Slides to my website's main slider on homepage. Now, the user has an option to link it to an existing news (using the news_slide field), so that a visitor can click on the slide and be redirected to the news article. The relationship between Slide & News is a 1-to-1 relationship. So, I had to filter the news_slide field so that it excludes News that are already linked to a slide (which I was able to do). But I have 2 problems now when user edits a Slide: The default value of news_slide is empty instead of the News it was associated to The News it was associated to is also excluded from the options. Let's say he only needed to change the Slide caption, but still he has to update the news_slide field (since it was changed to empty) yet he won't find that news on the options now. I need to know how to check if the Slide is linked to a News, and exclude ONLY those News that are linked to other Slides. Screenshot and code below: As shown, this Slide is linked to a News: But when I edit … -
Is it possible to make a mobile app in Django?
I was wondering if it is possible for me to use Django code I have for my website and somehow use that in a mobile app, in a framework such as, for example, Flutter. So is it possible to use the Django backend I have right now and use it in a mobile app? So like the models, views etc... -
Django Rest Framework CreateAPIView url primary key should be come from another model, not respected model
At first see my models: from django.contrib.auth.models import User class Group(models.Model): person = models.ManyToManyField( User, through='PersonGroup', related_name='person_of_the_group' ) class PersonGroup(models.Model): group = models.ForeignKey( Group, on_delete=models.CASCADE, related_name='group_person_of_group' ) person = models.ForeignKey( User, on_delete=models.CASCADE ) and this is my views: class AddGroupMembers(CreateAPIView): serializer_class = PersonGroupSerializers queryset = Group.objects.all() lookup_field = 'pk' def create(self, request, *args, **kwargs): # Make requst data mutable if not request.data._mutable: request.data._mutable = True request.data['person'] = request.user.pk request.data['group'] = kwargs['pk'] serializer = PersonGrouperializers(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) and this is my serializes: class PersonGroupSerializers(ModelSerializer): class Meta: model = PersonGroup fields = '__all__ I want the urls pk will be mess pk, http://127.0.0.1:8000/mess/api/v1/mess/<int:mess.pk>/ I want when i hit the endpoint, i should able to create PersonGroup where, if you see my views, you will know how i am populating this table. I mean, the endpoint url will be identified by any of Group pk but there i should able to PersonGroup Hope you got it, can anyone tell me how to achive this? -
Django - replace "model object" by the value
I have a model Currency defines below: class Currency(models.Model): """ Currency Model Defines the attribute of Currency """ class Meta: verbose_name = "Currency" verbose_name_plural = "Currencies" ordering = ['Currency_Name'] def __str__(self): return self.Currency_Name Currency_Date = models.DateTimeField(auto_now_add=True) Currency_Date_Update = models.DateTimeField(auto_now=True) Currency_Name = models.CharField(max_length=3, unique=True) Is_Secondary_Ccy = models.CharField(max_length=1, choices=Y_N_BOOLEAN) Primary_Currency = models.ForeignKey('self', on_delete=models.DO_NOTHING, null=True) # to refer to itself Primary_Factor = models.IntegerField(default=1) Currency_Name_Reuters = models.CharField(max_length=3) The model is linked to itself by the column "Primary_Currency" In my admin (image below) I can see the linked, but if i open the dropdown, the label is not user friendly "Currency object (0) etc..." Can I have the value "Currency_Name" of the "Primary_Currency" ? thanks for your help :) -
Not able to submit django form
I don't know why my form is invalid. Despite everything seems to be normal. I am not getting any error. sending you screenshot of models.py Here is my forms.py class LeadForm(forms.ModelForm): product_queryset = [] product_name = forms.MultipleChoiceField(choices=product_queryset, required=False) contact = PhoneNumberField() def __init__(self, *args, **kwargs): super(LeadForm, self).__init__(*args, **kwargs) self.fields["product_name"].choices = [(pro.get('id'), pro.get('name')) for pro in Products.objects.all().values('id', 'name')] class Meta: model = Lead exclude = ('created_at','created_by') widgets = { 'date_of_enquiry': DateInput(attrs={'type': 'date'}) } Here is my views.py def create_lead(request): u = User.objects.get(username=request.user.get_username()) if request.method == 'POST': print(request.POST) # form = LeadForm() form = LeadForm(request.POST) if form.is_valid(): print('inside valid') form.save(commit=True) form.created_by = u form.save() form = LeadForm() context = {"form": form} return render(request, 'create_lead.html', context) -
Python convert string to date-time format [duplicate]
This question already has an answer here: How to print a date in a regular format? 22 answers I have this string: '2020-04-10 10:00:23+00:00' I need this output: '04/10/2020 10:00 AM UTC' Is there any way to convert it in python or on front-end (angular/ionic4) -
Write data to xls and download it in python-django
I have successfully created .csv file and now want to create .xls for the same data. After which I want to download it as well. So after creation of csv file from python I am sending response to the ajax function and downloading it from there using jquery. def expense_export(request): print(request.POST) if request.is_ajax(): ids = request.POST.getlist('ids[]') expenses = Expense.objects.filter(id__in=ids) data = [] field = ['SLNO', 'Date of Recording', 'Category', 'Sub Category', 'Invoice Date', 'Invoice No', 'GST No. Mentioned', 'Vendor Name', 'Details', 'Gross Value', 'SGST', 'CGST', 'IGST', 'Total Invoice Value', 'TDS(if any)', 'Net Payble'] field1 = ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''] response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="Search Results.csv"' sno = 1 max = 0 for record in expenses: pay_data = [] if record.record: curr = 0 for pay_record in record.record: pay_row = [pay_record['date'], pay_record['amount'], pay_record['mode'], pay_record['ref'], pay_record['bank']] pay_data = pay_data + pay_row curr = curr + 1 if curr > max: max = curr gst_exist = 'No' if record.vendor: if record.vendor.gst_no: gst_exist = 'Yes' igst = int(record.gst) / 100 * record.amount tds = int(record.tds) / 100 * record.amount net_amount = int(record.amount) + int(igst) row = [ sno, record.timestamp.strftime('%d-%m-%Y'), record.expense_name, … -
JQuery - Changing calendar dates based on model data
As a part of a task, I created an "apartment listings" website. I managed to get that done, but now I need to make a "reservation system" for it. The basic idea is that a logged in user can select an apartment from the listed apartments, pick a "start_date" and an "end_date" (if the apartment already isn't booked ) and book the apartment. When the user clicks on the date input field, a jquery datepicker pops up and he can then pick the date via the calendar, same for end date. Once he goes through with the booking, I want the dates to be "disabled" in the calendar so no one else can pick them. This is the datepicker that I'm using: https://jqueryui.com/datepicker/ and the code: <script> $(function () { $("#datepicker").datepicker(); }); </script> Im a total Django / web development newbie, and need some pointers in order to start somewhere with this task, I know some JS but jquery is new to me, that's why I'd like some help. I have an Apartment model which contains all of the Apartments info that I use to print everything out with the template. I have an Reservation model which saves the start … -
Doubts how to design data with Django and PostgreSQL when having a value for every hour of the year
I am running a django app with PostgreSQL as my database. I have a building model called building. From this model I create many building instances. I have another model which is called forests from which I create many forests instances. (Let's assume I have even more models for which the same applies) Now I want to add data (let's call it x) for every building and for every forest for every hour of the year. That means I will have 8760 values for every building and forest instance. For instance: Hour1 : 234 Hour2 : 667 ... HourX : x ... Hour8760: 34 These 8760 values will be added, roughly estimated, 10-15 times a day, so that could lead to 131400 values a day. Now, I have doubts on how to design that. I thought I could go with a model like so: class Hour(models.Model): building = models.ForeignKey(Building, on_delete=models.CASCADE) forest = models.ForeignKey(Forest, on_delete=models.CASCADE) hour = models.IntegerField(...) value = models.FloatField(...) timestamp = models.CharField(max_length=200, null=True, blank=True) My second thought is to design it with a JSONField inside of an ArrayField like discussed here: Django JSONField inside ArrayField. So maybe I could save a dictionary for every building and every forest OR … -
problem with get_absolute_url django python
I used get_absolute_url in my app but it works only on admin site (by button view on site). On my website, the hyperlink is not responding. I've checked every line of code a couple of times and it seems like everything's fine. Does anyone know why it doesn't works? models.py class CrashReport(models.Model): number_id = models.AutoField(primary_key=True) date_notice = models.DateField(auto_now=False, auto_now_add=False) SHIFT_NUMBER = ( ('I', 'Zmiana I (6:00 - 14:00)'), ('II', 'Zmiana II (14:00 - 22:00)'), ('III', 'Zmiana III (22:00 - 06:00)'), ) which_shift = models.CharField( max_length=3, choices=SHIFT_NUMBER, blank=True, default='I', help_text='Zmiana.' ) who_notice = models.ManyToManyField(Author, help_text='Select a occupation for this employee') description = models.TextField(max_length=1000, help_text='Please type what happened') which_stuff = models.ManyToManyField(Device, help_text='Select a exactly devices') PROCESSING_STATUS = ( ('o', 'Otwarty'), ('p', 'Przetwarzanie'), ('z', 'Zakonczony'), ) status_notice = models.CharField( max_length=1, choices=PROCESSING_STATUS, blank=True, default='o', help_text='Status dokumentu.' ) def __str__(self): return f'ZGL /{self.number_id} / {self.which_stuff.all()} / {self.date_notice}' def get_absolute_url(self): return reverse('crashreport-detail', args=[str(self.number_id)]) views.py from django.shortcuts import render from django.views import generic from .models import CrashReport def index(request): """View function for home page of site.""" # Generate counts of some of the main objects num_crashreports = CrashReport.objects.all().count() # num_instances = BookInstance.objects.all().count() # Opens Crashreports (status = 'o') # num_crashreport_open = CrashReport.objects.filter(status__exact='o').count() context = { 'num_crashreports': num_crashreports, … -
Python Django render an html code from a db field
In my django project i have a model with a field that contain html code as text: html_test = models.TextField() for example in this field could be: <html> <header><title>This is title</title></header> <body> Hello world </body> </html> i would ti retrive this code and render dinamically showing the correspondenting html page without create a file or save it on disk. Someone know how can i render an html code in memory for display page and then destroy it? So many thanks in advance -
My swiper-pagination is overlapping with the text and my Hamburger appears behind the slider when open
i have a simple problem that i can't wrap my head around. My swiper-pagination that is supposed to appear at the bottom of the text overlaps with the text at the bottom of the page hence it cannot be seen clearly. I would like for it to appear like 10px below the text to clearly be seen by anyone visiting my site. Another problem is when you view it in mobile platform when you click on the hamburger the contents appear behind the slider and i would like then to come in-front of the slider and be clickable for clients to view the other pages. My project is on django and i have linked the swiper.min.js and swiper.min.css to my static root folder.My code is as follow below. If you seek more clarification please tell me and i will upload the additional details. Thanks in advance guys. Html {% load static %} <!DOCTYPE html> <html> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta http-equiv='X-UA-Compatible' content='IE=edge'> <meta name='viewport' content='width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1'> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'buyer/main.css' %}"> <link rel="stylesheet" href="{% static 'buyer/swiper.min.css' %}"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <script src="https://code.jquery.com/jquery-3.4.1.js"></script> <script …