Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django REST Framework: Can you mix API views with template views?
I am developing a web application using Django and React, and using Django REST Framework to have them talk to each other. I am trying to create a Django view that could handle both AJAX requests from React code AND render Django HTML templates. To accomplish this, I am using the TemplateHTMLRenderer class from Django REST Framework that I found here. However, when I try to fetch() data from that view from React I do not receive any valid response. Here is my view: # URL: "/" class IndexView(APIView): renderer_classes = [TemplateHTMLRenderer] template_name = "dictionary/index.html" def get(self, request, format=None): definitions = Definition.objects.all() return Response({"definitions": definitions}) And here is how I am trying to fetch() datafrom React: componentDidMount() { fetch("/") .then(response => response.json()) .then(data => { this.setState({ definitions: data }); }, error => { this.setState({ alert('ERROR') }); }) } This code ends up displaying the alert "ERROR". Apparently, my view is not returning a valid JSON object. How can I change it to provide both rendering and API functionality? -
Django form of CreateView not accepting submission after setting default value
My django form made using CreateView is refusing to get submitted because of the inital value I prepopulated it with ( and which is correct ) This is my model : class Post(models.Model): #some code author = models.ForeignKey(User, on_delete=models.CASCADE) #some more code This is my view for the form : class AddPostView(CreateView): model = Post form_class = PostForm template_name = 'add_post.html' def get_initial(self): initial = super(AddPostView, self).get_initial() #Setting the inital value of author in the form to the username of the logged in user initial['author'] = self.request.user.username return initial And this is the form being referred by the above view class PostForm(forms.ModelForm): class Meta: model = Post fields = ('x','y', 'author', 'z', 'm') widgets = { #some code 'author': forms.TextInput(attrs={'class': 'form-control','readonly':'readonly' }), #some more code } Now , When I am trying to submit the form , I am getting the error Select a valid choice. That choice is not one of the available choices. Why is this happening?d -
Error with Pillow library when dockerinzing Django app
I develop Django apps in Windows environnement and deploy my apps in production in Linux server. Python 3.8.3 I have a Django project that works (in dev and prod) and I try to "dockerize" it but I got an error when installing requirements.txt error seems to come from pillow library but even if I remove the Pillow==6.2.1 it doesn't change below the tracelog error requirements.twt Django==2.2.5 django-bootstrap4==1.0.1 django-crispy-forms==1.7.2 django-debug-toolbar==2.0 django-extensions==2.2.9 django-maintenance-mode==0.15.0 django-partial-date==1.2.2 django-safedelete==0.5.2 django-simple-history==2.7.3 django-widget-tweaks==1.4.5 Pillow==6.2.1 python-gettext==4.0 pytz==2019.2 reportlab==3.5.32 selenium==3.141.0 six==1.12.0 soupsieve==1.9.3 sqlparse==0.3.0 urllib3==1.25.6 xlwt==1.3.0 Creating network "coverage_africa_default" with the default driver Building web Step 1/10 : FROM python:3.8.3-alpine ---> 8ecf5a48c789 Step 2/10 : WORKDIR /usr/src/app ---> Using cache ---> 6e7b9e258aae Step 3/10 : ENV PYTHONDONTWRITEBYTECODE 1 ---> Using cache ---> 130a8576b1fa Step 4/10 : ENV PYTHONUNBUFFERED 1 ---> Using cache ---> 6e32ad96bd91 Step 5/10 : RUN apk update && apk add postgresql-dev gcc python3-dev musl-dev ---> Using cache ---> c4010960001d Step 6/10 : COPY requirements/ requirements/ ---> 2591c3840465 Step 7/10 : RUN pip install --upgrade pip && pip install -r requirements/dev.txt ---> Running in defe0caa7725 Collecting pip Downloading pip-20.2.3-py2.py3-none-any.whl (1.5 MB) Installing collected packages: pip Attempting uninstall: pip Found existing installation: pip 20.1.1 Uninstalling pip-20.1.1: Successfully uninstalled pip-20.1.1 Successfully … -
I am rendering HTML template and sending context with it but in fetch response it is not reading that context and showing an error regarding JSON
I am sending context json object to template here in views.py all the things are working properly views.py def adminLogin(request): if request.method == 'GET': return render(request, 'admin/login.html') elif request.method == 'POST': data = request.POST username = data['username'] password = data['password'] user = authenticate(username=username, password=password) if user is not None and isAdmin(user.username): token, created = Token.objects.get_or_create(user=user) context = { "login" : "Done", "token" : token.key, "username" : user.username, "email" : user.email, } print("admin login done") context = dumps(context) return render(request, 'admin/login.html', {"context" : context}) else: print("login unseccesfull") return render(request, 'admin/not-login.html') the context i am catching in javascript and try to read context but i am failed to read that context even i am using JON.parse() and also JSON.stringify() both are not working Template HTML ` var loginForm = document.getElementById("adminLogin"); loginForm.addEventListener('submit', function(event) { event.preventDefault(); const formData = new FormData(this); const searchParams = new URLSearchParams(); for (var pair of formData) { searchParams.append(pair[0], pair[1]); } fetch('http://127.0.0.1:8000/my_admin/login/', { mode: 'cors', method: 'post', headers: { "Content-type": "application/x-www-form-urlencoded; charset=UTF-8" }, body: searchParams, }) .then(res => { var context = JSON.stringify("{{context|escapejs") if (context.login === "Done"){ localStorage.clear(); localStorage.setItem("username", context.username); localStorage.setItem("token", context.token); localStorage.setItem("email", context.email); localStorage.setItem("login", "done"); window.location.href = "http://127.0.0.1:8000/my_admin/"; } }) .catch(function(error) { console.log(error) alert("Something went wrong"); }); }) </script>` -
Django get checkbox data list from HTML
I'm pretty sure that this is something basic, but I'm not really sure on how to do this. Anyway, I'm trying to get all of the selected fields from my checklist, but for some reason, it only returns the last one. For some reason when i try to access the values at 'a' I only get the last value, as a string. TLDR; im getting 'a' variable as a string of 'Wont Print' And i need it to be a list of ['Won't Fail', 'Won't Print'] HTML: {% for q in mquestions %} <h4 class="card-title alert">{{q.text}}</h4> <div class="form-check"> <input class="form-check-input " type="checkbox" name="mult{{q.id}}" id="{{q.id}}" value="{{q.option1}}"> <label class="form-check-label " for="{{q.id}}"> {{q.option1}} </label> <br> <input class="form-check-input" type="checkbox" name="mult{{q.id}}" id="{{q.id}}" value="{{q.option2}}"> <label class="form-check-label" for="{{q.id}}"> {{q.option2}} </label> <br> <input class="form-check-input" type="checkbox" name="mult{{q.id}}" id="{{q.id}}" value="{{q.option3}}"> <label class="form-check-label" for="{{q.id}}"> {{q.option3}} </label> <br> <input class="form-check-input" type="checkbox" name="mult{{q.id}}" id="{{q.id}}" value="{{q.option4}}"> <label class="form-check-label" for="{{q.id}}"> {{q.option4}} </label> <br> </div> {% endfor %} Code part from the view: try: if 'mult' in a: print(request.POST) print(a) print(request.POST.get(a)) except: continue current result: <QueryDict: {'csrfmiddlewaretoken': ['odREEU3kXpGvYZnNHllCBrOS1r9rTFZvejEq5zMGP6t4jLrtw1HHPTmB5BbBOAQg'], 'mult1': ['Won't Fail', 'Won't Print'], 'Submit': ['Submit']}> mult1 Won't Print #### Need this to be ['Won't Fail', 'Won't Print'] -
Logging in view not done when run via pytest
When my methods in a View class are executed by pytest, the logging statements don't produce any outputs on the console. Is that expected behavior or am I missing something? This is the view: import logging from django.views import View logger = logging.getLogger(__name__) class FancyWebhook(View): def post(self, request, *args, **kwargs): logger.info("DUMMY logging") print("DUMMY printing") return HttpResponse(status=200) The logging configuration in configs/settings/test.py: # ... LOGGING = { "version": 1, "disable_existing_loggers": False, "handlers": { "console": {"class": "logging.StreamHandler"}, }, "loggers": { "django": { "handlers": ["console"], "level": os.getenv("DJANGO_LOG_LEVEL", "INFO"), }, }, } The test method: import pytest @pytest.mark.django_db def test_fancy_webook_empty_payload_fails(client): print("calling client.post()...") response = client.post('/pricing/fancywebhook', {}, content_type='application/json') assert response.status_code == 403 Running the test via pytest --ds=config.settings.test only prints the error that assert 301 == 403 to the console, but neither the "DUMMY logging" nor the "DUMMY printing" statements. I'm surely missing the obvious, am I not? -
Python / Django Users Profile Page URL Turkish Character Problem
Its working on my localhost. But my server (centos 7-plesk) dosn't wok same code. Example My user profile link: domain.com/user/Maşuka This link working on my localhost without any problem. But this link auto redirect like this and i give 404 error page: domain.com/user/Ma%25c5%259fuka/ where is problem? How can i fix this. What's the difference between localhost and centos? Why working good only localhost. -
Django Celery Progress Bar
I'm using Celery in my Django project and I'm trying to add a progress bar for the status of the progress of the upload of my data. The script is just a simple API upload script. On the celery Git Hub they provide you with a example with a FOR loop using seconds. However, this is hard coding a time frame on the progress bar than actually pulling the status of the actual function in real time. So my question is, how do I make the progress bar pull the actual status of the script ? Id imagine some sort of Java Script will be needed for this. I am not by any means a Java Script expert. So I appreciate any help everyone can give me on this. Thank you so much ! API SCRIPT def ImportSchools(): AuthTokenP() print("Getting school data from SIS") url = "" payload = {} token = APIInformation.objects.get(api_name="PowerSchool") key = token.key headers = {'Authorization': 'Bearer {}'.format(key)} response = requests.request("GET", url, headers=headers, data = payload) encode_xml = response.text.encode('utf8') pretty_xml = xml.dom.minidom.parseString(encode_xml) pretty_xml_str = pretty_xml.toprettyxml() xml_string = ET.fromstring(encode_xml) schools = xml_string.findall("school") for school in schools: psid = school.find("id").text name = school.find("name").text school_number = school.find("school_number").text low_grade = school.find("low_grade").text … -
Django incorrect filename encoding on uploading file in FileField
I am uploading a file using ajax with non-ascii characters (hindi). After uploading, the filename saved is incorrect, instead of संज्ञा it shows सजञ. Models.py - class PostFile(models.Model): file = models.FileField(upload_to='posts/files/%Y/%m/%d') timestamp = models.DateTimeField(auto_now_add=True) views.py - def ajax_add_post_file(request): file = request.FILES['file'] print(file.name.encode()) # get correct filename encoding model_object = PostFile.objects.create(file=file) print(connection.queries[-1]['sql'].encode()) # get sql which gives the following output on terminal - b'\xe0\xa4\xb8\xe0\xa4\x82\xe0\xa4\x9c\xe0\xa5\x8d\xe0\xa4\x9e\xe0\xa4\xbe.pdf' b'INSERT INTO "posts_postfile" ("file", "timestamp") VALUES (\'posts/files/2020/09/21/\xe0\xa4\xb8\xe0\xa4\x9c\xe0\xa4\x9e.pdf\', \'2020-09-21T12:23:02.184338+00:00\'::timestamptz) RETURNING "posts_postfile"."id"' As you can see, the filename encoding of both the files is different. I am using Django 1.11, python 3, postgres 10 with UTF8 encoding database. How to resolve this? -
Why v-model not working when used in vue.extend?
I have a page structure similiar to this: <main id="app"> <div id="mount-place"></div> </main> <script type="text/x-template" id="my-template"> ...some code here... <input type="text" v-model="address"> ...some other code here... </script> <script> var ExtendedElement = Vue.Extend({ template: '#my-template', data: function() { return { address: {{ some_address|safe }}; // gets values from django } }, mounted: function() { console.log(this.address); // Works just fine } }); new ExtendedElement.$mount('#mount-place'); </script> ...some unimportant logic here... <script> const app = new Vue({ delimiters: ['[[', ']]'], el: '#app' }); </script> And the problem is it renders just fine, but v-model not working i.e. input shows nothing. When accessing it via console it shows values inside vue object. No errors or warnings. -
Why do we use tests.py in django ? or Why need tests?
Explain pls. I am a beginner in this project. I'm reading a book about Django and I didn't understand about test.py -
Aggregating a subquery with multiple OuterRefs in Django
I'm trying to solve an N+1 selects issue. Currently, the code looks something like this, somewhat simplified - the code is really in a DRF serializer and does some other things: for payment in Payment.objects.filter(...): refunds_total = Payment.objects.filter( batch__merchant=obj.batch.merchant, payment_id=obj.id, payment_type="refund", status="success", ).exclude( tab__is_void=True, ).aggregate( total=Sum('amount') ).get('total', 0.0) # Do something with refunds_total. The performance is really bad. What I'd like to do is something like this: refunds = Payment.objects.filter( batch__merchant=OuterRef("batch__merchant"), payment_id=OuterRef("id"), payment_type="refund", status="success", ).exclude( tab__is_void=True ).aggregate(total=Coalesce(Sum("amount"), 0.0)) return Payment.objects.filter( ... ).annotate(total_refunds=Subquery(refunds)) But Django doesn't allow aggregating in a subquery, as aggregating immediately evaluates the QuerySet. I've tried two approaches. The first is following this documentation. However, I'm not sure how I need to put the query together as there are multiple OuterRefs required. My first shot at a subquery looks like this: refunds = CustomerPayment.objects.filter( batch__merchant=OuterRef("batch__merchant"), payment_id=OuterRef("id"), payment_type="CreditRefund", status="success", ).exclude( tab__is_void=True ).order_by().values( "batch__merchant", "payment_id", ).annotate(total_refunds=Coalesce(Sum("amount"), 0.0)).values("amount") But however I try to get it working, it always returns multiple rows rather than single row with the total, so I can't use it in a subquery. I've also tried making my own Subquery subclass but I couldn't put together anything that worked. -
Django channels: what is an efficient way to implement chat notification system?
Currently I am working on a chat system using django channels and I am not able to find an efficient way to implement chat notification system. Can someone please help me. Any idea is appreciated :) So my problems are how can server notify clients if new messages has arrived when they are not in a chat view ? if we use websocket to send new messages from server to client, does it mean, whenever user is logged in one websocket channel is open for each user ? -how many simultaneous websocket channels/connections can django channels support? do we need to have separate websocket channels for chat notifications and sending actual chat messages? It would be great if someone can share their experiences :) :) - Thank you -
Getting error "Uncaught SyntaxError: Unexpected token o in JSON at position 1" in the front-end
I hope all are fine and safe! I am trying this below requirement where there is a voice synthesizer and it converts my voice (which is a question) into a text and it sends that text to the back-end Django through Ajax. I can see that the backend Django is able to get the value from the front-end and using that to get the value from the db and returning it to the front-end(status code is showing as 200 63) But the problem is that at the ajax success part its not getting the value from the back-end and displaying/speaking it. I am sharing both front-end and the back-end part of the requirement. def Answer(request): if request.method=='GET' and request.is_ajax(): question_asked=str(request.GET.get("message_now")) try: answer=QuestionAnswer.objects.filter(question=question_asked).values_list('answer', flat=True)[0] #data={"data1":answer} print(answer) return JsonResponse({"success": True, "data": answer}, status=200) except Exception as e: print(e) return JsonResponse({"success": False}, status=400) else: print("Not Suceess") function chatbotvoice(message){ const speech = new SpeechSynthesisUtterance(); if(message!==null && message!==''){ $.ajax({ url: "http://127.0.0.1:8000/getanswer", dataType: 'json', type: 'GET', data: { message_now:message }, success: function (data) { var yourval = JSON.parse(data); speech.text=yourval; window.speechSynthesis.speak(speech); chatareamain.appendChild(showchatbotmsg(speech.text)); }, error: function(error){ speech.text = "Oh No!! I don't Know !! I am still learning!! Your question got recorded and answer for your question will … -
def __str__(self) issue - Django
I'm trying to print the title of the first object in my DB in django. However, when I enter the command Project.objects.all() in the shell, it just returns the following: <QuerySet [<Project: Project object (1)>]> This is my code: # Create your models here. class Project(models.Model): title = models.CharField(max_length=100) progress = models.FloatField(default=0) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self.title): return self.title class Task(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) title = models.CharField(max_length=100) priority = models.SmallIntegerField(default=0) open_date = models.DateTimeField() close_date = models.DateTimeField() status = models.SmallIntegerField(default=0) def __str__(self.title): return {self.title} The str part doesn't seem to be doing anything, even when I purposely misspell something, no error is returned. There seems to be a few threads with similar issues with no accepted solutions as of yet. I would like it to return the title that I've entered, which should be <QuerySet [<Project: My First Project>]>. Thanks in advance for your help. -
Hwo to convert array into Comma Saperated string in python?
I Have following Array in python, [4,5,6] i want my output as ['4','5','6'] How to Do that? -
Django: how to set value to not displayed form field? 'WSGIRequest' object has no attribute 'seller'
I can not solve my issue. I need help, it will be really kind :) channel and consumer are automatically set thanks to the view "form.instance". But I don't know how to do the same with seller. Important, the page is dedicated to two user: seller and consumer. Only consumer can give a review. The page is a channel. So what's the best way to set automatically seller value? class Channel(models.Model): consumer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="channel_consumer", blank=True, null=True) name = models.CharField(max_length=10) seller = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="channel_seller") class Rating(models.Model): channel = models.OneToOneField(Channel,on_delete=models.CASCADE,related_name="rating_channel") consumer = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.CASCADE,related_name='rating_consumer') seller = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.CASCADE,related_name='rating_seller') is_rated = models.BooleanField('Already rated', default=True) comment = models.TextField(max_length=200) publishing_date = models.DateTimeField(auto_now_add=True) ratesugar = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(5)]) def __str__(self): return self.channel.name views.py ... def form_valid(self, form): if form.is_valid(): form.instance.channel = self.object form.instance.seller = self.request.seller.userprofile.pk form.instance.consumer = self.request.user form.save() return super(ChannelReview, self).form_valid(form) else: return super(ChannelReview, self).form_invalid(form) forms.py class ChannelRatingForm(forms.ModelForm): def __init__(self,*args,**kwargs): super(ChannelRatingForm, self).__init__(*args,**kwargs) self.helper = FormHelper() self.helper.form_method="post" self.helper.layout = Layout( Field("comment",css_class="form-control",style="margin-bottom:10px",rows="1"), Field("ratesugar",css_class="single-input"), ) self.helper.add_input(Submit('submit','Review',css_class="btn btn-primary single-input textinput textInput form-control")) class Meta: model = Rating widgets = { 'comment':forms.TextInput(attrs={'class':'','style':'','placeholder':'What a cook!'}), } fields = [ 'comment', 'ratesugar', ] -
Python Script Nor Running In PythonAnywhere
I am working on a Django project. It includes a functionality in which when admin clicks on a certain button, it runs a Python script and redirect it to some other page after complete process. Before hosting, it was working fine. Now that I hosted it here, the script doesn't run at all. It just redirects to another page without providing any error. Why's that? Also, my script includes chromedriver, in case it has anything to do with it. Kindly help me. This might be the error. Why doesn't it recognize it? Code out = run([sys.executable, '//home//maisum279//traffic//traffic//trafficapp//traffic.py', "--domain", url, "--threads", '5', "--max-clicks", maximum, "--min-clicks", minimum, "--stay", stay, "--requests", requests]) Server Log 2020-09-21 11:05:02 /usr/local/bin/uwsgi: unrecognized option '--domain' 2020-09-21 11:05:02 getopt_long() error The script is in Python, but now it seems to be running with uswgi. What can I do make it work? Please help. -
cannot unpack non-iterable bool object(when trying to filter result for user registered in auth>User module)
I’m Creating One django based web app and I have used Auth> User model(without any customization except password hiding) and for user detail I have created another model ChangeShift and model based form. case1: when i am using alluser = ShiftChange.objects.all()i'm able to see all the data available in ShiftChange model. Case2: Now i want that when user is logging he should be able to see data related to his name and i'm using def retrieve_view(request): # alluser = ShiftChange.objects.all() alluser = ShiftChange.objects.filter(ShiftChange.ldap_id == request.user.username) return render(request, 'apple/shift2.html', {'alluser': alluser}) for this i am getting error: cannot unpack non-iterable bool object Please find the below Trace [21/Sep/2020 11:13:18] "GET /static/css/auth.css HTTP/1.1" 404 1662 Internal Server Error: /alldata/ Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/shaileshyadaav/djangoshaileshdurga/mapsIT/apple/views.py", line 53, in retrieve_view alluser = ShiftChange.objects.filter(ShiftChange.ldap_id == request.user.username) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/query.py", line 942, in filter return self._filter_or_exclude(False, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/query.py", line 962, in _filter_or_exclude clone._filter_or_exclude_inplace(negate, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/query.py", line 969, in _filter_or_exclude_inplace self._query.add_q(Q(*args, **kwargs)) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1358, in add_q clause, _ = self._add_q(q_object, … -
Django upload image using page slud/id
I'm trying to add the ability to upload an image to a post but having issues. The image field is in its own model but uses a foreign key to show which post it relates to. At the moment the upload button does not post the form but also how would I use the post page url/slug/id as the image foreign key. Would i need to call it in the html post page? views.py def designUpload(request): if request.method == 'POST': form = ImageForm(request.POST, request.FILES) if form.is_valid(): form.save() return render(request, 'users/dashboard.html') else: form = ImageForm() return render(request, 'users/dashboard.html', { 'form': form }) **models.py** class Designs(models.Model): forbrief = models.ForeignKey(Brief, on_delete=CASCADE) postedby = models.ForeignKey(User, on_delete=models.CASCADE, null=True) design = models.ImageField(null=True, blank=True) date = models.DateTimeField(auto_now=True, blank=True) forms.py class ImageForm(forms.ModelForm): class Meta: model = Designs fields = ["design",] HTML Form <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="image" name="mydesign"> <button type="submit">Upload</button> </form> -
Django braces PermissionRequiredMixin raise 403 forbidden even on assigned permission
I'm working on a django(3) project in which I have a Course model and on signup I'm assigning the permission to Can add course but when I hit the the CourseCreate view which is using PermissionRequiredMixin it returns 403 forbidden Here's my code: User registration view: if request.method == 'POST': print('get post req') if form.is_valid(): user = form.save(commit=False) user.is_active = True user.save() if form.cleaned_data['is_instructor'] is True: permission = Permission.objects.get(name='Can add course') instructor_group = Group.objects.get(name='instructor') user.groups.add(instructor_group) user.user_permissions.add(permission) return HttpResponseRedirect(reverse_lazy('users:login')) else: print(form.errors) CreateCourse View: class CreateCourse(LoginRequiredMixin, PermissionRequiredMixin, CreateView): model = Course fields = ['title', 'subject', 'slug', 'overview', 'course_image'] template_name = 'courses/create_course.html' permission_required = 'courses.add_course' login_url = reverse_lazy('users:login') raise_exception = True I confirmed in admin that the permission is selected for the user successfully. -
How send table with form?
How i can send my table on server? I do not need html code, i want send only table data. This is my table: <table> <tr> <th>Company</th> <th>Contact</th> <th>Country</th> </tr> <tr> <td>Alfreds Futterkiste</td> <td>Maria Anders</td> <td>Germany</td> </tr> <tr> <td>Centro comercial Moctezuma</td> <td>Francisco Chang</td> <td>Mexico</td> </tr> <tr> <td>Ernst Handel</td> <td>Roland Mendel</td> <td>Austria</td> </tr> </table> This is my form: <form action="/actionpage" method="post"> <label for="fname">First name:</label> <input type="text" id="fname" name="fname"><br><br> <label for="lname">Last name:</label> <input type="text" id="lname" name="lname"><br><br> // How? **<label for="table">Table Rows</label> <input type="text" id="table" name="table"><br><br>** <input type="submit" value="Submit"> </form> How i can paste my table in form? May be exists special tag like a INPUT? -
upload file and other attributes with AJAX django
I want to upload my file with some other attributes using AJAX My AJAX code: var file = $('#uploaded-file').get(0).files[0] if (file != null) { var reader = new FileReader() reader.onload = function () { var filedata = reader.result; $.ajax({ url: '/upload_file', type: 'POST', dataType: 'json', headers: { 'X-CSRFToken': '{{ csrf_token }}' }, data:JSON.stringify({'data':filedata, 'name':file.name}), success: function (response) { console.log(response) }, error: function (response) { console.log(response) } }) }; reader.readAsArrayBuffer(file) } My Djnago view.py: def upload_file(request): print(json.loads(request.body)) return JsonResponse({'response':'request done'}) however i am not getting file data in my request body {'data': {}, 'name': 'abc.csv'} what i am missing here? -
Django Google Authentication Doesn't Work
I'm trying to implement the simplest google authentication to my django portfolio website using 'social_django', but whenever I go to my login page I get the 404 error, I tried moving the urls from portfolio to my main app but it didn't work: Using the URLconf defined in MyPortfolio.urls, Django tried these URL patterns, in this order: portfolio/ [name='index'] portfolio/ login/ ^login/(?P<backend>[^/]+)/$ [name='begin'] portfolio/ login/ ^complete/(?P<backend>[^/]+)/$ [name='complete'] portfolio/ login/ ^disconnect/(?P<backend>[^/]+)/$ [name='disconnect'] portfolio/ login/ ^disconnect/(?P<backend>[^/]+)/(?P<association_id>\d+)/$ [name='disconnect_individual'] portfolio/ logout/ [name='logout'] admin/ The current path, portfolio/login/, didn't match any of these. Here is my settings.py : (only changes are included) INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'portfolio', 'social_django' ] AUTHENTICATION_BACKENDS = ( 'social_core.backends.google.GoogleOAuth2', 'django.contrib.auth.backends.ModelBackend', ) SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = '**code here**' SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = '**code here**' LOGIN_URL = '/auth/login/google-oauth2/' LOGIN_REDIRECT_URL = '/' LOGOUT_REDIRECT_URL = '/' SOCIAL_AUTH_URL_NAMESPACE = 'social' My main app urls: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('portfolio/', include('portfolio.urls')), path('admin/', admin.site.urls) ] My portfolio app urls: from django.urls import path, include from django.conf import settings from django.contrib.auth.views import auth_logout from . import views app_name = 'portfolio' urlpatterns = [ path('', views.index, name='index'), path('login/', include('social_django.urls', namespace='social')), path('logout/', auth_logout, {'next_page': settings.LOGOUT_REDIRECT_URL}, name='logout') ] Portfolio app views: from … -
wagtail pagination, django, wagtail, python
I would be very grateful if someone can help me out on this. I am developing a wagtail site but am short on configuring pagination which when clicking through (ie it just returns the page but not the results), so I have pagination working but when I click, it just returns the page number but does not return the actual model. My code is this: from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator class BlogIndexPage(RoutablePageMixin, Page): introduction = models.TextField( help_text='Text to describe the page', blank=True) image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+', help_text='Landscape mode only; horizontal width between 1000px and 3000px.' ) content_panels = Page.content_panels + [ FieldPanel('introduction', classname="full"), ImageChooserPanel('image'), ] def children(self): return self.get_children().specific().live() def get_context(self, request, *args, **kwargs): context = super(BlogIndexPage, self).get_context(request, *args, **kwargs) all_posts = BlogPage.objects.descendant_of( self).live().order_by( '-date_published') paginator = Paginator(all_posts, 9) page = request.GET.get("page") try: posts = paginator.page(1) except PageNotAnInteger: paginator.page(1) except EmptyPage: posts = paginator.page(paginator.num_pages) context["posts"] = posts return context in my html I have the following: {% extends "base.html" %} {% load wagtailcore_tags navigation_tags wagtailimages_tags %} {% block content %} {% include "base/include/header-index.html" %} <div class="col-12"> {% if tag %} <p>Viewing all blog posts by <span class="outline">{{ tag }}</span></p> {% endif %} {% if page.get_child_tags …