Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Template Second Form Input Triggering Wrong View
Trying to have two forms on one page and have a user select a create input or load input. Should be pretty straight forward. Doesn't seem to work. Anytime I click select a person and click load, it evaluates the first URL for Create. Can someone please point out what I'm missing? I'm sure it's something simple. Views: def Create(request): print('Create View') def Load(request): print('Load View') URLs: urlpatterns = [ path('', views.Index, name='index'), path('person/', views.Create, name='Create'), path('person/', views.Load, name='Load'), Template: {% block body_main %} <form action={% url 'Create' %} method='POST'> <h2>Name</h2> {% csrf_token %} {{ form1 }} <input class="btn btn-success" name="form1btn" value="Submit" type="submit"/> </form> <br> <form action={% url 'Load' %} method='POST'> <h2>Select Existing Name</h2> {% csrf_token %} {{ form2 }} <input class="btn btn-success" name="form2btn" value="Submit" type="submit"/> <form> {% endblock %} -
Removing tasks from in queue until task handler finished with Celery and AMQP
Running worker and starts then stops automatically within 2 mins with the following message Removing tasks from in queue until task handler finished with Celery and AMQP Using celery 4.2.1, kombu 4.2.1 and amqp 2.5.2 -
probleme rendering in django
i'm using an api to get informations about coronavirus cases around the world and i have an issue in the last line of code from django.shortcuts import render import requests from django import forms from django.views.generic import TemplateView from .forms import homeform def home(request): if request.method =='POST': form = homeform(request.POST) if form.is_valid(): text = form.cleaned_data field = text['name'] print(field) country = field else: form = homeform() country = 'algeria' url = "https://covid-193.p.rapidapi.com/statistics" querystring = {"country": country} headers = { 'x-rapidapi-host': "covid-193.p.rapidapi.com", 'x-rapidapi-key': "36b864062emshac7e191eb5087e6p169e6bjsn24c86f3408c1" } response = requests.request("GET", url, headers=headers, params=querystring).json() data = response['response'] print(data) d = data[0] context = { 'all': d['cases']['total'], 'recovered': d['cases']['recovered'], 'deaths': d['deaths']['total'], 'new': d['cases']['new'], 'serioz': d['cases']['critical'], 'active':d['cases']['active'], 'deaths_new':d['deaths']['new'] } return render(request, 'index.html',{'form':form}, context) here i have a problem with rendering the page it just shows my html code in the webpage but when i remove context from the last line of code evrything becomes normal , please help me -
Accessing many-to-many details with through model in Django template
I have a models.py like this: class Work(models.Model): [...] instrumentations = models.ManyToManyField('Instrument', 'Percussion', through='Instrumentation', blank=True) class Instrument(models.Model): name = models.CharField(max_length=100) family = models.CharField(max_length=20, default='') class Percussion(models.Model): name = models.CharField(max_length=100) class Instrumentation(models.Model): players = models.IntegerField() work = models.ForeignKey(Work, on_delete=models.CASCADE) instrument = models.ForeignKey(Instrument, on_delete=models.CASCADE) percussion = models.ManyToManyField(Percussion, blank=True, default=None) # Ideally percussions should be in the Instrument model with family 'percussion', though I don't know how to make Django like that. A separate model is a good workaround for me. My view: def work_edit_view(request, id=id): InstrumentFormSet = inlineformset_factory(Work, Work.instrumentations.through, extra=1, can_delete=True, fields=('instrument', 'percussion', 'players', 'work'), widgets={ 'work': forms.HiddenInput(), 'players': forms.NumberInput(attrs={'placeholder': 'Number of players'}) form_details = InstrumentFormSet(request.POST or None, instance=obj_work, initial=[{'work' : obj_work.id}], prefix='instruments') }) The data gets saved correctly in my input form, so that's not an issue. My problem is visualising the information in my template. I can only access the 'instrument', not my 'percussion' or my 'players'. What am I doing wrong? {% for instrument in work.instrumentations.all %} {{ instrument }} {{ instrument.players }} # only instrument is output. {% for percussion in instrument.percussion.all %} # this looks to be empty. Percussion {{ forloop.counter }} ({{ percussion.players }}) # No luck here :( {% endfor %} -
Djano - 'str' object has no attribute 'decode'
I'm trying to run my Django project, but whenever i register a new account, i'm getting the following error: 'str' object has no attribute 'decode' I don't understand where is this coming from; for authentication and registration i'm using django-allauth, and until now i've never had this issue. What could be the problem here? Here is the full traceback (i'm using Django 3): Environment: Request Method: POST Request URL: http://127.0.0.1:8000/account/login/?next=/ Django Version: 3.0.6 Python Version: 3.8.3 Installed Applications: ['channels', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main.apps.MainConfig', 'faqs.apps.FaqsConfig', 'django.contrib.sites', 'django_otp', 'django_otp.plugins.otp_static', 'django_otp.plugins.otp_totp', 'two_factor', 'allauth', 'allauth.account', 'allauth.socialaccount', 'rest_framework_mongoengine', 'rest_framework', 'corsheaders', 'django_filters'] Installed Middleware: ['corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', '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', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django_otp.middleware.OTPMiddleware'] Traceback (most recent call last): File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\django\contrib\auth\backends.py", line 46, in authenticate user = UserModel._default_manager.get_by_natural_key(username) File "C:\Users\david\AppData\Local\Programs\Python\Python38\lib\site-packages\django\contrib\auth\base_user.py", line 44, in get_by_natural_key return self.get(**{self.model.USERNAME_FIELD: username}) File "C:\Users\david\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\david\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\query.py", line 415, in get raise self.model.DoesNotExist( During handling of the above exception (User matching query does not exist.), another exception occurred: File "C:\Users\david\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\david\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\david\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\david\AppData\Local\Programs\Python\Python38\lib\site-packages\django\views\generic\base.py", … -
TemplateSyntaxError: 'bootstrap4' is not a registered tag library
I installed django-bootstrap4 and added "bootstrap4" to the INSTALLED_APPS parameter in the "settings" file, and {% load bootstrap4 %} in my template. Still I am getting the error: TemplateSyntaxError: 'bootstrap4' is not a registered tag library.' Here is a message from Terminal about Bootstrap is successfully installed Here is Bootstrap added to Installed apps and "index.html" And here is an error: Can anyone help to fix this? I did not find any relative answers under other posts. -
how to redirect the user to another view after filling in a django form?
I created a form from django, and I would redirect the user to another page of my application (another url) once the user has filled out the form. The form is in the 'data/celiac' url ('celiac.html'), and I would like to redirect it to the 'data/cdr3' url. After writing the following code, when the user completes the form, he is redirected to the same url 'data/celiac'. What should I change in my code in order to be redirected to the 'data/cdr3' url please? CeliacViews: def CeliacView(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = forms.CeliacForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required columns = form.cleaned_data['columns'] algo = form.cleaned_data['algo'] context = {'form': forms.Cdr3Form()} return render(request, 'data/cdr3.html', context) else: tableData = get_table_data_to_representation() context = {'form': forms.CeliacForm(), 'tableData': tableData} return render(request, 'data/celiac.html', context) Cdr3Views: def Cdr3View(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: my_form = forms.Cdr3Form(request.POST) … -
djongo.models has no attribute 'ArrayModelField'
Hi I'm using djongo to connect my Django app with MongoDB and I am following the djongo documentation: https://djongo.readthedocs.io/docs/array-model-field/ I want to add an ArrayModelField to the my models: 20 class succesfull_injections(models.Model): 21 sqli = models.CharField(max_length=100) 22 23 class Meta: 24 abstract = True 25 26 class attack(models.Model): 27 succesfullInjections = models.ArrayModelField( 28 model_container = succesfull_injections, 29 ) 30 successSQLI = models.CharField(max_length=100) 31 time = models.CharField(max_length = 100) 32 triedInjections = models.CharField(max_length = 100) But when I migrate or makemigrations the following error shows: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/jagl/.virtualenvs/django-getting-started/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/jagl/.virtualenvs/django-getting-started/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/home/jagl/.virtualenvs/django-getting-started/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/jagl/.virtualenvs/django-getting-started/lib/python3.6/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/jagl/.virtualenvs/django-getting-started/lib/python3.6/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/jagl/Documents/Learning/Programming/Django/django-getting-started/meeting_planner/reports/models.py", line 27, in <module> class attack(models.Model): … -
Is there any method to update and create form data using the same url and view in django?
I am creating a form which is able to create a post if not existed or update the post if already existed. I want to do it using the same url and view. The django generic class view uses two urls for this. Although I was able to create a post but for updating, I can't fetch the existing data of corresponding foreign key. I would like to update those existing data if some data are already existed inside the database. My code are as follows. models.py class BookDetail(models.Model): book = models.ForeignKey(Book,default=None,on_delete=models.CASCADE) book_summary = models.CharField(max_length=255,null=True) book_details = RichTextUploadingField(blank=True,null=True) timestamps = models.DateTimeField(auto_now_add=True,auto_now=False) updated = models.DateTimeField(auto_now_add=False,auto_now=True) The bookdetails consists of foreign key for book model. I want to create book details using those foreign key. But if the details are already created and the user wants to update those detail, I want it to be updated using same url. I had used update_or_create method of django. But I wasn't able to send form data in the defaults attribute of update_or_create method. How can I create and update those data using same url? -
I am getting this error " RelatedObjectDoesNotExist at /admin/login/ User has no profile." when I tried adding signals
I can get access to admin page normally but when I added this signals.py to my code it throws the error saying user has no profile. If I comment the signals.py file then it again gives me access to the admin panel. Can anyone please help me solve this error? signals.py from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profiles.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() -
How to write algebric expression in django template
I want to write this expression (((33/(33+7))*100) in django template...,Please help me. -
Django file-browser can upload file but can't open file with 404 error
Can you please help about this issue ? I can upload file and existing in the folder. But when open it with 404 error. Here is the setting and error message. in Setting.py INSTALLED_APPS = [ 'grappelli', 'filebrowser', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') FILEBROWSER_DIRECTORY = '' DIRECTORY = '' In urls.py from django.contrib import admin from django.urls import path,include from filebrowser.sites import site urlpatterns = [ path('admin/filebrowser/', site.urls), path('grappelli/', include('grappelli.urls')), path('admin/', admin.site.urls), ] Upload succeed: [enter image description here][1] Error message:[Error Message][2] [1]: https://i.stack.imgur.com/j3nNh.png [2]: https://i.stack.imgur.com/QUx6u.png -
How to get the ID of record in another html?
why i cant get the ID of payment type, even i already print the ID in the html? in my first html (elementary.html) I have this code <select name="gradelevel" id="gradelevel" onchange="ChangeYearList(this.value)"> <option">-- Education Level --</option> {% for ylvl in edulevel %} <option value="{{ylvl.id}}">{{ylvl.Description}}</option> {% endfor %} </select> <div id="txtHint" class="scale-in-center" width="100%"></div> <script> function ChangeYearList(str) { var xhttp; var x = document.getElementById("gradelevel").value; if (str == "") { document.getElementById("txtHint").innerHTML = ""; document.getElementById("demo").innerHTML = x; return; } xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("txtHint").innerHTML = this.responseText; } }; xhttp.open("GET", "{% url 'paymentElementary' %}?payments_ID="+str, true); xhttp.send(); } </script> this is my views.py def paymentElementary(request): paymentsid = request.GET.get('payments_ID') payment = ScheduleOfPayment.objects.filter(Education_Levels=paymentsid).order_by('Payment_Type').distinct('Payment_Type') return render(request, 'accounts/paymentElementary.html', {"payment":payment}) This is my second html (paymentElementary.html) <select id="payments" name ="payments"> <option value="0">-- Payment Type --</option> {% for paymentschedule in payment %} <option value="{{paymentschedule.Payment_Type.id}}">{{paymentschedule.Payment_Type.id}}. {{paymentschedule.Payment_Type}}</option> {% endfor%} </select> this is what it looks like in web view it works like a charm. but when i tried to save it into my database id = request.POST.get('payments') payment = PaymentType(id=id) V_insert_data = StudentsEnrollmentRecord.objects.create( Payment_Type=payment ) this is the error this is the full traceback -
Django: All subsequent tests fail after one test fails
I've moved recently from Python 2.7 to Python 3.8. There's a strange new phenomenon when running the tests, that can be reproduced with this simple example: from django.test import TestCase from users.models import User class TestWTF(TestCase): def setUp(self): self.user = User.objects.create(email='admin@project.com') def test_failure(self): self.assertTrue(False) def test_success(self): pass When test_failure() fails the self.user object doesn't get removed from the DB. It seems like the promised rollback feature just doesn't happen. test_success() and all subsequent tests in the same class will fail with UNIQUE constraint being violated when setUp() tries to create the object again. It doesn't happen in Python 2. A partial output from pytest I'm using: ================================================= test session starts ================================================== platform linux -- Python 3.8.2, pytest-5.4.1, py-1.8.1, pluggy-0.13.1 django: settings: project_sites.settings.tests (from ini) rootdir: /home/emes/devel/project/project, inifile: pytest.ini plugins: django-3.8.0, env-0.6.2, case-1.5.3, cov-2.8.1 collected 2 items [...] =============================================== short test summary info ================================================ FAILED deals/tests/test_wtf.py::TestWTF::test_failure - AssertionError: False is not true FAILED deals/tests/test_wtf.py::TestWTF::test_success - django.db.utils.IntegrityError: UNIQUE constraint failed: use... ================================================== 2 failed in 22.76s ================================================== -
Highlighting searched queries on a Django template with a custom filter
I am trying to highlight the searched query on the searched results page on a Django template. But it isn't working Here's my views.py class SearchResultsView(ListView): model = Challenges template_name = 'mainapp/search_results.html' def get_queryset(self): query = self.request.GET.get('q') object_list = Challenges.objects.filter( Q(title__icontains=query) | Q(description__icontains=query) | Q(challenge_summary__icontains=query) | Q(offered_by__icontains=query) ) return object_list my Django template searched_results.html {% load template_filters %} <div class="row"> {% for object in object_list %} <div class="col-12 mx-auto"> <h3><a href="{{ object.get_absolute_url }}">{{object.title|highlight_search:query}}</a></h3> <p><a href="{{ object.get_absolute_url }}">{{object.challenge_summary|highlight_search:query}}</a></p> <hr> </div> {% endfor %} and my template_filters.py from django import template from django.utils.safestring import mark_safe register = template.Library() @register.filter def highlight_search(text, search): highlighted = text.replace(search, '<span class="highlight">{}</span>'.format(search) return mark_safe(highlighted) -
How to add objects from Django-admin to PostgreSQL database
I am trying to create a simple CRUD-APP wherein I am using PostgreSQL+django+DRF for my project, I created a model after connecting my django-settings to PostgreSQL, I then migrated those models. After that, I imported the data from csv into my 'migrated table'. Now when I tried adding a new object into my migrated-table it gave me the following error: The error is: duplicate key value violates unique constraint "gpuApi_products_pkey" DETAIL: Key (id)=(4) already exists. Error explained: when I migrated my table the pk is id field that generates automatically after the migrations in django, so after the csv file was successfully imported, I tried to create a new object to insert but the id inside the database wasn't be detected by django-admin thereby creating an object with id=4. Is there a better way to import csv into Postgres which will simultaneously update with django-admin and be coherent source for Database. models.py file class Product(models.Model): name = models.CharField(max_length=100) Architecture = models.TextField(blank=True, null=True) Boost_Clock = models.IntegerField(blank=True, null=True) Core_Speed = models.IntegerField(blank=True, null=True) Memory = models.IntegerField(blank=True, null=True) Memory_Speed = models.CharField(max_length=20, blank=True, null=True) Memory_Bandwidth = models.CharField(max_length=20, blank=True, null=True) DVI_Connection = models.CharField(max_length=20, blank=True, null=True) Dedicated = models.CharField(max_length=20, blank=True, null=True) Direct_X = models.CharField(max_length=20, blank=True, null=True) HDMI_Connection … -
Django ManyToMany query with listening in template
I'm struggling with ManytoMany relationship. What i'm trying to do is to get all applications with their coresponding servers ( an application can exist on more then one server ) and list them in template. So far I know how to query for Server using 'prefetch_related' and print them in template but how to query all Applicaions with their corresponding Servers and print them in template ? Example template: 'Some www application','www server','database server for www server'... Thank you in advance. class Server(models.Model): title=models.CharField(max_length=40,unique=True) class Application(models.Model): name = models.CharField(max_length=40,primary_key=True,unique=True) book = models.ManyToManyField(Server) -
DRF - Upload csv file , parse it / clean it , upload it to DB
I have a 2 apps in my Django project : files app sources app The idea is to upload a file and once that file is done, get it from the media directory clean it ( using pandas ) save it to CSV and uploaded it to the DB following the sources model. Questions : How do I link the creation of a new source instance to the file upload? Where should that logic sit on my project ( models.py ? views.py ? another_file.py ? )? Thanks ! -
Change input date form format passed to HTML
Hey :) It might be a silly question, but... {{ todo.due_date }} which should be my default value on this template is passed in format May 26, 2020. How could I change the format so that I could set a default value in a valid format 2020-05-26? edit.html <div class="form-group row"> <label for="dueDate" class="col-sm-2 col-form-label">Due date</label> <div class="col-sm-10"> <input type="date" name="due_date" class="form-control" id="dueDate" value={{ todo.due_date }} required> </div> </div> -
Error while logging in Keycloak in Django app
I've setup mozilla-django-oidc in my Django app and while trying to connect I get the following error message while authenticating: [26/May/2020 16:51:56] "GET /oidc/callback/?error=invalid_request&error_description=Missing+parameter%3A+response_type HTTP/1.1" 302 0 Any idea how to debug this missing parameter? Or maybe find what the name of the parameter that is missing? -
Why Django forms.Form never gets valid data in Django
I've created a form to add a new item to data which has an init data to set as queryset for the modelChoiceField in it, but it is never valid, whenever I submit it just simply refreshes. Forms.py class AddRecipeForm(forms.Form): def __init__(self, *args, **kwargs): self.current_product = kwargs.pop("current_product") super(AddRecipeForm, self).__init__(*args, **kwargs) self.fields['product_size'].queryset = productModels.ProductSizeRelation.objects.filter( product=self.current_product) product_size = forms.ModelChoiceField(queryset=None, widget=forms.Select()) item = forms.ModelChoiceField( queryset=itemModels.Item.objects.all(), widget=forms.Select()) quantity = forms.DecimalField(widget=forms.NumberInput(attrs={ 'steps': '0.01' })) views.py @login_required def add_recipes(request, pk): current_product = get_object_or_404(models.Product, pk=pk) all_recipes = Recipe.objects.filter(product_size__product = current_product) add_recipe_form = forms.AddRecipeForm(request.POST, current_product=current_product) if request.method == 'POST': if add_recipe_form.is_valid(): product_size = add_recipe_form.cleaned_data['product_size'] item = add_recipe_form.cleaned_data['item'] quantity = add_recipe_form.cleaned_data['quantity'] Recipe.objects.create(product_size=product_size, item=item, quantity=quantity) return redirect('add_recipes', pk=current_product.id) else: add_recipe_form = forms.AddRecipeForm(current_product=current_product) context = { 'current_product':current_product, 'add_recipe_form':add_recipe_form, 'all_recipes':all_recipes, } return render(request, 'add_recipe.html', context) it never goes after this line : if add_recipe_form.is_valid(): Any idea what could cause this ? -
'Attribute Error/ function' object has no attribute 'objects' in Django
I am trying to login but getting this error 'function' object has no attribute 'objects', here is my view function, def login(request): if request.method=='POST': email=request.POST['email'] password=request.POST['password'] if register.objects.filter(email=email,password=password).exists(): // Error at this line request.session['login'] = email return render(request,'user_dashboard.html',) messages.info(request,'Login Success.....!') else: messages.warning(request,'Invalid Credentials....!') return redirect('/login') else: return render(request,'login.html',) the database contains valid credentials, Tell me where I am going wrong............ Thanks in advance -
How do i attached an image when submitting a comment form
i am working on a project in django, i have a comment form and want users to be able to submit a comment and attached an image to it. My comment saved in database, but the image i attached to the form does not save in database. What shoud Models.py class Comments (models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, blank=True,null=True) commented_image = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments', null=True, blank=True) comment_post = models.TextField() comment_pic = models.FileField(upload_to='CommentedPics/%Y/%m/%d/', blank=True) active = models.BooleanField(default=True) date = models.DateTimeField(auto_now_add=True) parent = models.ForeignKey('self', null=True, blank=True, related_name='replies', on_delete=models.CASCADE) Forms.py class CommentForm(forms.ModelForm): class Meta: model = Comments fields = ( 'comment_post', 'comment_pic', ) Views.py def comment_view(request, id): post = get_object_or_404(Post, id=id) all_comments = post.comments.filter(active=True, parent__isnull=True).exclude( user__profile__blocked_users__user=request.user, active=True) if request.method == 'POST': # comment has been added form = CommentForm(request.POST, request.FILES) if form.is_valid(): comment = form.save(commit=False) comment.user = request.user comment.commented_image = post parent_obj = None # get parent comment id from hidden input try: # id integer e.g. 15 parent_id = int(request.POST.get('parent_id')) except: parent_id = None # if parent_id has been submitted get parent_obj id if parent_id: parent_obj = Comments.objects.get(id=parent_id) # if parent object exist if parent_obj: # create replay comment object replay_comment = form.save(commit=False) # assign parent_obj to replay comment replay_comment.parent = parent_obj # normal … -
OpenPyXL set number_format for the whole column
I'm exporting some data to Excel and I've successfully implemented formatting each populated cell in a column when exporting into Excel file with this: import openpyxl from openpyxl.utils import get_column_letter wb = openpyxl.Workbook() ws = wb.active # Add rows to worksheet for row in data: ws.append(row) # Disable formatting numbers in columns from column `D` onwards # Need to do this manually for every cell for col in range(3, ws.max_column+1): for cell in ws[get_column_letter(col)]: cell.number_format = '@' # Export data to Excel file... But this only formats populated cells in each column. Other cells in this column still have General formatting. How can I set all empty cells in this column as @ so that anyone, who will edit cells in these columns within this exported Excel file, will not have problems with inserting lets say phone numbers as actual Numbers. -
Django - How to authenticate a user with a query string from any url?
Let's say the user lands on "https://example.com/any/page?token=hhdo28h3do782". What's the recommended way to authenticate and login a user with the query string? I was thinking about creating some sort of catch-all view (I'd also like to know how to do this :D) that calls authenticate(). Then I would have in place a custom backend that would authenticate the user. Is this the ideal way to achieve what I want? Cheers!