Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I properly compare two different models based on their field values and output the differences?
I am trying to figure out how to produce the output between two querysets that have similar fields. I have two different models where I keep identical fields, and at times I want to show the differences between these two models. I have researched and successfully used sets and lists in my python code, but I can't quite figure out how to leverage them or determine if I Can. Sets seems to strip out just the field values, and when I try to loop through my sets, it doesn't currently work because it's just the values without the keys. Example: class Team(models.Model): player = models.Charfield coach = models.Charfield class TeamCommittee(models.Model): player = models.Charfield coach = models.Charfield I want to be able to query both models at times and be able to exclude data from one model if it exists in the other. I have spent the afternoon trying to use sets, lists, and loops in my django templates but can't quite work this out. I have also tried various querysets using exclude.... I tried something like.... query1 = TeamCommittee.objects.filter(id=self.object.pk).values('coach','player') query2 = Team.objects.filter(id=self.object.pk).exclude(id__in=query1) When I use the approach above, I get TypeError: Cannot use multi-field values as a filter value. I … -
Django Request.query_parmas issue
Below is the url that i am going to get, i am able to retrieve the specific data with the patientName and patientNRIC. However, how should I make to be variables, using params? like I would like to pass in to values to the function but achieved the same information instead of hard coded. Thank you for your help. test.py import requests def get_patient(): # patientName= {'patientName': patientName} # patientNRIC = {'patientNRIC': patientNRIC} p = {'patientName':'John','PatientNRIC':'S1111111A'} django_url = "https://4cfe2cdde986.ngrok.io/test/?patientName=John&patientNRIC=S1111111A" r = requests.get(django_url) r = r.json() print(r) get_patient() like so -
Why do i get "expected string or bytes-like object" while testing Fashion-mnist model in django with a local image?
I'm trying to deply Fashion-mnist model in a django project and found this error :"expected string or bytes-like object" when trying to test the model using predict function after doing some changes on the image (after loading it )with a local image from my computer . Here is the predict function in Views.py: @csrf_exempt def predict(request): path = "D:/desktop/pullover.jpg" im = Image.open(os.path.join(path)) convertImage(im) x = Image.open(OUTPUT, mode='L') x = np.invert(x) x = Image.resize(x, (28, 28)) x = x.reshape(1, 28, 28, 1) with graph.as_default(): out = model.predict(x) print(out) print(np.argmax(out, axis=1)) response = np.array_str(np.argmax(out, axis=1)) return JsonResponse({"output": response}) other functions i used in predict function in Views.py: def getI420FromBase64(codec): base64_data = re.sub('^data:image/.+;base64,', '', codec) byte_data = base64.b64decode(base64_data) image_data = BytesIO(byte_data) img = Image.open(image_data) img.save(OUTPUT) def convertImage(imgData): getI420FromBase64(imgData) utils.py from keras.models import model_from_json import tensorflow as tf import os JSONpath = os.path.join(os.path.dirname(__file__), 'models', 'model.json') MODELpath = os.path.join(os.path.dirname(__file__), 'models', 'mnist.h5') def init(): json_file = open(JSONpath, 'r') loaded_model_json = json_file.read() json_file.close() loaded_model = model_from_json(loaded_model_json) loaded_model.load_weights(MODELpath) print("Loaded Model from disk") loaded_model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) # graph = tf.get_default_graph() graph = tf.compat.v1.get_default_graph() return loaded_model, graph Any kind of help would be appreciated . -
How to check user type and direct them to respective pages in Django?
I am building a Django project where I have two categories of users. I have two models namely StudentUser and Recruiter. However, I provide only one login page and depending on the user type I direct them to either student_hompage or recruiter_homepage. I am not sure how to proceed for the recruiter part. Can you guys help please? Here is my code. models.py class StudentUser(models.Model): GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) user = models.OneToOneField(User, on_delete=models.CASCADE) gender = models.CharField(max_length=1, choices=GENDER_CHOICES) region = models.CharField(max_length=50) phone_num = PhoneNumberField() contact_email = models.EmailField() bio = models.TextField() linkedin = models.URLField(max_length=200) user_type = models.CharField(max_length=10) def __str__(self): return self.user.username class Recruiter(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) position = models.CharField(max_length=50) phone_num = PhoneNumberField() company_name = models.CharField(max_length=100) company_country = models.CharField(max_length=60) company_street = models.CharField(max_length=100) company_city = models.CharField(max_length=100) status = models.CharField(max_length=20) user_type = models.CharField(max_length=10) def __str__(self): return self.user.username views.py def user_login(request): error="" if request.method == "POST": username = request.POST['email'] print(username) password = request.POST['password'] #CHECK IN USER TABLE FOR MATCHING UNAME AND PASSWD user = authenticate(username=username, password=password) #CHECKING IF USER IS VALID -->RESOLVES TO TRUE/FALSE if user: try: user1 = StudentUser.objects.get(user=user) if user1.user_type == "Student": login(request,user) messages.success(request, "You are now logged in!") return redirect('home') else: error = True except: error = True else: … -
Django: Reverse not found. 'teachers_detail' is not a valid view function or pattern name
I'm new in django. I am using this tutorial https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Generic_views, but can't get the right work of my application. I created an app "education" in my "edusys" project. I'm trying to get the list of teachers from database and go to every teacher's page, where I'll be able to see their information from database. I get the next error when I use "runserver": Reverse for 'teachers_detail' not found. 'teachers_detail' is not a valid view function or pattern name. What am I doing wrong? I can't solve the problem myself and can't find the right answer in google. My files of this project looks like this: education/models.py : from django.db import models from django.urls import reverse class Teachers(models.Model): tcode = models.CharField(max_length=10, primary_key=True) last_name = models.CharField(max_length=20) first_name = models.CharField(max_length=30) middle_name = models.CharField(max_length=20, null=True, blank=True) department_s = models.ForeignKey('Departments', on_delete=models.SET_NULL, null=True) employee_post = models.CharField(max_length=20) academic_degree = models.CharField(max_length=40) email = models.EmailField(max_length=50) GENDER_UNIT = ( ('m', 'Мужчина'), ('f', 'Женщина'), ) gender = models.CharField(max_length=1, choices=GENDER_UNIT) class Meta: ordering = ['last_name'] def __str__(self): return '%s %s %s' % (self.last_name, self.first_name, self.middle_name) def get_absolute_url(self): return reverse("teachers_detail", args=[str(self.tcode)]) education/urls.py : from django.urls import path from . import views from django.conf.urls import url app_name = 'education' urlpatterns = [ url(r'^$', views.index, … -
How do I install a loader for my Vue project?
I'm trying to create a Vue project and, upon creating a new method in my 'myapi/views.py' file, I get this error message when running npm run serve from 'Django_Repository\DB_Vue_Project\vueproject': > vueproject@0.1.0 serve C:\Users\username\Documents\GitHub Projects\Django_Repository\DB_Vue_Project\vueproject > vue-cli-service serve INFO Starting development server... 98% after emitting CopyPlugin ERROR Failed to compile with 1 error 1:53:38 PM error in C:/Users/username/Documents/GitHub Projects/Django_Repository/myapi/views.py Module parse failed: Unexpected token (2:5) You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders | import requests > from django.shortcuts import render | from rest_framework import viewsets | from django.db import connection # This is for the my_custom_sql method. @ ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader-v16/dist??ref--0-1!./src/App.vue?vue&type=script&lang=js 5:0-52 139:18 -31 @ ./src/App.vue?vue&type=script&lang=js @ ./src/App.vue @ ./src/main.js @ multi (webpack)-dev-server/client?http://10.5.1.195:8080&sockPath=/sockjs-node (webpack)/hot/dev-server.js ./src/main.js Here's my views.py file: import requests from django.shortcuts import render from rest_framework import viewsets from django.db import connection # This is for the my_custom_sql method. from .models import Customer, Address, Order, Purchase, State, VideoGameID from .serializers import CustomerSerializer, AddressSerializer, OrderSerializer, PurchaseSerializer, StateSerializer, \ VideoGameIDSerializer def home(request): response = requests.get('http://127.0.0.1:8000/customers/') data = response.json() return render(request, 'test.html', { 'customerId': data['customerID'], 'cusFirstName': data['cusFirstName'] }) def my_custom_sql(self): with connection.cursor() as cursor: cursor.execute("UPDATE bar SET foo = 1 … -
Enable download button when Quiz pass
I have these models in my Django Quiz app class Quiz(models.Model): quiz_title = models.CharField(max_length=300) num_questions = models.IntegerField(default=0) subject=models.ForeignKey(Subject,on_delete=models.CASCADE,blank=True,null=True) def __str__(self): return self.quiz_title class Question(models.Model): quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE) question_text = models.CharField(max_length=300) question_num = models.IntegerField(default=0) def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=300) correct = models.BooleanField(default=False) def __str__(self): return self.choice_text I want when user pass Quiz then download certificate enable else disable I have different no. of Quizes in Different subjects...The main Idea is that I have courses and within courses I have sections And every sections of Course has Quizes so Every course has diffferent no. of sections and Quizes I want when user passes all the included Quiz in the sections like if first section has 3 quizes then if user pass all 3 quizes then certificate enable for download else disable...I have created logic for Quiz attempt and Result as well just problem is how can I get if student pass all the quizes that are included in the sections..Thanks Here is Quiz attempt and result views/logic def single_quiz(request, quiz_id): quiz = get_object_or_404(Quiz, pk=quiz_id) num_questions = len(quiz.question_set.all()) # deletes quiz and returns to home if no questions created if num_questions == 0: quiz.delete() … -
Django Annotate with additional data
I have a model of Courses and Categories for the courses which is a choice field. Ideally I would like to have a single query which counts the number of courses per category and shows the actual name of the course. CATEGORY = ( ('itd', 'IT Development'), ('wd', 'Web Design'), ('iandd', 'Illustration and Drawing'), ('sm', 'Social Media'), ('ps', 'PhotoShop'), ('crypto', 'CryptoCurrencies'), ) category = models.CharField(max_length=100, choices=CATEGORY) My current annotate query context['course_by_category'] = Course.objects.values('category').annotate(count=Count('category')) Returns the following which is correct but I also want the name of the Category, not the abbreviated [{'category': 'crypto', 'count': 6}, {'category': 'iandd', 'count': 5}, {'category': 'itd', 'count': 2}, {'category': 'ps', 'count': 6}, {'category': 'sm', 'count': 3}, {'category': 'wd', 'count': 5}] I end up using this in the HTML as follows: {% for course in course_by_category %} <div class="col-lg-4 col-md-6"> <div class="categorie-item"> <div class="ci-thumb set-bg" data-setbg="{% static 'img/categories/1.jpg' %}"></div> <div class="ci-text"> <h5>{{THIS_IS_WHERE_I_WANT_COURSE_NAME}}</h5> <p>Lorem ipsum dolor sit amet, consectetur</p> <span>{{course.count}} Courses</span> </div> </div> </div> {% endfor %} From what I read here, my request doesn't seem possible the way I'm approaching it: Selecting additional values after annotate in Django From what I read here, it isn't quite what I want but at least I can get the … -
Convert image in ImageField to numpy array
class Image(models.Model): image = models.ImageField(upload_to="uploads/%Y/%m/%d", null=False, blank=True) How convert ImageField to numpy array? -
How to pass a value from anchor tag to a function in views in Django
I have a model object movie and I want to pass movie.mid to addmovie function in views anchor tag in my html - <a href="{% url 'addmovie' %}" style="color:chocolate;">Add to watched</a></div> -
Django RestAPI - only allow access to users data with JWT Authentication
I have the following API: Model: class Todo(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=20, default="") text = models.TextField(max_length=450, default="") done = models.BooleanField(default=False) View: class TodoView(viewsets.ModelViewSet): serializer_class = TodoSerializer permission_classes = [IsAuthenticated] def get_queryset(self): id = self.request.query_params.get("id") queryset = Todo.objects.filter(owner__id=id) return queryset Serializer: class TodoSerializer(serializers.ModelSerializer): class Meta: model = Todo fields = ("id", "owner", "name", "text", "done") I use rest_framework_simplejwt for my tokens and the following path to receive my token: path("api/token/", TokenObtainPairView.as_view(), name="token_obtain_pair"), This is the token: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjE5Mjg4ODAwLCJqdGkiOiJhY2E4MjM5ZGMyZjA0NGE5YWE4NzM3NWZjMDc2NWQ0YSIsInVzZXJfaWQiOjF9.xJ4s971XE0c9iX0Ar1HQSE84u_LbDKLL4iMswYsk2U8 When I decode it on the jwt.io I can see that it contains the user id: { "token_type": "access", "exp": 1619288800, "jti": "aca8239dc2f044a9aa87375fc0765d4a", "user_id": 1 } A request on http://localhost:8000/todos/?id=1 without the token in my request header does not work (fine!), but with the token, I also can access http://localhost:8000/todos/?id=2 which is of course undesired. I only want access to http://localhost:8000/todos/?id=1 (the coresponding user_id from the payload) How can I do this? -
ModuleNotFoundError: No module named 'MyApp.urls'
This part of code is admin urls When i try to run this Error Occurs from django.contrib import admin from django.urls import path from django.conf.urls import url from django.conf.urls import include from MyApp import views urlpatterns = [ url(r'^first_app/', include('MyApp.urls')), path('', views.index, name="App"), path('admin/', admin.site.urls), ] This part of code is app urls i am trying to pass app urls to admin urls but seems something went wrong from django.conf.urls import url from MyApp import views urlpatterns = [ url('', views.second_index, name="index"), ] -
How to insert data on OneToOne relatiotion model in Django?
I have extended User model. Model name is userextend. I wanted to add two more field. Here is my userextend model. class userextend(models.Model): user= models.OneToOneField(User, on_delete=models.CASCADE) major = models.CharField(max_length=50) student_id = models.CharField(max_length=20) After user completed the registration, I want to run register function from views.py and want to save major and student_id on userextend model. views.py: def register(request): form = CreateUserForm() if request.method =='POST': form = CreateUserForm(request.POST) major = request.POST.get('major') student_id = request.POST.get('student_id') if form.is_valid(): b = userextend.objects.create(user=form,major=major,student_id=student_id) #I tried this form.save() context = {'form': form} return render(request, 'library_site/register.html',context) -
Query for chatapp in django
I need to query this model for a chat app(like WhatsApp). The question is how can I group the result of the query/queries ? class TimeStamp(models.Model): created = models.DateTimeField(auto_now_add=True, blank=True, null=True) modified = models.DateTimeField(auto_now=True, blank=True, null=True) class Messages(TimeStamp): sender = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="sender" ) receiver = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="receiver" ) message = models.TextField(max_length=1000) seen = models.BooleanField(default=False, blank=True) accepted = models.BooleanField(default=False, blank=True) The result should combine the messages where the sender/receiver is x without duplicate so I can show the user each conversation. Do I need to design the model differently? Thanks. -
How to create a DBMS project using django?
I have to make a project which includes making tables using sql in postgresql . Django makes its tables in models.py so I am not able to understand where is sql actually used? -
Create a register page with django
I have 2 problems, my css is not showing when i load my page and my register page is giving out error 404. At this point I am frustrated, I have tried fixing them but to no avail my index.html that shows the login page <body> <header class="header"> <div class="header-text"><a href="{% url 'login' % }">Login</a></div> <div class="header-text"><a href="{% url 'register' % }">Register</a></div> </header> my register.html {% extends 'index.html'} {% block content} <h2>Register</h2> <form method="post"> {% csrf_token %} {% for field in form %} <p> {{ field.label_tag }}<br> {{ field }} {% if field.help_text %} <small style="color: grey">{{ field.help_text }}</small> {% endif %} {% for error in field.errors %} <p style="color: red">{{ error }}</p> {% endfor %} </p> {% endfor %} <button type="submit">Register</button> </form> {% endblock %} my views.py from django.shortcuts import render, redirect from django.contrib.auth import login, authenticate from django.contrib.auth.forms import UserCreationForm from django.urls import reverse_lazy from django.views import generic from.models import Post def index(request): return render(request, 'index.html') class SignUpView(generic.CreateView): form_class = UserCreationForm success_url = reverse_lazy('login') template_name = 'register.html' and my urls.py from django.urls import path from django.conf import settings from django.conf.urls.static import static from .views import index, SignUpView urlpatterns = [ path('', index, name='index'), path('register/', SignUpView.as_view(), name='register'), ] Is … -
How do I pass data to success template from views with form.cleaned_data.get() in django?
I'm building an basic covid test appointment. Everything is working fine I am getting data from users in a form and saving it to database. But I'm trying to show some of that data to the form success page. Like when user enter their details in form such as name, data, time etc after clicking on submit button. I want the name, date, time of the form to render on success page. I even tried this but I'm getting an error like: NoReverseMatch at /covid_test Reverse for 'success' with arguments '({'name': 'Popes', 'test_date': datetime.date(2021, 4, 23), 'test_time': datetime.time(18, 0)},)' not found. 1 pattern(s) tried: ['success$'] Here is the screenshot of the error. Below is my code for the same. Models.py from django.db import models # Create your models here. class Covid_Test_Model(models.Model): gender_chooice = [ ('Male', 'Male'), ('Female', 'Female') ] name = models.CharField(max_length=100, null=False) age = models.IntegerField(null=False) gender = models.CharField(max_length=20, choices=gender_chooice, default='Male', null=False) phone = models.CharField(max_length=15, null=False) email = models.EmailField(max_length=100, null=False) adhaar_no = models.CharField(max_length=16, null=False) address = models.TextField(null=False) date = models.DateField(null=False) Time = models.TimeField(auto_now=False, auto_now_add=False, null=False) def __str__(self) -> str: return self.name Views.py from django.shortcuts import render, redirect # Create your views here. from covid_test_app.forms import Covid_Test_Form def covid_test(request): if request.method … -
running the 'python manage.py makemigrations' command is giving me syntax error
I am beginner to python and django and I following an online course 'CS50' so this is what I get when I run the command C:\Users\ramma\airlines>python manage.py makemigrations Traceback (most recent call last): File "C:\Users\ramma\airlines\manage.py", line 22, in <module>main() File "C:\Users\ramma\airlines\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\ramma\OneDrive\Desktop\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\ramma\OneDrive\Desktop\lib\site-packages\django\core\management\__init__.py", line 363, in execute settings.INSTALLED_APPS File "C:\Users\ramma\OneDrive\Desktop\lib\site-packages\django\conf\__init__.py", line 82, in __getattr__ self._setup(name) File "C:\Users\ramma\OneDrive\Desktop\lib\site-packages\django\conf\__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "C:\Users\ramma\OneDrive\Desktop\lib\site-packages\django\conf\__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\ramma\OneDrive\Desktop\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 786, in exec_module File "<frozen importlib._bootstrap_external>", line 923, in get_code File "<frozen importlib._bootstrap_external>", line 853, in source_to_code File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "C:\Users\ramma\airlines\airlines\settings.py", line 35 'django.contrib.admin', ^ SyntaxError: invalid syntax The code I wrote was class Flight(models.Model): origin = models.CharField(max_length=64) destination = models.CharField(max_length=64) duration = models.IntegerField() Pls help me find the mistake in this -
Django real time
I'm trying to build social media app as part of my django practicing, is there a JavaScript Framework or a library to help send real time events to other users? I tried ajax but it only updates for the user who sent request not to others Like notification system i commented on a post it sends a notification for post author but he has to reload the page to see it, is there a way to reload the notification div every few seconds instead of the whole page? And is it efficient or server overload will happen if this approach is used in production? -
expected string or bytes-like object in predict function of Fashion-mnist
I'm trying to deploy fashion-mnist model in django and i got this error when trying to test the predict function of the model with a local image . predict Function here any help will be appreciated . -
How can a call be made to the Google API from within Django?
I am currently trying to build a web app using Python and Django which will require information from the Google Calendar API. I've successfully managed to create the specific API credentials that I need using the Google Cloud Console, and downloaded the client secret JSON file to use for authentication. I have also been able to successfully access the API using the following code snippet: from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow scopes = ['https://www.googleapis.com/auth/calendar'] flow = InstalledAppFlow.from_client_secrets_file(r"client secret file location", scopes=scopes) flow.run_console() When I run it in VSCode, it creates a link in the terminal that I can click to go to the Google site and login. The issue I'm now having though is that the API is treating this as a PC app call, and once it opens in my browser it's asking me to recreate the API key (since the one I created is for Web Apps). A picture of the error can be seen here: Authorization Error Message from Google Now my question is, is there a way to call the API and have the user login be verified using Django? I am hesitant to remake the API credential as a desktop app because what … -
How to save and append input in the HTML render for the user in Django?
I want to save and render the input from the user at the withdrawals page, where the user should see previous withdraw amounts and the dates of the withdrawals that the user has made. @login_required def withdraw(request): if request.method == 'POST': if 'withdraw-amount' in request.POST: profile = Customer.objects.get(user=request.user) withdraw_amount = request.POST.get('withdraw-amount') if withdraw_amount > profile.credit: messages.error( request, 'You dont have enough Credit to withdraw!') else: profile.credit -= withdraw_amount profile.save() return render(request, 'withdraw.html') -
How can I set model items in html properly?
I have a form with which I intend to capture student marks. I have an issue like I don't know the best way to put it so that I have student name and markfield beside it for all the students. calling {{ form }} brings the form with select dropdown items(not what I want). Specifying form fields do not populate anything.i.e {% for field in form %} {{ field.student }} {{ field.marks }} {% endfor %} This is the form class AddMarksForm(forms.ModelForm): def __init__(self, school,klass,term,stream,year, *args, **kwargs): super(AddMarksForm, self).__init__(*args, **kwargs) self.fields['student'] = forms.ModelChoiceField( queryset=Students.objects.filter(school=school,klass__name__in=klass,stream__name=stream[0])) class Meta: model = Marks fields = ('student','marks') This is how I tried the html rendering <form method="post" enctype="multipart/form-data" action="{% url 'add_marks' %}"> {% csrf_token %} {% if form %} <table> <tr> <td>Student</td> <td>Marks</td> </tr> {% for field in form %} <tr> <td>{{ field.student }}</td> <td>{{ field.marks }}</td> </tr> </table> {% endfor %} <button class="btn btn-outline-primary">Save</button> </form> -
Django Form initial Value For Foreignkey Field
I have two django models which are : class Dataset(models.Model): name = models.CharField(max_length = 200) description = models.CharField(max_length=1000) owner = models.ForeignKey(Profile, null=True, on_delete=models.SET_NULL) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Source(models.Model): name = models.CharField(max_length = 200) description = models.CharField(max_length=1000) dataset = models.ForeignKey(Dataset, null=True, on_delete=models.SET_NULL) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) When saving a Source, I would like to initiate the value of the corresponding Dataset. I tried to initiate the value of my form as suggested here : foreign key as initial value not passed to the ModelForm in django def create_source(request, dataset_id): user = request.user dataset = Dataset.objects.get(id=dataset_id) form = SourceForm(initial={"dataset" : dataset, }) if request.method == "POST": form = SourceForm(request.POST or None, initial={"dataset" : dataset, }) if form.is_valid(): source = form.save() # dataset.source_set.add(source) # Only works if I add this line return redirect("source", dataset_id=dataset_id, source_id=source.id) context = {"form": form} return render(request, "sources/source_form.html", context) The suggested way does not work. I was able to achieve the desired result by adding the commented line above. It is not a recommended solution since it makes a second call to the database. Any idea how to give properly the dataset object to the source ? -
Django No Module Named With Inner Package Using
I want to write my own python package inside django's app. It looks like that: I have secondary app. It totally works except one thing. Someday I'd decided to make my app more structured. And there where problems started. First of all, I've added python package(with simple init.py inside directory) to the app. Then I've added second package inside that package. And when I try to run django.setup() inside packages' files, I'm getting this error: ModuleNotFoundError: No module named '<primary settings container module name goes here>' How to make my custom package's functions working properly?