Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
the filename of pdf file doesnt work correctly with wkhtmltopdf
I have a button download in my Django project, where I can export the report for a certain date in a pdf format. Everything works fine on my laptop with Linux, but when I set the project in the local server of our company, the name of the file is showing without a date. Here is my code: template_name = 'pdf.html' template = get_template(template_name) html = template.render({"data": data, "date":date, "index":index}) if 'DYNO' in os.environ: print('loading wkhtmltopdf path on heroku') WKHTMLTOPDF_CMD = subprocess.Popen( ['which', os.environ.get('WKHTMLTOPDF_BINARY', 'wkhtmltopdf-pack')], stdout=subprocess.PIPE).communicate()[0].strip() else: print('loading wkhtmltopdf path on localhost') WKHTMLTOPDF_CMD = ('/usr/local/bin/wkhtmltopdf/bin/wkhtmltopdf') config = pdfkit.configuration(wkhtmltopdf=WKHTMLTOPDF_CMD) options = { 'margin-bottom': '10mm', 'footer-center': '[page]' } pdf = pdfkit.from_string(html, False, configuration=config, options=options) response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="otchet-{}.pdf"'.format(date) return response when I download locally, the name of the file is - otchet-2021-06-30.pdf but on server, it looks like - otchet%20.pdf I have no idea, how to fix it... -
How to let AJAX read python render variable to HTML?
PLEASE HELP (T_T), I'm a new django learner. My question is how do I write Ajax to load my {{channel_mlx90614}} that I render from views.py ? I wanted to create a button to refresh the data from python, So I render the data from Views.py in Django, which is {{channel_mlx90614}}, but I wanted to button click refresh the data value when my firebase database data is changed, which in asynchronous way instead of refreshing the browser. **view.py** firebase = pyrebase.initialize_app(config) db = firebase.database() def index(request): channel_mlx90614 = db.child('mlx90614').child('1-set').child('ambient').get().val() if channel_mlx90614 >= 37.5: temperature_note = "High Temperature alert !" elif channel_mlx90614 <= 37.5: temperature_note = "Normal Temperature !" else: temperature_note = "No temperature detected !" return render(request, 'mysite1/index.html', { "channel_mlx90614":channel_mlx90614, "temperature_note":temperature_note }) **sample.html** <button id="myBtn">Try it</button> <p id="demo"></p> <script> document.getElementById("myBtn").addEventListener("click", displayDate); function displayDate() { document.getElementById("demo").innerHTML = "{{channel_mlx90614}}"; } <script language="javascript"> $(function(){ $(".myBtn").click(function(){ $("#demo").load( ????? ); // How to read {{channel_mlx90614}} render from python to html? }); }); </script> -
How to get active and inactive plans from M2M field in Django
I've three models named as E_Office, Plans and UserPlanSubscription. E_Office model have all the information about e-office and it is independent (not connected with any model like ForeignKey ), Plans models have all the plans information and it is connected with E_Office model using ManyToManyField and UserPlanSubscription model is stores Plans using ForeignKey. My problem is I want to separate active plans(which is stored in my UserPlanSubscription) and inactive plans (whole data from E_Office excluding active plans) and display it on page active plans will appear in white and inactive will appear in black I've tried like this given below but it's not scalable if data is more than thousand so please help me to improve my code. Plans model class Plans(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True) plan_name = models.CharField(max_length=255, null=True) plan_price = models.CharField(max_length=255, null=True) access_to = models.ManyToManyField(Add_e_office) UserPlanSubscription model class UserPlanSubscription(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE,null=True,blank=True) plan = models.ForeignKey(Plans, on_delete=models.CASCADE,null=True,blank=True) paid = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now=False, auto_now_add=True, null=True) expiry_date = models.DateTimeField(auto_now=False, auto_now_add=False,null=True) views.py @login_required def my_eoffice(request): context = {} mydata = [] left_plans = [] context['plans'] = Plans.objects.all() if UserPlanSubscription.objects.filter(user=request.user,expiry_date__gte=datetime.datetime.now()).exists(): # Active Plans user_plans = UserPlanSubscription.objects.get(user=request.user) active_plan = user_plans.plan.access_to.all() mydata.append({'active_plan':active_plan}) myeoffice = E_Office.objects.all() # want to improve for i in … -
trying to get a Django 3.2 app recognized in python 3.9
I'm trying my hand at Django 3.2. I installed the app, and followed what I could from the guidance, and I seem to can't to get the app module to be recognized. Here's my steps to reproduce the problem: in terminal django-admin startproject research django-admin startapp landing Then I made the following file changes: landing\__init__.py default_app_config = 'landing.apps.LandingConfig' landing\apps.py from django.apps import AppConfig class LandingConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'landing' landing\models.py (trying to add stripe in future release) from django.db import models # Create your models here. class StripeSubscription(models.Model): start_date = models.DateTimeField(help_text="The start date of the subscription.") status = models.CharField(max_length=20, help_text="The status of this subscription.") # other data we need about the Subscription from Stripe goes here class MyStripeModel(models.Model): name = models.CharField(max_length=100) stripe_subscription = models.ForeignKey(StripeSubscription, on_delete=models.SET_NULL) landing\urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] landing\views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse("Hello, world. You're at the landing index.") settings.py - Installed apps INSTALLED_APPS = [ 'landing.apps.LandingConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles' ] urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('landing/', include('landing.urls')), ] … -
Wouldn't login with email in Django
I'm trying to login with email and password in Django. This works with username and password. import requests from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import authenticate, login, logout from django.contrib import messages from django.views.decorators.csrf import csrf_exempt from django.views.decorators.csrf import csrf_exempt from .forms import PlayerCreationForm # REGISTER VIEW def register_view(request): if request.method != 'POST': form = PlayerCreationForm() else: form = PlayerCreationForm(request.POST) if form.is_valid(): form.save() requests.post('http://127.0.0.1:5000/credentials', json={'email': form.cleaned_data['email'], 'username': form.cleaned_data['username'], 'password': form.cleaned_data['password2']}) return redirect('/login') context = {'form': form} return render(request, "register.html", context) # LOGIN VIEW def login_view(request): if request.user.is_authenticated: return redirect('/') if request.method == 'POST': email = request.POST.get('email') password = request.POST.get('password') user = authenticate(request, email=email, password=password) if user is not None: login(request, user) return redirect('/') else: messages.info(request, 'Incorrect email or password') return render(request, 'login.html') # LOGOUT VIEW def logout_view(request): logout(request) return redirect('/') # HOMEVIEW def home_view(request): return render(request, "base.html") Do I need a different configuration to make user login with email? I the old username and password with email and password. I also reconfigured login.html to make it work with email and password. Is there anything wrong here? -
Imagefield in Django doesn't upload image
I was trying to work in my blog project so i make a create-post page where i can create blog posts . but it seems that the imagefield doesn't upload image . though it works on if i upload image from admin panel. I have created MEDIA URL and MEDIA ROOT and connected them in url so my code should work according to me and also in html form I have perfectly written enctype attr so i made a Imagefield in Model and connected that with form and using view I tried to make create post related code : models.py enter image description here this is the model file form.py: enter image description here view.py: enter image description here create-post.html: enter image description here urls.py enter image description here from the website page : enter image description here in the admin panel: enter image description here -
Django Value Error "The view capstone.views.home didn't return an HttpResponse object. It returned None instead."
I'm taking data that the user puts into a form and saving it to the database in Django. When I submit the form, the value actually does save to the database. But I keep getting this error. Not sure how to fix it? views.py def home(request): if request.method == "GET": form_for_post = {'form': PostForm()} return render(request, "capstone/home2.html", form_for_post) else: if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): city = form.cleaned_data['city'] place = Location.objects.create(username=request.user, city=city,) place.save() else: return render(request, "capstone/home2.html") models.py class User(AbstractUser): pass class Location(models.Model): city = models.CharField(max_length=500) username = models.ForeignKey('User', on_delete=models.CASCADE, related_name='author', null=True, blank=True) forms.py: class PostForm(forms.Form): city = forms.CharField(max_length=500) Form in html: <form method="POST"> {% csrf_token %} <label for="city">City:</label><br> <input type="text" id="city" name="city"><br> <input type="submit" value="Submit"> </form> -
Wagtail(Django) ModelAdmin Button view action
i want to put a button into wagtail admin for inspect in view mode, by default edit and delete are shown, but i don't know what need to do for call a view that contain only view of a model here is my code: products.models.py class CamisaOrder(models.Model): STATUS_CHOICES = ( ('PAYMENTVERFICATION','Verificacion Forma Pago'), ('PROCESSINGORDER','Procesando Orden'), ('MAKING','Elaboracion'), ('PROCESSINGSHIPING','Preparando Envio'), ('SHIPPED','Enviado'), ('DELIVERED','Recibido'), ('CANCELED','Cancelado'), ('RETURNED','Retornado'), ) camisa = models.ForeignKey('CamisetaProduct',related_name='+', on_delete= models.PROTECT) cantidad = models.IntegerField() status = models.CharField(max_length=20, null=False, blank=False, choices=STATUS_CHOICES, default="PROCESSINGORDER") panels = [ FieldPanel('camisa'), FieldPanel('cantidad'), FieldPanel('status') ] class Meta: verbose_name="Camisa Orden" verbose_name_plural="Camisas Ordenes" wagtail_hooks.py class ProductButtonHelper(ButtonHelper): view_button_classnames = ['button-small', 'icon', 'icon-site'] def view_button(self, obj): # Define a label for our button text = 'View {}'.format(self.verbose_name) logging.debug(obj) return { 'url': #url here for inspect model# 'label': text, 'classname': self.finalise_classname(self.view_button_classnames), 'title': text, } def get_buttons_for_obj(self, obj, exclude=None, classnames_add=None, classnames_exclude=None): btns = super().get_buttons_for_obj(obj, exclude, classnames_add, classnames_exclude) if 'view' not in (exclude or []): btns.append( self.view_button(obj) ) return btns class CamisetaOrderAdmin(ModelAdmin): model = CamisaOrder button_helper_class = ProductButtonHelper menu_label = 'Pedidos y Ordenes' menu_icon = 'mail' menu_order = 200 add_to_settings_menu = False exclude_from_explorer = False list_display = ('camisa', 'cantidad', 'status') list_filter = ('status',) search_fields = ( 'status',) modeladmin_register(CamisetaOrderAdmin) how i can achieve this approach? i need to … -
Problem with migrating my Database using Django
I currently have a database using Heroku and want to migrate it to AWS, where both use PostgresSQL. So, after some digging on how to get it done I followed the steps as on this youtube video. I initially ran python manage.py dumpdata > dumpdata.json with my Heroku database credentials in Django. Afterwards, I changed my database credentials in settings.py to the AWS database credentials, and ran python manage.py migrate --run-syncdb which worked successfully. And then I ran the code python manage.py loaddata dumpdata.json, when where I was thrown by an error. The following error came up... django.db.utils.IntegrityError: Problem installing fixture 'C:\Users\Acer\Desktop\Web Development\Proffesional\eblossom\eblossom\eblossom\dumpdata.json': Could not load contenttypes.ContentType(pk=9): duplicate key value violates unique constraint "django_content_type_app_label_model_76bd3d3b_uniq" DETAIL: Key (app_label, model)=(user, profile) already exists. I don't understand what has gone wrong over here, the site is working perfectly fine all this time with no database compilation error, but now when I try to migrate it to AWS, I am thrown with this problem. Just in case my models.py.... class Profile (models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) mobile_number = models.CharField(max_length=12, null=True) guest = models.BooleanField(default=False) def __str__(self): return f"{self.user}" Any help would be greatly appreciated. Thanks! -
How to iterate over the matches in django?
I'm sending notifications to a user via Django notifications, and I have username regex working on the HTML so anyone posts with @username it will post and the HTML is linkable so click on the @username it will take anyone to the username profile page. Now I am using Django signals to match the username and print out the username. When I'm using two or three @usernames the notification goes to only for one @username other two @username do not get the notifications. Models.py- class post(models.Model): parent = models.ForeignKey("self", on_delete=models.CASCADE, blank=True, null=True) title = models.CharField(max_length=100) image = models.ImageField(upload_to='post_pics', null=True, blank=True) video = models.FileField(upload_to='post_videos', null=True, blank=True) content = models.TextField() likes = models.ManyToManyField(User, related_name='likes', blank=True) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) objects = postManager() def __str__(self): return self.title class Meta: ordering = ['-date_posted', 'title'] def get_absolute_url(self): return reverse ('blog-home') def total_likes(self): return self.likes.count() def post_save_receiver(sender, instance, created, *args,**kwargs): if created and not instance.parent: user_regex = r'@(?P<username>[\w.@+-]+)' m = re.search(user_regex, instance.content) if m: username = m.group("username") notify.send(instance.author, recipient=m, actor=instance.author, verb='tagged you', nf_type='tagged_by_one_user') post_save.connect(post_save_receiver, sender=post) -
How to convert nav-pill to bootstrap pagination
I am trying to convert this nav-pills: <div class="col-auto"> <ul class="nav nav-pills" id="evidence-formset-tab" role="tablist"> {% for evidence_form in evidence_formset %} {% with index=forloop.counter|stringformat:'s' %} {% with id='evidence-form-'|add:index|add:'-tab' href='#evidence-form-'|add:index aria_controls='evidence-form-'|add:index %} <li class="nav-item"> {% if not current_tab and forloop.first or current_tab == index %} <a class="nav-link active" id="{{ id }}" data-toggle="pill" href="{{ href }}" role="tab" aria-controls="{{ aria_controls }}" aria-selected="true">{{ forloop.counter }}</a> {% else %} <a class="nav-link" id="{{ id }}" data-toggle="pill" href="{{ href }}" role="tab" aria-controls="{{ aria_controls }}" aria-selected="false">{{ forloop.counter }}</a> {% endif %} </li> {% endwith %} {% endwith %} {% endfor %} </ul> </div> <!-- .col --> To this pagination: <nav aria-label="Page navigation example"> <ul class="pagination" id="evidence-formset-tab" role="tablist"> <li class="page-item"><a class="page-link" href="#">Previous</a></li> {% for evidence_form in evidence_formset %} {% with index=forloop.counter|stringformat:'s' %} {% with id='evidence-form-'|add:index|add:'-tab' href='#evidence-form-'|add:index aria_controls='evidence-form-'|add:index %} {% if not current_tab and forloop.first or current_tab == index %} <li class="page-item active"> <a class="page-link" id="{{ id }}" data-toggle="tab" href="{{ href }}" aria-controls="{{ aria_controls }}" aria-selected="true">{{ forloop.counter }}</a> </li> {% else %} <li class="page-item"> <a class="page-link" id="{{ id }}" data-toggle="tab" href="{{ href }}" aria-controls="{{ aria_controls }}" aria-selected="true">{{ forloop.counter }}</a> </li> {% endif %} {% endwith %} {% endwith %} {% endfor %} <li class="page-item"><a class="page-link" href="#">Next</a></li> </ul> </nav> But for some … -
How can i delete item in django?
So can someone help me how can i delete the item in tech with tim django todo app project? I really need this one to understand how delete works and models in django. This is the source code for tech with tim django todo app -
Django Model Forms including Foreign Key Fields
I am trying to create a Model Form in Django that includes Foreign Key fields from the Athlete Table. Normally when referring to the Foreign Key fields I can use the field name 'athlete' then.followed by the field name. This does not seem to be working. I have tried using a queryset using the ModelChoiceField but think I am not setting this up correctly. Thanks in advance for any help. This is the main Model (ASP Bookings) including the Foreign Key Athlete class ASPBookings(models.Model): asp_booking_ref = models.CharField(max_length=10, default=1) program_type = models.CharField(max_length=120, default='asp') booking_date = models.DateField() booking_time = models.CharField(max_length=10, choices=booking_times) duration = models.CharField(max_length=10, choices=durations, default='0.5') street = models.CharField(max_length=120) suburb = models.CharField(max_length=120) region = models.CharField(max_length=120, choices=regions, default='Metro') post_code = models.CharField(max_length=40) organisation_type = models.CharField(max_length=120,choices=organisation_types, default='Government School') audience_number = models.CharField(max_length=10) presentation_form = models.CharField(max_length=120, choices=presentation_form_options, default='Face to Face') contact_name = models.CharField(max_length=80) email = models.EmailField() phone_number = models.CharField(max_length=120) comments = models.TextField() status = models.CharField(max_length=80, choices=statuses, default='TBC') email_sent = models.BooleanField(default=False) athlete = models.ForeignKey(Athlete, default= '1', on_delete=models.CASCADE) def __str__(self): return self.contact_name # return URL after the POST has been submitted. def get_absolute_url(self): return reverse('vistours:success') Athlete Model class Athlete(models.Model): athlete_ref = models.CharField(max_length=10, default=1) athlete_name = models.CharField(max_length=80) email = models.EmailField() phone_number = models.CharField(max_length=120) home = models.CharField(max_length=120) education = models.CharField(max_length=120) sport … -
What's up? You didn't select a choice. Django Pull apps
I am testing Django apps. In part 4, I am done creating from. There must be a radio button. <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"> as the code suggests. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>James-Cameron-Teaches-Filmmaking</title> </head> <body> <form action="{% url 'polls:vote' question.id %}" method="post"> {% csrf_token %} <fieldset> <legend><h1>{{ question.question_text }}</h1></legend> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} {% for choice in question.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br> {% endfor %} </fieldset> <input type="submit" value="Vote"> </form> </body> </html> this is the HTML I am using. This is the code for my view: from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404, render from django.urls import reverse from django.views import generic from .models import Choice, Question class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): """Return the last five published questions.""" return Question.objects.order_by('-pub_date')[:5] class DetailView(generic.DetailView): model = Question template_name = 'polls/detail.html' class ResultsView(generic.DetailView): model = Question template_name = 'polls/results.html' def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'polls/detail.html', { 'question': question, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes … -
Django find logged in user
I am trying to send data from sensor connected to an ESP8266 to a Django webserver but I can't send which user those readings belong to. I already put user as a foreign key in sensor model but how can I get the user ID. the request.user part doesn't return anything as user isn't known by the ESP @csrf_exempt def index(request): # current_user = request.user print("\n") data = json.loads(request.body) type1 = data.get("sensorType1", None) heart_rate = data.get("reading", None) type2 = data.get("sensorType2", None) spo2 = data.get("SpO2", None) sensor = Sensor() # print(current_user) print(type1) print(heart_rate) print(type2) print(spo2) # sensor.user = current_user sensor.SensorType1 = type1 sensor.HeartRate = heart_rate sensor.SensorType2 = type2 sensor.SpO2 = spo2 sensor.save() return render( request, "reading.html", ) -
django celery beat periodic task admin page loading error
I am using django_celery_beat and mongodb as my database. I am able to make migrations for django_celery_beat but when I was trying get access to the admin page on my local, http://127.0.0.1:8000/admin/django_celery_beat/periodictask/. I am facing a DatabaseError at /admin/django_celery_beat/periodictask/. specfically: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/admin/django_celery_beat/periodictask/ Django Version: 3.0.5 Python Version: 3.8.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'Reddit_app', 'crispy_forms', 'phonenumber_field', 'sorl.thumbnail', 'social_django', 'bootstrap4', 'ckeditor', 'ckeditor_uploader', 'django_celery_results', 'django_celery_beat'] 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.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware'] Template error: In template /Applications/anaconda3/lib/python3.8/site-packages/django/contrib/admin/templates/admin/base.html, error at line 0 (Could not get exception message) 1 : {% load i18n static %}<!DOCTYPE html> 2 : {% get_current_language as LANGUAGE_CODE %}{% get_current_language_bidi as LANGUAGE_BIDI %} 3 : <html lang="{{ LANGUAGE_CODE|default:"en-us" }}" {% if LANGUAGE_BIDI %}dir="rtl"{% endif %}> 4 : <head> 5 : <title>{% block title %}{% endblock %}</title> 6 : <link rel="stylesheet" type="text/css" href="{% block stylesheet %}{% static "admin/css/base.css" %}{% endblock %}"> 7 : {% block extrastyle %}{% endblock %} 8 : {% if LANGUAGE_BIDI %}<link rel="stylesheet" type="text/css" href="{% block stylesheet_rtl %}{% static "admin/css/rtl.css" %}{% endblock %}">{% endif %} 9 : {% block extrahead %}{% endblock %} 10 : {% block responsive %} Traceback (most recent call last): File … -
Simplify Django database creating execution number by using some data structure or algorithm
I have used Django2 to develop a web app. I have some task, which is needed to be created into the database based on user input. I have 5 user type, say hop, hop2, executive, executive2, executive3. The mysql database of the task table is like this: task table: 1, task name, assignee_hop, assignee_hop2, assignee_executive, assignee_executive2, assignee_executive3 If user input only hop2 and executive2 name, I have to write if condition to check, or would get error for not existing item, I have to write a if condition or would get error: Cannot assign "''": "Task.assignee_hop3" must be a "User" instance. the django create function should be like this: if hop2 and executive2: Task.objects.create(assignee_hop2=hop2, assignee_executive2=executive2) if user input only hop2 and executive3 name, the django create function should be like this: Task.objects.create(assignee_hop2=hop2, assignee_executive3=executive3) if user input only hop and executive3 name, the django create function should be like this: Task.objects.create(assignee_hop=hop, assignee_executive3=executive3) if user input only hop2 and executive name, the django create function should be like this: Task.objects.create(assignee_hop2=hop2, assignee_executive=executive) if user input only hop2 , executive and executive2 name, the django create function should be like this: Task.objects.create(assignee_hop2=hop2, assignee_executive=executive, assignee_executive2=executive2) if user input only hop2 , executive, executive2 and executive3 … -
Django POST multipart/form-data unexpectedly parsing field as array
I am testing an endpoint in the following manner: from rest_framework.test import APIClient from django.urls import reverse import json client = APIClient() response = client.post(list_url, {'name': 'Zagyg Co'}) I find that the model object is being created with a name of [Zagyg Co] instead of Zagyg Co. Inspecting the request object reveals the following: self._request.META['CONTENT_TYPE'] #=> 'multipart/form-data; boundary=BoUnDaRyStRiNg; charset=utf-8' self._request.body #=> b'--BoUnDaRyStRiNg\r\nContent-Disposition: form-data; name="name"\r\n\r\nZagyg Co\r\n--BoUnDaRyStRiNg--\r\n' self._request.POST #=> <QueryDict: {'name': ['Zagyg Co']}> Using JSON like so: response = client.post( list_url, json.dumps({'name': 'Zagyg Co'}), content_type='application/json', ) sets the name correctly. Why is this so? -
user authentication manually in Django
If certain conditions met I want to manually authenticate user, tried the following way but it is again redirecting to the login page. def owner_login(request): token = request.GET.get('token', '') user_token = User.objects.filter(username='xxxx').first().token if token and token == user_token: user = authenticate(username='xxxx', password='yyyyyy') if user: login(request, user, backend='django.contrib.auth.backends.ModelBackend') return redirect('client_admin_home') else: return HttpResponse('not authorized') return render(request, 'owner_login.html', {}) Any help is much appreciated, thank you -
The page at https://lyrics-chords.herokuapp.com/ was not allowed to display insecure content from http://localhost:8000/auth/user
I've just finished creating a Django-React app and have pushed the changes to Heroku. The frontend (JS and CSS) appear on the website no problem, but requests to the backend result in the following error: [blocked] The page at https://lyrics-chords.herokuapp.com/ was not allowed to display insecure content from http://localhost:8000/auth/user I've consulted the Internet but no one seems to be getting the same error message. Consulting a friend, it seems as if I have to https secure my backend, and futher researching the subject, it seems that there is no free way to upload a SSL/TSL certificate (reference: heroku: set SSL certificates on Free Plan?). Is there a solution to this? -
How do I resolve a Django database conflict
Can't figure what's wrong?? settings.DATABASES is improperly configured. " django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the NAME value. [30/Jun/2021 17:31:00] "GET / HTTP/1.1" 500 194335 -
Django Admin behaves weirdly
I have this Django app running perfectly but sometimes Django Admin works oddly, because If I click on any model, instead of taking me to the list of registries in that model, It takes me to the same model list but with a weird css. Here is the picture of the normal model list Here is the picture after clicking any model I can't add information to models or anything. -
Django form.is_valid() issue
The idea is a user will create a post on this page and fill out the title and content. Once they submit this form, a Post instance will be created with the inputs of the user for title and content. This instance will also have the id of the user associated to it. I've done a print test which yields the outputs I'm looking for but it appears that the form is not valid. Any thoughts? #views.py class LocationDetail(View): def post(self, request, locationname): current_user = request.user user_profile = Profile.objects.get(user_id = current_user) form = PostCreate() found_location = Location.objects.get(name = locationname) context = {"found_location": found_location, "form": form} if request.method == "POST": post_author = user_profile.user_id post_title = request.POST['title'] post_content = request.POST['content'] print(post_author) print(post_title) print(post_content) if form.is_valid(): Post.objects.create( title = post_title, content = post_content, author_id = post_author, ) form.save() return render(request,'location-detail.html', context) #forms.py + models.py class PostCreate(ModelForm): class Meta: model = Post fields = ['title', 'content'] class Profile(Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length = 30) profile_location = models.CharField(max_length = 80, blank=True, null=True) join_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Post(Model): author = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name="posts") title = models.CharField(max_length = 30) content = models.CharField(max_length=300) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.author} - … -
django views for uploading image file to api with auth token key and model id " pls help"
i need to fix the views uploading image to "api url" with "auth token" and "model ID" --- " it will return the prediction label and probability below code views pls help me def home(request): prediction = {} if 'prediction' in request.GET: prediction = request.GET['prediction'] url = 'https://app.nanonets.com/api/v2/ImageCategorization/LabelFile/' % prediction data = {'file': open('C:\\Users\\sanjay\\Desktop\\nanonets\\herpes-test.jpg','rb'), 'modelId': ('', 'a01c8d5f-4daf-40b4-958e-dcc09fb14c20')} response = requests.post(url, auth=requests.auth.HTTPBasicAuth('-4k7A3R', ''), files=data) user = response.json() return render(request, 'pages/home.html', {'prediction': prediction} """DIS IS HOW THE API LOOKS""" {"message":"Success","result":[{"message":"Success","prediction":[{"label":"herpes","probability":0.9999999},{"label":"scabies","probability":7.587139e-8}],"file":"herpes-test.jpg","page":0}],"signed_urls":{"uploadedfiles/a01c8d5f-4daf-40d4-958e-dce09fb14c20/390418475.jpeg":{"original":"https://nnts.imgix.net/uploadedfiles/a01c8d5f-4daf-40d4-958e-dce09fb14c20/390418475.jpeg?expires=1625106512\u0026or=0\u0026s=4c7813061401e0aa726bf21cc522e7d4","original_compressed":"https://nnts.imgix.net/uploadedfiles/a01c8d5f-4daf-407d4-958e-dce09fb14c20/390418475.jpeg?auto=compress\u0026expires=1625106512\u0026or=0\u0026s=0518d01e4c79a0e0024bf5af45263102","thumbnail":"https://nnts.imgix.net/uploadedfiles/a01c8d5f-4d7af-40d4-958e-dce09fb14c20/390418475.jpeg?auto=compress\u0026expires=1625106512\u0026w=2470\u0026s=936a8b57d9be6956aba0dd4c66de2222","acw_rotate_90":"https://nnts.imgix.net/uploadedfiles/a01c8d5f-4daf-40d4-958e-dce09fb14c20/390418475.jpeg?auto=compress\u0026expires=1625106512\u0026or=270\u0026s=6ca0360c5bbef4268ff4fb82038d9de4","acw_rotate_180":"https://nnts.imgix.net/uploadedfiles/a01c8d5f-4daf-40d4-958e-dce09fb14c20/390418475.jpeg?auto=compress\u0026expires=1625106512\u0026or=180\u0026s=1d37c1a4b0988e2563d4c87dc0a4633d","acw_rotate_270":"https://nnts.imgix.net/uploadedfiles/a01c8d5f-4daf-40d4-958e-dce09fb14c20/390418475.jpeg?auto=compress\u0026expires=1625106512\u0026or=90\u0026s=0bfac9da3377b3dff431eadaea3b0c4a","original_with_long_expiry":"https://nnts.imgix.net/uploadedfiles/a01c8d5f-4daf-40d4-958e-dce09fb14c20/390418475.jpeg?expires=1640644112\u0026or=0\u0026s=cc8227ba0a24e9ac4fb327d99e26a7c0"}}} -
Django InlineFormset: Size based on number of models
I am creating a gradebook app. With the following models: class Student(models.Model): student_id = models.IntegerField() first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) class Component(models.Model): CATEGORY_CHOICES = [ ('QZ', 'Quiz'), ('AS', 'Assignment'), ('TS', 'Test'), ] name = models.CharField(max_length=50) category = models.CharField( max_length = 2, choices = CATEGORY_CHOICES, default='AS', ) due_date = models.DateField() grade_total = models.PositiveIntegerField() class Score(models.Model): value = models.PositiveIntegerField() component = models.ForeignKey(Component, on_delete=models.CASCADE) student = models.ForeignKey(Student, on_delete=models.CASCADE) How can I populate a formset based on the number of students with a Component instanced? See: Concept