Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Saas and Multi Tenant
I am really struggling on how I should start this new project. This will be my first SaaS/Multi Tenant app. The app is an inventory management application. The way the app will work, the user will sign up and make an account. Once the user is signed up, they can create a Inventory Management portal. Now, I am struggling if it would be best to do the Multi Tenant (Shared Database, Isolated Schema) approach, or do it to where I just assign the the request.user to the Inventory Management portal that they had just created. Would it be better to go the Multi Tenant approach where they get their own subdomain, or better to just display data that is associated with the users/portal id? -
Django simplejwt + django-allauth how to issue personal access token for social media authentication
I'm implementing a service that allows users to sign up via normal username + password, google, facebook and github. I have the authentication working on my decoupled frontend and backend, but here's my issue. I am developing some python CLI tool which uploads data to the backend, but users must be authenticated to do so. I have had no issue authenticated users via the normal username + password endpoint, but i'm struggling to see how to achieve this with the social media authentication. I have been thinking that users should be able to issue personal access tokens via the frontend (similar to github's personal access token), but my question would be how can I do that? I would imagine this requires extending the login endpoint for django-simplejwt package? -
Django conditional many-to-many relation exists check
The model is: class RecordModel(BaseModel): visibility_setting = models.PositiveIntegerField() visible_to = models.ManyToManyField(UserModel, blank=True) I need to return rows depending on row visibility_setting: if visibility_setting == 0 - return row without any checks, if visibility_setting == 1 - I need to check if user is in visible_to m2m relation exists. In second case query works okay, but in first case my approach of setting None on first case not working (as expected): Feed.objects.filter( visible_to=Case( When(visibility_setting=0, then=None), # no data returned in this case, but I want to # return all rows with visibility_setting=0 When(visibility_setting=1, then=user.id), # rows with visibility_setting=1 are queried okay ) ) I am a little bit stuck which way to use in this situation? Can we not apply case at all in some conditions or use some specific default to skip visible_to relations check? -
serializer not being called AttributeError: 'str' object has no attribute '_meta'
I modified the Auth User by using AbstractUser Class. Registered it in settings. Everything else is working I can create an instance using the User Model BUT The Problem comes during the serialization. My serializer doesn't throw any error, but any time I try and use the serializer.data I get AttributeError: 'str' object has no attribute '_meta'. User Model class User(AbstractUser): # Add additional fields here email = models.EmailField(max_length=254, unique=True) name = models.CharField(max_length=100) username = models.CharField(max_length=100) password = models.CharField(max_length=100) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now=True) first_name=None last_name=None USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name', 'username', 'password'] objects = CustomUserManager() def __str__(self): return self.email # Ensure that the password is hashed before saving it to the database def save(self, *args, **kwargs): self.password = make_password(self.password) super(User, self).save(*args, **kwargs) Custom Manager from django.contrib.auth.base_user import BaseUserManager from django.utils.translation import gettext_lazy as _ class CustomUserManager(BaseUserManager): def create_user(self, email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): """ Create and save a SuperUser with the given email and password. … -
integrating Asynchronous Python code with Django
I have this asynchronous python code which is given below and performs sign-up functionality: async def add_account_endpoint(self, request: web.Request): """ Adds account to the list of accounts with username and password : param request: Web request from the URL where the parameters will come in :return: WebResponse with the outcome of a request """ data = await request.post() new_user_name = data.get('user_name') new_account_password = data.get('password') if new_user_name: if new_account_password: if new_user_name not in [account.user_name for account in self.accounts]: # Create and add new account to the accounts in the exchange new_account = Account(new_user_name, new_account_password, self.db_handler) self.accounts.append(new_account) return web.Response(content_type='text', body="Account added successfully") else: return web.Response(content_type='text', body="Unable to add account: user_name already exists") else: return web.Response(content_type='text', body="Unable to add account: please give password") else: return web.Response(content_type='text', body="Unable to add account: please give user_name") It is a signup code in which it is adding a user in DB. now I want to integrate it with Django using templates. How can I integrate it? -
Django - Set queryset in ListView depening on button pressed
I'm building a order management system in Django with a dashboard displaying some relevant information about the different stages of all orders. I have some counters displaying for example the number of quotes older than 30 days. This is done by defining the queryset filtering only orders on stage "Quote" and older than 30 days, I then update the context with the .count of this QS so I can access it in the template. I have a bunch of these counters with different filters (multiple) filter on each. What I would like to do is make this counter a button that send you to a new ListView page that displays a list of all orders matching the QS. I suppose I need to pass some kind of ID or text with each button in the URL that can be used in the views.py for the ListView to decide which QS to apply. But I cannot figure out how. I have tried searching for an answer, but I can only find examples to pass a single filter with the URL. I would rather use a shorter ID or string in the URL, and only define the full QS in views.py I … -
Django models filter objects for ManyToManyField
For example I have a model: class User(models.Model): is_active = models.BooleanField( 'Is active user?', default=True ) friends = models.ManyToManyField( 'self', default=None, blank=True, ) How can I filter only active users in ManyToManyField? (It won't work, just my ideas, ManyToManyField need Model in to=) queryset = User.objects.filter(is_active=True) friends = models.ManyToManyField( queryset, verbose_name='Friends', default=None, blank=True, ) -
Django form.is_valid() not returning file
I'm trying to validate a CSV fileupload by checking all of the expected headers are present. After I pass to validation on my form, the returned file doesn't seem to exist / or is not accessible. My View: @login_required @permission_required('products.report_upload', raise_exception=True) def uploadPackingNotesView(request): if request.method == "POST": form = UploadPackingNotesForm(request.POST, request.FILES) if form.is_valid(): csv_file = form.cleaned_data['csv_upload'] packing_list = csv.DictReader(io.StringIO(csv_file.read().decode('utf-8'))) # Pass to Celery for processing parsePackingNotes.delay(packing_list) return HttpResponseRedirect(reverse_lazy('product-csv-upload-successful')) else: form = UploadPackingNotesForm() return render(request, 'products/upload-packing-notes.html', {'form': UploadPackingNotesForm}) My Form: class UploadPackingNotesForm(forms.Form): """Form used to upload packing notes""" csv_upload = forms.FileField(label="Select Packing Notes File") def clean_csv_upload(self): data = self.cleaned_data.get('csv_upload') expected_headers = [ 'Branch', 'Carton', 'Delivered', 'SKU', 'PLU', 'Supplier Bar Code', 'Description', 'Size', 'Product Type', ] packing_list = csv.DictReader(io.StringIO(data.read().decode('utf-8'))) # Check that all required headers are present in the CSV, otherwise return error to frontend if not set(expected_headers).issubset(packing_list.fieldnames): raise ValidationError("Couldn't read uploaded CSV") return data I suspect the issue lies with the line: csv_file = form.cleaned_data['csv_upload'] after the form.is_valid() but I'm not sure what to use to get the confirmed file back. -
Function not implemented error when using Django sorl-thumbnail
Whenever i try uploading a post, with a jpg image attached to it through admin on my Django app, it gives me a Function not implemented errorno38. Im on android and i use pydroid. I followed the instructions when installing sorl-thumbnail, and i double-checked for typos and that stuff. What could be the problem? -
I want to make random unique id and check if that exeist then need to make new and save to users model admin pannel. Thanks in advance
I tried to save random account_id in User id of django User model. **** my code **** from .models import * from django.contrib.auth import get_user_model User = get_user_model() def User(): def account_id(): account_id = random.randint(1000000, 9999999) is_unique = User.objects.filter(account_id=account_id).exists() if not User.account_id: is_unique = False while not is_unique: account_id User.account_id = account_id User.save() else: account_id() account_id() User.save() ``` -
Empty request FILES in django
I have a Django model containing a fileField and a ModelForm which requests the user upload a file. Yet no matter what I seem to do, the request.FILES returned by the server does not contain anything. Here is the model: class RepoFile(models.Model): id = models.IntegerField(primary_key=True) repo = models.FileField(blank=False, null=True, upload_to="repos/") The ModelForm: class RepoUpload(forms.ModelForm): class Meta: model = RepoFile fields = ['repo'] widgets = { 'repo': ClearableFileInput(), } And the HTML <form action="" method="post" enctype="multipart/form-data">{% csrf_token %} {{ form }} <input type="submit" value="Submit" /> </form> Also here is the view that I am using: form = RepoUpload(request.FILES) if form.is_valid(): print('this passed') form.save() I noticed that no matter what file I upload in the "Choose File" section, the form.is_valid() returns false. If I just use HTML and the view to send request.FILES to a manually created object, len(request.FILES) returns 0. Does anyone know of a solution? -
Is timzone.now() cached when used in a checkconstraint?
I have a timezone aware model field with a CheckConstraint: class MyModel(models.Model): my_text = models.CharField() my_date = models.DateTimeField() class Meta: constraints = [ models.CheckConstraint( check=Q(my_date__lte=django.utils.timezone.now()), name='mycontraint' ] In my form I process the data to add my_date manually: def form_valid(self, form): obj = form.save(commit=False) obj.my_date = timezone.now() obj.save() When I save this model I get new row for relation "mymodel_mydate" violates check constraint 'myconstraint'. I know the reason it's failing is that the datetime for my_date is greater than timezone.now() in the checkconstraint, but why is this? Is timezone.now() in the checkconstraint somehow cached earlier? I can see the value for my_date in the debug failing row (which is correct, in UTC+00 and matches my system time as I expect), however I don't know how to compare this to the timezone value in the CheckConstraint? -
Static Root Issue - Static files won't load deploying to pythonanwhere
I'm currently trying to deploy my project and I can't seem to get my static files working correctly like they did on my local environment using the collectstatic command. The service I am deploying on is pythonanywhere - this is where I'm at right now. Any help would be greatly appreciated! settings.py BASE_DIR = Path(__file__).resolve().parent.parent STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / "static", BASE_DIR/"static"/"images", BASE_DIR/"static"/"css" ] MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') MEDIA_URL = '/images/' LOGIN_REDIRECT_URL = 'home' LOGIN_URL = 'login' My file structure Pythonanywhere Path -
What does it mean to "check code into GitHub"?
"So you’d make the migrations in developement environment, you get them right, and then you’d like check them into GitHub, perhaps. And then in production, you would pull your migrations out of GitHub and then they’ll migrate." So I'm listening to a lecture right now and it says this. It's in regards to models and migrations. I'm new so the only thing I know about GitHub is basically to store your projects etc. What do they mean by "then if you'd like check them into GitHub" perhaps. And then pull your migrations out of GitHub and then they'll migrate. Can someone explain in Fortnite terms please. Thank you. Just a newby trying to understand. Any help is appreciated. -
How do I change the path of an image when linking it in a HTML template?
When a category is clicked on, the user should be shown all of the items that are in that category. However, when I click on a category, the image of the items are not shown because the image is search for in CATEGORY/media/images/... (CATEGORY is the name of the category) instead of just /media/images/... This may be due to the fact that the path of the web page starts with the category name itself, so when the images are searched from the path. How do I change the path that the images are searched from? urls.py: path('<str:name>/', views.category, name='category') # so this would end up as a /Electronics/ if the Electronics category was clicked on # so I think that this is why the image are searched from the wrong path - it is searched from /Electronics/media/images/... category.html: <div class="listings-container"> {% for i in listings %} <div class="listing"> {% if i.photo_present != None %} <div class="img-container"> {% if i.photo_url != None %} <div class="img-center"> <a href="{% url 'listing' i.pk i.name %}"> <img src=" {{ i.photo_url }} " alt=""> </a> </div> {% else %} <div class="img-center"> <a href="{% url 'listing' i.pk i.name %}"> <img src=" media/{{ i.photo_upload }} " alt=""> </a> … -
create Django object with FileField using `File` wrapper and in-memory-file?
I am trying to build a functionality in my application where an In-memory PDF file will be created and that file will get saved on a FileField in my Document model. Explaination of the process: from io import BytesIO from PyPDF2 import PdfWriter in_memory_file = BytesIO() writer = PdfWriter() writer.add_blank_page(height=200, width=200) writer.write(in_memory_file) # The contents of the `writer` got saved to the `io` file To save the above created file we can do the following with open('new_local_file.pdf', 'wb') as local_file: local_file.write(in_memory_file.getbuffer()) The above code is working fine in terminal but since I cannot create local copies in my Django app, I have to do something like this to save the file from django.core.files import File obj = Document.objects.create(file_result=File(in_memory_file.getbuffer())) The File wrapper accepts the python file object but still the above code is not working. After execution no file is getting created in my Django Admin Please comment if you need any more info. -
how do i access the object referenced by Django GenericForeignKey
I don't know exactly how to access the object referenced by the generic foreign key class Cart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,related_name='cart_items') product_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, limit_choices_to=limits) product_id = models.UUIDField() content_object = GenericForeignKey('product_type', 'product_id') quantity = models.PositiveSmallIntegerField() I want to access the object referenced by the content_object field how do I do that exactly? -
How to get all data on page? Django
How to get all data on web-page more correctly using Django? from django.http import HttpResponse from .models import Student def get_students(request): students = Student.objects.all() return HttpResponse(''.join(f'<p>{student}</p>' for student in students)) -
What is function in django decorators
1.I have a django decorator but i don't know what is the meaning of function argument, like here by default it is set to None, what does that mean and what does actual_decorator(function) means? 2.also how does the condition 'if function' returns True while my function is None def teacher_required(function=None,): actual_decorator = user_passes_test( lambda u: u.is_teacher,) if function: return actual_decorator(function) return actual_decorator also what does sending argument to actual_decorator means? another question how can i return a permission denied error on decorator failure instead of login page? -
Type Error: Field 'id' expected a number but got <User: ILador>
I am working with Django models and Django-Rest-Framework. When I try to access the models through the Rest-Framework I get "TypeError at /home/profiles/: Field 'id' expected a number but got <User: ILador>." here's my code: Models.py- from django.db import models from django.contrib.auth.models import User from django.core.validators import MaxValueValidator, MinValueValidator from datetime import date from .countries import COUNTRIES class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) def username(self): usern = User.objects.get(id=self.user) usern = usern.username return usern setup = models.BooleanField(default=False) dob = models.DateField() def age(self): today = date.today() age = today.year - self.birthday.year - ((today.month, today.day) < (self.birthday.month, self.birthday.day)) return age orgin = models.CharField(max_length=300, choices=COUNTRIES) lives = models.CharField(max_length=300, choices=COUNTRIES) bio = models.CharField(max_length=150) email = models.CharField(max_length=255) hobbies = models.CharField(max_length=225) image = models.ImageField(upload_to='images') Serializers.py- from rest_framework import serializers from .models import Profile from django.contrib.auth.models import User from rest_framework.authtoken.models import Token class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields =('id', 'username', 'password') extra_kwargs = {'password': {'write_only': True, 'required': True}} def create(self, validated_data): user = User.objects.create_user(**validated_data) Token.objects.create(user=user) return user class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields=( 'id', 'username','email', 'setup', 'dob', 'age', 'orgin', 'lives', 'bio', 'hobbies', 'image',) Why am I getting this error? -
Django depoyment with mysql database on personal server
I am working on deploying my Django project on Linode. My MySQL database that I used during development was on a ubuntu server that I have at my house. This was different that the computer that I wrote the program on. In the settings.py file, I had the database connections set up and working. On my personal server at home, I have updated the UFW to allow the new linode ip address and granted privileges to the ip address also. When I go to run the server on deployed project on linode, I get an error (2003, "Can't connect to MySQL server on 'personal server ip address':3306' (110)"). How do I get the linode server to be able to talk to my personal server's MySQL database? Thank you!! -
Djnago CheckboxSelectMultiple group
I want to create dependent select fields. For example, if I сhoose PROCEEDING_CHOICES[0][1] of model Card I can't choose any of options field first_dispute. Different situation: if I choose CHOICES[1][1] of model FirstDispute I can't continue my work with field second1_dispute. How to implement it? models.py class FirstDispute(models.Model): CHOICES=( ('1', '01 О заключении, изменении и расторжении договоров'), ('2', '02 О недействительности сделок'), ('3', '03 О неисполнении или ненадлежащем исполнении обязательств по договорам'), ... ) value = models.CharField("Категория спора (подкатегория 1):", max_length=122, choices=CHOICES, default=CHOICES[0][1]) def __str__(self): return self.value class Card(models.Model): PROCEEDING_CHOICES =( ('Административное', 'Административное'), ('Интеллектуальное', 'Интеллектуальное'), ('Экономическое', 'Экономическое'), ) SECOND1_DISPUTE = ( ('None', 'Выбирается при значения "Подкатегория 1" - "01 О заключении, изменении и расторжении договоров"'), ('01.01 о понуждении к заключению договора', '01.01 о понуждении к заключению договора'), ... ) proceeding = models.CharField("Вид судопроизводства:", max_length=16, choices=PROCEEDING_CHOICES, default=PROCEEDING_CHOICES[0][1]) first_dispute = models.ManyToManyField(FirstDispute) second1_dispute = models.CharField("Категория спора (подкатегория 2-1)", max_length=122, choices=SECOND1_DISPUTE, blank=True, null=True) filters.py class CardFilter(django_filters.FilterSet): proceeding = django_filters.MultipleChoiceFilter(choices=Card.PROCEEDING_CHOICES, label="Вид судопроизводства (выберите подходящее значение)", widget=forms.CheckboxSelectMultiple()) first_dispute = django_filters.MultipleChoiceFilter(choices=FirstDispute.CHOICES, label="Первая подкатегория спора (выберите подходящее значение)", widget=(forms.CheckboxSelectMultiple())) second1_dispute = django_filters.MultipleChoiceFilter(choices=Card.SECOND1_DISPUTE, label="Вторая (1) подкатегория спора (выберите подходящее значение)", widget=(forms.SelectMultiple())) class Meta: model = Card fields = [ 'first_dispute'] -
Django Testing Client POST Request, Getting 403 Error
I'm trying to test some client requests for the first time, and I am able to successfully sent a POST request to register a new user. However, when I attempt to login, I receive a 403 error and I'm not sure what is causing it... thinking maybe I've missed something in the test? I am successfully able to login on my deployed app. Error message: ====================================================================== FAIL: test_user_login_POST (jwt_auth.tests.TestUsers) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/jz/Development/BetterCred/jwt_auth/tests.py", line 32, in test_user_login_POST self.assertEqual(response.status_code, 202) AssertionError: 403 != 202 ---------------------------------------------------------------------- Ran 3 tests in 1.416s Test: def setUp(self): User.objects.create( username = 'JohnnyBoy', password = 'pass123!', email = "email@gmail.com", first_name = "John", last_name = "Smith", ) def test_user_login_POST(self): req_url = reverse('user-login') login_details = { 'username': 'JohnnyBoy', 'password': 'pass123!' } response = self.client.post(req_url, login_details, content_type="application/json") print(response) self.assertEqual(response.status_code, 202) View (I added code=404 to see if my test was hitting that point, but doesn't seem like it): class LoginView(APIView): # POST - Login a user and return a token def post(self, request): # Save username and password from request to variables username = request.data.get('username') password = request.data.get('password') # Try to find user, if not found, return an ambiguous error try: user_to_login = User.objects.get(username = username) … -
I get AttributeError: 'HttpResponse' object has no attribute 'endswith' when calling window.location.reload(True) from script
i tried to reload my website just after i update the data so i tested function first adding it to management/commands an with plan to import it later: from django.core.management.base import BaseCommand from django.http import HttpResponse class Command(BaseCommand): help = 'reload page' def handle(self, *args, **kwargs): return HttpResponse("<script>window.location.reload(True);</script>") self.stdout.write("page reloaded") but whe i run puthon manage.py reload i get this error: File "C:\_dane\python\django\cryptosloth.live\venv\lib\site-packages\django\core\management\base.py", line 169, in write if ending and not msg.endswith(ending): AttributeError: 'HttpResponse' object has no attribute 'endswith' i tried many different version of this function, played with adding BASE_DIR = os.path.dirname(os.path.dirname(__file__)) STATIC_ROOT = os.path.join(BASE_DIR, 'static') i don't know why - just read some solution to other 'HttpResponse' object has no attribute problem. -
how can i solve too many values to unpack (expected 2) working with django?
guys im working with django , i have a html file that is related to a section of the site, here is my convertion.html file: {% extends 'dashboard/base.html' %} {% load static %} {% block content %} <div class="container text-center"> <form method="POST"> {% csrf_token %} <div class="form-group"> <legend class='border-bottom mb-4'></legend> {{form}} ######## <button href="" class="btn btn-outline-info" type="submit"> Select </button> </div> <fieldset class="form-group"> <legend class="border-bottom mb-4"></legend> <div class="row"> </div> </fieldset> <fieldset class="form-group"> answer </fieldset> <div class="form-group"> <button href="" class="btn btn-outline-info" type="submit"> Convert </button> </div> </form> </div> {% endblock content %} also my view.py: def conversion(request): form = ConversionForm() context = { 'form':form, 'input':False } return render(request, 'dashboard/conversion.html',context) and my forms.py: class ConversionForm(forms.Form): CHOICES = [('length'),('Length'),('mass'),('Mass')] measurment = forms.ChoiceField(choices = CHOICES, widget=forms.RadioSelect) that part i puted #####, is when i add it to my code, An error occurs: Error: Exception Value:too many values to unpack (expected 2) also this can i see in errors: Error during template rendering In template C:\Users\peima\AppData\Roaming\Python\Python310\site-packages\django\forms\templates\django\forms\table.html, error at line 16