Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to display images in a loop
In a loop I iterate over several URLs stored in movie.poster. If I only print movie.poster it returns the URL. <ul> {% for movie in all_movies %} <li> {{ <img src="movie.poster" alt="Cheetah!" /> }} </li> <!--<input type = "submit" value = "delete"/>--> <!-- <img src="movie.poster" alt="Cheetah!" />--> {% endfor %} </ul> When I run the code below I get the following error message "Could not parse the remainder: […]" How could I fix this? -
What is the correct method for implementing <mysite.com/some_user> URL routing in Django?
I want my site members to get access to other user's profile pages via URL mysite.com/some_user instead of mysite.com/profiles/some_user, but with every request to another url path, the view function responsible for the user profile page gets executed. I expect Django to stop looking for any other url path when it finds a matching path, this is my base URL configuration: urlpatterns = [ path('', include('events.urls')), path('<str:username>', view_profile) ] and this is the view responsible for /some_user: def view_profile(request,username): try: member = User.objects.get(username=username) member_events = Feed.my_events(member) return render(request,'profile.html',{'member_events':member_events}) except User.DoesNotExist: print('No data') return HttpResponse('No data') now when I send a request to mysite.com/feedstream , despite the page loads correctly the view_profile() gets executed (judging by the No data print on server console) I could not find any guide online maybe because I don't know the exact keywords for the problem, what am I doing wrong? -
Django TypeError: argument must be int or float when trying to access model
I have a very odd error any time I try to access one of my models. All other models work fine. Here is what my model looks like: class Hop(models.Model): name = models.CharField(max_length=100, null=True, blank=True) aa = models.DecimalField(max_digits=15, decimal_places=2, null=True, blank=True, default = 10) b = models.DecimalField(max_digits=15, decimal_places=2, null=True, blank=True) type = models.CharField(max_length=100, null=True, blank=True) description = models.CharField(max_length=600, null=True, blank=True) user_created = models.BooleanField(default=True) def __unicode__(self): return self.name When I run Hop.objects.all() I get the following error. Never seen this before. Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\corym\Documents\Projects\mybrewlab vue\Backend\mybrewlabapi\env3\lib\site-packages\django\db\models\query.py", line 250, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "C:\Users\corym\Documents\Projects\mybrewlab vue\Backend\mybrewlabapi\env3\lib\site-packages\django\db\models\query.py", line 274, in __iter__ self._fetch_all() File "C:\Users\corym\Documents\Projects\mybrewlab vue\Backend\mybrewlabapi\env3\lib\site-packages\django\db\models\query.py", line 1242, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Users\corym\Documents\Projects\mybrewlab vue\Backend\mybrewlabapi\env3\lib\site-packages\django\db\models\query.py", line 72, in __iter__ for row in compiler.results_iter(results): File "C:\Users\corym\Documents\Projects\mybrewlab vue\Backend\mybrewlabapi\env3\lib\site-packages\django\db\models\sql\compiler.py", line 1044, in apply_converters value = converter(value, expression, connection) File "C:\Users\corym\Documents\Projects\mybrewlab vue\Backend\mybrewlabapi\env3\lib\site-packages\django\db\backends\sqlite3\operations.py", line 285, in converter return create_decimal(value).quantize(quantize_value, context=expression.output_field.context) TypeError: argument must be int or float -
How to make user permissions that expire after 24 hours?
I'm creating a service where I give users who pay for access - access for a timed period, i.e. 24 hours. Once they've made a payment. I auto file data into this premium model: class Premium(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) datetime_payment = model.DateTimeField(default=datetime.now, blank=True) order_id = models.CharField(max_length=250, blank=True) has_premium = models.BooleanField(default=False) class Meta: ordering = ['user'] permissions = (("can_access_premium", "Premium Access"),) def __str__(self): return f'{self.user}({self.has_premium})' So I want the user permissions for premium access to end after 24 hours. How can I change a user permissions. They can buy multiple times, so the trigger for this 24-permission is a payment. -
How to get raw query image url in Django?
I am trying to get the url of image by raw queries results. Tell that how i can get the image url by image name. cursor.execute(f"select p.id,p.name,p.price,p.sale_price,p.img,c.category from product_product p inner join product_category c on p.category_id=c.id order by p.id desc") How i get the absolute url of p.img ? -
char_filter not set propoerly
I am setting up custom char_filter in elastic search django but I am unable to find how to do it properly, I have tried few methods but no success. I have tried two methods but none is working from elasticsearch_dsl import analyzer, tokenizer my_char_filter = { "type": "pattern_replace", "pattern": "&", "replacement": "and" } my_char_filter = {"char_filter": { "type": "mapping", "mappings": [ "&=> and "] }} html_strip = analyzer('html_strip', tokenizer="standard", filter=["standard", "lowercase"], char_filter=["html_strip", "my_char_filter"] ) As I have run the command to rebuild index, It's throwing error Custom Analyzer [html_strip] failed to find char_filter under name [my_char_filter] Expected Output : Index should have created with & replace by and -
Django and Processing raising: "raise AppRegistryNotReady("Apps aren't loaded yet.")"
I wanted to upload some stuff from DB into google sheets. So i figured I will use processing or multy treading. There was few options, so I decided for processing like in this answer I used processing module, inserted it into view and vola, error from title. So i am pretty positive that it has to do something with processing. Without processing everything works fine. #sheet function that is used as proces def sheet(uid,model): gc = gspread.authorize(creds) wks = gc.open("yelp") all_entries = model.objects.filter(uid=uid) worksheet = wks.get_worksheet(0) counter = 0 for entry in all_entries: print('working') if counter < 100: worksheet.append_row([ entry.name, entry.yurl,entry.categories,entry.rating,entry.review_count,entry.phone,entry.surl,entry.address,entry.city,entry.state]) counter = counter + 10 else: time.sleep(100) #view that calls it def upload(request, uid): p = Process(target=sheet, args=(uid, Result)) p.start() print('process started') return render(request, 'YelpGetter/status.html') So I am expecting for the stuff from DB to be imported to google spreadsheets however i get error: [27/Jul/2019 20:23:00] "GET /latest HTTP/1.1" 200 7588 process started [27/Jul/2019 20:23:12] "GET /upload/610482019207 HTTP/1.1" 200 4430 Traceback (most recent call last): File "<string>", line 1, in <module> File "c:\users\mlade\appdata\local\programs\python\python37-32\Lib\multiprocessing\spawn.py", line 105, in spawn_main exitcode = _main(fd) File "c:\users\mlade\appdata\local\programs\python\python37-32\Lib\multiprocessing\spawn.py", line 115, in _main self = reduction.pickle.load(from_parent) File "C:\Users\mlade\Desktop\YelpGetter\views.py", line 7, in <module> from YelpGetter.models import Search, … -
Unable to view django error pages on Google Cloud web app
Settings.py DEBUG=True But the django web application shows Server Error 500. I need to see the error pages to debug what is wrong on the production server. The web application works fine in development server offline. The google logs does not show detail errors. Only shows the http code of the request. -
I am trying to add include app urls to the project urls but it doesn't work It shows : issue is probably caused by a circular import
from django.contrib import admin from django.urls import path, include urlpatterns = [path('admin/', admin.site.urls), path('myapp/', include('myapp.urls')),] -
User authentication in django : Logging in using api rather than form
I'm using Django, and am looking to have the option to login both using a web page (the standard way) and through a separate client process (for the sake of my testing, using python requests) I've seen another answer about doing an ajax login, but my understanding of this solution is that it would be vulnerable to a CSRF attack, as it's only taking the POSTed username/password. What I'd like to do is request a CSRF token (with a GET call to my custom /auth-api/login view), and then pass this in a POST call along with the username and password. This is what I currently have in views.py from django.middleware import csrf from django.http import JsonResponse def login( request ) : return JsonResponse( { 'csrf_token': csrf.get_token( request ) } ) From Python on the client end, I'm then doing: (I have verify=False here because I am currently using a self-signed SSL certificate for development purposes) result = s.get( "https://<ip_addr>/auth-api/login", verify=False ) csrf_token = json.loads( result.text )['csrf_token'] s.post( "https://<ip_addr>/auth-api/login", verify=False, data={'csrfmiddlewaretoken': csrf_token, 'username': "<username>", 'password': "<password>" }, cookies=result.cookies ) However, the text of the response to this tells me that the CSRF token is missing or incorrect. Am I missing something … -
failed to load a library: cairo / cairo-2 / cairo-goobject-2 / cairo.so.2 in django saas application djaodjin/djaoapp
I'm trying to run an open-source Django SAAS project called djaodjin/djaoapp locally on my windows machine. After creating a virtual environment and installing all requirements I'm getting the following error, Traceback (most recent call last): File "C:\Users\abish\workspace\djaoapp\djaoapp_env\lib\site-packages\django\template\utils.py", line 65, in __getitem__ return self._engines[alias] KeyError: 'pdf' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\abish\workspace\djaoapp\djaoapp_env\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Users\abish\workspace\djaoapp\djaoapp_env\lib\site-packages\django\core\management\commands\runserver.py", line 124, in inner_run self.check(display_num_errors=True) File "C:\Users\abish\workspace\djaoapp\djaoapp_env\lib\site-packages\django\core\management\base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "C:\Users\abish\workspace\djaoapp\djaoapp_env\lib\site-packages\django\core\management\base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\abish\workspace\djaoapp\djaoapp_env\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\abish\workspace\djaoapp\djaoapp_env\lib\site-packages\django\core\checks\urls.py", line 16, in check_url_config return check_resolver(resolver) File "C:\Users\abish\workspace\djaoapp\djaoapp_env\lib\site-packages\django\core\checks\urls.py", line 26, in check_resolver return check_method() File "C:\Users\abish\workspace\djaoapp\djaoapp_env\lib\site-packages\django\urls\resolvers.py", line 256, in check for pattern in self.url_patterns: File "C:\Users\abish\workspace\djaoapp\djaoapp_env\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\abish\workspace\djaoapp\djaoapp_env\lib\site-packages\django\urls\resolvers.py", line 407, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\abish\workspace\djaoapp\djaoapp_env\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\abish\workspace\djaoapp\djaoapp_env\lib\site-packages\django\urls\resolvers.py", line 400, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\abish\workspace\djaoapp\djaoapp_env\lib\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 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line … -
I make top of Articles ? but when i start my project i had error unhashable type: 'slice'
I make a list of articles that will be filtered by submission, I want regular articles in me, and then the most popular articles go to articles. I do everything vrodiby and I want to display them with I made a function that will filter the articles and then I output them using {% for top in articles_top %} <h1> {{ top.title }} </h1> {% endfor %} And I just need a function and not a class like this class ArticleIndex(ListView): model = Articles queryset = Articles.objects.all().order_by('-view') template_name = 'news/posts.html' paginate_by = 6 my Traceback: File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\generic\base.py" in view 71. return self.dispatch(request, *args, **kwargs) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\generic\base.py" in dispatch 97. return handler(request, *args, **kwargs) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\generic\list.py" in get 157. context = self.get_context_data() File "D:\Users\MAestro\Desktop\RapterGame.com\itRapter\news\views.py" in get_context_data 34. context = super(ArticleIndex, self).get_context_data(**kwargs) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\generic\list.py" in get_context_data 119. paginator, page, queryset, is_paginated = self.paginate_queryset(queryset, page_size) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\generic\list.py" in paginate_queryset 69. page = paginator.page(page_number) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\paginator.py" in page 75. return self._get_page(self.object_list[bottom:top], number, self) Exception Type: TypeError at /news/ Exception Value: unhashable type: 'slice' views.py class ArticleIndex(ListView): model … -
Preview the photo after selecting the file - Django
I can not find information on this topic. How to easily create a preview of the photo in Django after selecting it (before saving the form). As on the video below: https://youtu.be/HVd2v1aUED0 Is there any simple plugin that will enable this? I think that sending photos in this mode is very popular (that is, a thumbnail of the photo, before saving the whole model). Any help will be appreciated. -
How do I add patient model objects to another model’s ModelForm(IpdForm) template with many to one relationship in Django?
I am trying to create a Hospital Management System in which have Two ModelForms, one ModelForm creates Patient Object, And another form of model two is used to admit that Patient which means it uses Patient Objects in New Form Template with new fields and creates new ID Which have model one id(patient ID) and model two id(IPD ID )as well and model two is linked with model one with Patient Id,one patient can have multiple Ipd id models.py : class Patient(models.Model): name = models.CharField(max_length=200); phone = models.CharField(max_length=20); address = models.TextField(); patient_id = models.AutoField(primary_key=True); gender= models.CharField(choices=GENDER, max_length=10) consultant = models.CharField(choices=CONSULTANT, max_length=20) def __str__(self): return self.name class Ipd(models.Model): reason_admission = models.CharField(max_length=200, blank=False) presenting_complaints = models.CharField(max_length=200,) ipd_id = models.AutoField(primary_key=True) rooms = models.ForeignKey(Rooms,on_delete=models.CASCADE, blank=False) date_of_admission = models.DateField(("Date"), default=datetime.date.today) patient = models.ForeignKey(Patient, on_delete=models.CASCADE, blank=False) def __str__(self): return self.patient.name forms.py : class PatientForm(forms.ModelForm): class Meta: model = Patient fields = ['name','phone','address','patient_id','consultant','gender'] class IpdForm(ModelForm): class Meta: model = Ipd fields = ['patient','ipd_id','reason_admission','presenting_complaints', 'rooms','date_of_admission','consultant'] def __init__(self, *args, **kwargs): super(IpdForm, self).__init__(*args, **kwargs) self.fields['patient']=forms.ModelChoiceField(queryset=Patient.objects.all()) views.py: @login_required def new(request): if request.POST: form = PatientForm(request.POST) if form.is_valid(): form.save() return redirect('index.html', messages.success(request, 'Patient is successfully created.', 'alert-success')) else: return HttpResponse(form.errors) else: form = PatientForm() return render(request, 'new.html', {'form':form}) @login_required def ipd(request, patient_id): … -
Django - QuerySet Index Instead of Loop
Home Page In the picture above, I am trying to find a way to have 6 featured posts from my database appear instead of just six static entities in HTML. Here is the view for the home page: from django.shortcuts import render from singlePost.models import Post # Create your views here. def index(request): queryset = Post.objects.filter(featured=True) context = { 'object_list': queryset } return render(request, 'index.html', context) Here is a little bit of code from the home page HTML (looping through object_list): {% if forloop.counter0 == 0 %} <h3 class="mb-15 mb-sm-5 font-sm-13"><b>{{ obj.title }}</b></h3> {% endif %} My question is: how can I get the indices of object_list so I can just use the first 6 featured Posts? I do not know how to do that, so it is currently looping through all posts and I use an if as seen above to check the current index, but that just seems wrong looping 6 times instead of using indices. The loop would be fine if all the divs were the same, but as you see in the picture, they are not. So, how do I get the indices of a QuerySet? Or are there any better ways to do this then … -
Related name not working for django many to many field django
I am trying to access the value of an object that holds the ManyToMany relationship, similar to a related name for a ForeignKey or a OneToOne. How do I need to change my models to allow this? This is my current models.py from django.db import models from django.contrib.auth.models import User class Account(models.Model): account_owner = models.OneToOneField(User, on_delete=models.CASCADE, related_name='account_owner') account_name = models.CharField(max_length=50) members = models.ManyToManyField(User, related_name='account_profile') When I try {{ request.user.account_owner.account_name }} I get the expected value of the account name (if they are the owner). But when I try {{ request.user.account_profile.account_name }} I get nothing. -
how to import urls.py below django project forder
when i create a django project naned test_pro with app01 in it. all settings is default . i wrte "from test_pro import urls". i get a error "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 dont know what mean it is ,the querstion is when i write "from test_pro import settings" run success. it makes me confused,could someone tell me why? thanks very much. django version=2.2 python interpreter version=3.7.3 this is my forder construction: -
how to fix 'Reverse for 'password_reset' not found. 'password_reset' is not a valid view function or pattern name.'
I was trying to use the custom password_reset but stucked now even login not working i already try changing url but still not working.i just can not understand why the login page is not working giving error at base.html urls.py from django.conf.urls import url,include from dappx import views app_name = 'dappx' urlpatterns=[ url('register/', views.register, name='register'), url('user_login/', views.user_login, name='user_login'), url('google_login/', views.google_login, name='google_login'), url('special/', views.special, name='special'), url('logout/', views.user_logout, name='logout'), ] views.py from django.contrib import messages from django.contrib.auth import update_session_auth_hash from django.contrib.auth.forms import PasswordChangeForm from django.shortcuts import render, redirect from django.shortcuts import render from dappx.forms import UserForm,UserProfileInfoForm from django.contrib.auth import authenticate, login, logout from django.http import HttpResponseRedirect, HttpResponse from django.urls import reverse from django.contrib.auth.decorators import login_required from google.oauth2 import id_token from google.auth.transport import requests from .models import UserProfileInfo from django.contrib.auth.models import User #from django.views.decorators.csrf import csrf_exempt def index(request): return render(request,'dappx/index.html') @login_required def special(request): return HttpResponse("You are logged in !") @login_required def user_logout(request): logout(request) return HttpResponseRedirect(reverse('index')) def register(request): if request.user.is_authenticated: return HttpResponseRedirect(reverse('index')) else: registered = False if request.method == 'POST': user_form = UserForm(data=request.POST) profile_form = UserProfileInfoForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user if 'profile_pic' in request.FILES: print('found it') profile.profile_pic = request.FILES['profile_pic'] profile.save() registered = True … -
Modifying Django's ORM query in a loop
G'day I'm struggling with modyfing/extending query in Django. Let's say I have query like this one below: query_set = Managers.objects.select_related('managers_contacts').all() and now I'd like to use a Python's loop to go through a dictionary which might looks like: {'continent': 'North America', 'country': '', 'city': ''} in case of some key is not none the query set should be extended by: .filter(managers_addresses__some_field='') I now how to build the loop but there problem is how add .filter() object to existed query set? Using class? Do You have any suggestions At the end I'd like to get something like query_set = Managers.objects.select_related('managers_contacts').all().filter(managers_addresses__some_field='') -
Django 2 stops working after deploying on Heroku
I'm working on a project using Django(2) in which I have some models and the application was working correctly on my local system. But when I have deployed this application to Heroku, it starts returning an error as: column core_votingvalueshistory.value1 does not exist LINE 1: SELECT "core_votingvalueshistory"."id", "core_votingvalueshi... ^ HINT: Perhaps you meant to reference the column "core_votingvalueshistory.value". Here's my model which causes the problem: class VotingValuesHistory(models.Model): # id = models.AutoField(primary_key=True, auto_created=True) value1 = models.CharField(max_length=40) value2 = models.CharField(max_length=40) value3 = models.CharField(max_length=40) value4 = models.CharField(max_length=40) value5 = models.CharField(max_length=40) score1 = models.CharField(choices=VOTE_CHOICES, max_length=20) score2 = models.CharField(choices=VOTE_CHOICES, max_length=20) score3 = models.CharField(choices=VOTE_CHOICES, max_length=20) score4 = models.CharField(choices=VOTE_CHOICES, max_length=20) score5 = models.CharField(choices=VOTE_CHOICES, max_length=20) user = models.EmailField(max_length=255) group = models.CharField(max_length=250, default='notingroup') date = models.DateTimeField(auto_now_add=True) and it's also pointing the view where I'm making a query to the objects as: From views.py: v1 = VotingValuesHistory.objects.all().filter() for item in v1: if item.group == groupname: if item.score1 == 'disaster': numscore_disaster += 1 elif item.score1 == 'meh': numscore_meh += 1 else: numscore_helpful += 1 I have tried makemigrations and migrate commands using: heroku run python manage.py makemigrations heroku run python manage.py migrate -
problem with dropdownlist in django netted from database
i have two apps in my project Immob and compte i want make froms with username and password and drop down list filled from database thank you for your help #INVEST_APP/compte/models.py from django.db import models from django.contrib.auth.models import User from immob.models import structure from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) structure=models.ForeignKey(Structure,on_delete=models.CASCADE) def __str__(self): return self.structure @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() -
Parsing fields in django-import-export before importing
I am using django-import-export field to expect a csv file containing a location's name and its longitude and latitude. I want to parse the longitude and latitude field from the csv to convert them into django.contrib.gis.geos.Point object so that I can input it to my Location model's geom field. # models.py from django.contrib.gis.db import models class Location(models.Model): name = models.CharField(max_length=200) geom = models.PointField(null=True, blank=True) def __str__(self): return self.name # admin.py from .models import Location from import_export import resources from import_export.admin import ImportExportModelAdmin class LocationResource(resources.ModelResource): geom = Field() latitude = Field() longitude = Field() class Meta: model = ProjectActivity fields = ('id','name', 'latitude', 'longitude') exclude = ('geom') export_order = ('id', 'name', 'latitude', 'longitude') def dehydrate_geom(self, data): return Point(data.longitude, data.longitude) class LocationAdmin(ImportExportModelAdmin): resource_class = LocationResource admin.site.register(Location, LocationAdmin) This is how far I got but to no success. Must have: Location(name='name', geom=Point(longitude, latitude)) -
Is it possible to register views to the django admin console like model.?
I tried to register the views in Django 2.2 admin interface, But I am not sure how to add it or can we able to add it.? When I tried I am getting the below error. admin.site.register(TargetView) File "/usr/local/lib64/python3.6/site-packages/django/contrib/admin/sites.py", line 102, in register for model in model_or_iterable: TypeError: 'type' object is not iterable -
how to add new features in a deployed django project?
I have a Django project already deployed on an AWS server(Linux distribution). now I want to add new features without messing with the database and without changing the folder structure as I set up a virtual environment in the project folder only on the server machine. I used Github to clone the project to the server, so is there any command that I can write to override the changed files on the server directory? I can override the DB now but in future what's the best practices? -
How to check if class already exists in django?
I have a fabric that creates classes. ...Some code here... def CreateClass(self, _context): classname = _context.__name__ + "Test" return type(classname, (viewsets.ModelViewSet,), { 'set_of_objects':_context.objects.all(), 'template_name': "base.html" Then I have some class when I calls this fabric: bla-bla-bla myClass = CreateClass(Foo) I would like to customize behaviour for specific classes, so I want to create them manually. for example I could create a class class FooTest: set_of_objects = FooSerializer(smth here) template_name = "Foo.html" The problem is, when I call this fabric it creates a FooTest class nevertheless it already exists in my app. I would like to write a method that will allow me: 1. check if class with specific name already exist. (or is there some uniq class ID?) 2. If class already exist method should returns it Could you please help me for first question? I checked some manuals but did not find a solution how can I do this. I already try to use something like this from django.apps import apps cls = apps.get_model(app_label = 'base', model_name = 'FooTest') The problem is, that this method is working, when FooTest is inherited from models.Model (from django.db import models) But is it possible to know if class exist if it not …