Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create Public URL for Django Localhost to access in Other Machines
I'm working Django Project. How to create a Public IP permanently for Localhost(127.0.0.1:8000) IP in Django Project. After Creating Public URL, how to allow access for Other users without Source Code when I run python manage.py runserver x.x.x.x:8088 in command prompt it is generating a URL with specified IP address. But when I share/open this URL with others it is not working Can any one help me to configure this issue. Thanks in advance. -
no such table: two_factor_phonedevice when using django-two-factor-auth==1.14.0 and --nomigrations
I have a 2.2 Django project with django-otp==0.8.0, django-two-factor-auth[phonenumbers]==1.14.0, and an app two_factor_auth that makes use of these two libraries. When tests are run with migrations, they pass. $ ./manage.py test two_factor_auth Applying two_factor.0001_initial... OK Applying two_factor.0002_auto_20150110_0810... OK Applying two_factor.0003_auto_20150817_1733... OK Applying two_factor.0004_auto_20160205_1827... OK Applying two_factor.0005_auto_20160224_0450... OK Applying two_factor.0006_phonedevice_key_default... OK Applying two_factor.0007_auto_20201201_1019... OK ---------------------------------------------------------------------- Ran 13 tests in 5.549s OK Note that these migrations are the ones from the django-two-factor-auth package as the two-factor-auth app has no migrations. However, when tests are run without migrations (as is done in CI and local environments because our project has hundreds of migrations), they fail. $ ./manage.py test two_factor_auth --nomigrations Traceback (most recent call last): File "/opt/miniconda3/lib/python3.8/site-packages/two_factor/views/profile.py", line 38, in get_context_data 'default_device': default_device(self.request.user), File "/opt/miniconda3/lib/python3.8/site-packages/two_factor/utils.py", line 16, in default_device for device in devices_for_user(user): File "/opt/miniconda3/lib/python3.8/site-packages/django_otp/__init__.py", line 80, in devices_for_user for device in model.objects.devices_for_user(user, confirmed=confirmed): File "/opt/miniconda3/lib/python3.8/site-packages/django/db/models/query.py", line 274, in __iter__ self._fetch_all() ... File "/opt/miniconda3/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 383, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: two_factor_phonedevice I can confirm that this issue no longer appears if I go back to using django-otp==0.7.5 and django-two-factor-auth==1.9.1. What could be the problem? -
csv report From filtered Data in django
i have a search field in my django app and filtering Data work well . when i want get csv report , whole of record will be print in csv not filtered data . thank you for help me . qs=EventkindofProblem.object.all() MyFilter=eventfilter(request.GET,queryset=qs) return djqscsv.render_to_csv_response(myFilter.qs,append_data_stamp=True)``` -
Django filter by date gives wrong results
I am trying to filter data retrieved from a postgresSQL table using django filter method. Below is the code I am using for that and I am giving "2022-7-13" as the filter_date in the query. The database has 62 entries for the date "2022-7-13" but, the API gives 23 as the result. I have set USE_TZ = True in my django settings.py file and I am using pendulum.timezone('America/Los_Angeles') as the timezone in django settings file. Can anyone help to resolve this issue. def get_runs(self, obj): """ drf serializer method field """ runs = 0 date = self.context.get('request').query_params.get('filter_date', None) if date is not None: filter_date = datetime.strptime(date, '%Y-%m-%d')\ .replace(tzinfo=pendulum.timezone('America/Los_Angeles')).date() runs = obj.runs.filter(created_on__date=filter_date).count() else: runs = obj.runs.count() return runs -
Why isn't the current directory in sys.path for a django application
To my understanding, the sys.path has the current directory (the directory the module is in) as its first index, yet this seems inconsistent with django. I have a project structure: In my_file_1.py, printing sys.path gives me: In my_file_2.py, printing sys.path gives me: These two sys.path prints makes sense since that red underline is the directory the modules are in (their respective current directory). However, in my django app with the following project structure: When printing sys.path in urls.py, I get: Which is the root directory of the project, instead of the current directory of urls.py which should be c:\\Users\\5403\\Desktop\\tutorial\\tutorial Could someone explain this inconsistency and correct me if I have any misconceptions, thanks. -
How to check data exist in database or not while uploading large dataset using django
I am going to make a scripts that load excelsheet which contain 17000 rows to django model. But, I don't get idea to check given data already exist or not in database efficiently. in models.py # no fields value are unquie here, class Student(models.Model): name=models.CharField(max_length=100) address=models.CharField(max_length=100) age=models.CharField(max_length=100) rollno=models.CharField(max_length=100) in views.py def upload_script(request): wb = openpyxl.load_workbook(excel_file) worksheet = wb["All DMAs"] for row in worksheet.iter_rows(): datacollection=row[0:9] name=datacollection[0] address=datacollection[1] rollno=datacollection[2] age=datacollection[3] # everytime this call the database which load more time if(Student.objects.filter(name=name,address=address,rollno=rollno,age=age).first(): continue student_obj=Student( name=name, address=address, rollno=rollno, age=age ) student_list.append(student_obj) if len(student_list)>1000: Student.objects.bulk_create(student_list) student_list=[] Student.objects.bulk_create(student_list) -
Getting user input from a input field in Django
So what I am trying to do is grab the users input, and then it append it to the HTML, I am making an attempt to make a chatbot system, I have the modules wrote I am just having trouble getting the users input. I have been looking around and I thought something like this would work but I am receiving back this: {'rawText': None} I will take the input, and pass it to the python module I wrote, and then append the results also to the HTML, like a messenger, still new to python, and django so confused as to why I am not getting any text back in console. views.py: from django.shortcuts import redirect, render from django.shortcuts import HttpResponse from .forms import messageForm from .main import get_weather, take_user_input def home(request): form = messageForm() # Get the message to display to view. if request.method == "POST": rawText = request.GET.get('textInput') context = {'rawText': rawText} print(context) return render(request, 'home.html', {'form': form}) forms.py: from django import forms class messageForm(forms.Form): message = forms.CharField(max_length=1000) home.html: {% extends 'base.html'%} {% load static %} {% block content %} <h2>Blue's Chatbot</h2> <div> <div id="chatbox"> <p class="botText"><span>Hi! Let's get to chatting.</span></p> </div> <div id="userInput"> <form type="text" id="textInput" action="" … -
How to customize showing query parameter with DRF filtering (ManyToManyfield)
I hope my question is not a duplicated.. I'm building a rest API with DRF, now I'm trying to do filtering hashtag. The url I want is article/list?hashtags=dobi BUT I got id, like article/list?hashtags=13 How can I override? Here is models.py: class Article(AbstractTimeStamp): user = models.ForeignKey('users.User', on_delete=models.CASCADE) title = models.CharField(max_length=300,blank=False) content = models.TextField(max_length=1000) hashtags = models.ManyToManyField('Hashtag', max_length=200, related_name='articles', blank=True) class Hashtag(models.Model): hashtag = models.CharField(max_length=200, unique=True, blank=True) Here is my serializers.py: class ListSerializer(serializers.ModelSerializer): hashtags = HashtagsSerializer(many=True) class Meta: model = Article fields = ['id','title','hashtags'] Here is my views.py: class ArticleListAPIView(generics.ListAPIView): queryset = Article.objects.all() serializer_class = ListSerializer filter_backends = [filters.SearchFilter,DjangoFilterBackend] search_fields = ['title'] filterset_fields = ['hashtags'] -
Django Error: from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django'
I'm using django and virtual environment "virtualenv", activate it, try to run the server in the project folder like this: python manage.py runserver, but I get this error: from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django'. what could be happening? if someone can help, thank you in advance -
In django whenever I try to run the server, I want to see the login page first, but I am seeing the index page?
I am attaching my code in views and urls.py. Whenever the server runs, I want to see the login page first, but I am seeing an error that this page is not working. def loginPage(request): if request.user.is_authenticated: return redirect('/') else: if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('/') else: messages.info(request, 'Username OR password is incorrect') context = {} return render(request, 'accounts/login.html', context) urlpatterns = [ path('', views.loginPage, name="login"), path('index/',views.index,name="index"), -
DJANGO custom user model: create_superuser() missing 1 required positional argument: 'username'
I have the following User model which uses email as USERNAME_FIELD and leave the actual username unused. All authentication features work fine, but I just realized I cannot create superuser with manage.py because of the error: create_superuser() missing 1 required positional argument: 'username' Can anyone help me debug this error? users/models.py class User(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) username = None first_name = models.CharField(max_length=100, default="unknown") last_name = models.CharField(max_length=100, default="unknown") profile_pic = models.CharField(max_length=200, default="unknown") premium = models.BooleanField(default=False) email = models.EmailField(unique=True, db_index=True) secret_key = models.CharField(max_length=255, default=get_random_secret_key) USERNAME_FIELD = "email" REQUIRED_FIELDS = [] class Meta: swappable = "AUTH_USER_MODEL" users/services.py def user_create(email, password=None, **extra_fields) -> User: extra_fields = {"is_staff": False, "is_superuser": False, **extra_fields} user = User(email=email, **extra_fields) if password: user.set_password(password) else: user.set_unusable_password() user.full_clean() user.save() return user def user_create_superuser(email, password=None, **extra_fields) -> User: extra_fields = {**extra_fields, "is_staff": True, "is_superuser": True} user = user_create(email=email, password=password, **extra_fields) return user @transaction.atomic def user_get_or_create( *, email: str, first_name: str, last_name: str, profile_pic: str ) -> Tuple[User, bool]: user = User.objects.filter(email=email).first() if user: return user, False return ( user_create( email=email, first_name=first_name, last_name=last_name, profile_pic=profile_pic, ), True, ) Full error log ❯ docker-compose run --rm web ./manage.py createsuperuser ─╯ Email: example@email.com Password: Password (again): Traceback (most recent call last): File "./manage.py", line … -
for loop in django template returning blank list items
I'm looping through the field of joined for my Group model and returning the list of joined members in my GroupDetail template: class Group(models.Model): leader = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=55) description = models.TextField() joined = models.ManyToManyField(User, blank=True) Each member in the for loop relates to a User (or username) that has joined the Group: <ul> {% for member in joined_members %} <li>{{ member }}<li> {% endfor %} </ul> There are four members in the Group, and all members are being returned, however four empty list items are also being returned as such (via chrome dev tools): <ul style="display: block;"> <li>joe</li> <li></li> <li>johnny</li> <li></li> <li>ralph</li> <li>/li> <li>mike</li> <li></li> </ul> There are only four members (Users) joined to this particular group, so I don't understand what's happening. I assume the issue is from how I passed the data into the template from my view: class GroupDetail(DetailView): model = Group template_name = 'group_details.html' def get_context_data(self, *args, **kwargs): group = get_object_or_404(Group, id=self.kwargs['pk']) joined_members = group.joined.all() context = super(GroupDetail, self).get_context_data() context["joined_members"] = joined_members return context There are no actual errors, just these four empty list items. Is the issue with my for loop? Or is it with how I'm passing my context? -
PrimaryKeyRelatedField does not serialize the object
I have a game model like this: class Game(models.Model): owner = models.ForeignKey(User, null=True, blank=True, on_delete=models.SET_NULL) name = models.CharField(max_length=255) slug = models.SlugField() ... And a serializer like this: class GameSerializer(serializers.ModelSerializer): owner = serializers.PrimaryKeyRelatedField(many=False, read_only=True) class Meta: model = Game fields = ( "id", "name", "description", "owner" ) When I make a request I get this: description: "TestDescription" name: "TestName" owner: 1 I was expecting owner to be a dictionary with fields like an email, a username and so forth. What is wrrong? -
Fixing load static Django Templates
I've been searching for an answer to this and I feel like I'm doing everything right and have taken on suggestions in multiple posts but this is still stumping me. I'm trying to load static in my django template but for some reason I keep getting and unresolved template error and it won't load in my browser. project/settings.py # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.0/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATIC_FILES_FIRS = [os.path.join(BASE_DIR, 'static')] I've set up the static root. Then in my base.html I've got: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="icon" type="image/png" sizes="16x16" href="{% static "favicon/favicon.png" %}"> <title>Title</title> <script src="https://cdn.tailwindcss.com"></script> </head> <body> {% include "navbar.html" %} <img src="{% static "favicon/favicon.png" %}" alt="img"/> <main class="container mx-auto p-8"> {% block main %}{% endblock %} </main> </body> </html> I feel like I'm missing something because that directory should exist but the django template isn't finding it! I've tried using {% load staticfiles %} instead but that errors saying it can't find staticfiles. Any help would be appreciated! Thanks, Mitchell -
django ajax send form and csv
I am saving a form with ajax , I use the following code and it saves my form,but I have an input that captures a csv file that is not saved in a field of the form but I need to save the records of that csv in a different table. I don't know how to send both the form and the csv with ajax and capture them in the post method of the view , So far I send the data of the form form.py class AsignacionGeneralForm(forms.ModelForm): # idproyecto = forms.ModelChoiceField(queryset=None) def __init__(self, *args, **kwargs): super(AsignacionGeneralForm, self).__init__(*args, **kwargs) for field in iter(self.fields): self.fields[field].widget.attrs.update({ 'class': 'form-control' }) self.fields['fecha_descarga'].widget.attrs.update({ 'class': 'form-control', 'data-inputmask-alias':'datetime', 'data-inputmask-inputformat':'mm/dd/yyyy', 'data-mask inputmode':'numeric' }) class Meta: model=Recaudo fields=['fecha_descarga','observacion'] html <form method="post" action="." enctype="multipart/form-data"> {% csrf_token %} <input type="hidden" name="action" value="{{ action }}"> {{form}} <div class="form-group"> <label>Cargar Archivo:</label> <div class="input-group"> <input type="file" class="form-control" name='file' accept=".csv" id="inputGroupFile" aria-describedby="inputGroupFileAddon04" aria-label="Upload" required> <button class="btn btn-outline-secondary" type="button" id="inputGroupFileAddon" onclick="resetFile()">Borrar</button> </div> </div> <div class="form-group"> <button type="button" class="btn btn-danger" data-dismiss="modal" onclick="cancelar()">Cancelar</button> <button type="submit" class="btn btn-success float-right"> <i class="fas fa-save"></i> Guardar </button> </div> </form> ajax $('form').on('submit',function(e){ e.preventDefault(); var parameters=$(this).serializeArray(); console.log(parameters); var formData = new FormData(); formData.append('file', $('#inputGroupFile')[0].files[0]); formData.append('csrfmiddlewaretoken', '{{ csrf_token }}'); console.log(formData); $.ajax({ url: '{% url 'gestionAsignacion:asignacion_general' … -
django custom serializer field not working
I am trying to add an additional field in the serializer but at the moment of adding it I get the following error error view During handling of the above exception ('MovieSerializer' object has no attribute 'len_name') I have seen many posts and all of them are working, what could it be? this is my code Model: from django.db import models class Movie(models.Model): title = models.CharField(max_length=255, unique=True) description = models.TextField() active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(default=None, null=True) def __str__(self): return self.title serializer: from rest_framework import serializers from watchlist_app.models import Movie from watchlist_app.api.validations import MovieValidations class MovieSerializer(serializers.ModelSerializer): len_name = serializers.SerializerMethodField(method_name='len_name') class Meta: model = Movie fields = "__all__" read_only_fields = ['id', 'len_name', 'created_at'] required_fields = ['title', 'description'] @staticmethod def create(self, validated_data): return Movie.objects.create(**validated_data) @staticmethod def update(self, instance, validated_data): instance.title = validated_data.get('title', instance.title) instance.description = validated_data.get('description', instance.description) instance.active = validated_data.get('active', instance.active) instance.save() return instance @staticmethod def get_len_name(self, obj): return len(obj.title) validators = [MovieValidations.validate_title, MovieValidations.validate_description, MovieValidations.validate_equals] everything works fine until I add the serializerMethodField -
Django Templates Syntax Error For If (Could not parse the remainder)
Why does this not work in Django? {% for img in image_list %} {% if img != image_list[-1] %} <img src="{% get_media_prefix %}{{ img.image }}" class="img-fluid rounded" alt="Recipe Image Secondary"> <br> {% endif %} {% endfor %} Simple Python (works): for img in image_list: if img != (image_list[-1]): print(img) {% if img != image_list[-1] %} throws a TemplateSyntaxError Could not parse the remainder: '[-1]' from 'image_list[-1]' -
How to annotate the number of times a related field appears for the parent [Django]
I've got 2 classes: class Agent(models.Model): pass class Client(models.Model): agent = models.ForeignKey( "agents.Agent", on_delete=models.SET_NULL, ) connected = models.BooleanField( default=False, ) I know that if connected was an integer, I could use Sum like this: Agent.objects.all().annotate( Sum("client__connected"), ) But how would I get the count based on the value of the related field? I've also tried: Agent.objects.all().annotate( connected=Count( "connected", filter=Q(client__connected=True), ) ) But this just gives me the error: An exception of type FieldError. Arguments: ("Cannot resolve keyword 'connected' into field. -
Making user.username (or any field) anonymous for certain users
I'm trying to make certain PII related attributes such as user.username or profile_picture anonymous for certain users. I have a field in my database called cant_see_pii that tracks whether a user can see other users sensitive data. class UserAttributes(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name = 'user_attribute') cant_see_pii = models.BooleanField(null=True, blank=True, default = False) profile_picture = models.ImageField("Profile Picture", default='images/default.svg', upload_to='images/', null=True, blank=True) If this field is true I want to obfuscate all other users pii related data, without hiding their own. Example: When a template has <H1>{{other_user.username}}</H1>, I want this to return <H1>Anonymous User</H1> or even better <H1>Anonymous User 12345</H1> I don't want to have to do this for every instance I use this in every template so something like this won't work: <H1>{% if userattribute.cant_see_pii == True %}Anonymous User{%else%}{{other_user.username}}{%endif%}</H1> -
Edit request in Django Rest Framework Testing
Im using django rest API for my requests and im trying to run some tests on them . GET/POST works correctly but when im trying to post something and then change it it just adds an extra instance to the db instead of editing the already existing one . edit works when placing the pk of the object in the url but instead of changing the already assigned ID it creates a new one . post request self.client.force_authenticate(self.user) response = self.client.post(reverse(xx:xx), { "user": '1', "friendly_name": "xx", "soil_type": "xx", "cultivation": "xx" },format='json') edit request self.client.force_authenticate(self.user) response = self.client.put( reverse('xx:xxx', kwargs={'field_id':1}), { "user": '1', "friendly_name": "XX", "soil_type": "XX", "cultivation": "XX" } ) -
please, how do I get over "int() argument must be a string, a byte-like object or a real number, not a 'NoneType'" error in my code?
<h1>This is food box page</h1><br><br> `<image src= "{% static 'food_app/image1.jpeg' %}">` <h2>{{food_box1.0}}</h2> <h3>{{food_box1.1}}</h3> <button type= "button"><strong>EAT ME!</strong></button><br><br> <form action="{% url 'food_app:price' %}" method="POST"> {% csrf_token %} <label for="price in packs"><strong>Price in packs</strong></label> `<input type="text" id="price in packs" name="price1" placeholder="Enter number between 20 and enter code h 500">` <h1>{{new_price}}</h1> <button type= "button"><strong>EAT ME!</strong></button> </form> <br> <br> <image src= "{% static 'food_app/image2.jpeg' %}"> <h2>{{food_box2.0}}</h2> <h3>{{food_box2.1}}</h3> <button type= "button"><strong>EAT ME!</strong></button><br><br> <form action="{% url 'food_app:price' %}" method="POST"> {% csrf_token %} <label for="price in packs"><strong>Price in packs</strong></label> `<input type="text" id="price in packs" name="price2" placeholder="Enter number between 20 and 500">` <h1>{{new_price2}}</h1> <button type= "button"><strong>EAT ME!</strong></button> </form> Python if request.method == "POST": price_pack_box = int(request.GET.get("price1")) if price_pack_box >= 20 and price_pack_box <= 500: food = Food.objects.get(pk=40) food_price = food.food_price total_price1 = price_pack_box*food_price elif price_pack_box < 20: messages.info(request, "number input too small!") return redirect('food_app:foodbox') elif price_pack_box > 500: messages.info(request, "number input too large!") return redirect('food_app:foodbox') print(total_price1) `elif request.method == "POST":` `price_pack_box = int(request.POST.get("price2"))` `if price_pack_box >= 20 and price_pack_box <= 500:` `food = Food.objects.get(pk=41)` `food_price = food.food_price` total_price2 = price_pack_box*food_price elif price_pack_box < 20: messages.info(request, "number input too small!") return redirect('food_app:foodbox') elif price_pack_box > 500: messages.info(request, "number input too large!") return redirect('food_app:foodbox') print(total_price2) my_dict = {'new_price':total_price1,'new_price2':total_price2,'new_price3':total_price3} return render(request, … -
django | model.objects.filter(user = request.user) not returning any data
I've been trying to render out user specific content, but when I use the line 'Job.objects.filter(user = request.user)' I don't get anything rendered in the form. I don't think that the problem is the template because when I use the line Job.objects.all() all instances are rendered out with no problem. What I'm trying to do is render out the instances that are 'posted' by a user. views.py @login_required(login_url='login') def manage_jobs(request): if request.user.is_employee: return redirect('home') else: form = JobForm(request.POST) jobs = Job.objects.filter(user=request.user) if form.is_valid(): form.save() context = {"form":form, "jobs":jobs} return render(request, 'employer/manage-jobs.html', context) class Account(AbstractBaseUser): email = models.EmailField(verbose_name='email', max_length=60, unique=True) name = models.CharField(max_length=45, unique=False) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_employee = models.BooleanField(default=True, verbose_name='Are you using FilmLink as an employee?') USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name', 'is_employee'] objects = MyAccountManager() class Meta: permissions = [ ("post_jobs", "Can post jobs"), ] def __str__(self): return self.name def has_perm(self, perm, obj=None): return True def has_perms(self, perm): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.is_admin class Job(models.Model): company = models.CharField(max_length=40, null=True, verbose_name="Company/Employer") description = models.TextField(null=True) role = models.CharField(max_length=25) area_of_filming = models.CharField(max_length=50, verbose_name="Area Of Filming", default="") … -
can you please check if i done "register" function correctly in django
i am new in django , can you please check if I done "register" function in the correct way , without applying django forms because i find difficult to do it , so i choose this way my function: def register(request): if request.method == 'POST': db = Customers() db.fname = request.POST['fname'] db.lname = request.POST['lname'] db.email = request.POST['email'] db.password = make_password(request.POST['password']) repassword = request.POST['repassword'] db.username = request.POST['username'] db.save() if check_password(repassword, db.password): if User.objects.filter(username=db.username).exists(): messages.info(request, 'Username is already taken') return redirect("register") elif User.objects.filter(email=db.email).exists(): messages.info(request, 'Email is already taken') return redirect("register") else: user = User.objects.create_user( username=db.username, password=db.password, email=db.email, first_name=db.fname, last_name=db.lname) user.save() return redirect("login_user") else: messages.info(request, 'Both passwords are not matching') return redirect(register) else: return render(request, "compte/register.html") -
django.db.utils.IntegrityError: duplicate key value violates unique constraint "package_code_key"
I have written a test case for create api in Django but I am getting the above error. I see in database it creates some objects and says that there is a duplicate key value in the error. My model is: class Example(models.Model): package = models.ForeignKey( Destination, related_name="packages", on_delete=models.CASCADE ) user = models.ForeignKey( User, on_delete=models.CASCADE, null=True, related_name="user_packages", ) tour = models.ForeignKey( Tours, on_delete=models.CASCADE, null=True, related_name="tour_packages", ) My test case is as follows: import factory # Define your factories class PackageFactory(factory.django.DjangoModelFactory): class Meta: model = 'example.Package' class UserFactory(factory.django.DjangoModelFactory): class Meta: model = 'example.User' class TourFactory(factory.django.DjangoModelFactory): class Meta: model = 'example.Tour' class ExampleFactory(factory.django.DjangoModelFactory): package = factory.SubFactory(PackageFactory) user = factory.SubFactory(UserFactory) tour = factory.TourFactory(TourFactory) class Meta: model = 'example.Example' # And now, create a new example instance together with all related models. example = ExampleFactory() I cleared the database and start running the test but I get the same error. How to solve this?? -
How do I update settings.py using views and forms in Django? [duplicate]
I want to set my variables in settings.py through the front-end using Views and Forms. Let's say, I have following in settings.py: # My personal settings NO_OF_DAYS = 0 and I have following in my forms.py: def class SettingsForm(froms.Form): no_of_days = forms.CharField(max_length=254) Now, I want mixture of views and forms, something like below in my views.py: from django.conf import settings from .forms import SettingsForm class UpdateSettings(View): def get(self, request): settings_form = SettingsForm() return render(request, "settings-template.html", "form": settings_form) def post(self, request): settings_form = SettingsForm(request.POST) if settings_form.is_valid(): form_data = settings_form.cleaned_data settings.NO_OF_DAYS = int(form_data["no_of_days"]) # I WANT SOMETHING LIKE THIS, BUT I WANT SETTINGS.PY TO STORE THE VALUE FOREVER, NOT JUST IN THIS VIEW return redirect("/success/") How do I accomplish it?