Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Foreign key in Ajax POST request in Django
I have some problems with my web app . When I try to add new item I get an error: TypeError: Field 'id' expected a number but got . Is the any solutions ? Here is my code: views.py if request.method == 'POST': if request.is_ajax(): form = AddTask(request.POST) if form.is_valid(): form.cleaned_data form.save() user_membership = User.objects.get(id=request.user.id) expence_object = model_to_dict(Task.objects.get(pk=user_membership)) return JsonResponse({'error': False, 'data': expence_object}) models.py class Task(models.Model): title=models.CharField(max_length=200) date = models.DateTimeField(default=datetime.now,blank=True) is_published=models.BooleanField(default=True) usertask=models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=True, blank=True) Ajax form $('#taskpost').submit(function (e) { // console.log("Creating the book"); e.preventDefault(); // get the form data var formData = { 'title': $('#id_title').val(), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), contentType: 'application/x-www-form-urlencoded', encode: true, }; $.ajax({ type: 'POST', url: 'create/', data: formData, dataType: 'json', }).done(function (data) { -
How to download a file from FileField django
I am building an application that should allow users to upload and download files using Django. I have a model that stores files: class Document(models.Model): description = models.CharField(max_length=255, blank=True) unit_code = models.CharField(max_length=6) input = models.FileField(upload_to='documents/') uploaded_at = models.DateTimeField(auto_now_add=True) @property def filename(self): return os.path.basename(self.document.name) I am able to display the list of uploaded files in my template from my view as such: def Document(request, str): documents = Document.objects.filter(unit_code=str) And in the template an anchor tag to download the file using the url as seen here: {% for document in documents %} {{document.filename}}<a href="{{document.input.url}}"> Download Document </a> {% endfor %} Right now I'm getting an error page not found (The url is directing to 127.0.0.1:8000/media/documents/file_name Is it possible to download the file using the anchor tag with the Django development server? -
(Django) How to send the same data to some clients instead of others?
I need your help! I have a server running into django with clients connecting to it. Once they are connected some objects "User" are added to the database with some property, such as user_id etc.. I'd like to write a function that send the same data (e.g. a color) back to only some of them to color the body of the html, and other data to others..how can I identify the clients to which the server should send the data? I was thinking to trigger the function with a button that make an ajax call to the server, but then I don't know how to take track of the "identification" of the client in the server. -
Django profile pic upload saves picture in two folders
I've made a group picture upload in Django, but it saves in /media folder and in /media/group_pics folder. Expected behaviour: It only saves to /media/group_pics folder models.py: class Group(models.Model): name = models.CharField(max_length=15, unique=True) date_created = models.DateField(default=timezone.now) image = models.ImageField(default='group_pics/default-group.jpg', upload_to='group_pics/') def __str__(self): return self.name def image_url(self): if self.image and hasattr(self.image, 'url'): return self.image.url def save(self, *args, **kwargs): try: group = Group.objects.get(id=self.id) if not ('default-group.jpg' in group.image.url) and group.image != self.image: group.image.delete() except: pass if not self.slug: self.slug = self._get_unique_slug() super().save(*args, **kwargs) forms.py class GroupUpdateForm(ModelForm): image = forms.ImageField(max_length=150, allow_empty_file=False) x = forms.FloatField(widget=forms.HiddenInput(), required=False) y = forms.FloatField(widget=forms.HiddenInput(), required=False) width = forms.FloatField(widget=forms.HiddenInput(), required=False) height = forms.FloatField(widget=forms.HiddenInput(), required=False) class Meta: model = Group fields = ['image'] def save(self): group = super(GroupUpdateForm, self).save(commit=False) if self.cleaned_data.get('x') != None: x = self.cleaned_data.get('x') y = self.cleaned_data.get('y') w = self.cleaned_data.get('width') h = self.cleaned_data.get('height') image = Image.open(group.image) cropped_image = image.crop((x, y, w+x, h+y)) resized_image = cropped_image.resize((350, 350), Image.ANTIALIAS) resized_image.save(group.image.path) group.save() return group and views.py if request.method == 'POST': update_form = GroupUpdateForm(request.POST, request.FILES, instance=group) if update_form.is_valid(): update_form.save() Where is my mistake that causes the double image save? -
Wagtail rendering if referenced pages in an inlineModel
In my Article pageModel I have an InlinePanel('technologies', label="Technologies"), which loads up an ArticlesPageTechnologies(Orderable) which is using PageChooserPanel('technologies', 'rb_tech_portfolio.TechnologiesPage'),. This is all working nicely. But what I want to do is to list links to these referenced pages, but I cannot seem to work out the best way to do this. The closest I have gotten is with {% for technology in page.technologies.all %} but this simply gives me the object which connects the 2 page models, whereas I want the referenced object. Is this all there ready to use, or do I need to do an extra query in def_context to do this? Thanks, Dan -
Where to build database objects in Django(without using shell)?
I have created my database models in my model.py file, but I want to be able to populate them with data. I have the code written that reads in the data from a text file I have and create the objects for my models. But I am not sure where to actually run this code, all the tutorials I can find they only create the objects through the shell, but since I am reading in from a text file and since the code is quite long I dont want to use the shell. My solution was to create a file called buildDB in my application folder, and run the code there, but this will not work: if I try to import my models at top of file using from .models import * I get ImportError: attempted relative import with no known parent package when I run it. If I try using from applicatonName.models import* I get django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. When I google the second error message, it would appear that this happens becasue I am not using manage.py shell, and … -
NOT NULL constraint failed: community_comment.posts_id?
how can I fix this issue? the page runs perfectly. when I do post the post. it posts but when I want to type the comment and send by 'GET' I get this error. so, how can I ignore this error this my first question? - also, I need anyone to give me the best way to make a relationship between post and comment models.py from django.db import models from django.contrib.auth.models import User class Publication(models.Model): title = models.CharField(max_length=30) class Meta: ordering = ['title'] def __str__(self): return self.title class Article(models.Model): publications = models.ManyToManyField(Publication) headline = models.CharField(max_length=100) class Meta: ordering = ['headline'] def __str__(self): return self.headline class Post(models.Model): users = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100) question = models.TextField(max_length=500) def __str__(self): return self.title class Comment(models.Model): posts = models.ForeignKey(Post, on_delete=models.CASCADE) comment = models.TextField(max_length=500) def __str__(self): return self.comment views.py from django.shortcuts import render, redirect from django.contrib.auth.models import User from .models import Post, Comment from .forms import PostForm, CommentForm def index(request): # All questions posts = Post.objects.all() return render(request, 'community/index.html', {'posts': posts}) def post_view(request): post_form = PostForm context = {'posted': post_form} # Create post if request.method == 'GET': post_form = PostForm(request.GET) if post_form.is_valid(): user_post = post_form.save(commit=False) user_post.title = post_form.cleaned_data['title'] user_post.question = post_form.cleaned_data['question'] post = Post.objects.create(users=User.objects.get(username=request.user), title=user_post.title, … -
How can I get a members list from a discord bot and then display it on my site?
import random from discord.ext import commands client = commands.Bot(command_prefix = '.') channel = None @client.event async def on_ready(): channel = client.get_channel(677999369642836037) async def members_list(request): curMembers = [] for member in channel.members: curMembers.append(member) return render(request, "discordTool/discordTool.html", { 'members_list': curMembers, }) client.run('my token') This is my views.py, I use django and I am well aware of the fact that I need to place the bot code in a different file, my main issue is that I don't know how I would get the members list from the bot if it's placed in a different file? or how to call the bot and run it only whenver I need it to run? -
Cannot import class from models in Django project
So I made the following class in models.py class MovieTile(models.Model): movie_name = models.CharField(max_length=200) movie_picture = models.CharField(max_length=200) movie_link = models.CharField(max_length=200) I want to import this class into a .py file by using from scraper import models or from scraper.models import MovieTile But then I get the following error: C:\Users\CLeen\Anaconda3\envs\WebsitescraperV1\python.exe "C:\Users\CLeen\PycharmProjects\WebsitescraperV1\locallibrary\bs4 test.py" Traceback (most recent call last): File "C:\Users\CLeen\PycharmProjects\WebsitescraperV1\locallibrary\bs4 test.py", line 4, in <module> from scraper import models File "C:\Users\CLeen\PycharmProjects\WebsitescraperV1\scraper\models.py", line 4, in <module> class Search(models.Model): File "C:\Users\CLeen\Anaconda3\envs\WebsitescraperV1\lib\site-packages\django\db\models\base.py", line 103, in __new__ app_config = apps.get_containing_app_config(module) File "C:\Users\CLeen\Anaconda3\envs\WebsitescraperV1\lib\site-packages\django\apps\registry.py", line 252, in get_containing_app_config self.check_apps_ready() File "C:\Users\CLeen\Anaconda3\envs\WebsitescraperV1\lib\site-packages\django\apps\registry.py", line 134, in check_apps_ready settings.INSTALLED_APPS File "C:\Users\CLeen\Anaconda3\envs\WebsitescraperV1\lib\site-packages\django\conf\__init__.py", line 79, in __getattr__ self._setup(name) File "C:\Users\CLeen\Anaconda3\envs\WebsitescraperV1\lib\site-packages\django\conf\__init__.py", line 64, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Process finished with exit code 1 So I figured I had to add the class into my settings file like this: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'scraper.apps.ScraperConfig', 'scraper.models.MovieTile', ] But when I try to make migrations I get the following Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File … -
In Django I am unable to pass pk value through url when creating new child instance
This is an issue I have been struggling with for a long time, so posting it on here hoping for some guidance. When I am creating a new child instance of an item, I am struggling to pass the pk value from the parent, so the child instance is created under the correct parent. Parent Models.py class listofbooks(models.Model): booktitle = models.CharField(max_length = 100) description = models.TextField(null=True) Child Models.py class author(models.Model): listofbooks = models.ForeignKey("books.listofbooks",on_delete=models.CASCADE, blank=True, null=True) authorname= models.CharField(max_length = 100, null=True) authorage = models.IntegerField() Parent urls.py app_name = 'books' urlpatterns = [ path('', BookListView.as_view(), name='book-list-view'), path('new/', BookCreateView.as_view(), name='book-create'), path('<int:listofbooks_pk>/', BookDetailView.as_view(), name='book-detail'), ] Child urls.py app_name = 'author' urlpatterns = [ path('<int:listofbooks_pk>/authors', AuthorListView.as_view(), name='author-list'), path('<int:author_pk>', AuthorInfoView.as_view(), name='author-detail'), path('<int:listofbooks_pk>/new/', AuthorCreateView.as_view(), name='author-create'), ] Child views.py class AuthorInfoView(DetailView): model = author pk_url_kwarg = "author_pk" class AuthorListView(ListView): model = author pk_url_kwarg = "author_pk" context_object_name = 'listofauthors' def get_queryset(self, *args, **kwargs): return author.objects.filter(listofbooks=self.kwargs['listofbooks_pk']) class AuthorCreateView(CreateView): model = author pk_url_kwarg = "listofbooks_pk" fields = ['authorname','authorage'] def get_success_url(self, *args, **kwargs): return reverse('author:author-detail',kwargs={'author_pk':self.object.pk}) Here is the author_list.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>This is the list of Authors page</h1> {% for item in listofauthors %} <br> {{ item.authorname }} <br> {{ … -
PostgreSQL/psycopg2 Password Authentication using SSH Tunneling
I am trying to connect to a PostgreSQL Database via ssh tunnel. I am able to connect using the psql command, but for some reason when I attempt to use psycopg2, I get the error FATAL: password authentication failed for user Here is part of my pg_hba.conf for reference: local all postgres peer # TYPE DATABASE USER ADDRESS METHOD # "local" is for Unix domain socket connections only local all all peer # IPv4 local connections: host all all 127.0.0.1/32 md5 # IPv6 local connections: host all all ::1/128 md5 # Allow replication connections from localhost, by a user with the # replication privilege. local replication all peer host replication all 127.0.0.1/32 md5 host replication all ::1/128 md5``` -
Django ArrayField on Frontend Form?
I'm currently in the process of rebuilding my WordPress website into a full Django web app. With WordPress, I had made great use of the awesome Advanced Custom Fields plugin, and I'm struggling to get the same functionality with Django. One field in particular with ACF is called a "Repeater Field" that lets me click a button to add another row to an array. I did manage to get something similar working with Django, but only in the Admin part. I've used this plugin "Django Better Admin ArrayField" - https://github.com/gradam/django-better-admin-arrayfield and it displays the arrayfield exactly as I want: Django Better Admin ArrayField How can I get this to work on the frontend of the site, like in a user-submitted form? -
Django: Passing context to another view
I'm trying to pass my context of items to another view, with only the specific item's details, but I'm having trouble to even find the correct documentation on how this works. I need to get my specific package to another view, and have all of it's properties with it, like dependencies, description, homepage etc. Views: from django.shortcuts import render import re, random def index(request): packages = {} latset_header = None with open("app/packages/status.real.txt", encoding="UTF-8") as f: for l in f: l = l.strip() # if line contains a keyword if "Package: " in l: latset_header = l.replace("Package: ", "") packages[latset_header] = {'name': latset_header} elif "Depends: " in l: packages[latset_header]['depends'] = l.replace("Depends: ", "") elif "Description: " in l: packages[latset_header]["description"] = l.replace("Description: ", "") elif "Homepage: " in l: packages[latset_header]["homepage"] = l.replace("Homepage: ", "") context = {'items': packages} return render(request, 'packages_index.html', context) def show_package_details(request, package): context = {'item': package} return render(request, 'packages_details.html', context) Urls: from django.urls import include, path from . import views urlpatterns = [ path('', views.index, name='index'), path('<str:package>', views.show_package_details, name='package-details') ] packages_index.html - template: {% extends "home.html" %} {% block container %} <h2>The packages</h2> {% if items %} <ul> {% for item, value in items.items %} <li> <a href="{{item}}">{{ item … -
Django and HTML : Too many values to unpack (expected 2)
I'm new to django and html and I have to do a project for school. I tried to learn how forms works with django and I think I got it django forms right. But I simply don't know how to make it work with my html. I got the too many values to unpack (expected 2). Here is the important part of my form: class ConfiguratorForm(forms.Form): queryOfProject = TypeOfProgram.objects.values('name') queryOfFramework = Framework.objects.values('name','version') listOfProject = [] listOfFramework = [] listOfFramework += queryOfFramework listOfProject += queryOfProject listFramework=[] listProject = [] for i in range(0,len(listOfFramework)): listFramework.append(listOfFramework[i]['name'] + " " +listOfFramework[i]['version']) for i in range(0,len(listOfProject)): listProject.append(listOfProject[i]['name']) typeOfTheproject = forms.ChoiceField(choices = listProject) wantedFramework = forms.MultipleChoiceField(choices = listFramework) Where listProject and listFramework are both list containing elements. And I know it is no good code but I'm learning how everything works and I haven't much time. For the html code. I absolutly don't know what exactly I wrote. I've search so lang and tried a lot of things I've seen. {% block content %} <form method="post"> {% csrf_token %} {{form}} <input type="submit" value="Submit"> </form> {% endblock %} If anyone could tell me how to correct the html file or if my form is wrong? -
Failed to load the native tensorflow runtime when we use command python manage.py runserver
Failed to load the native TensorFlow runtime. See https://www.tensorflow.org/install/errors for some common reasons and solutions. Include the entire stack trace above this error message when asking for help. -
How to start a new Django project using poetry?
How to start a new Django project using poetry? Where will are virtualenv files located? With virtualenv it is simple: virtualenv -p python3 env_name --no-site-packages source env_name/bin/activate pip install django django-admin.py startproject demo pip freeze > requirements.txt -
Django AllAuth KeyError at /accounts/login/ 'BACKEND'
When I log in with the wrong/right credentials I don't just get a simple form error or login I go a full debug error page https://imgur.com/a/KxR5pIo I have all auth fully installed and provider Google is working for signup and login. I'm also doing this on the allauth standardized login form and URL. Please let me know if I should post any more info besides the pictures. settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ #'django.template.context_processors.debug', 'django.contrib.auth.context_processors.auth', # `allauth` needs this from django 'django.template.context_processors.request', 'django.contrib.messages.context_processors.messages', ], 'libraries': { 'staticfiles': 'django.templatetags.static', }, }, }, ] AUTHENTICATION_BACKENDS = ( # Needed to login by username in Django admin, regardless of `allauth` 'django.contrib.auth.backends.ModelBackend', # `allauth` specific authentication methods, such as login by e-mail 'allauth.account.auth_backends.AuthenticationBackend', ) ACCOUNT_AUTHENTICATION_METHOD = 'username_email' EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' ACCOUNT_ADAPTER = "allauth.account.adapter.DefaultAccountAdapter" # Application definition INSTALLED_APPS = [ 'dal', 'dal_select2', # Django Specific 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', # django-allauth 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', # Make sure 'collectfast' is in INSTALLED_APPS, before 'django.contrib.staticfiles' 'collectfast', 'django.contrib.staticfiles', 'django.contrib.sites', # Packages / Modules 'ckeditor', 'ckeditor_uploader', 'rest_framework', 'storages', 'flatpickr', # Local apps 'portfolios', ] SITE_ID = 3 LOGIN_REDIRECT_URL = 'dash' LOGOUT_REDIRECT_URL = 'home' ACCOUNT_LOGOUT_ON_GET = True SIGNUP_REDIRECT_URL … -
Django Foreign Key Create Form Get Instance
When I am creating a new object with a foreign key field, is there a way in the template to get the foreign key object fields in the template on the create form? Whenever I create a new note I would like to have: "Add new note to {{ applicant.full_name }}" class Applicant(models.Model): first_name = models.CharField(max_length=128,blank=False, verbose_name="First Name") middle_name = models.CharField(max_length=128,blank=True, verbose_name="Middle Name") last_name = models.CharField(max_length=128,blank=False, verbose_name="Last Name") @property def full_name(self): "Returns the applicant's full name." return '%s %s %s' % (self.first_name, self.middle_name, self.last_name) class Note(models.Model): applicant = models.ForeignKey(Applicant, related_name='notes', on_delete=models.CASCADE) description = models.TextField(blank=True) ) -
Can I assign custom name for path converters in Django?
I want to assign custom name for slug path converter in urlpatterns of my Now it looks like this: urlpatterns = [ ... path( route="<slug:category>/", view=views.Category.as_view(), name="shop_category" ), ... ] In this view I'm using DetailListView. The slug contains only ASCII characters, but anyway it doesn't let me in. After some manipulations with passed value, I return from get with return super().get(request, *args, **kwargs) line. Then it throws me an error: AttributeError: Generic detail view Category must be called with either an object pk or a slug in the URLconf. But if I change in category name in urlpatterns to slug, error disappears. Now, the question: can I assign custom name for path converters in Django? -
How to run django web app with mysql in the same Docker? ERROR (docker-compose up -d seems to work ok)
Everything seems working fine: But I cannot access it on localhost:8000 ''' root@zenek:~/InternF# sudo docker-compose ps Name Command State Ports internf_app_1 sh -c python manage.py run ... Up 0.0.0.0:8000->8000/tcp internf_db_1 docker-entrypoint.sh mysqld Up 0.0.0.0:3306->3306/tcp, 33060/tcp ''' I get this error after after trying to migrate. I got similar error using postgres db as well ''' root@zenek:~/InternF# sudo docker-compose run app python manage.py migrate Starting internf_db_1 ... done Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 217, in ensure_connection self.connect() File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 195, in connect self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 227, in get_new_connection return Database.connect(**conn_params) File "/usr/local/lib/python3.6/site-packages/MySQLdb/__init__.py", line 84, in Connect return Connection(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/MySQLdb/connections.py", line 179, in __init__ super(Connection, self).__init__(*args, **kwargs2) MySQLdb._exceptions.OperationalError: (1045, 'Plugin caching_sha2_password could not be loaded: /usr//usr/lib/x86_64-linux-gnu/mariadb19/plugin/caching_sha2_password.so: cannot open shared object file: No such file or directory') The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 361, in execute self.check() File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 64, in _run_checks issues = … -
How to get the child model object from the parent in Django?
I have the following models class Layer(models.Model): pass class Geometry(models.Model): layer = models.OneToOneField(Layer) class Circle(Geometry): radius = models.CharField(max_length=255) class Rectangle(Geometry): height = models.CharField(max_length=255) width = models.CharField(max_length=255) Layer has a one-to-one relationship with Geometry, that must either a Circle or a Rectangle, or one of the other 10 geometry children. I can easily get which geometry a layer currently has by doing layer.geometry, but I dont know an easy way of checking which of the geometry children it is. I can check if layer.geometry.circle exists and perform this check for all fields, but I am looking for an easier way to get child, since it is a one-to-one relationship I am guessing Django provides a better way of accessing that. Thanks in advance! -
Many to many relation entries not added by .add() method in Django
I am having idea regarding adding entry to a many to many relation field. I have the models as follows class Address(models.Model): id = models.AutoField(primary_key=True) country = CountryField(blank_label='(select country)', blank=False, null=False, verbose_name='Country') state = models.CharField( max_length=50, choices=STATE_CHOICES, verbose_name='State', blank=False, null=False ) ... class Volunteer(models.Model): userID = models.OneToOneField(User, on_delete=models.CASCADE, to_field='id', primary_key=True, related_name='volunteer') identificationNumber = models.CharField(max_length=50, unique=True, blank=False, null=False, verbose_name='Identification Number') currentAddress = models.ManyToManyField(Address, related_name='volunteerCurrentAddress', verbose_name='Current Address', blank=False) permanentAddress = models.ManyToManyField(Address, related_name='volunteerPermanentAddress', verbose_name='Permanent Address', blank=False) ... def save(self, *args, **kwargs): self.slug = self.userID.username super(Volunteer, self).save(*args, **kwargs) And in the views, I get both the currentAddress and permanentAddress fields as a ManyToManyRelatedManager. They are temporaryVolunteer.currentAddress and temporaryVolunteer.permanentAddress. I use these to create a new Volunteer instance as volunteer = Volunteer(...) volunteer.save() volunteer.currentAddress.add(temporaryVolunteer.currentAddress.all()[0]) volunteer.permanentAddress.add(temporaryVolunteer.permanentAddress.all()[0]) volunteer.save() But when I do print(volunteer.currentAddress.all()) or print(volunteer.permanentAddress.all()), it returns an empty queryset. I also checked the admin site for confirmation and there are no entries of address on the volunteer instance. Is there any way the entries can be added with this approach? -
Cannot import modul in tests file
Hi I have strange problem cause when I'm trying to import models to my test file I'm receiving error: ModuleNotFoundError: No module named 'Book' module exist cause I have copied & paste it from another file. My models code: from django.db import models from isbn_field import ISBNField from Book.validators import page_validator, date_validator class Book(models.Model): title = models.CharField(max_length=100) publication_date = models.CharField(validators=[date_validator,], max_length=10) authors = models.ManyToManyField("Author", related_name="author") ISBN = ISBNField() #validators=[book_unique_validator,] pages = models.IntegerField(validators=[page_validator,], blank=True) language = models.CharField(max_length=4) def __str__(self): return self.title def get_all_authors(self): return "".join([x.name.title() +", " for x in self.authors.all()])[:-2] class Meta: ordering = ["title"] My test code: from django.test import TestCase from Book.models import Book, Author class BookAPITestCase(TestCase): def create(self): author_obj = Author.create( name="test author" ) book_obj = Book.create( title="Test_title", publication_date="2019-11-20", authors=author_obj, ISBN="9788381107419", pages=295, language="en" ) def test_author(self): author_count = Author.objects.count() self.assertEqual(author_count, 1) -
How to run wordpress on localhost and django on localhost/product?
I have developed a wordpress website for a product.And the product is made using django.So after the user logs in ,i have to redirect him to the django project.I have to achieve this on the same domain.I have nginx installed. -
How to properly link domain to site
I have deployed on digitalocean django project. Configured with with nginx and gunicorn. I am trying to link it (project) to domain name in settings.py ALLOWED_HOSTS = ['domain', 'IP_address'] In nginx configuration for my site is following server { listen 80; server_name isli.site; location = /favicon.ico {access_log off; log_not_found off;} but when I am trying to access domain by browser it' arrise me error DNS_PROBE_FINISHED_NXDOMAIN What I am doing wrong?