Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Accessing UserProfile data from foreign key related Post
I am currently working on a little django app, the app is like a social media app. User can post, like and comment. I recently created the User Profiles. Which I can now see the user for that user profile in my view, but I cant seem to dig into the Posts that may be related to the UserProfile. what I am trying to do is in my view of HTML, I want to be able to get the post from the userprofile and the comment, and likes. But I have tried everything and nothing works. Currently in my HTML view I have rendered {{ profile.user }} and it displays the users name, but If I try profile.user.post or profile.user.comments I get nothing. Here is some code to show where I am at. Any help would be much appreciated. Profile View. def profile(request): profile = get_object_or_404(UserProfile, user=request.user) template = 'profiles/profile.html' context = { 'profile': profile, # 'posts': posts } return render(request, template, context) Profile Model from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class UserProfile(models.Model): """ A user profile model to link posts and likes """ user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile") def … -
Django: EmailMessage encode the subject in base64 when translated and contains non US-ASCII characters
The usual behavior of the EmailMessage class regarding its subject is to keep it as it is if i contains only US-ASCII characters and to encode it as quoted-printable if it contains non US-ASCII characters. That works well and avoid our emails to be considered as pishing by antispam from email servers But in the specific context of translations there is a bug -> if the subject of an email is translated into another language (through the built-in django translations tools) and contains non US-ASCII characters, by an mechanism I didn't catch, the subject is encoded as base64 and not quoted-printable. This results in being considered as spam by the email servers (tested on Gandi and Gmail)... I submitted a ticket on https://code.djangoproject.com/ Do you have any idea of the mechanism that leads to this encoding in base64 instead of quoted-printable when we translate the subject of a mail ? -
I am getting this IntegrityError at /registration/ NOT NULL constraint failed: bankapp_registration.date_of_birth error
models.py from django.db import models # Create your models here. class Registration(models.Model): bank_ac = models.CharField(max_length=64) first_name = models.CharField(max_length=64) last_name = models.CharField(max_length=64) user_name = models.CharField(max_length=64) mobile_number = models.CharField(max_length=10) email = models.EmailField() password = models.CharField(max_length=18) date_of_birth = models.DateField(max_length=64) address = models.CharField(max_length=160) pin_code = models.IntegerField() views.py from django.shortcuts import render from bankapp.forms import RegistrationForm, LoginForm from bankapp.models import Registration from django.http import HttpResponse # Create your views here. def Home(request): return render(request, 'home.html') def RegistrationView(request): if request.method == 'POST': rform = RegistrationForm(request.POST) if rform.is_valid(): bac = request.POST.get('bank_ac') fname = request.POST.get('first_name') lname = request.POST.get('last_name') uname = request.POST.get('user_name') mnumber = request.POST.get('mobile_number') email = request.POST.get('email') password = request.POST.get('password') dob = request.POST.get('date_of_birth') address = request.POST.get('address') pin_code = request.POST.get('pin_code') data = Registration( bank_ac = bac, first_name = fname, last_name = lname, user_name = uname, mobile_number = mnumber, email = email, password = password, date_of_birth = dob, address = address, pin_code = pin_code ) data.save() rform = RegistrationForm() return render(request,'Registration.html', {'rform':rform}) else: return HttpResponse('User Entered invalid data') else: rform = RegistrationForm() return render(request,'Registration.html', {'rform':rform}) def LoginView(request): sform = LoginForm() if request.method == "POST": sform = LoginForm(request.POST) if sform.is_valid(): uname = request.POST.get('user_name') pwd = request.POST.get('password') print(uname) print(pwd) user1 = Registration.objects.filter(user_name=uname) password1 = Registration.objects.filter(password=pwd) if user1 and password1: return redirect('/') else: … -
Django datatable server side processing tutorial
I am using Django and there are lots of data in my table which takes times to load. Therefore, i would like to utilize enable server side processing. Is there a tutorial i can follow you may suggest. I tried to employ the datatable serverside and rest framework POST option as mentioned here. However, i could not utilize it because i am missing an intuitive understanding of the concept. If there would be any tutorial for me to follow i would like to know. Thanks for your attention. -
HTML Input Tage Values not saving in SQLite Database - Django
I am trying to save data from HTML Form to SQLite database. My database is connected to my app and project. I am able to enter from Django Admin, but my values from Input tag are not going in database. Views.py def add_record(request): if request.method == 'POST': ref_no = request.POST.get('ref_no') token_no = request.POST.get('token_no') agent_name = request.POST.get('agent_name') trip_no = request.POST.get('trip_no') date = request.POST.get('date') vehicle_no = request.POST.get('vehicle_no') bora = request.POST.get('bora') katta = request.POST.get('katta') plastic = request.POST.get('plastic') farmer_name = request.POST.get('farmer_name') farmer_address = request.POST.get('farmer_address') farmer_mob = request.POST.get('farmer_mob') gross_weight = request.POST.get('gross_weight') tier_weight = request.POST.get('tier_weight') net_weight = request.POST.get('net_weight') bora_weight = request.POST.get('bora_weight') suddh_weight = request.POST.get('suddh_weight') loading = request.POST.get('loading') unloading = request.POST.get('unloading') unloading_point = request.POST.get('unloading_point') dharamkanta_man = request.POST.get('daramkanta_man') rate = request.POST.get('rate') bardana = request.POST.get('rate') gross_total = request.POST.get('gross_total') deduction = request.POST.get('deduction') kanta = request.POST.get('kanta') hemali = request.POST.get('hemali') our_vehicle_rent = request.POST.get('our_vehicle_rent') agent_commission = request.POST.get('agent_commission') other_amt = request.POST.get('other_amt') other_remarks = request.POST.get('other_remarks') advance = request.POST.get('advance') net_total = request.POST.get('net_total') var_datasave = paddy_purchase(ref_no=ref_no, token_no=token_no, agent_name=agent_name, trip_no=trip_no, date=date, vehicle_no=vehicle_no, bora=bora, katta=katta, plastic=plastic, farmer_name=farmer_name, farmer_address=farmer_address, farm_mob=farmer_mob, gross_weight=gross_weight, tier_weight=tier_weight, net_weight=net_weight, bora_weight=bora_weight, suddh_weight=suddh_weight, loading=loading, unloading=unloading, unloading_point=unloading_point, dharamkanta_man=dharamkanta_man, rate=rate, bardana=bardana, gross_total=gross_total, deduction=deduction, kanta=kanta, hemali=hemali, our_vehicle_rent=our_vehicle_rent, agent_commission=agent_commission, other_amt=other_amt, other_remarks=other_remarks, advance=advance, net_total=net_total ) var_datasave.save() messages.success(request, 'Record saved successfully.') return redirect('index') return render(request, 'add.html') Models.py class paddy_purchase(models.Model): ref_no = models.IntegerField(primary_key='true') token_no = … -
django View - 'Comment' object has no attribute 'comments'
I'm trying to get my comments to be deleted but when I run the code the following error shows up: my comment_delete views: class CommentDelete(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Comment template_name = 'comment_delete.html' success_url = reverse_lazy('article_list') def test_func(self): obj = self.get_object() return obj.comments == self.request.user models.py Comment model: class Comment(models.Model): article = models.ForeignKey( Article, on_delete=models.CASCADE, related_name='comments', ) name = models.CharField(max_length=140) body = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('article_list') -
broken django production webpage
I cannot figure out why only one webpage in django production server is broken. The same webpage renders as expected on the development server. Django renders the webpage partially. The script files are executed partially. This is very confusing and I don't know where to look. All the webpages render and execute script files as expected, except for one. Please help static settings: STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL = 'media/' TEMP_ROOT = os.path.join(BASE_DIR, 'temp/') TEMP_URL = 'temp/' -
Django How to do I search for a model data in HTML?
I have the following classes in my models.py file. class Resident(models.Model): house_number = models.CharField(max_length=100,unique=True,primary_key=True) name = models.CharField(max_length=100) contact_number = PhoneNumberField() def __str__(self): return self.house_number + " : " + self.name class Balance(models.Model): residents = models.OneToOneField(Resident, on_delete=models.CASCADE, primary_key=True) date = models.DateTimeField(default=timezone.now) previous_balance = models.DecimalField(max_digits=1000, decimal_places=2 , null=True) transaction = models.DecimalField(max_digits=1000, decimal_places=2, null=True) final_balance = models.DecimalField(max_digits=1000, decimal_places=2, null=True, editable=False) def save(self, *args, **kwargs): self.final_balance = self.previous_balance + self.transaction return super().save(*args, **kwargs) def __str__(self): return self.residents.name + " : " + str(self.final_balance) class Transaction(models.Model): transaction_id = models.UUIDField(primary_key=True,default=uuid.uuid4(), editable=False,unique=True) residents = models.ForeignKey(Resident, on_delete=models.CASCADE) created = models.DateTimeField(blank=True) transaction_Amount = models.DecimalField(max_digits=1000, decimal_places=2) date = models.DateTimeField() category_choices = ( ('Monthly-Bill', 'Monthly-Bill'), ('Cash', 'Cash'), ('Transfer', 'Transfer'), ('EFT', 'EFT'), ) category = models.CharField(max_length = 13 ,choices = category_choices, default = 'Monthly-Bill') def save(self, *args, **kwargs): if self.transaction_id == "": self.transaction_id = generate_code() if self.created is None: self.created = timezone.now() try: last_bal = Balance.objects.filter(pk = self.residents).get() except Balance.DoesNotExist: Balance.objects.create(residents = self.residents, date=self.date, previous_balance=Decimal.from_float(0.00), transaction=self.transaction_Amount) else: last_bal.date = date=self.date last_bal.previous_balance = last_bal.final_balance last_bal.transaction = self.transaction_Amount last_bal.save() return super().save(*args, **kwargs) def __str__(self): return str(self.transaction_id) + " : " + self.residents.name I would like to know how can I create a dropdownlist using the Resident.name to search/filter for a particular Transaction in html? … -
django: populate multiple image upload with initial data
I have an image form field that accepts multiple images like so: images = forms.ImageField(widget=forms.ClearableFileInput(attrs={'class': 'form-control', 'multiple': True}), required=False) Now when you use a ClearableFileInput with an ImageField that accepts one image and populate it with initial data, it renders as something like this: I am wondering if it is possible to achieve a similar result with an ImageField that accepts multiple files? I.e. is it possible to populate the above field with initial data? -
Postgres asking unknown password
installing PostgreSQL for my Django Project. (vent) my_name@Name-MBP dir % createuser my_user createuser: error: connection to server on socket "/tmp/.s.PGSQL.5432" failed: FATAL: password authentication failed for user "my_name" Problem: I do not specify any password for user "my_name" and don't even create such user. HELP PLEASE!!! -
How to encrypt responses in DRF?
I want to encrypt my DRF project APIs responses Is there a way to encrypt large responses so that I only have access to the data on the front end side? I want to encrypt all responses. -
How can i split the value of a dropdown list option and pass it in two different input fields
How can i split the value of a dropdown list option and pass it in two different input fields scripts <script> function getsciname() { ("#selectsci").change(function() { var sciname = (this).val().split(','); ("#sid").val(sciname[0]); ("#sname").val(sciname[1]); }}; </script> (dropdown) select option code <select id="scinameid" class="scinameclass" onchange="getsciname()"> <option disabled="true" selected>-- Scientific name --</option> {% for getData in TaxonmyDistributionInsert %} <option value={{getData.id}},{{getData.ScientificName}}>{{getData.id}} - {{getData.ScientificName}}</option> {% endfor %} </select> input box code <input type="text" style="font-size: 16px" placeholder="Shrimp Prawn ID" name="ShrimpPrawnID" id="sid" /> <input type="text" style="font-size: 16px" placeholder="Scientific Name" name="ScientificName" id="sname" /> -
Check for a certain condition before processing each view in Django
I'm building a multi-tenant Django app, where I need to check for a certain condition before processing each view, similar to the login_required decorator which checks if user is authenticated or not. And if the condition is not true, stop processing the view and send the user to the login page. How can I implement this for each view in my app My condition - def index_view(request): domain1 = Domain.objects.get(tenant=request.user.client_set.first()) domain2 = request.META["HTTP_HOST"].split(":")[0] // Condition if str(domain1) != domain2: return redirect("accounts:login") return render(request, "dashboard/index.html") -
How can i run a python script in django
So a python script like Sherlock on Git hub, which sources usernames. Can that be run by clicking a button on a HTML page in a Django project and return a CSV file. How would this be done ? -
Stock quantity update when and order is placed in Django app
I have a product and order create models where I'd like to update the quantity of the product when and order is placed for that product. Using a ForeignKey, I am able to select the product but so far I'm definitely missing something as nothing i have tried seems to work, please take a look at my code below and assist. Thank you in advance Models.py #Product Model class Product(models.Model): SKU = models.CharField(max_length=30, unique=False,default='input SKU') Category = models.CharField(max_length=200,default='Input Category') Name = models.CharField(max_length=250,unique=False, default='Input product name') Platform = models.CharField(max_length=50, default='platform') Price = models.PositiveIntegerField(default='price') Discount = models.PositiveIntegerField(default='discount') Prod_Qty = models.PositiveIntegerField(unique=False, default=0) Date = models.CharField(max_length=30, default='Char field') Cost = models.PositiveIntegerField() created_date = models.DateField(auto_now_add=True) def __str__(self): return self.Name class Order(models.Model): STATUS_CHOICE = ( ('pending', 'Pending'), ('decline', 'Decline'), ('approved', 'Approved'), ('processing', 'Processing'), ('complete', 'Complete'), ('bulk', 'Bulk'), ) SALE_CHOICE = ( ('platform1', 'platform1'), ('platform2','platform2') ) supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(null=False) sale_type = models.CharField(max_length=50, choices=SALE_CHOICE, null=True) cost_goods_sold = models.PositiveIntegerField(default=6) shipping_fee = models.PositiveIntegerField(null=False) shipping_cost = models.PositiveIntegerField(default=0) buyer = models.ForeignKey(Buyer, on_delete=models.CASCADE, null=True) manifest = models.ForeignKey(Manifest, on_delete=models.CASCADE) status = models.CharField(max_length=10, choices=STATUS_CHOICE) created_date = models.DateField(auto_now_add=True) def __str__(self): return self.product.Name Views.py # Product views @login_required(login_url='login') def create_product(request): forms = ProductForm() context = {"form": forms} if request.method … -
1v1 Game Django using Javascript / Html
I'm having for the moment a memory card game using JS & html on Django I would know where do I have to search to make it like a 1v1 game. People would be able to create a 1v1 room (lobby) and then play this memory card game If you guys have any clues, will appreciate. Bru -
CS50w commerce project: 'The bid must be as large as the starting bid, and must be greater than any other bids that have been placed (if any)'?
So I have solved this particular problem, but there is something that I noticed and didn't get why was it behaving the way it did. So the below code worked the way I wanted it to work: def bid_placed(request,listing_id): if request.method == "POST": recent_bid = Bid( Bid_amount = request.POST["bid_amount"], listing = Listing.objects.get(pk=listing_id) ) listing = Listing.objects.get(pk=listing_id) starting_Bid = listing.Starting_Bid recent_bid_int = int(recent_bid.Bid_amount) if recent_bid_int > starting_Bid: listing.Starting_Bid = recent_bid_int listing.save() return HttpResponse("Bid SUCCESSFULLY Placed") else: return HttpResponse("Bid CANNOT be placed") But the below code is NOT working as desired, even though the starting_Bid variable has been declared: def bid_placed(request,listing_id): if request.method == "POST": recent_bid = Bid( Bid_amount = request.POST["bid_amount"], listing = Listing.objects.get(pk=listing_id) ) listing = Listing.objects.get(pk=listing_id) starting_Bid = listing.Starting_Bid recent_bid_int = int(recent_bid.Bid_amount) if recent_bid_int > starting_Bid: starting_Bid = recent_bid_int listing.save() return HttpResponse("Bid SUCCESSFULLY Placed") else: return HttpResponse("Bid CANNOT be placed") ``` Can someone please guide, why it might be the case.? Thanking you in advance.! -
Why I am getting the NGINX welcome page instead of my Django application
I have deployed my Django Application on a VPS server. I have configured NGINX and uWSGI server. Here is my Nginx configuration # the upstream component nginx needs to connect to upstream django { server unix:///root/PIDC/ProjetAgricole/ProjetAgricole.sock; # for a file socket # server 127.0.0.1:8001; # for a web port socket (we'll use this first) } # configuration of the server server { # the port your site will be served on listen 8000; # the domain name it will serve for server_name my_public_IP_address; # substitute your machine's IP address or FQDN charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste # Django media location /media { alias /root/PIDC/ProjetAgricole/media; } location /static { alias /root/PIDC/ProjetAgricole/static; } # Finally, send all non-media requests to the Django server. location / { uwsgi_pass django; include /root/PIDC/ProjetAgricole/uwsgi_params; } } Here is my mysite_uwsgi.ini file # mysite_uwsgi.ini file [uwsgi] # Django-related settings # the base directory (full path) chdir = /root/PIDC/ProjetAgricole # Django's wsgi file module = project.wsgi # the virtualenv (full path) home = /root/my_project/venv # process-related settings # master master = true # maximum number of worker processes processes = 10 # the socket (use the full path to be safe … -
How to get data from a running task in Python(Django)
I have a script to compare and move my files around, which is to be called by cmp_object = my_cmp.Compare('/mnt/f/somedir', '/mnt/f/newdir') cmp_object.main() and the Compare class is defined as class Compare: def __init__(self, path1, path2): self.path1 = path1 self.path2 = path2 self.totalFileNumber = getTotalFileNumber(path1) self.totalFileSize = getTotalFileSize(path1) self.progress = 0 self.progressPercent = 0 self.status = 'Not started' self.started = False self.finished = False def start(self): self.status = 'Started' self.started = True self.finished = False def update(self, index): self.progress = index self.progressPercent = round( self.progress / self.totalFileNumber * 100, 2) self.status = f'{self.progressPercent}%' if self.progressPercent == 100: self.status = 'Finished' self.finished = True def getStatus(self): return self.status def getProgress(self): return self.progressPercent def getTotalFileNumber(self): return self.totalFileNumber def getTotalFileSize(self): return self.totalFileSize def isStarted(self): return self.started def isFinished(self): return self.finished def main(self): self.start() for index, file in enumerate(listAllFiles(self.path1)): compareFiles(file, self.path2 + file[len(self.path1):]) self.update(index) self.update(self.totalFileNumber) self.finished = True , which has functions to get and set some states like progress, status and finish. I am running this on Django backend, where I would be retrieving information from the backend by setting an interval... I am using cache to set and get the states across different views, but I'm not sure how can I keep on … -
Django Terraform digitalOcean re-create environment in new droplet
I have saas based Django app, I want, when a customer asks me to use my software, then i will auto provision new droplet and auto-deploy the app there, and the info should be saved in my database, like ip, customer name, database info etc. This is my terraform script and it is working very well coz, the database is now running on terraform { required_providers { digitalocean = { source = "digitalocean/digitalocean" version = "~> 2.0" } } } provider "digitalocean" { token = "dop_v1_60f33a1<MyToken>a363d033" } resource "digitalocean_droplet" "web" { image = "ubuntu-18-04-x64" name = "web-1" region = "nyc3" size = "s-1vcpu-1gb" ssh_keys = ["93:<The SSH finger print>::01"] connection { host = self.ipv4_address user = "root" type = "ssh" private_key = file("/home/py/.ssh/id_rsa") # it works timeout = "2m" } provisioner "remote-exec" { inline = [ "export PATH=$PATH:/usr/bin", # install docker-compse # install docker # clone my github repo "docker-compose up --build -d" ] } } I want, when i run the commands, it should be create new droplet, new database instance and connect the database with my django .env file. Everything should be auto created. Can anyone please help me how can I do it? or my approach is … -
django.db.utils.OperationalError: sequence must have same owner as table it is linked to
I am trying to update the USER auth model in Django in the middle of a project. I am also trying to learn a bit more, so I chose to do the "hard way" and switch out the standard auth model with a modified AbstractUserModel than doing the 'profile' 1-to-1 method often suggested. I feel I am quite close, as I am trying to apply the final migration with walkthrough suggestions from here and here. There is some inclination that Django runs the ALTER SEQUENCE OWNED BY with a different (auth user maybe?) user than the database user (who you are logged in as maybe?). I have confirmed that the OWNER of the tables and sequences are owned by all the same OWNER, but am still getting the migrate error. Thank you all in advance :) When trying to run ./manage.py migrate --verbosity 3, I get the following error: IN DEV XXXXXXX Operations to perform: Apply all migrations: account, … trucks Running pre-migrate handlers for application auth … Running pre-migrate handlers for application account Running pre-migrate handlers for application trucks Running migrations: Applying accounts.0004_auto_20220424_0024...Traceback (most recent call last): File "/Users/me/.virtualenvs/virtualENV/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.ObjectNotInPrerequisiteState: sequence must … -
Incorrect padding when attempting to update profile picture
My project is built on React and Django. I would like to enable users to update profile information. Noticed that I was initially getting a 304 error when it specifically comes to updating the profile picture. and realized that this had something to do with Django requiring multipart form data. I then tried to upload the profile picture using a base64 encoding string, but now getting the error Incorrect padding Here is my serializers.py: #upload profile picture using base64 encoding string instead of raw file (not supported by default) class Base64ImageField(serializers.ImageField): def to_internal_value(self, data): from django.core.files.base import ContentFile import base64 import six import uuid #check if this is base64 string if isinstance(data, six.string_types): #check if the base64 is in the data format if 'data:' in data and ';base64' in data: header,data = data.split(';base64,') try: decoded_file = base64.b64decode(data) except TypeError: self.fail('invalid_image') #Generate file name: file_name = str(uuid.uuid4())[:12] #Get the file name extension file_extension = self.get_file_extension(file_name, decoded_file) complete_file_name = "%s.%s" % (file_name, file_extension, ) data = ContentFile(decoded_file, name=complete_file_name) return super(Base64ImageField, self).to_internal_value(data) def get_file_extension(self, file_name, decoded_file): import imghdr extension = imghdr.what(file_name, decoded_file) extension = "jpg" if extension == "jpeg" else extension return extension #updating user profile class UpdateUserSerializer(serializers.ModelSerializer): email = serializers.EmailField(required=False) city = … -
Reverse for 'list-events' not found
Im currently following a Django tutorial to learn views and URLs. I have watched the tutorial over and over and cant see what I am doing wrong. I receive the error: Exception Value: Reverse for 'list-events' not found. 'list-events' is not a valid view function or pattern name. Views.py from django.shortcuts import render, redirect import calendar from calendar import HTMLCalendar from datetime import datetime from .models import Event, Venue from .forms import VenueForm, EventForm from django.http import HttpResponseRedirect # Create your views here. # all events is listed in the urls.py hence why the function is named all_events def update_event(request, event_id): event = Event.objects.get(pk=event_id) form = EventForm(request.POST, instance=event) if form.is_valid(): form.save() return redirect('list-events') return render(request, 'events/update_event.html', {'event': event, 'form':form}) def add_event(request): submitted = False if request.method == 'POST': form = EventForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/add_event?submitted=True') else: form = EventForm if 'submitted' in request.GET: submitted = True return render(request, 'events/add_event.html', {'form': form, 'submitted': submitted}) def update_venue(request, venue_id): venue = Venue.objects.get(pk=venue_id) form = VenueForm(request.POST, instance=venue) if form.is_valid(): form.save() return redirect('list-venues') return render(request, 'events/update_venue.html', {'venue': venue, 'form': form}) def search_venues(request): if request.method == "POST": searched = request.POST['searched'] venues = Venue.objects.filter(name__contains=searched) return render(request, 'events/search_venues.html', {'searched': searched, 'venues': venues}) else: return render(request, 'events/search_venues.html', {}) … -
Test of Django ProfileListView fails with ValueError: Cannot assign "<SimpleLazyObject:....>": "Profile.user" must be a "User" instance
I am a Django beginner and a SOF newbie, sorry if this question sounds a silly to some. I am struggling with my integration tests. In my app I have a one-to-one User/Profile relationship. I have a list view to show registered users' profile data: class ProfileListView(views.ListView, LoginRequiredMixin): model = Profile template_name = 'registration/profile_list.html' paginate_by = 8 def get_context_data(self, *, object_list=None, **kwargs): context = super(ProfileListView, self).get_context_data() # superuser raises DoesNotExist at /accounts/profiles/ as they are created with createsuperuser in manage.py # hence are not assigned a profile automatically => create profile for them here try: context['current_profile'] = Profile.objects.get(pk=self.request.user.pk) except ObjectDoesNotExist: Profile.objects.create(user=self.request.user) context['current_profile'] = Profile.objects.get(pk=self.request.user.pk) # get all other users' profiles apart from staff and current user regular_users = User.objects \ .filter(is_superuser=False, is_staff=False, is_active=True) \ .exclude(pk=self.request.user.pk) context['non_staff_active_profiles'] = Profile.objects.filter(user__in=regular_users) return context I want to test the get_context_data() method to ensure it returns: correct logged in user correct queryset of non-staff profiles My test breaks as soon as I try something like: response = self.client.get('/accounts/profiles/') I understand I need to pass user/profile data to the client but I could not figure out how to do that. It looks like it fails because of context['current_profile'] = Profile.objects.get(pk=self.request.user.pk) and I have no idea why. … -
Embed Plotly in html with responsive behavior: can I change legend position based on screen width?
I am using Plotly to embed a plot on an HTML page. My website is responsive, but I am not satisfied with the legend of the plot that I have embedded. Here you can see two screenshots: on the left, we see the plot on a widescreen, and on the right with a narrow one. vs As shown in the figure, the plot looks good on the widescreen (left). However, when the screen is narrow (right), the legend takes too much space and the plot is shrunk. Moving the legend below when the screen is small would solve the issue (as depicted with the red drawing). Is it possible to embed such a responsive behavior in Plotly when adding the legend? Thanks in advance! :)