Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I keep getting an "Invalid Format" error when creating Python Models with timestamps
Hey guys I'm creating a basic app and it was running fine until I created a new table with my Models.py file that had a timestamp. My NewPost model already had the Timestamp and that was working fine. However, when I run migrate (makemigrations runs OK) I'm now getting a weird error in the console that the format is not correct and I'm unable to start my app. I delete the timestamp fields, and I'm still getting the error! Can someone help me figure out what to do? Below is the error and my Models.py code. If you need any more code let me know. Thanks! Models.py: from django.contrib.auth.models import AbstractUser from django.contrib.postgres.fields import ArrayField from django.db import models from datetime import datetime class User(AbstractUser): userRanking = models.IntegerField(default=0) class NewPost(models.Model): username = models.CharField(max_length=64) body = models.CharField(max_length=64) category = models.CharField(max_length=64, default="movies") title = models.CharField(max_length=64, default="Hi", null="True") rating = models.IntegerField(default=0) timestamp = models.DateTimeField(auto_now_add=True, null=True) class Vote(models.Model): postID = models.IntegerField(default=0) userID = models.IntegerField(default=0) upVotes = models.IntegerField(default=0) downVotes = models.IntegerField(default=0) class Reply(models.Model): postID = models.IntegerField(default=0) username = models.CharField(max_length=64) body = models.CharField(max_length=64, default="") rating = models.IntegerField(default=0) timestamp = models.DateTimeField(auto_now_add=True, null=True) Error Message in Console: C:\school\project4>python manage.py migrate network Operations to perform: Apply all migrations: network … -
How to make a ModelForm with many to many relationship in Django?
I'm making a form that needs to send multiple "estados", and I need it to be able to send one or even 5 items at once. I have 3 tables connected by "estados" with an intermediary "flora2estado" table: models.py: class Listaflor(models.Model): especie_id = models.AutoField(primary_key=True) estados = models.ManyToManyField(Estados, through='Flora2Estado') class Flora2Estado(models.Model): estado = models.ForeignKey(Estados, models.DO_NOTHING, primary_key=True) especie = models.ForeignKey('Listaflor', models.DO_NOTHING) Class Estados(models.Model): estado_id = models.AutoField(primary_key=True) estado_nome = models.CharField(max_length=100, blank=True, null=True) views.py def CreateFlo(request): form = FloForm() if request.method == 'POST': form = Flo(request.POST) if form.is_valid(): Listaflor = form.save(commit=False) Listaflor.aprovado_id = 2 Listaflor.save() context = {'form': form} return render(request,'accounts/flora_form.html', context) forms.py: class FloForm(forms.ModelForm): class Meta: model = Listaflor fields = ['Especie','familia','estados' ] exclude = ["aprovado"] -
Can't find a github package inside docker container
I've been trying to install a github repository inside a docker container through a requirements.txt file. Running "docker-compose build --no-cache" I can see it being installed, but when I get inside the container itself, I try a "pip freeze" and all the other packages explicited inside requirements.txt are there, except the one from github. Here is my requirements: psycopg2-binary>=2.8,<2.9 Pillow>=7 django-rosetta gunicorn pytest pytest-django pytest-bdd pytest-xdist djangorestframework -e git://github.com/tb-brics/dorothy-data-reader.git#egg=xrayreader and my dockerfile (not complete here but I guess this is enough for understanding the problem): #Setting working environment WORKDIR /service #Here is where we will mount the volume containing all the x-ray images RUN mkdir /imagesrep RUN chown -R www-data:www-data /imagesrep #Installing dependencies COPY requirements.txt ./ RUN pip install --upgrade pip RUN pip install --no-cache-dir -r requirements.txt #Copying necessary files for production execution. COPY django ./ #Creating folder to contain static files. RUN mkdir -p /var/www/dorothy/static RUN chown -R www-data:www-data /var/www/dorothy/static #Creating folder for dorothy logs RUN mkdir -p /var/log/dorothy RUN chown -R www-data:www-data /var/log/dorothy Really need this asap, accepting any suggestion, thanks. -
How i can update email in a stripe customer object?
i didn't able to update the email of o customer with stripe API. This is the way what i have do, but in dashboard, the new email of customer not updated. stripe.Customer.modify(customer.id, metadata={'email': newEmail}) what i have to do? thanks for your time. -
Emulating JS environment in Django
I am developing a Django webapp and I need to enable users to submit JavaScript programs as solutions to certain puzzles. Those programs need to be ran by my server against a number of inputs, and their output need to match the expected one (stored in a json file or db record), or ran through a verification function that can give a parametrized score to the program provided by the user. This is pretty different than anything I've ever done. I'd like to be pointed to the right direction. What's the best way to execute JS code in a sandbox inside of python? Is there any way to preferably accomplish this inside of django? Any libraries worth checking out? -
using MySql with Django
I am trying to connect MySql to the Django project on Windows 10, and I am getting this error when using this command : pip install mysqlclient even though I installed visual studio tools and c++, the error : ERROR: Command errored out with exit status 1: command: 'c:\users\tech one\appdata\local\programs\python\python39\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\Tech One\AppData\Local\Temp\pip-install-7i9pm26h\mysqlclient\setup.py'"'"'; file='"'"'C:\Users\Tech One\AppData\Local\Temp\pip-install-7i9pm26h\mysqlclient\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record 'C:\Users\Tech One\AppData\Local\Temp\pip-record-sgylccv3\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\users\tech one\appdata\local\programs\python\python39\Include\mysqlclient' cwd: C:\Users\Tech One\AppData\Local\Temp\pip-install-7i9pm26h\mysqlclient Complete output (23 lines): running install running build running build_py creating build creating build\lib.win-amd64-3.9 creating build\lib.win-amd64-3.9\MySQLdb copying MySQLdb_init_.py -> build\lib.win-amd64-3.9\MySQLdb copying MySQLdb_exceptions.py -> build\lib.win-amd64-3.9\MySQLdb copying MySQLdb\connections.py -> build\lib.win-amd64-3.9\MySQLdb copying MySQLdb\converters.py -> build\lib.win-amd64-3.9\MySQLdb copying MySQLdb\cursors.py -> build\lib.win-amd64-3.9\MySQLdb copying MySQLdb\release.py -> build\lib.win-amd64-3.9\MySQLdb copying MySQLdb\times.py -> build\lib.win-amd64-3.9\MySQLdb creating build\lib.win-amd64-3.9\MySQLdb\constants copying MySQLdb\constants_init_.py -> build\lib.win-amd64-3.9\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win-amd64-3.9\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win-amd64-3.9\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win-amd64-3.9\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win-amd64-3.9\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win-amd64-3.9\MySQLdb\constants running build_ext building 'MySQLdb._mysql' extension error: Microsoft Visual C++ 14.0 is required. Get it with "Build Tools for Visual Studio": https://visualstudio.microsoft.com/downloads/ ---------------------------------------- ERROR: Command errored out with exit status 1: 'c:\users\tech one\appdata\local\programs\python\python39\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\Tech One\AppData\Local\Temp\pip-install-enter code here7i9pm26h\mysqlclient\setup.py'"'"'; file='"'"'C:\Users\Tech One\AppData\Local\Temp\pip-install-7i9pm26h\mysqlclient\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' … -
Semantic UI accordion with a modal inside shows when visible
I am using Semantic UI accordion to show different tables. The problem is that I have a modal on each table's row to show the deatils of that row. Everything works fine when click on the row (the modal pops up). But when I click the dropdown to show the rows the modals are shown too. I see that $('.ui.accordion').accordion() adds transition and visible classes to all his childs. So, I don't know if there is a way in Javascript to remove/modify classes AFTER .accordion() ends. I mean AFTER because the changes should be triggered after .accordion() and not asynchronous. Any help? Regards This is my code: <div class="ui accordion"> {% for status in status_list %} <div class="title"> <i class="dropdown icon"></i> <h3>{{status.grouper}}s</h3> </div> <div class="content"> <table class="ui olive selectable table transition hidden tablesorter" id="{{status.grouper}}"> <thead> <tr> <th>Name <i class="sort icon"></i></th> <th>Industry <i class="sort icon"></th> <th>Country <i class="sort icon"></th> ..... </tr> </thead> <tbody> {% for account in status.list %} <tr> {% comment %} TODO: Agregar link para modal de edit {% endcomment %} <td class="modal-button" data-account="{{account.slug}}" data-tooltip="Click for details" data-position="top left" data-inverted=""><a href="#">{{account.name}}</a></td> <td>{{ account.industry}}</td> <td><i class="{{account.country|lower}} flag"></i>{{ account.country}}</td> .... </tr> {% include 'accounts/modals.html' %} {% endfor %} </tbody> </table> </div> … -
how to retrieve first instance of saved value as string
what I am looking is retrieve the saved value from models as string, I tried this way class ExternalKeys(models.Model): public = models.CharField(max_length=80, blank=True, null=True) secret = models.CharField(max_length=80, blank=True, null=True) webhook_secret = models.CharField(max_length=80, blank=True, null=True) and call it in views as this stripe.api_key = ExternalKeys.objects.first().public but this is not working, but if I do this way it prints the correct value to template def get_public_key(request): public = ExternalKeys.objects.first().public return render(request, 'templat.html', {'public': public}) so how I can get this value as sting in views -
Django Unix Socket not connecting to Cloud SQL
Hey so I'm trying to connect my Django server properly to Cloud SQL but no luck. After double checking the Environment Variables, I tried reading the logs and I see issues like: connections on Unix domain socket "/cloudsql/project_name:us-central1:db_instance_name/.s.PGSQL.5432"? Connect exception: could not connect to server: No such file or directory Here are my production settings currently connecting to the Cloud SQL instance. DB_NAME = os.environ.get("DB_NAME") DB_USER_NM = os.environ.get("DB_USER_NM") DB_USER_PW = os.environ.get("DB_USER_PW") INSTANCE_CONNECTION_NAME = os.environ.get('INSTANCE_CONNECTION_NAME') DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': DB_NAME, 'USER': DB_USER_NM, "PASSWORD": DB_USER_PW, "HOST": f'/cloudsql/{INSTANCE_CONNECTION_NAME}', } } I feel like its a settings issue in GCP and nothing to do with coding. Please help me out! Thanks -
Django DetailView getting access to users in M2M field to restrict access?
I am currently working with a DetailView, returning a JsonResponse of some business details. I am using the test_func and UserPassesTestMixin to make sure that only users who have is_admin=True are getting access to these admin only views. Now in my BusinessDetail model, I have a field called owner which is a M2M field linked to users who are owners of the business. I also need to restrict views of course to make sure that self.request.user is in the BusinessDetail model's owner field. I have tried a few things including this... class BusinessDetailView(LoginRequiredMixin, UserPassesTestMixin, DetailView): model = BusinessDetail def test_func(self): return self.request.user.is_admin def get_object(self, queryset=None): business = get_object_or_404(BusinessDetail, pk=self.kwargs.get('pk')) serialized_obj = serializers.serialize('json', [business]) return serialized_obj def get(self, request, *args, **kwargs): try: business = self.get_object() logger.debug(business obj: {business}') if self.request.user not in business.owner.all(): logger.debug('Error: Access not granted.') return JsonResponse({'Error': 'Access restricted.'}) return JsonResponse(json.loads(business), status=200, safe=False) except Exception as e: logger.error(f'Error getting business detail with error: {e}') return JsonResponse({'Error': 'DB error, return to previous page'}, status=500) My logger is looking like... ==> /var/log/app/logger/debug.log <== DEBUG 2020-12-08 21:35:19,935 /app_site/business_admin/views.py get 379 Business obj: [{"model": "authentication.business_detail", "pk": 3, "fields": {"name": "test name", "phone_no": "(111)-111-1111", "street": "111 5th st, "city": "Fort Lauderdale", "state": "Florida", "zip": … -
Should backend variables be updated to match frontend changes?
A project I am working on involves categorising data into four separate categories. These categories are pivotal to the project logic and appear everywhere in the code. The project is pretty much finished. Yesterday, the client asked us to rename the categories. This is a very simple change to appear in the frontend, only a few lines of code. However, the old names are used in many variable names spread throughout the backend, and it would take quite a while to comb through the code and update all variable names and comments. Is it better to keep the old variable names and save time and keep things consistent for existing developers, or spend the time changing the variable names and ensure the frontend and backend are consistent and make things clearer for future development? -
How to provide Django error codes that are not hardcoded
I'm currently implementing some System Checks of my own, and noticed that Django recommends using hardcoded error identifiers, like so: Error( 'an error', hint='A hint.', obj=checked_object, id='myapp.E001', ) I thought that maybe this is merely serving tutorial purposes, but turns out that's actually how they do it. From the same code above, I noticed that they use a prefix scheme for identifying the type of message that is being created (e.g. E for Error, W for Warning, C for Critical, etc). But I don't understand the numbering system. You just enter any three digit number and that's it? What happens if there's a collision? Has anyone come across a better paradigm to manage the error codes? -
Django tenant Access another tenant data from public
Need to pass tenant specific user data to template. I've done following things. class ClientDetailView(DetailView): model = Client template_name = 'customer/detail.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) with schema_context(self.object.schema_name): context['users'] = User.objects.all() return context django-tenants schema context decorator is like below class schema_context(ContextDecorator): def __init__(self, *args, **kwargs): self.schema_name = args[0] super().__init__() def __enter__(self): self.connection = connections[get_tenant_database_alias()] self.previous_tenant = connection.tenant self.connection.set_schema(self.schema_name) def __exit__(self, *exc): if self.previous_tenant is None: self.connection.set_schema_to_public() else: self.connection.set_tenant(self.previous_tenant) On exit it just reset schema and also reset my user data of previous tenant. Is there anyway to get required tenant data? -
Django - Class Table Inheritance with model forms
I am very confused about how will I achieve my goal of doing this in Django, I am a beginner. It is quite simple, all I want is to create a form from models, and eventually use it to get the data back from it via POST when the user submits it. The user should be able to select the category first. e.g He goes over to Electronics -> PC and eventually should be able to select any of the last subcategory like Deskstop or Laptop and it's form should then be generated for the user to fill. Confusing part for me is that I am using Class Table Inheritence here and I am new to Django so it is getting hard for me to do this simply. Now to sum it up, anyone's help is greatly appreciated if he can tell how it's done with Models Form. I will add many more categories with their subcategories so no cheating, Models Form should be dynamic else it will get really tedious writing each ModelForm for every category and subcategory I will create Optional is if you can also help with the POST request after the form is finally submitted considering … -
django restful api with nested objects in url
I am try to expose an endpoint which looks like /v1/organizaions/org1/members so that I would be able to post to it and create a new member. The member model has org_id field but I can't figure out how to hook up the ModelViewSet to populate the new member object's org_id with the id corresponding to org1. Looking for some example code. -
Apache permissions overriding Django function for authorization check
I built an app where users can upload their files and only the user who uploaded the file can view it. This was working while I was developing the application but now after I hosted in on a VPS with Apache, it doesn't work. I gave permissions to www-data to create and read files and folders inside of /file which is a folder where I save all of the files. A folder inside of file is created for each user when he uploads his first file and the name of that folder is the username of the user i.e. if TestUser uploads his first file, then a folder will be created at /file/TestUser. I wrote a function that checks if the URL which the user opens, has /file in it. If it does, it check if it has the user's username and then opens the file. I have no clue why is this not working now, and anyone can open any file. def auth_file_check(request): url = request.build_absolute_uri() if not '//' in url: url = 'http://' + url o = urlparse(url) user = o.path.split("/") if str(request.user) == user[2].split("_", 1)[1] or request.user.is_superuser: # Change link to path where files will be stored … -
display category and sub category in django
I am Working on the Web Application and it needs to show the categories and sub catgories to the side bar. Here is the screenshot of the database.please take a look and hep enter image description here def home(request): return render(request,"myApp/index.html") def info(request): ac = REFERENCE_DATA_LOOKUP.objects.all() L_C_U = L_C_S = L_W_U = L_W_S =L_S_U= L_P_S= L_N_I= L_C_O=0 for row in Kpi_Data.objects.all(): if (row.kpi_Group == 'LOGIN_STATS' and row.kpi_subgroup== 'CONSUMER_PORTAL' and row.kpi_key == 'CP_USER'): L_C_U = row.kpi_value if (int(row.kpi_delta_ind) >= 0): L_C_U_A = 0 elif (int(row.kpi_delta_ind) < 0): L_C_U_A = -1 elif (row.kpi_Group == 'LOGIN_STATS' and row.kpi_subgroup== 'CONSUMER_PORTAL' and row.kpi_key == 'CP_SCRNS'): L_C_S = row.kpi_value if (int(row.kpi_delta_ind) >= 0): L_C_U_S = 0 or 1 elif (int(row.kpi_delta_ind) < 0): L_C_U_S = -1 elif (row.kpi_Group == 'LOGIN_STATS' and row.kpi_subgroup== 'WORKER_PORTAL' and row.kpi_key == 'WP_USER'): L_W_U = row.kpi_value if (int(row.kpi_delta_ind) >= 0): L_W_U_A = 0 elif (int(row.kpi_delta_ind) < 0): L_W_U_A = -1 elif (row.kpi_Group == 'LOGIN_STATS' and row.kpi_subgroup== 'WORKER_PORTAL' and row.kpi_key == 'WP_SCRNS'): L_W_S = row.kpi_value if (int(row.kpi_delta_ind) >= 0): L_W_U_S = 0 elif (int(row.kpi_delta_ind) < 0): L_W_U_S = -1 elif (row.kpi_Group == 'APP_STATS' and row.kpi_subgroup== 'CONSUMER_PORTAL' and row.kpi_key == 'CP_SUB'): L_S_U = row.kpi_value if (int(row.kpi_delta_ind) >= 0): L_C_P_S = 0 elif (int(row.kpi_delta_ind) < 0): … -
Djagno Rest Framework, updating multiple objects in one
I am trying to update using PATCH to my Django backend. This is the request I am sending: [ { "pk":78, "weekday":1, "from_hour":"21:00", "to_hour":"12:00:00", "closed":false, "lunch":true, "lunch_start":null, "lunch_end":null, "lunch2":false, "lunch_start2":null, "lunch_end2":null, "appointment_interval":15, "num_appointments_interval":4, "office":79 }, { "pk":79, "weekday":2, "from_hour":"09:00:00", "to_hour":"12:00:00", "closed":false, "lunch":true, "lunch_start":null, "lunch_end":null, "lunch2":false, "lunch_start2":null, "lunch_end2":null, "appointment_interval":15, "num_appointments_interval":4, "office":79 }, { "pk":80, "weekday":3, "from_hour":"09:00:00", "to_hour":"12:00:00", "closed":false, "lunch":true, "lunch_start":null, "lunch_end":null, "lunch2":false, "lunch_start2":null, "lunch_end2":null, "appointment_interval":15, "num_appointments_interval":4, "office":79 }, { "pk":81, "weekday":4, "from_hour":"09:00:00", "to_hour":"12:00:00", "closed":false, "lunch":false, "lunch_start":"14:59:50", "lunch_end":"14:59:51", "lunch2":false, "lunch_start2":null, "lunch_end2":null, "appointment_interval":15, "num_appointments_interval":4, "office":79 }, ] I send this to a custom view where I am trying to serialize and update the data. @api_view(['PATCH']) @parser_classes((JSONParser,)) def updateOfficeHours(request): office_id = request.data[0]['office'] qs = OfficeHour.objects.filter(office__pk=office_id) office_hours = OfficeHoursSerializer(qs, data=request.data, many=True, partial=True) if not office_hours.is_valid(): print(":(") return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR) else: office_hours.save() return Response(status=status.HTTP_200_OK) I only end up getting this error: AttributeError: 'QuerySet' object has no attribute 'pk' It seems like this error comes up when you are looking for one object, but I have many=True. What am I doing wrong? -
Can't submit a csrf token using javascript in Django
I'm using the following code to submit a csrf token purely in js since I want to cache the pages with the form. axios.defaults.xsrfHeaderName = 'X-CSRFTOKEN' axios.defaults.xsrfCookieName = 'csrftoken' axios.defaults.withCredentials = true This works locally (localhost, 127.0.0.1) without a problem. This is to get rid of the 403 errors that happen when I login into the app and try to submit a form that no longer has a csrf token embedded in the dom. The issue is I can't get this run in our development environment. The development environment uses CloudFront but i don't think that's an issue. Here is my dev config for Wagtail + Django: #Important for CloudFront USE_X_FORWARDED_HOST = True # Security Headers SECURE_HSTS_SECONDS = 63072000 SECURE_HSTS_PRELOAD = True SECURE_HSTS_INCLUDE_SUBDOMAINS = False CSRF_COOKIE_SECURE = True SESSION_COOKIE_SECURE = True UPGRADE_INSECURE_REQUESTS = True SECURE_BROWSER_XSS_FILTER = True SECURE_CONTENT_TYPE_NOSNIFF = True PREPEND_WWW = False All my API views have csrf_exempt on them, but i still need the token when i try to submit after a login. My middleware is: MIDDLEWARE = [ "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.locale.LocaleMiddleware", "app.site_translation.middleware.TranslationMiddleware", "django.middleware.common.CommonMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", "django.middleware.security.SecurityMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "app.base.middleware.AdditionalSecurityHeadersMiddleware", "app.base.middleware.CookieMiddleware", "app.base.middleware.DomainRedirectMiddleware", "app.base.middleware.CustomRedirectMiddleware", "app.base.middleware.LegacyURLsMiddleware", "debug_toolbar.middleware.DebugToolbarMiddleware", ] I don't know what is going on I keep getting CSRF Failed: CSRF … -
Django assign a task to many users
I want to create a task for many users(students) but I want every student to have his own "copy" of this task so students can't edit each other's tasks. E.g.: I, as a teacher, creates a task and assign 4 students to that task. Every student get exactly the same task and can change it's progress etc. Does anyone has any idea how to achieve that? I've stucked. Thanks in advance. models.py class Task(Timestamp): STATUSES = ( ("new", "new"), ("in-progress", "in-progress"), ("done", "done") ) id = models.UUIDField(primary_key=True, default=uuid.uuid4, unique=True, editable=False) owner = models.ForeignKey(CustomUser, on_delete=models.CASCADE) title = models.CharField(max_length=50) description = models.TextField() status = models.CharField(choices=STATUSES, max_length=50, default="new") students = models.ManyToManyField(CustomUser, related_name='students') def __str__(self): return self.title serializers.py class TaskSerializer(serializers.ModelSerializer): owner = serializers.HiddenField( default=serializers.CurrentUserDefault() ) class Meta: model = Task fields = [ 'id', 'owner', 'created_at', 'updated_at', 'title', 'description', 'status', 'attachments', 'students' ] -
Understanding order_by of multi-valued fields (Django)
Having read the django docs on order_by there is a note/warning that (if I have understood correctly) says that: If you are ordering a queryset using a multi-valued field, then every element in that queryset that has multiple related items, will be added multiple times to the resulting queryset created by order_by. I tried testing this out with a basic example: Minimal Reproducible Example class Pizza(models.Model): name = models.CharField(max_length=100) toppings = models.ManyToManyField('Topping', through='PizzaToppings') class PizzaToppings(models.Model): pizza = models.ForeignKey('Pizza', on_delete=models.CASCADE, related_name="pizza_toppings") topping = models.ForeignKey('Topping', on_delete=models.CASCADE, related_name="pizzas_with_topping") amount = models.IntegerField() class Meta: ordering = ["amount",] class Topping(models.Model): ingredient = models.CharField(max_length=100) then >>> p1 = Pizza.objects.create(name="Cheese and Tomato") >>> p2 = Pizza.objects.create(name="Pepperoni") >>> cheese = Topping.objects.create(ingredient="Cheese") >>> tomato = Topping.objects.create(ingredient="Tomato puree") >>> p1.toppings.add(cheese, through_defaults={"amount":4}) >>> p1.toppings.add(tomato, through_defaults={"amount":3}) >>> p2.toppings.add(cheese, through_defaults={"amount":2}) >>> p2.toppings.add(tomato, through_defaults={"amount":1}) So far, so normal. But this is where things get confusing: >>> q1 = Topping.objects.all() <QuerySet [<Topping: Topping object (1)>, <Topping: Topping object (2)>]> >>> q2 = p1.toppings.all() <QuerySet [<Topping: Topping object (1)>, <Topping: Topping object (2)>]> >>> q1.order_by("pizzas_with_topping") <QuerySet [<Topping: Topping object (2)>, <Topping: Topping object (1)>, <Topping: Topping object (2)>, <Topping: Topping object (1)>]> >>> q2.order_by("pizzas_with_topping") <QuerySet [<Topping: Topping object (2)>, <Topping: Topping object (1)>]> The problem As … -
ModuleNotFoundError: No module named 'crud.core' in python 3 and windows 10
Researched a bit and haven't found any solution whatsoever. My application name is CRUD. Whenever I try to run my application using the: python manage.py runserver I get the following error: ModuleNotFoundError: No module named 'crud.core' I used the following commands: python -m venv crud pip install django pip install djangorestframework python manage.py startapp rental And the file that's causing trouble (api.py): from rest_framework import routers from .core import views as myapp_views router = routers.DefaultRouter() router.register(r'friends', myapp_views.FriendViewset) router.register(r'belongings', myapp_views.BelongingViewset) router.register(r'borrowings', myapp_views.BorrowedViewset) I'm on windows and running python 3.9.0 -
How to determine Django version of a given code?
I have a site in Django. How to know (by watching at code), which version of Django it requires and which Python it requires? -
How to access individual form objects from a modelformset_factory?
I've deployed a formset using modelformset_factory. However rather than saving the entire formset, I need to loop through the forms in the formset, perform some logic on them, and save each one individually. At the moment I'm having to use the ID from each form in the formset to get the object it represents. Is there a cleaner way of doing this? def accounts_import(request,pk): account = get_object_or_404(Account, pk=pk) # Create transactions queryset for use in formset transactions = Transaction.objects.filter(account=account.monzo_account, import_type=None).order_by('-id') FormSet = modelformset_factory(Transaction, form=TransactionsImportForm, extra=0) if request.method == 'POST': formset = FormSet(request.POST) if formset.is_valid(): for form in formset: object = Transaction.objects.get(id=form.cleaned_data['id']) # Do some stuff on the object object.save() -
How make users own their data in django
Currently, if you’re logged in, you’ll be able to see all the products, no matter which user you’re logged in as.how can i show merchants only the products that belongs to them. i try this views.py def users_homepage(request): product=Product.objects.filter(merchant=request.user).order_by('date_added') and i get this error " Cannot query "mustapha": Must be "Merchant" instance" my models.py class Merchant(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE, primary_key=True) class Product(models.Model): merchant=models.ForeignKey(Merchant, on_delete=models.CASCADE) date_added = models.DateTimeField(auto_now_add=True)