Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Add Cancel/Close button to Django admin model editor
I would like to add a Cancel button to the django default admin model editor to enable going back to previous page in case users decide to cancel editing/creating a model. One Option to do that will be extending the 'admin/submit_line.html' and add a Cancel button to it. However, the default django 'admin/submit_line.html' template already includes a 'Close' button as shown in the code snippet below. <div class="submit-row"> {% block submit-row %} {% if show_save %}<input type="submit" value="{% trans 'Save' %}" class="default" name="_save">{% endif %} ... {% if show_save_as_new %}<input type="submit" value="{% trans 'Save as new' %}" name="_saveasnew">{% endif %} {% if show_save_and_add_another %}<input type="submit" value="{% trans 'Save and add another' %}" name="_addanother">{% endif %} ... {% if show_close %}<a href="{% url opts|admin_urlname:'changelist' %}" class="closelink">{% trans 'Close' %}</a>{% endif %} {% endblock %} </div> If I copied the above template and override the show_close variable to True, the Close button will be shown and closes the form as expected. But Isn't there a way to configure 'show_close' visibility from the models.py or admin.py classes? -
Autoit install whit Python 2.7 and Windows 64 bit
I tried to install autoit like documentation: pip install -U pyautoit But give 32bit error: WindowsError: [Error 193] %1 is not a valid Win32 application How install on 64 bit? TY -
How to dynamically change content of a web page using Django when the structure is the same for multiple links but the content is different?
I have a design problem I am trying to build my web page and currently working on the projects section where I show off my work. In it, I have a list of projects and each of them has a link that loads a description of four paragraphs and an image of it. Since each project is represented by four paragraphs and an image I wonder if I could use Django to store the information and load them according to the project's link instead of hardcoding everything. I am not sure but I suspect that will have to inject Django code somewhere in my template file but do not know where. I posted the code on Pastebin as well to show the HTML code in StackOverflow so here is the link to segment my project: https://pastebin.com/S7HfCfpg. ` <!DOCTYPE html> <html> <body> {% block content %} <div id='vignereCypherPage'> <h1 id="vignereCypherHeading">VIGENERE CYPHER</h1> <section id="projectsDescriotion" class=""> <div id="firstSection"> <div id="insertImage"></div> <div id="insertTheTwoParagraphs"> <p id="fist"></p> <p id="second"></p> </div> </div> <div id="secondSection"> <p id="third"></p> <p id="forth"></p> </div> </section> </div> {% endblock content %} </body> ` -
Why my app doesnt appear and renders the wrong app template?
Hi I started another app called "A-board" using startapp command and wrote the app name in settings file. But I didnt like the initially set app name so I changed it to "board" in root urlconfig using 'name' parameter. Everthing is fine except the new app doesnt show up in my admin interface. In root urlconfig I tried the home to point to this app by removing the old app and make it Path('', include('A-board.urls"), name ="board")) But the home page throws an error showing The old app's template is rendered instead of my new app even after I removed the old app's urlconfig code snippet. Why does it act like this and what am I missing? Thank you for your answer in advance. -
Run all Django tests
I have this project structure when I run python manage.py test --settings=backend.settings.bitbucket Only tests in backend/core/tests are run. When I run python manage.py test backend.apps.sar --settings=backend.settings.bitbucket or move the files to backend/core/tests, everything works fine... How can I run all the tests at once? -
Django Autocomplete Light - "The results could not be loaded"
I'm using Django-autocomplete-light on a small application. The UI seems to work, and I can select from some visible values. The problem arises when I type one or more letters into the box. Normally it should filter/select the results, instead, I get the error "The results could not be loaded" (see picture). Seems like the jquery is working fine, except for not filtering when I type in the box. Happy to add more code, just not sure what I need to add yet. models.py class Encounter(models.Model): patid = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, verbose_name=('Patient Name'), related_name='patient') created_by = models.ForeignKey(Users, editable=False, null=True, blank=True, on_delete=models.PROTECT, related_name='encounter_created_by') encounter_date = models.DateField() encounter_label = models.ForeignKey(EncounterReason, on_delete=models.PROTECT, verbose_name=('Encounter Reason'), related_name='fk_reason') class EncounterReason(models.Model): reason = models.CharField(max_length=256, blank=True, null=True) valueset_id = models.CharField(max_length=256, blank=True, null=True) views.py class EncounterReasonAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): # Don't forget to filter out results depending on the visitor ! if not self.request.user.is_authenticated: return EncounterReason.objects.none() qs = EncounterReason.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs forms.py class EncounterForm(forms.ModelForm): encounter_date = forms.DateField(initial=datetime.date.today, widget = DateInput()) encounter_notes = forms.CharField(widget=forms.Textarea(attrs={'placeholder': 'Encounter Notes', 'id': 'editor', 'rows':50, 'cols':25})) encounter_label = forms.ModelChoiceField(queryset=EncounterReason.objects.all(), widget=autocomplete.ModelSelect2(url='encounterreason-autocomplete') ) class Meta: model = Encounter fields = ('__all__') urls.py urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('django.contrib.auth.urls')), path('', include('clinicalviewer.urls')), path('encounterreason-autocomplete/', views.EncounterReasonAutocomplete.as_view(), name='encounterreason-autocomplete'), ] … -
django-dynamic-scrapy do not work with python3.x after upgrading
i am using Scrapy (1.1.2) with Django (1.8.19) and Django dynamic scrapy (0.11.2) on python (2.7), its works fine with me but after upgrading to python 3 i got errors in logs when my spiders run as follow : File "/root/.pyenv/versions/3.4.10/envs/sharq-3.4.10/lib/python3.4/site-packages/scrapy/loader/__init__.py", line 154, in _get_item_field_attr value = self.item.fields[field_name].get(key, default) KeyError: 'photos' i tried to use many python versions (3.4.x, 3.5.x, 3.6.x) with many versions of Django dynamic scrapy but still the problem appears, so the result which i arrived to it that this package do not support python 3 although the documentation says it support pyhthon 3. my question is which part in this packed occurred this problem and where in need to edit in the core of this package to make my upgrade success ? -
Problem with saving multiple records in JSON file to MySQL using django-rest-framework
I'm newbie in django I'm trying to save JSON record using Dango-rest-framework, here is my JSON file. {"result":{"lists":[{"resAccountBalance":"0","resWithdrawalAmt":"0","commStartDate":"20190124","commEndDate":"20190724","resTrHistoryList":[{"resAccountTrDate":"20190723","resAccountTrTime":"070609","resAccountOut":"132795","resAccountIn":"0","resAccountDesc1":"","resAccountDesc2":"BC","resAccountDesc3":"카드출금","resAccountDesc4":"","resAfterTranBalance":"0"},{"resAccountTrDate":"20190722","resAccountTrTime":"071125","resAccountOut":"0","resAccountIn":"17","resAccountDesc1":"","resAccountDesc2":"이자","resAccountDesc3":"2019년결산","resAccountDesc4":"","resAfterTranBalance":"132795"},{"resAccountTrDate":"20190515","resAccountTrTime":"031314","resAccountOut":"0","resAccountIn":"180000","resAccountDesc1":"","resAccountDesc2":"타행이체","resAccountDesc3":"지원금","resAccountDesc4":"","resAfterTranBalance":"626109"}]}]}} I want to save 3 records in 'resTrHistoryList' to MySQL, but only last record({"resAccountTrDate":"20190515","resAccountTrTime":"031314","resAccountOut":"0","resAccountIn":"180000","resAccountDesc1":"","resAccountDesc2":"타행이체","resAccountDesc3":"지원금","resAccountDesc4":"","resAfterTranBalance":"626109"}) is saved. Here is my code. model.py class QuickQuiryBankKDB(models.Model): result = models.TextField() resAccountTrDate = models.CharField(max_length=20, default='1000') resAccountTrDate = models.CharField(max_length=20, default='1000') resAccountTrTime = models.CharField(max_length=20, default='1000') resAccountOut = models.CharField(max_length=20, default='1000') resAccountIn = models.CharField(max_length=20, default='1000') resAccountDesc1 = models.CharField(max_length=20, default='1000') resAccountDesc2 = models.CharField(max_length=20, default='1000') resAccountDesc3 = models.CharField(max_length=20, default='1000') resAccountDesc4 = models.CharField(max_length=20, default='1000') resAfterTranBalance = models.CharField(max_length=20, default='1000') created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) def __unicode__(self): # __str__ on Python 3 return self.QuickQuiryBankKDB serializers.py class QuickQuiryBankKDBSerializer(serializers.ModelSerializer): def __init__(self, *args, **kwargs): many = kwargs.pop('many', True) super(QuickQuiryBankKDBSerializer, self).__init__(many=many, *args, **kwargs) class Meta: model = QuickQuiryBankKDB # fields = '__all__' fields = ['result'] views.py class QuickQuiryBankKDBViewSet(viewsets.ModelViewSet): queryset = QuickQuiryBankKDB.objects.all() serializer_class = QuickQuiryBankKDBSerializer def perform_create(self, serializer_class): if (serializer_class.validated_data['result'][2:8] == 'result'): json_text = serializer_class.validated_data['result'] json_unpacked = json.loads(json_text) for i in json_unpacked['result']['lists'][0]['resTrHistoryList']: resAccountTrDate = i['resAccountTrDate'] resAccountTrTime = i['resAccountTrTime'] resAccountOut = i['resAccountOut'] resAccountIn = i['resAccountIn'] resAccountDesc1 = i['resAccountDesc1'] resAccountDesc2 = i['resAccountDesc2'] resAccountDesc3 = i['resAccountDesc3'] resAccountDesc4 = i['resAccountDesc4'] resAfterTranBalance = i['resAfterTranBalance'] serializer_class.save(resAccountTrDate=resAccountTrDate, resAccountTrTime=resAccountTrTime, resAccountOut=resAccountOut, resAccountIn=resAccountIn, resAccountDesc1=resAccountDesc1, resAccountDesc2=resAccountDesc2, resAccountDesc3=resAccountDesc3, resAccountDesc4=resAccountDesc4, resAfterTranBalance=resAfterTranBalance) Hope to have a hint to solve the problem. Thank you! -
Django using reverse OneToOne in filter?
I have two models: class CustomUser(models.Model): ... class Profile(models.Model): user = models.models.OneToOneField(CustomUser) fielda = models.IntegerField() I'm trying to perform a filter query based on the value of a field on the Profile model from the CustomUser model but it's giving me the error name 'profile' is not defined CustomUser.objects.all().select_related('profile').filter(profile.fielda=0) I need to start the selection from CustomUser model because I have to prefetch other models with FK to CustomUser so I cannot simply start from Profile model -
save() prohibited to prevent data loss due to unsaved related object 'task_title'
I am Trying to create Task and inserting it's related information of intermediary model in intermediary table but I am getting below error. save() prohibited to prevent data loss due to unsaved related object 'task_title'. My models.py class Task(models.Model): id = models.AutoField(primary_key=True) task_audit_title = models.ForeignKey(MainAudit,on_delete= models.CASCADE, related_name='audit_title_for_task',verbose_name= ('Audit Title')) task_subtask_name = models.ManyToManyField(SubTask, related_name='subtask_for_task',verbose_name= ('Subtask Title')) task_subject = models.CharField(verbose_name= ('Task Subject'),max_length=100,blank=False) task_description = models.CharField(verbose_name= ('Task Description'),max_length=1000,blank=True) task_assign_to = models.ManyToManyField(User, related_name='task_assign_to', through='TaskComplete') task_assign_by = models.ForeignKey(User,on_delete= models.CASCADE, related_name='task_crt_by') task_deadline = models.DateTimeField(null=True,blank=True) task_perticulars = models.ManyToManyField(Perticular, related_name='task_perticular', blank=True) task_created_time = models.DateTimeField(default=timezone.now) task_modified_by = models.ForeignKey(User,on_delete= models.CASCADE, related_name='task_mod_by', null=True, blank=True) task_modified_time = models.DateTimeField(null=True,blank=True) is_del = models.BooleanField(default=0) class Meta: permissions = ( ("change_temp_delete_task", "Can delete temporarily"), ) def __str__(self): return self.task_subject def get_absolute_url(self): return reverse('create-task') class TaskComplete(models.Model): id = models.AutoField(primary_key=True) task_title = models.ForeignKey(Task,on_delete= models.CASCADE, related_name='assigned_task') is_completed = models.BooleanField(default=0) task_cmt_by_doer = models.CharField(verbose_name= ('Submit Comment'),max_length=100,blank=True) completed_by = models.ForeignKey(User,on_delete= models.CASCADE, related_name = 'task_completed_by') completed_time = models.DateTimeField(null=True,blank=True) My views.py class TaskCraeteView(LoginRequiredMixin,CreateView): model=Task success_message = " Task Craeted successfully!" reverse_lazy('create-task') login_url = 'login' template_name = 'create-task' form_class = TaskCreateForm def form_valid(self,form): print(self.kwargs) for users in form.cleaned_data['task_assign_to']: TaskComplete.objects.create(completed_by=users, task_title= form.instance) form.instance.task_assign_by = self.request.user return super(TaskCraeteView, self).form_valid(form) How Can i insert the data in intermediary table while creating task? I tried to get Primary key … -
django filter duplicates in one table to serialize in json
in the database i have some duplicate Customers and they have one field similar. i can't get json so that this similar field would be the key and other info would be fields inside this key Customers = Customer.objects.values('id','fNameEng', 'lNameEng','crmId').filter( billingId__gt=0, crmId__gt=0).order_by('crmId') this filter selects all the customers with (crmId and billingId) > 0 there are some customers who have same crmId.I want to select duplicates and get them into json like this { "6275": { // this would be crmId "0":{ "id": 5, "fNameEng": "Alise", "lNameEng": "Dupan chang" } "1":{ "id": 10922, "fNameEng": "Alise", "lNameEng": "Dupan chang" } } } but with filter specified above i get something like this { "6275": { // this would be crmId "id": 5, "fNameEng": "Alise", "lNameEng": "Dupan chang" } }, { "6275": { // this would be crmId "id": 12135, "fNameEng": "Alise", "lNameEng": "Dupan chang" } } -
getting datetime when user logs-in
i made a django app which contains a user login form. I have used MySQL database in the app. when the of user logs-in the name and Hashed Password an entry is created in the database. As of now i m trying, to get the datetime in the database when the user logs-In. here's the code form.py from django import forms from django.contrib.auth.hashers import make_password from django.core import validators from first_app.models import Login from django.contrib.auth.models import User #some other code class authForm(forms.ModelForm): class Meta: model= Login fields = ["username","password",] models.py from django.db import models from datetime import datetime from django.contrib.auth.models import User # Create your models here. class Login(models.Model): username = models.CharField(max_length=50) password = models.CharField(max_length=32) date_and_time = models.DateField(auto_now_add=True) #<-- tried to add but it shows a non editable field def __str__(self): return self.username I want to store the datetime whenever the user logs-In thnx for the help. :-) -
Django - No module named C:\Users\<old deleted django project path>\settings
I have created a virtual environment and then installed Django & created a project "DjangoWeb" using below cmd in my virtual space "virenv_1". django-admin startproject DjangoWeb My directory structure is as follow: main_dir/ ├── virenv_1/ └── DjangoWeb/ ├── manage.py └── DjangoWeb/ ├── __init__.py ├── settings.py ├── urls.py └── wsgi.py When I run the django server using the below cmd in my virtual space, I get an unusual error as shown in the screenshot. (virenv_1) C:\Users\..\main_dir\DjangoWeb>python manage.py runserver Error screenshot: The path to 'settings' file shown in error is of an old project I had created earlier and which no more exists now. Please help me solve this problem. Thanks in advance. -
Django admin returns 404 on POST, 200 on GET
On production server, when I try to edit/create an object then saving fails, returning 404. This only occurs for POST requests, GET requests (loading the page) work fine. Django is deployed via cPanel and WSGI, DEBUG is False (though it does not work even when it's set to True) I have deployed the Django app with cpanel, running in a virtualenv. This only seems to happen for a model that uses FileField for file upload, other models can be changed/created just fine. The model: def get_image_path(instance, filename): name, ext = filename.split('.') return f'images/{instance.advert_id}/{name}.{ext}' class AdvertImage(models.Model): advert = models.ForeignKey(Advert, on_delete=models.CASCADE) image = models.ImageField(upload_to=get_image_path) URL conf: urlpatterns = [ path('i18n/', include('django.conf.urls.i18n')), ] + i18n_patterns( path('admin/', admin_site.urls), # ... other views.... prefix_default_language=False ) if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Navigate to domain.com/admin/colli/advertimage/1/change/ - the page loads correctly. Fill the form, click save: Using the URLconf defined in Colli.urls, Django tried these URL patterns, in this order: i18n/ admin/ [name='home'] advert/<slug:slug> [name='detail'] tagauks [name='admin_list'] tagauks/lisa [name='insert'] tagauks/muuda/<int:pk> [name='edit'] tagauks/kasutaja/<int:pk> [name='user_edit'] tagauks/save_image [name='save_image'] accounts/login/ [name='login'] accounts/logout/ [name='logout'] api/ ^media/(?P<path>.*)$ The current path, colli/advertimage/1/change/, didn't match any of these. The model should be saved and no 404 should occur. Other models, that do not use FileField, … -
How to make known field specified for User in django?
I made a lot of changes in my code. But whenever I makemigrations it is giving me same error of Unknown field(s) (Id_card_number) specified for User forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField(required=True)._unique = True Id_card_number = forms.CharField(max_length=15, required=True)._unique = True class Meta: model = User fields = ['username','email','password1','password2','Id_card_number'] views.py from django.contrib.auth import get_user_model UserProfile = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) models.py from django.db import models from django.contrib.auth.models import AbstractUser class UserProfile(AbstractUser): Id_card_number = models.CharField(max_length=15) admin.py from django.contrib.auth.admin import UserAdmin admin.site.register(UserProfile, UserAdmin) settings.py AUTH_USER_MODEL = 'users.UserProfile' -
Allow Only Specific users and superuser to edit a particular field in model
I have a model called test. Test models have three fields - Question, answer, verified. admin.py file model = Test def get_fields(self, request, obj=None): fields = ['question','answer','verified'] if request.user.is_superuser: fields.append('verified') return fields This code only allows the superuser to edit the verified record. But what I want is I have to give permission to some of the users to edit this field. -
How to save the list obtained from checkbox in django Modelform in databsae
Here, I am trying to save the multiple items checked from my form into the database using django Modelform. I got the list of item using the query but I couldn't save the data. Everything else works fine, the data from other fields are being saved in the database. How can I save these multiple items I got from checkbox? models.py class MyModel(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) skills = models.ManyToManyField(Skills, blank=True, null=True) facility = models.ManyToManyField(Facility, blank=True, null=True) forms.py class AddMyModelForm(forms.ModelForm): class Meta: model = MyModel fields = '__all__' views.py def my_view(request, slug): if request.method == 'POST': form = AddMyModelForm(request.POST or None) if form.is_valid(): selected_skill = Skills.objects.filter(id__in=request.POST.getlist('skill')) selected_facility = Facility.objects.filter(id__in=request.POST.getlist('facility')) form.save_m2m() return redirect('/') else: form = AddMyModelForm() context = {'form': form} return render(request, 'template.html', context) template <form action="{% url '...' type.slug %}" method="post"> {% csrf_token %} <h3>Choose the below skills:</h3> {% for skill in skills %} <input type="checkbox" name="skill" id="skill-{{skill.id}}" value="{{skill.id}}"> <label for="skill-{{ skill.id }}">{{skill.title}}</label> {% endfor %} <h3>Choose the facilities below:</h3> {% for facility in facilities %} <input type="checkbox" name="facility" id="facility-{{facility.id}}" value="{{ facility.id }}"> <label for="facility-{{facility.id}}">{{ facility.title }}</label> {% endfor %} <button type="submit">Submit</button> </form> -
Verify record should only visible to admin not other users
I have to display the Verified field only to admin and to specific users and not to all users in list_display in admin.py file If I write list_display = ('question_name','type','verified') It is visible to all users and I have to hide this verified field to specific users and show to specific users. Can Anyone Please Help Me Out of this problem...? This is admin.py file class TestAdmin(admin.ModelAdmin): search_fields = ['question_name','type','added_by__username'] list_filter = ['type'] list_display = ('question_name','type') readonly_fields = ('added_by','date',) list_per_page = 20 def save_model(self, request, obj, form, change): if not obj.pk: # Only set added_by during the first save. obj.added_by = request.user super().save_model(request, obj, form, change) model = C_lang def get_fields(self, request, obj=None): fields = ['added_by', 'type', 'question_name', 'code', 'output', 'date'] if request.user.is_superuser: fields.append('verified') return fields Here is Models.py class Test(models.Model): class Meta: verbose_name_plural = 'C Language' type_choices = [ ('----', '----'), ('A', 'A'), ('B', 'B'), ] added_by = models.ForeignKey(User, null=True, blank=False, on_delete=models.SET_NULL) type = models.CharField(max_length=50,default='----',choices=type_choices) question_name = models.CharField(max_length=50, default='', validators=[MinLengthValidator(4)]) Ans = models.TextField(max_length=5000, default='') date = models.DateTimeField(default=now, blank=False) verified= models.BooleanField() -
what is the best and fast way to deploy django in a centos server?
I want to deploy Django in my centos server, and I don't know how? and do you know which panel is better for background server and this have auto-install and config? -
TypeError at /reg/ save() got an unexpected keyword argument 'force_insert'
I created a blog app in Django 2.2. And now I have a problem with registration users. The result gave TypeError at /reg/ save() got an unexpected keyword argument 'force_insert' .These are my views.py and models.py code: def register(request): if request.method == "POST": form = UserOurRegistration(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f"Akkaunt {username} muvaffaqiyatli ravishda yaratildi, akkauntga kirish uchun login va parolingizni kiriting") return redirect('user')``` And this is code of models.py: `from django.db import models from django.contrib.auth.models import User from PIL import Image class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) img = models.ImageField(default='default.jpg', upload_to='user_images') def __str__(self): return f'Foydalanuvchi {self.user.username} profili' def save(self, *args, **kwargs): super(Profile, self).save(*args, **kwargs) image = Image.open(self.img.path) if image.height > 64 or image.width > 64: resize = (256, 256) image.thumbnail(resize) image.save(self.img.path)` i tried to rewrite code 3 times, searched in the internet to solve this problem, but I can't solve it. If you can, help me please. -
Django/Heroku: ModuleNotFoundError: No module named 'dj_database_url
In my requirements.txt: dj-database-url==0.5.0 psycopg2-binary==2.7.7 In setting.py import dj_database_url db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) When I run: heroku run python manage.py migrate Error: import dj_database_url ModuleNotFoundError: No module named 'dj_database_url' I have also tried running: heroku run pip install dj-database-url It gets installed correctly, but the error is still there. -
Django: No module named 'project'
I was working on a Django project on my work laptop. Then I cloned the project to my work laptop and I'm getting a very weird error when I try to run any command, such as python manage.py runserver: 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 "/Users/jmetz/github/personal/golf-swings-api/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/jmetz/github/personal/golf-swings-api/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/jmetz/github/personal/golf-swings-api/venv/lib/python3.7/site-packages/django/core/management/base.py", line 336, in run_from_argv connections.close_all() File "/Users/jmetz/github/personal/golf-swings-api/venv/lib/python3.7/site-packages/django/db/utils.py", line 219, in close_all for alias in self: File "/Users/jmetz/github/personal/golf-swings-api/venv/lib/python3.7/site-packages/django/db/utils.py", line 213, in __iter__ return iter(self.databases) File "/Users/jmetz/github/personal/golf-swings-api/venv/lib/python3.7/site-packages/django/utils/functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/jmetz/github/personal/golf-swings-api/venv/lib/python3.7/site-packages/django/db/utils.py", line 147, in databases self._databases = settings.DATABASES File "/Users/jmetz/github/personal/golf-swings-api/venv/lib/python3.7/site-packages/django/conf/__init__.py", line 79, in __getattr__ self._setup(name) File "/Users/jmetz/github/personal/golf-swings-api/venv/lib/python3.7/site-packages/django/conf/__init__.py", line 66, in _setup self._wrapped = Settings(settings_module) File "/Users/jmetz/github/personal/golf-swings-api/venv/lib/python3.7/site-packages/django/conf/__init__.py", line 157, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/Users/jmetz/miniconda3/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in … -
Django - How to exclude a list of numbers from a QuerySet?
I have a list of integers: numbers = [1, 2, 3, 4] I have a model, MyModel, with primary keys ranging 1 to 1000 I would like to exclude the models with primary keys in the list 'numbers' from MyModel during a QuerySet: MyModel.objects.exclude(pk in numbers) The above doesn't work. What's the best way to do so? -
ContentType matching query does not exist on django 2.2
I have been using django to build a Blog, and when i tried to make a comment section under each post i get the comment icon(where i can type some comments) but when i post the comment i get the error straight away, which is "ContentType matching query does not exist". I tried to find the problem on stack and youtube but they said that solving this problem requires experience on dumpdata class Comment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,default=1,null=True,on_delete=models.SET_NULL) content_type = models.ForeignKey(ContentType,on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type','object_id') content = models.TextField() timestamp = models.DateTimeField(auto_now_add=True,auto_now=False) objects = CommentManager() def blog_post_detail_view(request,slug): instance = get_object_or_404(BlogPost, slug=slug) share_string = quote_plus(instance.content) initial_data = { 'content_type':instance.get_content_type, 'object_id':instance.id } form = CommentForm(request.POST or None,initial=initial_data) if form.is_valid(): c_type = form.cleaned_data.get('content_type') content_type = ContentType.objects.get(model=c_type) obj_id = form.cleaned_data.get('object_id') content_data = form.cleaned_data.get('content') new_comment, created = Comment.objects.get_or_create( user = request.user, content_type = content_type, object_id = obj_id, content = content_data ) comments = instance.comments template_name = 'blog/detail.html' context = { "object":instance, 'comments': comments, 'share_string':share_string, 'comment_form':form } return render(request,template_name,context)from django import forms from .models import Comment class CommentForm(forms.Form): content_type = forms.CharField(widget=forms.HiddenInput) object_id = forms.IntegerField(widget=forms.HiddenInput) content = forms.CharField(widget=forms.Textarea) So basically i should have gotten my comment posted but instead i get that error:"ContentType matching query does not … -
Why django uses "ModelName.objects" to all model related function
Why django uses ModelName.objects to call all related function? There is no any other way to call these using only ModelName. To get all posts we use Post.objects.all()