Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django syndication framework: prevent appending SITE_ID to the links
According to the documentation here: https://djangobook.com/syndication-feed-framework/ If link doesn’t return the domain, the syndication framework will insert the domain of the current site, according to your SITE_ID setting However, I'm trying to generate a feed of magnet: links. The framework doesn't recognize this and attempts to append the SITE_ID, such that the links end up like this (on localhost): <link>http://localhost:8000magnet:?xt=...</link> Is there a way to bypass this? -
Define Django testing database
I am working on django testing. problem is need to specify a database for test which is already created and tables have data inside. I want to use this database for testing. how can i do that. -
Python, Django , Jet dashboard
I am just stepping in python with django framework. And now I want my admin dashboard with better ui with jet dashboard. I have done everything exact same as in the documentation of jet documentation link. In my setting.py JET_INDEX_DASHBOARD = 'dashboard.CustomIndexDashboard' JET_APP_INDEX_DASHBOARD = 'dashboard.CustomAppIndexDashboard' And in my dashboard.py class CustomIndexDashboard(Dashboard): columns = 3 def init_with_context(self, context): self.available_children.append(modules.LinkList) self.available_children.append(modules.Feed) self.available_children.append(google_analytics.GoogleAnalyticsVisitorsTotals) self.available_children.append(google_analytics.GoogleAnalyticsVisitorsChart) self.available_children.append(google_analytics.GoogleAnalyticsPeriodVisitors) site_name = get_admin_site_name(context) # append a link list module for "quick links" self.children.append(modules.LinkList( _('Quick links'), layout='inline', draggable=False, deletable=False, collapsible=False, children=[ [_('Return to site'), '/'], [_('Change password'), reverse('%s:password_change' % site_name)], [_('Log out'), reverse('%s:logout' % site_name)], ], column=0, order=0 )) # append an app list module for "Applications" self.children.append(modules.AppList( _('Applications'), exclude=('auth.*',), column=1, order=0 )) # append an app list module for "Administration" self.children.append(modules.AppList( _('Administration'), models=('auth.*',), column=2, order=0 )) # append a recent actions module self.children.append(modules.RecentActions( _('Recent Actions'), 10, column=0, order=1 )) # append a feed module self.children.append(modules.Feed( _('Latest Django News'), feed_url='http://www.djangoproject.com/rss/weblog/', limit=5, column=1, order=1 )) # append another link list module for "support". self.children.append(modules.LinkList( _('Support'), children=[ { 'title': _('Django documentation'), 'url': 'http://docs.djangoproject.com/', 'external': True, }, { 'title': _('Django "django-users" mailing list'), 'url': 'http://groups.google.com/group/django-users', 'external': True, }, { 'title': _('Django irc channel'), 'url': 'irc://irc.freenode.net/django', 'external': True, }, ], column=2, order=1 )) … -
ImproperlyConfigured: The SECRET_KEY setting must not be empty when run kobocat
I am trying to set up kobocat When I try to run ./manage.py runserver I am getting the following error: Here is the full error message: Traceback (most recent call last): File "manage.py", line 20, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 399, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 392, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 242, in run_from_argv self.execute(*args, **options.__dict__) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 279, in execute saved_locale = translation.get_language() File "/usr/local/lib/python2.7/dist-packages/django/utils/translation/__init__.py", line 154, in get_language return _trans.get_language() File "/usr/local/lib/python2.7/dist-packages/django/utils/translation/__init__.py", line 52, in __getattr__ if settings.USE_I18N: File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 54, in __getattr__ self._setup(name) File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 49, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 151, in __init__ raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. -
Django: Can I use a filter to return objects where a condition is valid across an entire related set?
My objects are set up similar to this: class Event(Model): pass class Inventory(Model): event = OneToOneField(Event) def has_altered_item_counts(self): return any(obj.field_one is not None or obj.field_two is not None for obj in self.itemcounts_set.all()) class ItemCounts(Model): inventory = ForeignKey(Inventory) field_one = IntegerField(blank=True, null=True) field_two = IntegerField(blank=True, null=True) Basically, I'd like to filter uniquely on Event where inventory.has_altered_item_counts would return False I have Q(inventory__itemcounts__field_one__isnull=True) & \ Q(inventory__itemcounts__field_two__isnull=True) but that returns the event every time it meets those conditions. Given that result, I want to exclude that event if the number of times it appears is less than the total number of item counts. Does any of this make sense? Is this possible with filter? I really sort of need it to be, this is part of a programmatically built batch update -
how to represent class instances in another class
I am new to django and I want to represent instances of class Item in class Category ( so when I go to pizza category I want to see margarita pizza and any other created item ) so here is my admin interface and this is the pizza categorie Item margarita pizza in Items table and this is my models.py code from django.db import models class Customer (models.Model): name = models.CharField(max_length=500) email = models.CharField(max_length=1000 , unique=True) phone = models.IntegerField() address = models.CharField(max_length=3000) class Category(models.Model): name = models.CharField(max_length=100 , unique=True) def __str__(self): return self.name class Order (models.Model): time = models.DateTimeField(auto_now_add=True) total = models.IntegerField() created_by = models.ForeignKey(Customer, related_name='orders') class Item (models.Model): name = models.CharField(max_length=100 ,unique=True) details = models.CharField(max_length=1000) price = models.IntegerField() item_logo = models.ImageField(upload_to='res/images') category = models.ForeignKey(Category , related_name='items' , on_delete= models.CASCADE) def __str__(self): return self.name -
how to create a url pattern on path(django 2.0) for a *item*_id in django
Here's my code from django.urls import path urlpatterns = [ # /audios/ path('', views.audio ), # /audios/4344/ path('(<record_id>[0-9]+)/', views.record_detail), ] Please can someone help out -
How do I trace UnicodeDecodeError: 'utf8' codec can't decode byte 0x85 in position 1950: invalid start byte
Am trying to run an app in development but I keep getting UnicodeDecodeError: 'utf8' codec can't decode byte 0x85 in position 1950: invalid start byte Please how do trace the exact part of the code where this is coming from as I can't make sense of it's error source Below is the full error screen {u'selected': {}, u'categories': {u'ratings': ((1, u''), (2, u''), (3, u''), (4, u'****'), (5, u'*****')), u'genre s': , u'actors': , u'directors': }} Internal Server Error: /movie/ Traceback (most recent call last): File "c:\python27\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "c:\python27\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "c:\python27\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Roland\Documents\Web2\myproject_env\myproject2\movies\views.py", line 70, in movie_list return render(request, "movies/movie_list.html",context) File "c:\python27\lib\site-packages\django\shortcuts.py", line 30, in render content = loader.render_to_string(template_name, context, request, using=using) File "c:\python27\lib\site-packages\django\template\loader.py", line 67, in render_to_string template = get_template(template_name, using=using) File "c:\python27\lib\site-packages\django\template\loader.py", line 21, in get_template return engine.get_template(template_name) File "c:\python27\lib\site-packages\django\template\backends\django.py", line 39, in get_template return Template(self.engine.get_template(template_name), self) File "c:\python27\lib\site-packages\django\template\engine.py", line 162, in get_template template, origin = self.find_template(template_name) File "c:\python27\lib\site-packages\django\template\engine.py", line 136, in find_template name, template_dirs=dirs, skip=skip, File "c:\python27\lib\site-packages\django\template\loaders\base.py", line 38, in get_template contents = self.get_contents(origin) File "c:\python27\lib\site-packages\django\template\loaders\filesystem.py", line 29, in get_contents return fp.read() File … -
i installed python3.6 and django2.0.1 but python manage.py runserver does nothing.Why?
enter image description here the python and django is installed but python manage.py runserver does nothing -
Multiple file upload in Python Flask
I am trying to upload multiple files through the below snippet in a Flask app: @app.route("/", methods=['GET', 'POST']) def index(): if request.method == 'POST': file = request.files['file_ref'] for x in file: if x and allowed_file(x.filename): fileX = secure_filename(x.filename) x.save(os.path.join(app.config['UPLOAD_FOLDER'], fileX)) return redirect(url_for('index')) return render_template('index.html') Here, allowed_file(args) checks for allowed file extensions. My template is: <form action="" method=POST enctype=multipart/form-data> <p><input type=file name=file_ref multiple> <input type=submit value=Upload></p> But I get the following error: AttributeError: 'bytes' object has no attribute 'filename' According to this solution: I tried using getlist() of werkzeug, but then I get this error: AttributeError: '_io.BufferedRandom' object has no attribute 'getlist' But without the for loop, single file upload works. -
python mock Django settings variable
settings.py IMAGE_LIMIT = 256 thumbnail_utils.py from settings import IMAGE_LIMIT def thumbnail(): image_memory = 10 if image_memory > IMAGE_LIMIT: return Ture else: pass test.py @patch('thumbnail.IMAGE_LIMIT', '0') def test_thumbnail(self, mock_IMAGE_LIMIT): status = thumbnail() assert status == False The above is the wrong test.I urgently want to know how I should do it. -
insert in database that is not the default DJANGO
I know django works with multiple database connections, I need to insert in a database that is not the default, but I get the following error. ProgrammingError at /api-jde/f59presapi/2279/ (1146, 'Table \'dblocal."oracle"."FPRES"\' doesn\'t exist') this is the configuration of my settings.py file DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'dblocal', 'USER': 'root', 'PASSWORD': '', 'HOST': '', 'PORT': '', }, 'bd2': { 'ENGINE': 'django.db.backends.oracle', 'NAME': 'XXXX', 'USER': 'oracle', 'PASSWORD': 'xxxxx', }, } the bd in which I need to insert is the db2 (I'm not putting all the data here but if I have them full), in the created model I have the METa configuration with the following: class Meta: managed = False db_table = u'"oracle"."FPRES"' -
Django ManyToMany Validation Constraint
I have a ManyToMany link, and a Foreign key which links three objects. [A]>--<[B]>---[C] A can belong to many of B, and vice versa. However, A can only belong to B objects with the same parent C. I'm trying to do something in the clean() method of the model. I'm using Django Rest Framework and no ModelForms or anything like that. I haven't been able to figure it out yet -
Do i need to update AUTH_USER_MODEL in my settings.py?
I am creating my own users, Restaurant and Customer. I have extended the AbstractUser class and then created a OneToOneField field for each user. I am wondering if I need to add the AUTH_USER_MODEL in my settings.py. And also wondering what that does exactly... What I was planning on doing was adding to my settings.py: AUTH_USER_MODEL = 'myapp.Customer','myapp.Restaurant' Do I have the right idea here? My models.py: class User(AbstractUser): is_restaurant = models.BooleanField(default=False) is_customer = models.BooleanField(default=False) class Restaurant(models.Model): user = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE) restaurant_name = models.CharField(max_length=50) def __str__(self): return self.restaurant_name class Customer(models.Model): user = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE) address = models.CharField(max_length=200) def __str__(self): return self.user.get_full_name() -
ImportError: No module named 'django.core.urlresolvers' : but innate
I have a problem with Django version conflicting. when I run my Django project, I got message. ImportError Traceback (most recent call last) /usr/local/lib/python3.5/dist-packages/rest_framework/compat.py in <module>() 21 try: ---> 22 from django.urls import ( 23 NoReverseMatch, RegexURLPattern, RegexURLResolver, ResolverMatch, Resolver404, get_script_prefix, reverse, reverse_lazy, resolve ImportError: cannot import name 'RegexURLPattern' During handling of the above exception, another exception occurred: ImportError Traceback (most recent call last) <ipython-input-1-0639a9fdda0c> in <module>() 1 from urllib.parse import urlencode, quote_plus 2 from urllib.request import Request, urlopen ----> 3 from hospital.serializers import HospitalSerializer ~/earlierdoctorserver/hospital/serializers.py in <module>() ----> 1 from rest_framework.serializers import ModelSerializer 2 from .models import Hospital 3 4 class HospitalSerializer(ModelSerializer): 5 class Meta: /usr/local/lib/python3.5/dist-packages/rest_framework/serializers.py in <module>() 28 from django.utils.translation import ugettext_lazy as _ 29 ---> 30 from rest_framework.compat import JSONField as ModelJSONField 31 from rest_framework.compat import postgres_fields, set_many, unicode_to_repr 32 from rest_framework.exceptions import ErrorDetail, ValidationError /usr/local/lib/python3.5/dist-packages/rest_framework/compat.py in <module>() 24 ) 25 except ImportError: ---> 26 from django.core.urlresolvers import ( # Will be removed in Django 2.0 27 NoReverseMatch, RegexURLPattern, RegexURLResolver, ResolverMatch, Resolver404, get_script_prefix, reverse, reverse_lazy, resolve 28 ) ImportError: No module named 'django.core.urlresolvers' Looking straight at the lines of code, my project does not have that statement, and there seems to be a problem with the package … -
How to change DJango default admin login page
a beginner here in Django programming. followed several tutorials and kinda thinking how do i change the default admin page of Django? this is where the user will type http://something/admin, then it direct you to a default admin page by Django. I would like to make my own admin page. Is this an html file Django is using? if so, where can i find it so i can modify it. or where do i start? i browsed several topics here but answers are kinda vague and no beginner friendly. I hope someone could help me on this. Some snippets of my working codes(basic & default): **from urls.py:** urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('website.urls')), ] **from setting.py:** INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'website', ] when i hit https://localhost/admin, it takes me to this: enter image description here -
Links that I have in 'navbar' overlaps each other:/
Hello everyone:) Links that I have in 'navbar' overlaps each other when I make a transition into another link. For instance, I have a navbar menu with four different links (home, catalog, distributors and contacts) and 'home' is a base webpage. I.e when I make a transition from the base webpage 'http://127.0.0.1:8000/' to catalog I get this http://127.0.0.1:8000/catalog (all right) but then I make a transition into section 'distributors' and then I get this 'http://127.0.0.1:8000/catalog/distributors (and it's not normal) How to rectify this? My url patterns seems right :/ urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^catalog/$', views.catalog, name='catalog'), url(r'^distributors/$', views.distributors, name='distributors'), url(r'^contacts/$', views.contacts, name='Contacts'), ] Can someone help me with this problem? Django version 1.11.2 -
Django Authenticate with Remote User IIS vs. django-python3-ldap
I have a Django project, and it will be hosted on IIS from the same server. Therefore, I have two options for authentication with active directory. IIS windows authentication coupled with Django's Remote User Backend django-python3-ldap coupled with no authentication on IIS (i.e. allowing anonymous logins) What are the advantages and disadvantages of these approaches? Is security inherently more dangerous/difficult with one vs. the other? -
Django project deployed to two environments, TypeError in one environment but not the other
I have the exact same django project deployed to a staging and test environment. I'm struggling to understand why I only get this error in the test environment but not staging. <ExecutionEnvSet: JobExec job=ANDR_master_CI build_id=31 id=5980_app_branch_master> is not JSON serializable Here is a snippet of the views.py class execution(APIView): def get(self, request, platform, tool_name, job_name, build_id, format=None): this_job_execution = Execution.objects.filter(job__tool__platform__name=platform).filter(job__name=job_name).filter(job__tool__url__icontains=tool_name).filter(build_id=build_id) stage_executions = StageExecution.objects.filter(job_execution__build_id=build_id).filter(job_execution__job__tool__platform__name=platform) build_user_id = VariableName.objects.filter(name='userId') jobexec_env_set = ExecutionEnvSet.objects.filter(execution__id=this_job_execution[0].id).exclude(name_id__id=build_user_id).order_by('id') build_user = ExecutionEnvSet.objects.filter(job_execution__id=this_job_execution[0].id).filter(name_id__id=build_user_id) My question (unless you are able to determine the issue from this post) is how can I print the ExecutionEnvSet that I am querying in the environment that's working so that I can compare the results of the queries from both environments. Both environments are identical except they both have different data in the db, I'm wondering if the issue is related to this. -
Django-el-pagination for template variables inside for loop
I am having issues with django-el-pagination here is my code: includes.html {% load el_pagination_tags %} {% paginate post.comments.all using "comment_page" as comments%} {% for comment in comments %} <div class="row"> <p class="text-left mb-0 ml-4"> {{comment.message}} </p> </div> {% endfor %} {% show_more %} base.html {% for post in posts %} . # posts is a context variable display posts {% include 'includes.html' %} {% endfor %} How can I pass my template variable in the views. thank you -
Is a self-join on a model in a django app an acceptable pattern?
Apologies if this question is too subjective. If you are planning to close this question: please comment with a suggestion for a more appropriate place to post. I'm super new to django and python, and I'm building a test app that keeps track of employees and who their managers are. I would like to set up the domain model so that there there is only one list of employees, any of which can be managers, and all of which can be managed by any other employee who is designated a manager. To achieve this, I did a self-join on the Employee model and have an "is_manager" flag to keep track of who is a manager and who isn't (see model below). Is an acceptable pattern? I'm worried it violates a design principle I'm not considering and there's some hairy trap that I'm walking into as a noob. Thank you very much for your time. models.py for the app: class OrganizationTitle(models.Model): def __str__(self): return "{}".format(self.organization_title_name) organization_title_name = models.CharField(max_length=150, unique=True) class ClassificationTitle(models.Model): def __str__(self): return "{}".format(self.classification_title_name) classification_title_name = models.CharField(max_length=150, unique=True) class WorkingTitle(models.Model): def __str__(self): return "{}".format(self.working_title_name) working_title_name = models.CharField(max_length=150, unique=True) class Category(models.Model): def __str__(self): return "{}".format(self.category_name) category_name = models.CharField(max_length=150, unique=True) class Department(models.Model): … -
does galera setup cause db down and slower db read?
recently I realized after I setup master to master replication using galera, my db seems to be loading slower than usual. Also, sometimes it cannot be connected. I am currently using django and I have it setup that if main DB cannot be connected while making a request, then use the second db until the main DB is back online. I will receive an email if the DB cannot be connected while making a request. This would happen randomly and sometimes when I get the email, then right away I login into mariadb to check its status...it's actually actively running. As for db seems to be loading slower than usual is because, when I go into the django admin dashboard, usually it just boom when I check any records or go into any model but now it'll LOAD...........then show. I can barely find out any reason for this, does any one have any idea or which / where log I can setup for a more thorough check? Thanks in advance for any advices. -
'ascii' codec can't encode characters in position 1-2: ordinal not in range(128)
i know there is a few questions related to this, but i cant seem to find a specific answer or solution i need my python django on an aws instance gives me this 'ascii' codec can't encode characters in position 1-2: ordinal not in range(128) error but in my local it is working perfectly fine, i installed the same requirements needed to run it, it has the same virtual environment, the same version of everything. and i cant seem to find where is the error specially since it is working 100% fine and not on the server im using. the whole thing error it gives is this: error (appearently im not allowed to post images) i realize its a country with a weird name -
Generate PDF using Reportlab with custom size page and best image resolution
I have a generated Image (with PIL) and I have to create a PDF with specific size that it will contains this (full size) image. I start from size= 150mm x 105mm I generated the corresponding image 1818px x 1287px (with small border) (mm to px with 300dpi) I use this code pp = 25.4 # 1 pp = 25,4mm return int((dpi * mm_value) / pp) Now I have to create the PDF file with size page = 150mm x 105mm I use reportlab and I would a pdf with the best image quality (to print). Is possible to specify this? Is correct to create the PDF page size with this: W = ? // inch value?? H = ? // inch value?? buffer = BytesIO() p = canvas.Canvas(buffer) p.setPageSize(size=(W, H)) and to draw the image: p.drawImage(img, 0, 0, width=img.width, preserveAspectRatio=True, mask='auto', anchor='c') -
Differences between django version
Currently i am php developer, but i want to learn django and i want to go even deeper in it. I like to watch video tutorials when learning, Current version of django is 2.0.1 and most of video courses about django is 1.9 and earlier. Is there any difference between version ? if yes which one must i use ? and finally if you have any suggestions about video courses of django 2 please share with us.