Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting one or zero elements of QuerySet in Django?
In Django 3.1, suppose I have some model M, and I have a QuerySet over M that I expect has either one or zero elements. How do I branch on whether it is one or zero elements (throwing an exception if it has two or more), and in the branch with one element, how do I get the one M object: try: my_query_set = M.objects.filter(some_filter_expr) if ???: m = ??? # the one M object else: on_zero_objects() except ???: more_than_one_object() -
Django rest framework CORS( Cross Origin Resource Sharing) is not working
I have done token authentication for the url 'localhost:8000/api/posts' and according to django-cors-headers library I have also changed the settings.py file. Here is my settings.py file, INSTALLED_APPS = [ 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', 'rest_framework', 'rest_framework.authtoken' ] Here is my middleware settings, MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', '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.middleware.clickjacking.XFrameOptionsMiddleware', ] Here are my other settings, CORS_ALLOW_ALL_ORIGINS = False CORS_ALLOW_CREDENTIALS = True CORS_ALLOWED_ORIGINS = ["http://127.0.0.1:4000"] Here I have given access only for "http://127.0.0.1:4000" This is my client django project views file which is hosted on "http://127.0.0.1:3000" import requests from django.http import HttpResponse def get_token(): url = "http://127.0.0.1:8000/api/authentication/" response = requests.post(url, data={'username':'thomas','password':'thomas1234567890'}) token=response.json() return token token=get_token() def get_details(): url = "http://127.0.0.1:8000/api/posts/" header = {"Authorization": "Token {}".format(token['token'])} response = requests.get(url, headers = header) return response.text def homepage(request): x= get_details() return HttpResponse(x) Now even though I am requesting for the data from other domain which is not mentioned on django cors origin whitelist, I am able to fetch the data without any error, I am not able to restrict other domains for accessing the data. Can anyone please help me in solving this issue. -
Need help on Matching Engine
I am trying to simulate stock trading app as part of an assignment in django. I found one python algorithm for order matching but I am not sure how can I use this in django model. from django.db import models from threading import Thread from collections import deque class Order(models.Model): # order_type = models.CharField(max_length=255, blank=True, null=True) # order_side = models.CharField(max_length=255, blank=True, null=True) # price = models.DecimalField(max_digits=10, decimal_places=2,default=0.00) # quantity = models.IntegerField(default=0) def __str__(self): return self.order_type def __init__(self, order_type, side, price, quantity): self.type = order_type self.side = side.lower() self.price = price self.quantity = quantity class Trade(models.Model): pass def __init__(self, price, quantity): self.price = price self.quantity = quantity class OrderBook: def __init__(self, bids=[], asks=[]): self.bids = sortedcontainers.SortedList(bids, key = lambda order: -order.price) self.asks = sortedcontainers.SortedList(asks, key = lambda order: order.price) def __len__(self): return len(self.bids) + len(self.asks) def add(self, order): if order.direction == 'buy': self.bids.insert(self.bids.bisect_right(order), order) elif order.direction == 'sell': self.asks.insert(self.asks.bisect_right(order), order) def remove(self, order): if order.direction == 'buy': self.bids.remove(order) elif order.direction == 'sell': self.asks.remove(order) def plot(self): fig = plt.figure(figsize=(10,5)) ax = fig.add_subplot(111) ax.set_title("Limit Order Book") ax.set_xlabel('Price') ax.set_ylabel('Quantity') # Cumulative bid volume bidvalues = [0] for i in range(len(self.bids)): bidvalues.append(sum([self.bids[x].quantity for x in range(i+1)])) bidvalues.append(sum([bid.quantity for bid in self.bids])) bidvalues.sort() # Cumulative ask … -
how can i get total price from ManyToManyField in django?
how can i calculate each vital price with ManyToManyField. if you have any other option please tell me. if i add some vitals in patient report then how can i get the total price of these vitals? Patient from django.db import models from vital.models import Vital class Patient(models.Model): name = models.CharField(max_length=50) father = models.CharField(max_length=50) age = models.CharField(max_length=2) sex = models.CharField(choices=GENDER_CHOICES, max_length=6) phone = models.CharField(max_length=11, blank=True) vitals = models.ManyToManyField(Vital) def __str__(self): return f'{self.name} {self.father}' Vital from django.db import models class Vital(models.Model): name = models.CharField(max_length=100, help_text='Test name') price = models.IntegerField(default=0) def __str__(self): return self.name -
When does Django commit transactions in management commands/outside views?
I have a Django app managing some ETL jobs. The ETL jobs live in a subdirectory of my main app called /scripts. Each ETL job has its own script with a single run() function that contains the ETL logic. I use the django-extensions run_script command to execute these scripts manually. Otherwise, they are run on a schedule using APScheduler. The jobs collect data from a source database, does some transformations, then are created as models in the Django database. The source database is normalized and relational, so I am often creating a model instance that will be referenced in the same script later as a foreign key. For example, suppose I have a City model and a Street model that are related via foreign-key: class City(Model): name = models.CharField(max_length=100) class Street(Model): name = models.CharField(max_length=100) city = models.ForeignKey(City, on_delete=CASCADE) In the source database, it's frequent that a new City and its related Streets are created on the same day, and thus, are also both created for the first time in the Django database. So effectively, this can happen in the same script executed by APScheduler or run_script: new_city = City(name='Boston') new_city.save() ... ... existing_city = City.objects.get(name='Boston') # DoesNotExist new_street = Street(name='Mass … -
Can someone clarify these tasks for Django app?
I've been learning django since 6 days and I got a task with this TODO list which I cannot clearly understand. So, can anybody help me with understanding and maybe expanding these? I understand the generic views tasks etc. but I don't know what expenses.Category for example is. Is it a file which I have to create? Is it a model? I'am a total newbie who's still learning whole structure of projects in Django and else, that's why I would absolutely appreciate your help, It would help me a lot. my project structure | app screen Allow searching by date range in expenses.ExpenseList. Allow searching by multiple categories in expenses.ExpenseList. In expenses.ExpenseList add sorting by category and date (ascending and descending) In expenses.ExpenseList add grouping by category name (ascending and descending) In expenses.ExpenseList add total amount spent. Add list view for expenses.Category. Add number of expenses per category per row in expenses.CategoryList. Add create view for expenses.Category. Add update view for expenses.Category. Add message for create/update in expenses.Category if name already exists Add delete view for expenses.Category. In expenses.CategoryDelete add total count of expenses that will be deleted. Add detail view for expenses.Category with total summary per year-month. Add option … -
filtering using a OneToOneFields returning empty query set
I have a User model with phone field as pk. The a Transaction model with recharge_number as a OneToOne field. I can not filter data from Transaction model using the phone number even though i do a print and the number is received from the request successfully. Below are my code: Models.py - User class User(AbstractBaseUser): phone = models.CharField(max_length = 15, unique = True) first_name = models.CharField(max_length = 50, blank = False, null = False) last_name = models.CharField(max_length = 50, blank = False, null = False) Models.py - Transaction class Transaction(models.Model, Main): recharge_number = models.OneToOneField(User, on_delete=models.CASCADE, related_name='recharge_number') network = models.CharField(choices=Main.NETWORK, max_length=10) recharge_amount = models.DecimalField(decimal_places=2, max_digits=10000) serializers.py - TransactionDetailSerializer class TransactionDetailSerializer(serializers.ModelSerializer): model = Transaction fields = ( 'recharge_number', 'network', 'recharge_amount' ) views.py - Transactions class Transactions(RetrieveAPIView): def get(self, request, *args, **kwargs): phone = request.data.get('recharge_number', False) print(phone) transaction = Transaction.objects.filter(recharge_number=phone).order_by("-timestamp") serializer = TransactionDetailSerializer(transaction, many=True) return Response(serializer.data, status=status.HTTP_200_OK) Results gets an empty Query - <QuerySet []>. Should not be as they are lots on transaction records with the phone number Thanks -
Hosted django app not showing images but it wasshown on local server...i hosted on heroku
It shows card image cap instead of displaying image enter image description here -
url has more than expected django mediaFile in django
I have a model Photo class Photo(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4) created_at = models.DateTimeField(auto_now_add=True) photo = models.ImageField(upload_to='dice') title = models.CharField(max_length=30) kind = models.CharField(max_length=30) size = models.CharField(max_length=30) strength = models.CharField(max_length=30) combinations = models.CharField(max_length=30) favors = models.CharField(max_length=30) availability = models.BooleanField(default=True) iscarousel = models.BooleanField(default=False) def __str__(self): return "%s %s %s %s %s %s %s %s %s %s" % (self.created_at, self.photo, self.title, self.kind, self.size, self.strength, self.combinations, self.favors, self.availability, self.iscarousel) in a template or view when I get a photo and do photo.photo.url I get the url that the photo is associated with but with a ? and right after the question mark more characters appended. I don't understand why this is but basically because of this my image does not render How do I get my url to just be the url of where my image is saved in aws -
I have learned a part of front-end but i prefer back-end so which the best for back-end php or python [closed]
Which the best for back-end php or python ? -
Django forms filter greater than doesn't work
I'm trying to filter a chained dropdown list, so it only shows hora greater than 0. But I don't know why .filter(cupos__gt=0) in forms.py doesn't work but if I try to print it in the terminal it works forms.py class ReservaForm(forms.ModelForm): class Meta: model = Reserva fields = ('actividad', 'dia', 'hora') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['dia'].queryset = Dia.objects.none() if 'actividad' in self.data: try: actividad_id = int(self.data.get('actividad')) self.fields['dia'].queryset = Dia.objects.filter(actividad_id=actividad_id).order_by('name') except (ValueError, TypeError): pass # invalid input from the client; ignore and fallback to empty Dia queryset elif self.instance.pk: self.fields['dia'].queryset = self.instance.actividad.dia_set.order_by('name') self.fields['hora'].queryset = Hora.objects.none() if 'dia' in self.data: try: dia_id = int(self.data.get('dia')) self.fields['hora'].queryset = Hora.objects.filter(dia_id=dia_id,cupos__gt=0).order_by('name') except (ValueError, TypeError): pass # invalid input from the client; ignore and fallback to empty Dia queryset elif self.instance.pk: self.fields['hora'].queryset = self.instance.dia.hora_set.order_by('name') views.py def reserva_add(request): form = ReservaForm() hora = Hora.objects.filter(cupos__gt=0) print(hora) context = { 'form': form, } return render(request, "agenda/reserva_form.html", context) Terminal <QuerySet [<Hora: 09:00:00 52 >]> 8 am shouldn't appear -
Django pagination based on a field not a number of records per page
Using Django 3.1 I want to allow users to be able to paginate based on a table column value - same value - one page. I use ListView CBV to show a table where one column is a date and one date should be shown on one page. So instead of: class RecipeListView(SingleTableMixin, LoginRequiredMixin, FilterView): model = Recipe table_class = RecipeTable template_name = 'kitchen/recipe/list.html' filterset_class = RecipeFilter form_class = RecipeSearchForm paginate_by = 15 I am trying to achieve something like this: class RecipeListView(SingleTableMixin, LoginRequiredMixin, FilterView): model = Recipe table_class = RecipeTable template_name = 'kitchen/recipe/list.html' filterset_class = RecipeFilter form_class = RecipeSearchForm paginate_by_attribute = 'date' Full example code: https://github.com/valasek/kicoma/blob/master/kicoma/kitchen/views.py Docs Pagination, Paginator did not helped. Any hint appreciated. -
I try to connect django with postgreSQL on ubuntu 18.04
I am newbie on django , and I am facing the following issue. I have search for solution on the web but I couldn't find any yet. File "/home/r00t/projects/mp/mp/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 187, in get_new_connection connection = Database.connect(**conn_params) File "/home/r00t/projects/mp/mp/lib/python3.6/site-packages/psycopg2/__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: invalid port number: "<5432>" settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql' 'NAME': '<mpdb>', 'USER': '<admin>', 'PASSWORD': '<r00t>', 'HOST': '<127.0.0.1>', 'PORT': '<5432>', } } I have tried the following: port no: correct database name: correct user name: correct password: correct Could you please help me out with thanks -
DjangoCMS Plugin to list out specific staff from apphook model
I am new to DjangoCMS. So please bear with me if the question is too trivial. I have made an app hook for adding staff for a website with model.py from django.db import models from filer.fields.image import FilerImageField from djangocms_text_ckeditor.fields import HTMLField from django.urls import reverse from cms.models.fields import PlaceholderField # Create your models here. class Designations(models.Model): class Meta: app_label = 'voxstaff' verbose_name_plural = 'designations' desingation = models.CharField( blank=False, help_text="Please provide a label for the Designation", unique=True, max_length=100 ) def __str__(self): return self.desingation class Staffs(models.Model): class Meta: app_label = 'voxstaff' full_name = models.CharField( blank=False, unique=True, help_text="Please enter the full name of the staff", max_length=100 ) slug = models.SlugField( blank=False, default='', help_text='Provide a unique slug for this staff member', max_length=100, ) desingation = models.ForeignKey( Designations, on_delete=models.SET_NULL, blank=True, null=True ) photo = FilerImageField( blank=True, null=True, on_delete=models.SET_NULL, ) staff_intro = HTMLField(blank=True) bio = PlaceholderField("staff_bio") is_featured = models.BooleanField() def get_absolute_url(self): return reverse("voxstaff:staffs_detail", kwargs={"slug": self.slug}) def __str__(self): return self.full_name class LinkTypes(models.Model): link_type = models.CharField(max_length=100) def __str__(self): return self.link_type class Links(models.Model): staff = models.ForeignKey(Staffs,on_delete=models.CASCADE) link_type = models.ForeignKey(LinkTypes,on_delete=models.SET_NULL,null=True,blank=True) link_url = models.CharField(max_length=200) def __str__(self): return self.link_type.link_type And cms_apps.py as below from cms.app_base import CMSApp from cms.apphook_pool import apphook_pool from django.utils.translation import ugettext_lazy as _ from .menu import StaffSubMenu … -
Django Ordering Fields in django allauth
I am trying to order the fields to be in the order of 'full name', 'email' and then 'password' but right now it is 'email', 'full_name' and then 'password'. Here is the image I tried adding this to my signUp form but it didn't work: if 'keyOrder' in self.fields: self.fields.keyOrder = ['full_name', 'email', 'password'] Here are the rest of my files: forms.py from allauth.account.forms import SignupForm from django.contrib.auth.forms import UserCreationForm, UserChangeForm from django import forms from .models import CustomUser class CustomSignupForm(SignupForm): full_name = forms.CharField(max_length=50, label='Full Name') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['full_name'].widget.attrs.update({'autofocus': 'autofocus'}) # Doesn't work if 'keyOrder' in self.fields: self.fields.keyOrder = ['full_name', 'email', 'password'] for fieldname in ['password1']: self.fields[fieldname].help_text = "Your password" adapters.py Here, I am saving the full name to customuser model from allauth.account.adapter import DefaultAccountAdapter from django import forms class UserAccountAdapter(DefaultAccountAdapter): def save_user(self, request, user, form, commit=True): """ This is called when saving user via allauth registration. We override this to set additional data on user object. """ user = super(UserAccountAdapter, self).save_user(request, user, form, commit=False) user.full_name = form.cleaned_data.get('full_name') user.save() in settings.py These are the django all-auth configuration I set at the bottom of my settings file AUTH_USER_MODEL = 'accounts.CustomUser' # django-allauth config LOGIN_REDIRECT_URL = 'home' ACCOUNT_LOGOUT_REDIRECT … -
How can I create a pdf from a django html with including text, images and graphs (result from an assessment)
I have a django web application generating an assessment result. The result page contains graphs, images and text. I created it using Chart.js I need to generate a pdf file from this same assessment result html. I tried it with pisa.pisaDocument (code bellow), it shows the text and images, but it lost the formating and doesn't show the graphs. I don't know if the problem is on chart.js or pisaDocument. I tried several different ways to generate the pdf file, that's why I'm asking myself if I should change the way I generate the graphs. def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None -
How to save url into django model
I have a model called Photo and looks like this... class Photo(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4) created_at = models.DateTimeField(auto_now_add=True) photo = models.FileField() title = models.CharField(max_length=30) kind = models.CharField(max_length=30) size = models.CharField(max_length=30) strength = models.CharField(max_length=30) combinations = models.CharField(max_length=30) favors = models.CharField(max_length=30) availability = models.BooleanField(default=True) iscarousel = models.BooleanField(default=False) def __str__(self): return "%s %s %s %s %s %s %s %s %s %s" % (self.created_at, self.photo, self.title, self.kind, self.size, self.strength, self.combinations, self.favors, self.availability, self.iscarousel) I am can save to my aws s3 bucket but I do not have a url path to it, or so I believe this is the case. How can I save my model where once I upload my photo the url gets saved in my model as well. So I am thinking that I will need a url field and I know there is a models.UrlField or something like that. I am just curious though how I tell django to extract that url and add it to some field so I can later access it. If I don't have it I don't know how I am suppose to retrieve it to later show it on my web application -
How to test Django JSON-ified ISO8601 Datetime
I'm testing with AjaxResponse with my request factory on a datetime. The problem is the string that Django gives is like this: 2020-08-27T22:46:07.354Z But when I have datetime object, and I use the isoformat() method, I don't get the same string: 2020-08-27T22:46:07.354734+00:00 How am I going to be able to assert? I'm looking to assert by comparing the JSON with my own Python list (The list is what I can customize). -
Django/HTML form input alignment
I'm trying to make something very simple. What I have is currently this: The current code is this: {% extends 'base.html' %} {% load static %} {% block content %} <style> .center { margin: auto; width: 50%; border: 3px solid green; padding: 10px; } </style> <div class='center'> <form action='.' method='POST'> {% csrf_token %} <div align="right"> <input type="text" name='title' placeholder='Food title'/> </div> <div align='left'> <input type="text" name='q' placeholder='Search Image'/> <input type="submit" value='Search!'> </div> {% for image in images %} <img src="{% static 'img/search/' %}{{ image }}", alt=""/> <input type="radio" name="imageRadio" value=" "> </br> {% endfor %} <input type="submit" value='Go!'> </form> </div> {% endblock content %} My issue is, no matter what I try, I can't get the Food title input and the search bar to line up. I would like to have them spaced apart but on the same horizontal line and not one slightly above the other. How can I achieve this? -
Fetch and XMLHttpRequest not working on IOS
Can someone please help me figure this out. Stack: Backend: Django Frontend: Vanilla Javascript/HML/CSS I have a simple web application that downloads a file that is dynamically created from user data. So I have a progress bar that is updated by polling the server to check the current download percentage. It works fine on desktop browsers and even on Android using google chrome, but it is not working on IOS (tested with Safari and Chrome on IOS 14 and IOS 13.3.1) Here is my attempt when using fetch: function updateProgressOld(token) { const statusURL = `/status/download-progress/${token}`; const progressBar = document.getElementById("progress-bar"); const progressMessageDisplay = document.getElementById("progress-message"); fetch(statusURL) .then((response) => response.json()) .then((data) => { let percentProgress = data.download_progress; let downloadToken = data.download_token; let downloadETA = data.download_eta; let progressMessage = data.progress_message; let downloadETADisplay = downloadETA ? `, ETA: ${downloadETA}` : ""; console.log(downloadETADisplay); if (downloadToken === token) { progressBar.style.width = percentProgress; progressMessageDisplay.innerText = `${progressMessage}${downloadETADisplay} ⏳`; if (progressMessage === "done") { progressMessageDisplay.innerText = "Done! File coming your way! 📥"; clearInterval(fetchStatus); } } }); const fetchStatus = setTimeout(updateProgress, 500, token); } I later tried XMLHttpRequest because I thought it might be a compatibility issue and I also tried to use a … -
Filter dates between two dates in Django Orm
I've have this model class Batch(models.Model): id = models.AutoField(primary_key=True); start_date = models.DateField(null=False, blank=False, default=date.today); end_date = models.DateField(null=False, blank=False, default=date.today); description = models.TextField(blank=True); name = models.CharField(max_length=22, null=False, blank=False, default=None); date_created = models.DateField(verbose_name='Date created', default=date.today, editable=False); school = models.ForeignKey(User,on_delete=models.CASCADE, default=None,blank=False,null=False); I need to filter "start_date" and "end_date" to check if a specified date is in between. Something like this SELECT * FROM philiri.group_batch where (Date("04-11-1997") BETWEEN start_date and end_date) Im try to use __range, __lte, __gte , __lt, __gt but it doesn't fit this problem. -
Django Channels 2.4 and Websockets giving 502 error on Elastic Beanstalk and ElastiCache
I have integrated a chat component into my django web app via django channels in a very similar way as documented here. I used elasticache to create my redis instance. My settings.py looks as follows: ASGI_APPLICATION = 'MyApp.routing.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('my-redis-instance.cache.amazonaws.com', 6379)], }, }, } In deploying my application to elastic beanstalk, I have tried following this tutorial and this tutorial with no luck. My django.config file currently looks as follows: container_commands: 01_collectstatic: command: "source /opt/python/run/venv/bin/activate && python manage.py collectstatic --noinput" 02_migrate: command: "django-admin.py migrate" leader_only: true 03_load-data: command: "python manage.py load_database" leader_only: true option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: MyApp.settings aws:elasticbeanstalk:container:python: WSGIPath: MyApp/wsgi.py "aws:elasticbeanstalk:container:python:staticfiles": /static/: "static/" aws:elbv2:listener:80: DefaultProcess: http ListenerEnabled: 'true' Protocol: HTTP Rules: ws aws:elbv2:listenerrule:ws: PathPatterns: /ws/* Process: websocket Priority: 1 aws:elasticbeanstalk:environment:process:http: Port: '80' Protocol: HTTP aws:elasticbeanstalk:environment:process:websocket: Port: '5000' Protocol: HTTP I also tried creating a Procfile to configure gunicorn and daphne. It looks like this: web: gunicorn --bind :8000 --workers 3 --threads 2 MyApp.wsgi:application websocket: daphne -b 0.0.0.0 -p 5000 MyApp.asgi:application The security groups that are attached to my ElastiCache redis instance have an inbound rule with Custom TCP set to port 6379 and the source set to Any. In trying all … -
Django check if queryset QUERIES are equal WITHOUT evaluation
How to check if two QuerySet objects will result into the same query without evaluation? > q1 = MyModel.objects.all() > q2 = MyModel.objects.all() > q1 == q2 False Please note, that I don't need to compare the results that the queryset will return. I need to identify when two non-evaluated queryset objects will result into the same query. If I try > q1.query == q2.query False it doesn't work, as the Query object doesn't have __hash__ defined properly inside. I can do > str(q1.query) == str(q2.query) True But this is still heavy operation as it will require Django to traverse models fields, validate the query, compile SQL code, etc. Is there any better way to do that? -
Django-Oscar - Forking nested applications
I'm having trouble forking Django-oscar apps that are a part of a sub-set of other Django-oscar apps. For the documentation/tutorial I am following along with, view here. I have gone though and successfully forked the applications that aren't nested in others and updated my installed apps accordingly. Heres a subset of the apps to demonstrate the general pattern of the nested applications 'dashboard_folder.dashboard.apps.DashboardConfig', 'oscar.apps.dashboard.reports.apps.ReportsDashboardConfig', 'oscar.apps.dashboard.offers.apps.OffersDashboardConfig', However, the docs (linked above) do not clearly outline how to call the nested applications. I thought they might be forked automatically with their "parents" however, a simple test (code below) proved other-wise: If I change 'oscar.apps.dashboard.reports.apps.ReportsDashboardConfig', to dashboard_folder.dashboard.reports.apps.ReportsDashboardConfig', I get the following error: ModuleNotFoundError: No module named 'dashboard_folder.dashboard.reports' I figured id try a few 'educated' guesses as to how to call the nested apps to fork them however all of the following unfortunately failed: manage.py oscar_fork_app offers offers_folder CommandError: There is no app with the label 'offers' manage.py oscar_fork_app dashboard.offers offers_folder CommandError: There is no app with the label 'dashboard.offers' manage.py oscar_fork_app ReportsDashboard ReportsDashboard_folder CommandError: There is no app with the label 'ReportsDashboard' manage.py oscar_fork_app reportsdashboard ReportsDashboard_folder CommandError: There is no app with the label 'reportsdashboard' manage.py oscar_fork_app dashboard/reportsdashboard ReportsDashboard_folder CommandError: There is no … -
relationships in django which one to use
I am having trouble trying to decide what kind of relationship I should use for my application. I want to have a database that shows something like... A Movie table with fields title, year, language, description, duration and so on. A User table with fields username, email (I am new to django and am not worrying about authentications or passwords or any of that for now) I want a user to be able to favorite a movie so I am trying to wrap my head around how it would actually work, for instance, would it be a user can favorite many movies and a movie can be favorited by many users (this makes sense to me) or is it a user can favorite many movies and a movie is favorited by a user. so If I pick the second option I guess it would be a one-to-many rather than the first option which is a many-to-many relationship. However, I am not sure which one is actually correct. After looking at the docs in django for many-to-one I see that a foreign key should be given to the Movie that references a user from User but they use an option that …