Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Find the location of data base file that gets created when a user is created in django application
In a django application with 'postgresql' as data base ,where do the users get stored ? any file where can i check the users info...basically where will be the .db file stored in django -
how to create django form with multiplechoicefield and add those value to database
what I want to achieve is user will submit 3 inputs in the form 1) name 2) dropdown to select technician, 3) multiselect dropdown to select multiple products. Once the user submit the details it will generate one lead in database with value like name,foreignkey of selected technician and id of selected products in different table. I don't know how to achieve this below I have mentioned my approch to achieve what I want. Please let me know if the models need any changes and how I can write a view for the same. models.py class product(models.Model): name = models.CharField(max_length=20) class technician(models.Model): name = models.CharField(max_length=20) class lead(models.Model): name = models.CharField(max_length=20) technician = models.ForeignKey(technician,on_delete=models.SET_NULL,null=True) #only single selection products = models.ManyToManyField(product) #user can select multiple product in dropdown form.py class leadForm(form.ModelForm): products = forms.MultipleChoiceField(queryset=Product.objects.all()) technician = forms.CharField(max_length=30,choices=[(i.id,i.name) for i in Technician.objects.all().values('id','name') class Meta: model = lead fields = ('name','technician') -
Django reverse optional path parameters
Before anyone comments I have seen both: Django optional url parameters and How to have optional parts of a django url and reverse to it And while similar these existing questions do not answer or solve my problem. I have good reasons to attempt to use optional path parameters. In fact I have gotten it 90% working but stumbled across a seeming inconsistency between Django's Redirect (and reverse) and the {% url %} templatetag I've written a custom optional parameter: class OptionalStringConverter: regex = '((_)*[a-zA-Z]+)*' def to_python(self, value): if value: return str(value) else: return None def to_url(self, value): return str(value) if value is not None else '' register_converter(OptionalStringConverter, 'opt_str') urlpatterns = [ # url with optional params path('<opt_str:optional_a>/<opt_str:optional_b>/foo/', foo.bar, name='foo_bar'), ] Inside of the view: def bar(request, optional_a=None, optional_b=None): // do some stuff view_name = 'some:namespaced:viewname' return redirect(view_name, optional_a=optional_a, optional_b=optional_b) This gives me exactly what I want, if I manually go to http://0.0.0.0:8888/some/namespaced/foo/ http://0.0.0.0:8888/some//foo/ http://0.0.0.0:8888//namespaced/foo/ The urls all resolve nicely and the parameters entered come through nicely and more importantly the redirect also works nicely (None values get passed) But when I try reversing inside of a template with one of the following however: {% url 'some:namespaced:viewname' optional_a=optional_a optional_b=optional_b %} … -
Compare django template varaiable with javascript varaible
I am trying to populate a table in django template, but I want to compare cell values, one of them is javascript variable and another is django template variable. Is it possible to compare them without converting django variables to javascript variables? or is there a quick work around? {% for x in price_data %} <script> counter++ var VALUE =document.getElementById("price_table").rows[0].cells.item(counter).innerHTML; </script> {% if x.room_scan == i and x.checkin == VALUE %} I want to check if x.checkin is equals to VALUE. Thanks. -
django ascii error when loading to AWS elasticbeanstalk
I'm getting this error when trying to upload an update version (from python2.7 to 3.6 and Django 1.11 to 2.2) of an app to AWS Traceback (most recent call last): File "hjsm/./manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/opt/python/bundle/2/app/hjsm/researcher_UI/management/commands/populate_instrument.py", line 22, in handle instruments = json.load(open(os.path.realpath(PROJECT_ROOT + '/static/json/instruments.json'))) File "/usr/lib64/python3.6/json/__init__.py", line 296, in load return loads(fp.read(), File "/opt/python/run/venv/lib64/python3.6/encodings/ascii.py", line 26, in decode return codecs.ascii_decode(input, self.errors)[0] UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 2029: ordinal not in range(128). This is running a ./manage.py populate_items management command. It works locally and the file doesn't seem to have any ascii issues. It also works using Pythjon2.7 and Django 1.11. I include the json file below (I do wonder if the accented French characters are the issue but then I do not understand why it is working locally): [ { "language": "English", "form": "WS", "verbose_name": "Words and Sentences", "min_age": 16, "max_age": 30, "csv_file": "cdi_form_csv/[English_WS].csv", "json_data": "cdi_forms/form_data/English_WS_meta.json", "fillable_headers": "cdi_form_csv/EnglishWS_pdf_headers.csv", "scoring_json" : "cdi_forms/form_data/scoring/English_WS_scoring.json", "benchmark" : "cdi_forms/form_data/benchmarking/English_WS_benchmark.csv" }, { "language": "English", "form": "CDI3", … -
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, …