Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to update a Django model with a large CSV file (54 fields, ~5000 rows)?
I have a model describing data center items (e.g. Racks, PDUs, patch panels, switches, servers, blades, ...). The data is exported regularly as CSV (once a month) and the export currently has close to 5000 lines and 54 fields per row. For our Django App, roughly 80% of the rows are relevant: their equipment type must be in a pre-defined type list and the item must have a barcode (internal asset number) associated with it. The rest of the lines is skipped. The model (see below) captures all of the available fields, even if they're not used. The reason for that is that the app, once it becomes productive, will have several models related to each other but fed from different data sources. Until now all of them are completely unrelated, the goal is to detect lint in the various databases and, over time, clean the data. Maybe in the future some data sources may even be declared authoritative so their data can be used to automatically generate updates for secondary databases whenever a primary representation changes. In the app we currently upload the CSV file via form, here is a sample of the CSV (data anonymized): "Name";"Serial Number";"Barcode";"Installation Date";"Model … -
how to query google about position of webpage on keyword in django
I'm half way through creating my application. Now I don't know how to do it to the end. I want to query Google on what position the page is, on the keyword. From what to start here and what to do not to get an IP ban and not to display the recaptcha? -
django-scheduler how to relate model to an event?
I have the following models: class UserProfile(models.Model): user = models.OneToOneField(User, related_name='user', on_delete=models.CASCADE, primary_key=True) title = models.CharField(max_length=100, blank=True) address = models.CharField('Dirección', max_length=220, blank=True) colonia = models.CharField(max_length=220, blank=True) estado = models.CharField(max_length=220, blank=True) municipio = models.CharField(max_length=220, blank=True) cp = models.IntegerField('C.P.', max_length=6, blank=True, default=0) telefono = models.IntegerField('Tel.', max_length=13, blank=True) def user_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> return 'user_{0}/{1}'.format(instance.user.username, filename) upload = models.FileField('Archivo .ZIP con las xml dentro', upload_to=user_directory_path, null=True, blank=True, ) def set_avatar(self): _avatar = self.avatar if not _avatar: self.avatar = "static/logos/default.png" @receiver(post_save, sender=user) def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) @receiver(post_save, sender=user) def save_user_profile(sender, instance, **kwargs): instance.UserProfile.save() def __str__(self): return self.user.username class Client(models.Model): pattern = models.ForeignKey('auth.User', on_delete=models.PROTECT) namec = models.CharField(max_length=200) description = models.TextField() address = models.CharField('Dirección', max_length=220, blank=True) colonia = models.CharField(max_length=220, blank=True) estado = models.CharField(max_length=220, blank=True) municipio = models.CharField(max_length=220, blank=True) cp = models.IntegerField('C.P.', max_length=6, blank=True, default=0) telefono = models.IntegerField('Tel.', max_length=13, blank=True) created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.namec Each user-UserProfile can create appointments in its own calendar, in each event in addition to the description to be able to attach files and a field to select a client of the client model. How can I achieve this? … -
try except doesn't work fine
I'm working on django and this is the code: def checkRights( self ): resources_rights = Resources_rights.objects.filter( self.checkRead(), self.checkWrite(), self.checkExecute(), group_id__in = self.groups ).distinct().order_by( "resource_id" ) return resources_rights def checkRead( self ): if self.query_dict[ 'read' ] is None: read_statement = Q( ) else: try: read_statement = Q( read = self.query_dict[ 'read' ] ) except Exception as e: read_statement = Q( ) self.errors = e self.warnings = "Resources have not been filtered" return read_statement I passe it self.query_dict[ 'read' ] as true so it rightly returns the ValidationError, because read is boolean and it must be True or False. Right for that, I've put a try except, the problem is that it never goes in the except, despite the try returns an error. What am I doing wrong? -
running inspectdb on a legacy msql database
I have successfully connected to a database from sql-server and my server starts perfectly, i tried to run inspectdb to get the models generated for me but these errors. Unable to inspect table 'AccountManagers' The error was: __new__() missing 1 required positional argument: 'default' I want to be able to generate models from this database -
Can't display different forms for different user types
I have 2 user types, teacher and student. I have built the view to be able to edit a student profile. But I also needed a different one for teacher. I didn't want 2 views, because that would be pointless. Now, for teacher it works as intended, but for some reason for teacher, the same form as for the student is displayed... a teacher has different attributes so it has a different form I need to show. class TeacherEditForm(forms.ModelForm): email = forms.EmailField(required=False) name = forms.CharField(max_length=30, required=False) surname = forms.CharField(max_length=50, required=False) academic_title = forms.CharField(max_length=30, required=False) bio = forms.Textarea() website = forms.URLField(required=False) photo = forms.ImageField(required=False) phone = forms.CharField(required=False) class StudentEditForm(forms.ModelForm): email = forms.EmailField(required=False) name = forms.CharField(max_length=30) surname = forms.CharField(max_length=50) photo = forms.ImageField(required=False) phone = forms.CharField(max_length=15, required=False) @login_required def profile_edit(request): user = request.user try: student = Student.objects.get(user=user) s = True except ValueError: teacher = Teacher.objects.get(user=user) if not s: if request.method != 'POST': form = TeacherEditForm(instance=teacher) else: form = TeacherEditForm(request.POST, instance=teacher) if form.is_valid(): user.email = form.cleaned_data['email'] user.save() form.save() return redirect('index') elif s: if request.method != 'POST': form = StudentEditForm(instance=student) else: form = StudentEditForm(request.POST, instance=student) if form.is_valid(): user.email = form.cleaned_data['email'] user.save() form.save() return redirect('index') context = { "form": form, } return render(request, "registration/profile_edit.html", context) -
Error deploying Django app on heroku
I'm kinda new to Django as well as heroku and have encountered a problem while publishing my app to heroku. The error I get is this: remote: Compressing source files... done. remote: Building source: remote: remote: -----> App not compatible with buildpack: https://codon-buildpacks.s3.amazonaws.com/buildpacks/heroku/python.tgz remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to shielded-lake-72150. remote: To https://git.heroku.com/shielded-lake-72150.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/shielded-lake-72150.git' I tried a lot of solutions given online, but nothing worked. I even set the buildpack to python. But it still shows me the same error. Any help appreciated, thanks. -
How to send message from user in telegram in web application
I am trying to create web application using python3.x and django2.x I am create view that authorize user in telegram, but when i get secure code and send it to function sign_in i recieve an error "You also need to provide a phone_code_hash." I don't know what is the phone_code_hash, and where I can get it. views.py:: def authorize_user(request): if request.method == 'POST': secure_code = request.POST.get('secure_code') phone = request.POST.get('phone') api_id = request.POST.get('api_id') api_hash = request.POST.get('api_hash') client = TelegramClient('spamer', api_id, api_hash) if secure_code: try: client.sign_in(phone, secure_code) except Exception as e: print(e) return JsonResponse({'status': 0, 'error': 'error'}) return JsonResponse({'status': 2}) client.connect() client.send_code_request(phone) return JsonResponse({'status': 1}) return render(request, 'spamer/add_user.html') I use telethon library for API interaction. Maybe someone from you know how to authorize user and send message from him many times in different days. Maybe you suggest more suitable library or to use API requests with urllib. I only want to authorize user and use him to send many messages to another people, is it real? -
posible to store an excel file into a html element? [duplicate]
This question already has an answer here: How to serve static files in Flask 12 answers Python - Write to Excel Spreadsheet 8 answers Create and download a CSV file from a Flask view 1 answer we are making a website using flask where we display a table with information, and the user want to be able to export that to excel, we can do that with javascript but some of the charts that we created cant be transfer, so we thought doing the excel file in the back end and pass it to a button, that way the user can have the table in the browser and click a button and that will already have in it the excel file. how can I store/pass the excel file into a html element button? -
how to post callback to Background [duplicate]
This question already has an answer here: How can I upload files asynchronously? 25 answers This is an easy Html. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form method="POST" action="https://sm.ms/api/upload" enctype="multipart/form-data"> <input name="smfile" type="file"> <input type="submit" name="upload"> </form> </body> </html> When i post an image to the server(third party) , the server(third party) returned the json and changed my web.. { code: "success", data: { width: 440, height: 440, filename: "timg.jpg", storename: "5a7b1807506b2.jpg", size: 11941, path: "/2018/02/07/5a7b1807506b2.jpg", hash: "m8FqIYBGWL1HDrT", timestamp: 1518016519, ip: "111.29.138.47", url: "https://i.loli.net/2018/02/07/5a7b1807506b2.jpg", delete: "https://sm.ms/delete/m8FqIYBGWL1HDrT" } } my question is how to POST this json to my background and how to don't change my web .. -
Django: why does NOT this give a syntax error? [duplicate]
This question already has an answer here: Why does python allow spaces between an object and the method name after the “.” 3 answers UPDATE This question has been marked as duplicate. The linked question answers my question partially. I have two questions and it answers one. ORIGINAL I am new to Django. I just by mistake put a space between this query and realized that it still works when I would expect it to give an error. ClinicDoctorDayShift.objects.filter(clinic_doctor__doctor_id = doctor_id).all() .order_by('day_shift__time') There is a space between all() and .order_by. Why doesn't it raise an error? the order_by still works. WHY? And one more thing. what is difference between ClinicDoctorDayShift.objects.filter(clinic_doctor__doctor_id = doctor_id) and ClinicDoctorDayShift.objects.filter(clinic_doctor__doctor_id = doctor_id).all() One is without all(). They work same way, apparently, when I use them in my template. Thank you -
Django: set the foreign key field of model which is related with User [duplicate]
This question already has an answer here: Using request.user with Django ModelForm 2 answers My model Resume has a user field as foreign key: class Resume(models.Model): name = models.CharField(max_length=25) base_info = models.TextField() created_at = models.DateTimeField(auto_now_add=True) User = get_user_model() superuser = User.objects.get(username=<superuser_username>) user = models.ForeignKey(User, on_delete=models.CASCADE, default=superuser.id) (Set default as superuser since I added that after some migrations and it is working right.) I want to set the user field automatically login user where the new ResumeForm saved. I think saving the user in view is better than in template but following doesn't work: def resume_form(request): if request.method == 'POST': form = ResumeForm(request.POST, request.FILES) form.user = request.user if form.is_valid(): resume = form.save() return redirect('resume:list') else: form = ResumeForm() return render(request, 'resume/index.html', { 'form': form, }) How can I do that? +) Where is the proper part to save(set) user, in view or template? (or any other can access to user context?) -
How to display records belonging to exacly one category
I've create something like this In the label 'Monitoring www' the records now are displaying correctly. If the user is logged, they can add Websites, and after that the user can add keywords.Now I want to display the websites and the keywords belonging to the website record. In view.py I have: @login_required def website_list(request): website_list_user = Website.objects.filter(user=request.user).order_by('-user') context = {'website_list_user': website_list_user} return render(request, 'konto/dashboard.html', context=context) @login_required def keyword_list(request): keyword_list_user = Keyword.objects.filter(keyword=request.keyword).order_by('-keyword') context = {'keyword_list_user': keyword_list_user} return render(request, 'konto/dashboard.html', context=context) in forms.py class KeywordForm(forms.ModelForm): class Meta: model = Keyword fields = ('www', 'keyword') def __init__(self, user, *args, **kwargs): super(KeywordForm, self).__init__(*args, **kwargs) self.fields['www'].queryset = user.website_set.all() self.user = user def save(self, commit=True): instance = super(KeywordForm, self).save(commit=False) instance.user = self.user if commit: instance.save() return instance and my template : {% if request.user.is_authenticated %} <b>Monitoring www:</b><br> {% for website in website_list_user %} {{website.website}}<br> {% endfor %} <b>Słowa kluczowe:</b><br> {% for keyword in keyword_list %} {{keyword.keyword}}<br> {% endfor %} {% endif %} EDIT: my urls.py from django.urls import path from django.contrib.auth import views as auth_views from .views import dashboard, register, settings, del_user, website_list, keyword_list, new_website, new_keyword, main_page urlpatterns =[ path('', main_page, name='main_page'), path('login/', auth_views.login, name='login'), path('logout/', auth_views.logout, name='logout'), path('logout-then-login/', auth_views.logout_then_login, name='logout_then_login'), path('password-change/', auth_views.password_change, name='password_change'), path('password-change-done/', auth_views.password_change_done, … -
Django DRF - serializing foreign key relationship in a linear form
I am using DRF to power up my Django REST api. Consider the following model: class Author(models.Model): name = CharField(...) class Book(models.Model) author = ForeignKey(Ablum) title = CharField(...) My desired output should be a linear JSON looking like this: [ { "name": "Jack London", "title": "White fang" } { "name": "Jack London", "title": "Martin Iden" } { "name": "Charles Dickens", "title": "David Coperfield" } { "name": "Charles Dickens", "title": "Oliver Twist" } ] I accomplished the result using the corresponding serializers class BookSerializer(serializers.ModelSerializer): author = serializers.CharField(source='album.author') class Meta: model = Book depth = 1 fields = ('author', 'title ') ...but the problem is that this solution is very dirty in terms of DRYness. Every time I add new field to Author, I would like it to appear in Book as well. Is there any way to tell Django to include all fields of the related model ? Or I also tried the following approach: class BookSerializer(serializers.ModelSerializer): author = CalendarEventSerializer(read_only = True) class Meta: model = Book depth = 1 fields = ('author', 'title ') but with this I ended up with nested JSON structure like this: [ { "name": "Jack London", "author": {...} }, ... ] which does not meet … -
How to programmatically generate the CREATE TABLE SQL statement for a given model in Django?
I need to programmatically generate the CREATE TABLE statement for a given model in my Django app. The ./manage.py sql command was useful for this purpose but it has been removed in Django 1.8 Do you know about any alternatives? -
rq-scheduler does not pass the job to "worker"(django / redis)
I'm trying to figure out the work of the scheduler "rq-scheduler". There is a scheduler.py: from redis import Redis from rq_scheduler import Scheduler from datetime import datetime from task import save_exchange_rates redis_conn = Redis() scheduler = Scheduler(connection=redis_conn) scheduler.schedule( datetime.utcnow(), save_exchange_rates, interval=10, repeat=None, ) it's a script that writes data to the database, if I run it manually, it works. task.py: import os os.environ['DJANGO_SETTINGS_MODULE'] = 'market_capitalizations.settings' import django django.setup() import requests from exchange_rates.models import Currency def save_exchange_rates(): url = 'https://api.coinmarketcap.com/v1/ticker/' repositories = requests.get(url).json() for exchange in repositories: Currency.objects.create(name=exchange['name'], price_usd=exchange['price_usd'], last_updated=exchange['last_updated'],) if __name__ == '__main__': save_exchange_rates() I installed the modules: rq, rq-shcheduler, redis. enter image description here But the scheduler "rq-scheduler" does not transfer the task to "worker". Tell me, please, what am I doing wrong and what is the cause of the problem? -
How do I fetch url parameters of the current page in Django?
Sample URL: https://www.samplewebsite.com/search?query=my+site+is How do I fetch the query parameters in Django? Required: variable = "my site is" -
Django Form errors not displaying in template (custom forms)
I'm using Django 1.11. I have a model with regex validators. Unfortunately validation errors not displaying in my template. Everythink works fine on standard forms, but on custom forms in template it doesnt work. Whats wrong with that? template.html: {% for form in answers_formset %} <tr> <input type="hidden" name="answer-{{forloop.counter0}}-id" value="{% if form.instance.id %}{{ form.instance.id }}{% endif %}" /> <td class="place_in_td"> <p class="forloop-counter">{{forloop.counter}}</p><input type="hidden" name="answer-{{forloop.counter0}}-place_in_sequence" value="{% if form.place_in_sequence.value %}{{ form.place_in_sequence.value }}{% else %}{{ forloop.counter }}{% endif %}"> </td> <td> <input type="text" class="form-control" name="answer-{{forloop.counter0}}-command" id="id_answer-{{forloop.counter0}}-command" placeholder="{% trans 'command' %}" value="{{ form.command.value | default_if_none:'' }}"/> {{ form.command.errors }} </td> <td> <input type="text" class="form-control" name="answer-{{forloop.counter0}}-answer" id="id_answer-{{forloop.counter0}}-answer" placeholder="{% trans 'answer' %}" value="{{ form.answer.value | default_if_none:'' }}"/> {{ form.answer.errors }} </td> <td> {{ form.is_correct }} </td> <td><button type="button" class="remove-row pull-right btn btn-danger btn-sm"><span class="fa fa-minus-circle"></span></button></td> </tr> {% endfor %} views.py(a part of) for form in self.answer_formset: form.is_valid() if form.cleaned_data: answer = form.save(commit=False) answer.question = question try: answer.save() except IntegrityError: formset_errors.append(answer.command) else: submitted_answers_ids.append(answer.id) -
Datetime.time error django
I'm trying to import data from an excel file into my database in Django. Unfortunately, I'm getting this error when trying to import a time. AttributeError at /datavisual/upload/ 'datetime.time' object has no attribute 'total_seconds' Models.py CallRecord(models.Model): timeOfCall = models.TimeField() and in my Excel logic py file: class ExcelParser(): def read_excel(Document): wb2 = load_workbook('Sheet1.xlsx',guess_types=True) for row in wb2.active.iter_rows(range_string=wb2.active.calculate_dimension()): newRecord = CallRecord.objects.create(timeOfCall = row[1].value) newRecord.save() So far, the rest of the fields are saving as expected but I'm not sure what is causing this issue. Full error report: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/datavisual/upload/ Django Version: 2.0.1 Python Version: 3.6.4 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'datavisual.apps.DatavisualConfig'] Installed 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'] Traceback: File "C:\Users\d_aqu\AppData\Local\Programs\Python\Python36-32\lib\site- packages\django\core\handlers\exception.py" in inner 35. response = get_response(request) File "C:\Users\d_aqu\AppData\Local\Programs\Python\Python36-32\lib\site- packages\django\core\handlers\base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "C:\Users\d_aqu\AppData\Local\Programs\Python\Python36-32\lib\site- packages\django\core\handlers\base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Michael\callcentre\callcentre\datavisual\views.py" in model_form_upload 29. ExcelParser.read_excel(request.FILES['file']) File "C:\Michael\callcentre\callcentre\datavisual\ExcelParser.py" in read_excel 21. invoiceNumber = row[19].value) File "C:\Users\d_aqu\AppData\Local\Programs\Python\Python36-32\lib\site- packages\django\db\models\manager.py" in manager_method 82. return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\d_aqu\AppData\Local\Programs\Python\Python36-32\lib\site- packages\django\db\models\query.py" in create 417. obj.save(force_insert=True, using=self.db) File "C:\Users\d_aqu\AppData\Local\Programs\Python\Python36-32\lib\site- packages\django\db\models\base.py" in save 729. force_update=force_update, update_fields=update_fields) File "C:\Users\d_aqu\AppData\Local\Programs\Python\Python36-32\lib\site- packages\django\db\models\base.py" in save_base 759. updated = self._save_table(raw, cls, force_insert, force_update, … -
background image in css style from static files with django
I used this template to create a home page in a django project, however I can't have the background image displayed correctly (bg.jpg) The background image is used as foollows in the css file : .wrapper.style3 { background-color: #000; color: #bfbfbf; background-image: url(/media/usr/path_to_project/project_name/home/static/images/bg.jpg); background-size: cover; background-attachment: fixed; background-position: center; position: relative; } I read these topics How to add background image in css? How to use background image in CSS? use static image in css, django How do I put a background image on the body in css with django using static? and tried all of the solutions but non of them seems to work. My project tree is like project_name - home - static --home ---style.css --images ---bg.jpg - templates -- home ---base.html ---home_template.html in the style.css file I tried the following background-image: url(/media/usr/path_to_project/project_name/home/static/images/bg.jpg); background-image: url("/media/usr/path_to_project/project_name/home/static/images/bg.jpg"); background-image: url(../images/bg.jpg); background-image: url("../images/bg.jpg"); background-image: url("{% static 'images.bg.jpg' %}); in my base.html template I have : {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'home/style.css' %}"/> and in my home_template.html I have {% block body %} {% load staticfiles %} <section id="two" class="wrapper style3"> <div class="inner"> <header class="align-center"> <p>Nam vel ante sit amet libero scelerisque facilisis eleifend vitae urna</p> <h2>Morbi maximus justo</h2> … -
How to add conditional intermediary page in Django admin
I have a model: class Survey(BaseModel): name = models.CharField(max_length=500, help_text='name') user = models.ForeignKey('User') json = JSONField(default=dict) status = models.CharField( max_length=50, default=INCOMPLETE, choices=STATUS_CHOICES) I override the save() method inside that models class and run some other pre save operations there. In that logic you can see where I want to do the confirmation: def save(self, *args, **kwargs): if self.status == self._status: # Status was unchanged. self.skip_history_when_saving = True else: self._status = self.status if self.status == 'live': # DO INTERMEDIARY CHECK HERE super(Survey, self).save(*args, **kwargs) What I'm trying to do I want like to add an intermediary page (see the delete confirmation) only if the status is going from incomplete to live, for example. I've been trying to trigger it with a function in my admin.py but not been able to do it. Here's my intermediary template method which right now is in admin.py SurveyAdmin class. I understand how it works, but I don't know how to link it in the the save() method I'm using to check in my models.py: @csrf_protect_m @transaction.atomic def conditional_status_confirm(self, request, object_id=None, form_url='', extra_context=None): survey = Survey.objects.get(pk=object_id) if request.method == 'POST': survey.status = Survey.LIVE survey.save() msg = _('Survey updated successfully.') messages.success(request, msg) return HttpResponseRedirect(reverse('admin:survey_change', args=(survey.pk,))) else: context … -
Django 1.11 admin list_filter to include fields in another model
I have a Django Admin class that displays all registered Users. I want to add a column next to each user that displays their latest Response (it's a survey app). What I've tried so far is: Response Model class Response(models.Model): """ A Response object is a collection of questions and answers with a unique interview uuid. """ created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) survey = models.ForeignKey(Survey, related_name="responses") user = models.ForeignKey(User, null=True, blank=True) interview_uuid = models.CharField(_(u"Interview unique identifier"), max_length=36) class Meta(object): verbose_name = _('response') verbose_name_plural = _('responses') def Quarter(self): msg = u"Q%d %d" %(((self.created.month-1)//3)+1, self.created.year) return msg Admin.py class ResponseAdmin(admin.ModelAdmin): list_display = ('survey', 'created', 'user', 'Quarter') **works here class UserAdmin(admin.ModelAdmin): list_display = ('username', 'latest_response') list_filter = ('is_staff', 'latest_response') def latest_response(self, obj): (return "Quarter" from Response Model) **how do I get it to work here too? admin.site.register(Response, ResponseAdmin) admin.site.register(User, UserAdmin) A few of my attempts resulted in the following error: FieldError: Cannot resolve keyword 'Quarter' into field. Choices are: answers, created, id, interview_uuid, survey, survey_id, updated, user, user_id So I can see the issue is that UserAdmin isn't getting the Quarter field from the Response Model for some reason. When I change def Quarter(self) to __str__(self), it displays as I want in … -
Django import export: skip_unchanged = True doesn't skip older records and also imports unchanged values
@admin.register(Hospital) class HospitalAdmin(ImportExportModelAdmin): pass class HospitalResource(resources.ModelResource): model = Hospital skip_unchanged = True report_skipped = False I have also tried using other available mixins, but somehow cannot get this working. I want unchanged records/values to be skipped during the import. -
How do I pass Javascript variables from my html template page to a Django views function?
I am working on a Django environment. I have created a form in my html page which contains a textbox for input for a label like "Enter your name" . I have a submit button below the textbox. I need to pass the inputted name to the button as a value and then this button value is to be passed to a python function in views.py. Can anyone help me with this ? -
Django UpdateView, get the current object being edit id?
I am trying to get the current record being edited's id, but am failing thus far. my view is as per the below: views.py class EditSite(UpdateView): model = SiteData form_class = SiteForm template_name = "sites/site_form.html" @method_decorator(user_passes_test(lambda u: u.has_perm('config.edit_subnet'))) def dispatch(self, *args, **kwargs): self.site_id = self.object.pk return super(EditSite, self).dispatch(*args, **kwargs) def get_success_url(self, **kwargs): return reverse_lazy("sites:site_overview", args=(self.site_id,)) def get_form_kwargs(self, *args, **kwargs): kwargs = super().get_form_kwargs() return kwargs def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['SiteID']=self.site_id context['SiteName']=self.location context['FormType']='Edit' return context and the error: File "/itapp/itapp/sites/views.py" in dispatch 890. self.site_id = self.object.pk Exception Type: AttributeError at /sites/site/edit/7 Exception Value: 'EditSite' object has no attribute 'object' ive tried: self.object.pk object.pk self.pk