Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
SelectRelatedMixin in braces
How to use select_related attribute in the braces module in django. Please explain. I looked into the docs but it was pretty difficult to understand. Thanks -
Django Singal Populating one model if another model is populated
I have a Django project with two apps.. one is contact and annother is contactus my contact model is: project/contact/models.py below: from django.db import models class ContactList(models.Model): phone = models.CharField(max_length=15) email = models.EmailField() and my contactus model is: project/contactus/models.py below: from django.db import models class ContactUs(models.Model): subject = models.CharField(max_length=50) phone = models.CharField(max_length=15) email = models.EmailField() message = models.TextField() I want when ContactUs class gets data by user input, in the same time, ContactUs's phone and email should be populated in ContactList class I created two signal.py file in my two apps but tried a lost with some code, i failed.. i think this is the very easiest task for expert.. Can anyone help me to solve this problem? -
Django Form not saving
I am relatively new to django and i'm trying to implement some modelforms. My page consists of two views, a Politics section and a Sports section, each one with the same form for making comments (my comment model is named Comentario). It has a field for the content and a field for the section the comment belongs to. Both views are basically the same so I'm going to showcase just the politics one: from django.contrib import messages from django.shortcuts import render from django.views.generic import CreateView from usuarios.models import Usuario from .forms import CrearComentario from .models import Comentario usuarios = Usuario.objects.all() comentarios = Comentario.objects.all() pag = '' def politics(request): if request.user.is_authenticated: if request.method == 'POST': form = CrearComentario(request.POST, instance=request.user) if form.is_valid(): messages.success(request, 'Publicado!') pag = 'politics' form.save() form = CrearComentario() else: form = CrearComentario(request.POST,instance=request.user) else: messages.warning(request, 'Comentario no válido') form = CrearComentario(request.POST) return render(request, 'main/politics.html', {'usuarios': usuarios, 'comentarios': comentarios, 'form': form}) In case you're wondering, 'pag' is a control variable that is checked by my signals.py file to update the 'pagina' field I had trouble with the submit buttons in my custom modelsforms, the form displays correctly, and when I write something in the form and submit it, it displays a … -
organize urls in django
I have a problem with my urls, first of all here my urls.py: from .views import ( CouponListView, CouponDetailView, buy_coupon, UserCouponListView, CouponOnResaleCreateView, CouponOnResaleListView, ) from django.urls import path coupons_patterns = ([ path('', CouponListView.as_view(), name = 'list'), path('<int:pk>/<slug:slug>/', CouponDetailView.as_view(), name = 'detail'), path('create/<int:pk>/<slug:slug>/', CouponOnResaleCreateView.as_view(), name = 'create'), path('<slug:slug>/', UserCouponListView.as_view(), name = 'user'), path('coupon/<int:pk>/<slug:slug>/buy/', buy_coupon, name = 'buy_coupon'), ], 'coupons') Well, I want to add another "pattern" of urls so to speak, that is, the "pattern" of urls that I have is: coupons: name and I want to add one like this: coupons_on_resale: name, but without having to create another app. How should I do it? It occurs to me to create other patterns like the one I showed before and include it, but is it good practice? Are there other ways? I want a scalable, clean and easy to maintain structure in my urls. Thanks for your suggestions in advance! -
Django-Rest-Framework POST request to ManyToMany Field
I have a django model that is a message. It has a name which is a CharField, then also an array of users which is a ManyToManyField. So This is what my API looks like: [ { "id": 13, "content": "hej", "date": "2019-07-09", "sender": { "id": 1, "username": "william" } }, { "id": 14, "content": "hej william", "date": "2019-07-09", "sender": { "id": 3, "username": "ryan" } } ] What I've tried to send via postman POST: { "content": "Hello", "sender": {"username": "william"}, "date": "2019-09-02" } The Error I get: sqlite3.IntegrityError: NOT NULL constraint failed: chat_message.sender_id ManyToManyField(Userprofile=User): class Message(models.Model): sender = models.ForeignKey(UserProfile, on_delete=models.CASCADE, related_name="sendermessage") content = models.CharField(max_length=500) date = models.DateField(default=date.today) canview = models.ManyToManyField(UserProfile, blank=True, related_name="messagecanview") class Meta: verbose_name_plural = 'Messages' def __str__(self): return "{sender}".format(sender=self.sender) -
Return existing record rather than creating Rest API framework
In my API, I have a create view tied that references another record OneToOne. However, occasionally it seems that users send through two requests at once and the second fails due to a duplicate record clash: class CreateProfileLink(generics.CreateAPIView): def perform_create(self, serializer): ins = serializer.save(user=self.request.user) serializer_class = ProfileLinkSerializer Is there a way I could override the create method to return the record if it already exists rather than creating it? -
How to reload a custom command from inside shell?
I'm looking to test some custom commands and wondering if there's a way to reload a command once I'm already inside shell? ie: > python manage.py shell > from django.core import management > management.call_command('get_embeds') > # make some changes to file > # reload command > management.call_command('get_embeds') We're running on a vagrant VM so running something such as python manage.py get_embeds takes a bit of time to load each time I want to test the script. -
How to do many to one relationship in Django
I am doing a many to one relationship but I get a prompt that the field person in the report is without a default. I tried setting the default to an empty space, I get an IntegrityError: NOT NULL constraint failed class Person(models.Model): person_name = models.CharField(max_length=255) person_location = models.CharField(max_length=255, null=True) classReport (models.Model): person = models.ForeignKey( Person, related_name='people', default="", on_delete=models.CASCADE) product_name = models.CharField(max_length=255) product_description = models.CharField(max_length=255) -
Could not parse the remainder: '{{' from '{{' , while inside html if loop
I am creating a table in html, but if the value that will be outputted is equal to the value above I want to merge the cells. I am sure that all the variables work as they are correct later. However, when I use them in the if loop I get an error <table> <tr> <th>id</th> <th>peptide_id</th> <th>protein_id</th> <th>group_id</th> <th>search_id</th> <th>peptide_parsimony</th> </tr> {% for elem in elem_list %} <tr> {% for sub_elem in elem %} elem.2 = {% if {{ elem.2 }} == {{sub_elem}} %} <td> </td> {% else %} <td onclick="location.href='/protein/proteinseq/{{ elem.1}}/{{ elem.2 }}/{{ elem.4 }}/'" style = " text-decoration: underline; cursor: pointer" >{{ sub_elem }}</td> {% endif %} {% endfor %} </tr> {% endfor %} </table> This gives me the error : Could not parse the remainder: '{{' from '{{' Does anybody know how to merge cells in a specific column if they have the same value, preferably with an example as I am new to html and JS? Thanks! -
Cannot get send_mail to work in Django 2.3. No error message. No log message indicating email is sent or not sent
So I have been scouring the internet trying to get my code to work and i feel like I've read every post about this issue and still haven't figured out why I can't get my form to send me an email. I created a class based view which inherits FormView and have written a method that should send an email to me anytime there is a post-request. For the life of me, I can't get it to work. For those who are in the same boat, this is one post that seemed promising so hopefully this will help you even if it doesn't help me: Django sending email My views.py: (both email addresses are the same. It should simulate me sending an email to myself.) class CandRegisterView(FormView): template_name = 'website/candidate_register.html' form_class = UploadResumeForm def contact_email(self, request): first_name = request.POST.get('first_name') if first_name: try: send_mail(first_name, 'Their message', 'myemail@gmail.com', ['myemail@gmail.com'], fail_silently=False) return HttpResponse('Success!') except BadHeaderError: return HttpResponse('Invalid header found.') return HttpResponseRedirect('') else: return HttpResponse('Makes sure all fields are entered and valid.') my forms.py: from django import forms class UploadResumeForm(forms.Form): first_name = forms.CharField( widget=forms.TextInput( attrs={ 'type':'text', 'class': 'form-control', 'placeholder': 'First Name', }), required=True) my settings.py (the variables are stored in a .env file and … -
How to fix 'CustomUser' object has no attribute 'get'
I am trying to get some data from the database to display on the view, but I shows me an error that I have code that is not even there. I have the model CustomCliente: class CustomCliente(AbstractUser): email = models.EmailField(unique=True, null=False, blank=False) full_name = models.CharField(max_length=120, null=False, blank=False) password = models.CharField(max_length=40, null=False, blank=False) username = models.CharField(max_length=110, unique=True, null=False, blank=False) And I have a view with the following method: def mostrar_relatorio(request, id): aluguel = Aluguel.objects.get(cliente=CustomCliente.objects.get(id=id)) if aluguel is not None : context = {'aluguel', aluguel} template_name = 'relatorio.html' else: raise Http404 return render(request, template_name, context) And my urls patterns from that model is: urlpatterns = [ path('cliente/<int:id>', CustomCliente, name='relatorio'), ] What happens is that when I try to access the following url 127.0.0.1:8000/cliente/2, I get the error: 'CustomCliente' object has no attribute 'get. Even though I don't even have anywhere in my code calling CustomCliente.get. I have tried shutting down the server and trying again, rewrited the code, but it doesn't seem to work. -
Import error: oracle client library with python wsgi
When I deployment don't get any problem to run, but when I trying run with apache wsgi got this error: DatabaseError: DPI-1047: Cannot locate a 64-bit Oracle Client library: "libclntsh.so: cannot open shared object file: No such file or directory" Tried to use ldconfig and setup on environment LD_LIBRARY_PATH but didn't worked. The server is a linux x64 with cx_oracle 7.2.0 and django 1.11.22 with python 2.7.15+ and installing libaio. root@webservice:/opt/instantclient_11_2# ls -la lrwxrwxrwx 1 root root 17 Jul 10 15:41 libclntsh.so -> libclntsh.so.11.1 -rwxrwxr-x 1 root root 53865194 Aug 24 2013 libclntsh.so.11.1 -r-xr-xr-x 1 root root 7996693 Aug 24 2013 libnnz11.so lrwxrwxrwx 1 root root 15 Jul 10 15:41 libocci.so -> libocci.so.11.1 -rwxrwxr-x 1 root root 1973074 Aug 24 2013 libocci.so.11.1 -rwxrwxr-x 1 root root 118738042 Aug 24 2013 libociei.so -r-xr-xr-x 1 root root 164942 Aug 24 2013 libocijdbc11.so -r--r--r-- 1 root root 2091135 Aug 24 2013 ojdbc5.jar -r--r--r-- 1 root root 2739616 Aug 24 2013 ojdbc6.jar -rwxrwxr-x 1 root root 192365 Aug 24 2013 uidrvci -rw-rw-r-- 1 root root 66779 Aug 24 2013 xstreams.jarre root@webservice:/opt/instantclient_11_2# cat /etc/ld.so.conf.d/oracle-instantclient.conf /opt/instantclient_11_2 -
DRF - How to correctly Update a Foreing Key
I'm having trouble updating my User object since my request send a "customer id" (example: 12) but my serializer y waiting for a dict To be more clear, here is the message I get: Invalid data. Expected a dictionary, but got int. What I'm trying to acomplish is to update my customer field from my user which is a ForeingKey here is my viewset.py: def update(self, request, *args, **kwargs): try: customer = BankCustomer.objects.filter(id=request.data.get('customer')) serializer = UserSerializer(customer, data=request.data) except BankCustomer.DoesNotExist: return Response(None, status=status.HTTP_400_BAD_REQUEST) if serializer.is_valid(): serializer.save() else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) return Response(serializer.data, status=status.HTTP_200_OK) user serializers.py: class UserSerializer(serializers.ModelSerializer): customer = BankCustomerSerializer() email = serializers.EmailField() class Meta: model = User fields = ('id', 'email', 'name', 'lastname', 'type', 'customer', 'is_blocked') def update(self, instance, validated_data): instance.customer = validated_data.get("customer", instance.customer) instance.email = validated_data.get("title", instance.email) instance.name = validated_data.get("name", instance.name) instance.lastname = validated_data.get("lastname", instance.lastname) return instance customer serializer: class BankCustomerSerializer(serializers.ModelSerializer): users = serializers.PrimaryKeyRelatedField(many=True, source='customer_r', queryset=User.objects.all(), default='') class Meta: model = BankCustomer fields = ('id', 'customer', 'ruc', 'address', 'phone', 'users') -
Requested setting INSTALLED_APPS, but settings are not configured
When I try to run my scraper in Django I get the following error. This happened when I tried to put the scraped data into the database using the built-in Django models. traceback and error: /usr/bin/python3.6 /home/xxxxxx/Desktop/project/teo/movierater/scrap.py Traceback (most recent call last): File "/home/xxxxxx/Desktop/project/teo/movierater/scrap.py", line 7, in <module> from teo.movierater.api.models import * File "/home/xxxxxx/Desktop/project/teo/movierater/api/models.py", line 3, in <module> class Author(models.Model): File "/usr/local/lib/python3.6/dist-packages/django/db/models/base.py", line 103, in __new__ app_config = apps.get_containing_app_config(module) File "/usr/local/lib/python3.6/dist-packages/django/apps/registry.py", line 252, in get_containing_app_config self.check_apps_ready() File "/usr/local/lib/python3.6/dist-packages/django/apps/registry.py", line 134, in check_apps_ready settings.INSTALLED_APPS File "/usr/local/lib/python3.6/dist-packages/django/conf/__init__.py", line 79, in __getattr__ self._setup(name) File "/usr/local/lib/python3.6/dist-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. I put it in bin/activate: export DJANGO_SETTINGS_MODULE=mysite.settings Here is the code snippet from scraper.py: import django import os import requests from bs4 import BeautifulSoup as bs from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from teo.movierater.api.models import * os.environ['DJANGO_SETTINGS_MODULE'] = 'movierater.settings' django.setup() My project structure and the settings: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'movierater.api', ] wsgi.py file: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'movierater.settings') application = get_wsgi_application() -
Axios POST request from Vuejs to Django rest framework
I create a rest api with vuejs and django rest framework. The probleme is when i made a post request. With a get request he works but not with a post request. axios .get('http://127.0.0.1:8000/api/users/') .then(response => (this.info = response.data)) axios .post('http://127.0.0.1:8000/api/users/', { params : { email : "test@gmail.com", username : 'test' } }) .then(response => (this.info = response.data)) class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all().order_by('-date_joined') serializer_class = UserSerializer router = routers.DefaultRouter() router.register(r'users', UserViewSet) urlpatterns = [ path('', include(router.urls)), ] My get request works but not my post request. In my console i have : http://127.0.0.1:8000/api/users/?username=test&email=test@gmail.com 400 (Bad Request) And when i watch network i have {"username":["This field is required."]} I don't uderstand why i have this error. -
Passing Django Model to Javascript
I'm trying to pass my complete model with it fields because I need to use it on a Javascript function. I've tried everything I've seen (using json.dumps(), serializers..) and anything worked for me. I've donde the query this way: cancion = Cancion.objects.get(pk = cancion_id) The reason is because I need specific data depending on the id. Doing this, it throws me the following error: 'Cancion' object is not iterable So I don't find the correct way I have to do this stuff and use the model field in my javascript function. The field I want to use is a .mid file. If you have any doubts about the code feel free to ask anything -
How do I greet the user when they log into my website?
I'm trying to greet the user when they log into my django website, but using the django login has made it too difficult to send a message to my template and redirect to the new url behind the scenes. How can I greet the user(preferrably with that user's name) on the template of the url I redirect to? I've tried working with messages, but redirecting to the new url always overrides the message and it never appears. Regular logging in and out works fine, I'm just trying to figure out how to display welcome text to the user to let them know they have successfully logged in and are using their own account. views.py def loginPage(request): return render(request, "registration/login.html") def login(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: #Success! messages.success(request, "Welcome " + user) #NOT WORKING :( login(request, user) else: return HttpReponseRedirect("/DataApp/accounts/login/") settings.py LOGIN_URL = "/DataApp/accounts/login/" LOGIN_REDIRECT_URL = "/DataApp/search/" base.html <!-- This is nested in a div tag inside of the html class body --> {% if messages %} <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}" {% endif %}> {{ message }}</li> {% … -
How to fix django model manager to work with serializer
I have used model managers in my app to do the heavy lifting. Was able to use it well for the web version but having difficulty with the serialization of the Query to move data into a mobile app via an API. The model manager works fine for the web based interface. Trying to serialize so data can get into React Native for mobile app. The override of the queryset seems to be the way to go. here is the code in the serializer: class UserBeltsSerializer(serializers.ModelSerializer): class Meta: model = UserBelts fields = ('__all__') here is the code in .api: class SingleUserBeltViewSet(generics.ListAPIView): permission_classes = [ permissions.IsAuthenticated, ] serializer_class = UserBeltsSerializer def get_queryset(self): beltlist = UserBelts.objects.all_belts(user=self.request.user) return beltlist error message is as follows: AttributeError at /api/singleuserbelts Got AttributeError when attempting to get a value for field `user` on serializer `UserBeltsSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `str` instance. Original exception text was: 'str' object has no attribute 'user'. -
How to combine Django forms, formsets, and formwizard for multi-step form
I'm looking to replicate the following form structures in a Django application. These are already coded in a PHP application. On the first page there are two separate forms for entry, where the top form is slightly different from the bottom form. At the moment they are two separate forms under forms.py, but could be combined together: forms.py: # forms.py from django import forms from .models import Data2, Data3 class ExampleEntryFormTop(forms.Form): example_date = forms.DateField(widget=forms.HiddenInput()) data_top = forms.IntegerField() data2 = forms.ModelChoiceField(Data2.objects, to_field_name="name", empty_label=None, widget=forms.RadioSelect) additional = forms.MultipleChoiceField(choices=( ('one', 'One'), ('two', 'Two'), ('three', 'Three')), widget=forms.CheckboxSelectMultiple ) data3 = forms.ModelChoiceField(Data3.objects, empty_label=None, widget=forms.RadioSelect) data4 = forms.MultipleChoiceField(choices=( ('alpha', 'Alpha'), ('beta', 'Beta'), ('gamma', 'Gamma')), widget=forms.CheckboxSelectMultiple ) class ExampleEntryFormBottom(forms.Form): example_date = forms.DateField(widget=forms.HiddenInput()) data_bottom = forms.IntegerField() data2 = forms.ModelChoiceField(Data2.objects, to_field_name="name", empty_label=None, widget=forms.RadioSelect) additional = forms.MultipleChoiceField(choices=( ('one', 'One'), ('two', 'Two'), ('three', 'Three')), widget=forms.CheckboxSelectMultiple ) data3 = forms.ModelChoiceField(Data2.objects, empty_label=None, widget=forms.RadioSelect) class ExampleEntryFormPage2(forms.Form): example_date = forms.DateField(widget=forms.HiddenInput()) data_top = forms.IntegerField() data_bottom = forms.IntegerField() data2 = forms.ModelChoiceField(Data2.objects, to_field_name="name", empty_label=None, widget=forms.RadioSelect) additional = forms.MultipleChoiceField(choices=( ('one', 'One'), ('two', 'Two'), ('three', 'Three')), widget=forms.CheckboxSelectMultiple ) data3 = forms.ModelChoiceField(Data2.objects, empty_label=None, widget=forms.RadioSelect) On the second page of the wizard I need to pre-load the next three days. I've been using the following to create the formset: forms.py: def get_example_set(): … -
Django - ORM - datetime field different formats
i am currently working on a Django app where every single DateTimeField should have the exact same format... to start with, this is my abstract model: from django.db import models class AbstractModel(models.Model): created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: abstract = True Both created and updated field have the same format, like this: 2019-01-01 12:12:12.123456+00 # right BUT: When i add some other DateTimeField to any model, like: some_other_field = models.DateTimeField() and save it via django-admin, it gets this format in database: 2019-01-01 12:12:12+00 # wrong WHY ?! Right now i have two different DateTimeField formats in my database, which is conceptually very bad.. Can anybody help me out? I simply want one format (the upper one) in every single datetime field.. Settings: LANGUAGE_CODE = 'en-US' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True -
Reading and creating nested relation in single serializer django
I have two models Category and Products, and a classic one to many relatoin between them. Each product belongs to a category. I am using Django-Rest-Framework. I am using ModelViewSet as a ViewSet and ModelSerializer as a Serializer. I created the ProductViewSet which has the full CRUD opertions. What I am trying to achieve is to include the relation in the READ operations ( list , retrieve ). The response should look something like that. { "id" : 2, "name" : "foo product" , "category" : { "id" : 4, "name" : "foo relation" } } So I set the depth field in Meta equal to 1. class ProductSerializer(ModelSerializer): class Meta: model = Product exclude = ('createdAt',) depth = 1 What makes the category read only.But I want it to be writable in the other actions (POST , PUT). I know I can solve the problem using two serializes but this is a repetitive problem and I don't want to write two serializes for each model I have. I tried to add category_id field in the serializer but I had to override the create method to make it work correctly. And again I am trying to write less code. because … -
How can I convert this JSON request function to object orientated?
So I'm working on a ETL engine like application in Django and I've created a view that is very inefficient in that it doesn't follow D.R.Y principles and is really ugly. Can I get some help refactoring this to make it more object orientated in fashion? Here is a link to the full code: https://pastebin.com/At45Agcm I'm following along here: python turn giant function into Class but I'm still lost on how to instantiate a class where (as you can see from the pastebin code) you have a dynamic amount of variables to represent the individual JSON objects I want to extract. Here's a sample method that I want to convert to a more OOP like. Really struggling to figure this out since the number of parameters I'm extracting are variable amount. Thanks a ton for the help! def repositories(request): ''' Method that dynamically gets team members from a team given a team ID. Args: request: HTTP request payload Returns: POST string ''' parsed_list = [] parsed_data = [] if request.method == 'POST': # EXTRACTION PHASE repo_endpoint = request.POST.get('org_name') link = 'MY_GITHUB_URL' headers = {'Authorization': 'token MY_TOKEN_NUMERICAL'} response = requests.get(link + repo_endpoint, headers=headers) extraction_filename = datetime.now().strftime('repos_extraction_%Y-%m-%d-%H-%M-%S.json') transformed_file = datetime.now().strftime('repos_transformed_%Y-%m-%d-%H-%M-%S.json') with open(extraction_filename, … -
how to fix class ['classname'] has no object member in VSCode when running a populate file in django
I am populating a script in Django by running 'python populate_project_2_app.py' in the terminal. But I'm getting these errors 1- Unable to import 'faker'pylint(import-error) 2- Class 'Topic' has no 'objects' member pylint(no-member) Here is what displayed on my terminal after running 'python populate_project_2_app.py' C:\MyDjangoDev\Project_2>python populate_project_2_app.py python: can't open file 'populate_project_2_app.py': [Errno 2] No such file or directory C:\MyDjangoDev\Project_2>cd project_2 C:\MyDjangoDev\Project_2\project_2>python populate_project_2_app.py File "populate_project_2_app.py", line 6 os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project_2.settings') settings.configure() ^ SyntaxError: invalid syntax C:\MyDjangoDev\Project_2\project_2>python populate_project_2_app.py Traceback (most recent call last): File "populate_project_2_app.py", line 2, in from project_2_app.models import AccessRecord, Webpage, Topic File "C:\MyDjangoDev\Project_2\project_2\project_2_app\models.py", line 6, in class Topic(models.Model): File "C:\Users\iam_xamuel\Miniconda3\lib\site-packages\django\db\models\base.py", line 103, in new app_config = apps.get_containing_app_config(module) File "C:\Users\iam_xamuel\Miniconda3\lib\site-packages\django\apps\registry.py", line 252, in get_containing_app_config self.check_apps_ready() File "C:\Users\iam_xamuel\Miniconda3\lib\site-packages\django\apps\registry.py", line 134, in check_apps_ready settings.INSTALLED_APPS File "C:\Users\iam_xamuel\Miniconda3\lib\site-packages\django\conf__init__.py", line 79, in getattr self._setup(name) File "C:\Users\iam_xamuel\Miniconda3\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. Below is the populating script from project_2_app.models import AccessRecord, Webpage, Topic import random import django import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project_2.settings') django.setup() # settings.configure() # Fake Population Script fake_generation = Faker() topics = ['Search', 'Social', 'Marketplace', 'News', 'Games'] def add_topic(): t = Topic.objects.get_or_create(top_name=random.choice(topics))[0] … -
Can I override __new__ in Django ModelForm?
I have a ModelForm with Django 1.11, and I'm moving a few fields to another model. Calling make_migrations causes an error because these fields don't exist in the current model. I added some of the fields to the form, but one of the fields is a TranslatedField and therefore there are currently 2 fields, and in the future there might be more, depending on the number of languages. The name of the field is city, and currently I get an error message "Unknown field(s) (city_en, city_he) specified for SiteProfile" (because I'm using 2 languages - "en" and "he") - but I want to create all the fields dynamically with a for loop over the languages we use in the project. Can I override (and is it a good programming method) the new method or is there another way? I prefer not to hard-code the specific field names (city_en and city_he) because they may change in the future, depending on how many languages we use. You can see my current commit (not working) on GitHub. And the current code of this branch. I would like to know what is the best programming method to define a dynamic list of fields (which … -
My existing Django project is being required by totally different, newly-created Django project
Hi I wanna ask about this strange behavior I've discovered just now in my PC when running a newly-created Django project. I have an existing and ongoing Django project pgadn_website that has its own virtual env, and I just created a fresh Django project called Blog which I intend to use for testing some stuff which is also has its own virtual env. So strange that when I execute runserver on Blog, it gives me this error: I'm suspecting I might have set something globally but I don't know where to look for it. P.S. the error also happens on pretty much every new project I create, not just the Blog one.