Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Markdownx preview shown only after reloading page
I want django-markdownx to show maths formulas and equations and therefore integrated 'python-markdown-math' with it. Everything works as usual apart from the fact that I need to reload the page to get a preview of the typed mathematical formulas or symbols. The issue is only occurring when I type mathematical formula not others texts or upload image. Maths related stuffs (like $$..$$) seems to get skipped in preview and is shown only when I reload/refresh the page. Parts of my code: # settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static/") MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') FORM_RENDERER = 'django.forms.renderers.TemplatesSetting' MARKDOWNX_MARKDOWN_EXTENSIONS = [ 'mdx_math', ] MARKDOWNX_UPLOAD_MAX_SIZE = 5 * 1024 * 1024 # 5 MB MARKDOWNX_SERVER_CALL_LATENCY = 1000 MARKDOWNX_IMAGE_MAX_SIZE = { 'size': (500, 500), 'quality': 90, 'crop': True, } MARKDOWNX_MEDIA_PATH = 'markdownx/' # models.py class MyModel(models.Model): content = MarkdownxField() @property def get_content(self): return mark_safe(markdownify(self.content)) # in my template <head> <title>MathJax TeX Test Page</title> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [["$","$"],["\\(","\\)"]]} }); </script> <script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"> </script> </head> <body> <form method="POST" action=""> {% csrf_token %} {{ form }} <input type="submit" name="" value="submit"> </form> {{ form.media }} </body> </html> Please help me find the problem which is causing such a behaviour. Note: Reloading … -
functools has no 'lru_cache' installing Django
$ pip install django Collecting django Using cached Django-2.0.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-build-capC7C/django/setup.py", line 32, in <module> version = __import__('django').get_version() File "django/__init__.py", line 1, in <module> from django.utils.version import get_version File "django/utils/version.py", line 61, in <module> @functools.lru_cache() AttributeError: 'module' object has no attribute 'lru_cache' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-capC7C/django/ -
How can I formulate this ForeignKey scheme?
I'm finding some difficulty resolving this problem in designing my Django models. The essential setup is a bipartitie graph (allowing for parallel edges), where the vertices on both sides of the graph express a lot of common logic. I am having trouble creating a model which allows for both vertices to be shared within the same database, and allows querying of all the edges incident to a vertex. I considered using an inheritance scheme, wherein vertices in a partition inherit from a parent Vertex class, but I kept tripping up, and really started perseverating on whether Django had some hidden, native and concise means of doing this. The current setup is about: class Vertex(models.Model): PARTITION_CHOICES = ( ('a': 'type a'), ('b': 'type b') ) partition = models.CharField(choices=PARTITION_CHOICES) # A bunch of other logic... class Edge(models.Model): ref_a = models.ForeignKey(Vertex, limit_choices_to={'partition': 'a'}, related_name='edges') ref_b = models.ForeignKey(Vertex, limit_choices_to={'partition': 'b'}, related_name='edges') # More logic... The obvious issue here is that both these foreign keys have the same related name, therefore clash. Tips from the wise? -
SQL error when running Django Migration
Environment: Ubuntu/Apache I am getting the following error when running a migration. Below the error is the migration file. The migration runs fine on a dev machine, but is erroring out when trying to deploy. The error is coming up within the Django code, so I don't have a lot to go on in order to sort this out. A summary of the migration is that it is removing null=True from three ManyToManyField fields and is changing the upload_to value for the remaining fields shown. Django (1.11.9) and psycopg2 (2.7.3.2) versions match on both machines. Is it possible to tell from this error message which field (if a specific field is the problem) is causing the error? Running migrations: Applying manager.0035_auto_20180119_1138...Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 356, 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 283, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 244, … -
Django Pipeline 1.6 & Sass
Javascript compresses fine and straight CSS works. But SASS doesn't seem to work at all What I'm using 1.7.11 Django 1.6.13 django-pipeline 2.7.9 Python I installed ruby-sass on debian apt-get -y install ruby-sass And it runs from the commandline using the default SASS_BINARY command /usr/bin/env sass -h Usage: sass [options] [INPUT] [OUTPUT] Description: Converts SCSS or Sass files to CSS. Here are my django settings.py pipeline settings # Static files (CSS, JavaScript, Images) STATIC_URL = '/static/' STATICFILES_DIRS = ['assets'] STATIC_ROOT = '/app/static' PIPELINE_STORAGE = STATICFILES_STORAGE = 'pipeline.storage.PipelineCachedStorage' STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'pipeline.finders.PipelineFinder', ) PIPELINE = { 'PIPELINE_ENABLED': True, 'COMPILERS': ('pipeline.compilers.sass.SASSCompiler'), 'JAVASCRIPT': { 'application': { 'source_filenames': ( 'assets/javascripts/*', ), 'output_filename': 'javascripts/application.js', } }, 'STYLESHEETS': { 'application': { 'source_filenames': ( 'assets/stylesheets/application.scss' ), 'output_filename': 'stylesheets/application.css', 'extra_context': { 'media': 'screen,projection', }, }, } } -
All my files are rendered instead of selected ones
So I have this FileField which allows users to upload many files in the admin panel. Everything is fine. But when I want to see the files in the template, for each lecture, then each each lecture displays all the files from other lectures as well. Each lecture is supposed to show its particular uploaded files. So my guess its either the view, either the template. <ul> {% regroup lectures by get_lecture_category_display as category_list %} <h3>Lectures</h3> <ul> {% for category in category_list %} <strong> <li>{{ category.grouper }}</li> </strong> <ul> {% for c in category.list %} ............. <li>{{ c.lecture_title }}</li> <li>{{ c.content }}</li> {% for file in files %} {% if file.files %} <li><a href='{{ MEDIA_URL }}{{ file.files.url }}'>download</a></li> {% endif %} {% endfor %} {% endfor %} </ul> {% endfor %} </ul> </ul> def courses(request, slug): query = Course.objects.get(slug=slug) context = {'courses': Course.objects.filter(slug=slug), 'lectures': query.lectures.order_by('lecture_category'), 'files': FileUpload.objects.order_by('files'), } return render(request, 'courses/courses.html', context) -
Conditional HTML table td cell
I have the following HTML table td with Django tags. If the value of the tag is false I want the td value to be a red 'X' image. If the value of the tag is true I want the td value to be a green check image. Does anybody have any simple examples that will help me out? {% for sport in all_sports %} <tr class="sportrow {% cycle '' 'altrow' %}"> <td><a href="show/{{ sport.id }}">></a></td> <td>{{ sport.skill }}</td> <td>{{ sport.skilllevel }}</td> <td>{{ sport.yearswithsport }}</td> <td>{{ sport.certified }}</td> <td>{{ sport.new }}</td> </tr> {% endfor %} -
MultiValueDictKeyError when I trying to post image
When I trying to add image from admin panel all OK, but when I trying to add image from site, I have this error: image of error. views.py: def new_detail(request): if request.user.is_authenticated: if request.user.is_superuser: if request.method == 'POST': car = request.POST['car'] author = request.user detail = request.POST['detail'] price = request.POST['price'] description = request.POST['description'] image = request.FILES['images'] detail = Detail(car = car, author = author, detail = detail, price = price, description = description, images = image) detail.save() return redirect('/new_detail/') else: return redirect('/login/') return render(request, 'shop/new_detail.html') new_detail.html: {% extends 'base.html' %} {% block content %} <div class="content container"> <div class="row"> <div class="col-md-8"> <div class=".signin"> <form action="" method="POST"> {% csrf_token %} <h3>Автомобіль: </h3> <select name="car"> <option selected>Audi A8 D2 3.3 TDI</option> <option>Audi A8 D2 3.7</option> ... ... ... <h3>Ціна: </h3><textarea name="price"></textarea> <h3>Фотки: </h3><input type="image" name="images" /> <p> <input type="submit" value="Опублікувати" /> </form> </div> </div> </div> models.py: from django.db import models class Detail(models.Model): author = models.ForeignKey( 'auth.User', on_delete=models.CASCADE,) car = models.CharField(max_length=100) detail = models.TextField() description = models.TextField() price = models.CharField(max_length=30) images = models.ImageField(upload_to='details', null = True, blank = True) def __unicode__(self): return self.detail def __str__(self): return self.detail When I trying to post Detail without image, I have the same problem. Before this wasn't. -
Django concatenate list queries from two models
As a Django newbie, I am trying to return JSON Objects from two models with each object containing the username, id, ticketID. Right now the code is simply putting the lists together without indexing. I should point out that there is a relationship between user and ticket so that can be traversed also. {"username":"Paul","id":2}, {"username":"Paul","id":2}, {"username":"Ron","id":19}, {"id":"1c6f039c"}, {"id":"6480e439"}, {"id":"a97cf1s"} class UsersforEvent(APIView): def post(self, request): body_unicode = request.body.decode('utf-8') body = json.loads(body_unicode) value = body['event'] queryset = Ticket.objects.filter(event = value) referenced_users = User.objects.filter(ticket_owner__in=queryset.values('id')) result_list = list(itertools.chain(referenced_users.values('username', 'id'), queryset.values('id'))) return Response((result_list)) -
Django RestFramework: two way ForeignKey relation
There are two models Parent and Children. class Parent(models.Model): name = models.CharField(max_length=128) children = ? class Children(models.Model): name = models.CharField(max_length=128) parent = ? If we need the children instances to have parent as link to model Parent we can use ForeignKey in Children and vice versa. If parent A has children B and C and we want A to have ids of children B and C and children B and C to have id of parent A. i.e. A.children = (B.id, C.id) and B.parent = A.id, C.parent = A.id. How can we achieve this? parent = models.ForeignKey(Parent, related_name='children') can this be used? -
NoReverseMatch at /signup/
when the user registers, does not show the page that the confirmation email was sent and does not send the confirmation email.django -
Django: relation "django_site" does not exist in app with psql using sites framework
after switching from sqlite to postgres for local dev db, I am unable to migrate my app. Several fixes and approaches I've attempted have not resolved (ex: Django: relation "django_site" does not exist). python: 3.6.3 Django Version: 1.11.9 psql (PostgreSQL): 10.1 err: File "/.pyenv/versions/3.6.3/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: relation "django_site" does not exist LINE 1: SELECT (1) AS "a" FROM "django_site" LIMIT 1 installed apps: DJANGO_APPS = ( # Default Django apps: 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.gis', 'django.contrib.humanize', 'django.contrib.admin', ) THIRD_PARTY_APPS = ( 'widget_tweaks', 'mptt', 'channels', 'honeypot', 'gunicorn', 'djangosecure', # Allauth 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', ) LOCAL_APPS = ( 'users.apps.UsersConfig', #because of a signal 'common', 'geo', 'community', 'objects', ) INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS in .env file: SITE_ID=1 solutions I have attempted: Cleared all migrations and migration files and ran: $ ./manage.py makemigrations then I have attempted sequential and manual migrations of apps starting with django.contrib, such as: $ ./manage.py migrate sites (first) then applying additional migrations. but regardless of how I order app migrations does not change err or allow migration to complete. I have also tried migrations with --fake-initial. it looks like it is calling a site object before creating … -
Where should user specific model filters live in Django
I am designing a school app where users will be provided with model objects wrt their positions and roles. Now generally this seems to be handled by custom manager methods. However, they also need to be user specific, and user is in the request. So, how do I design a system without breaking the separation of concerns, i.e., MVC. I also intend to use Guardian app for object permissions in addition to the default authorization backend. I am not sure how to coordinate them either. -
can we use django authentication as a micro service in different project?
In my project we are trying to create micro service type architecture using djnago/django-rest-framework. We've some services like: User management service Asset Management Service Tool management service All three services running on different Ports with different database. Now my question is, Can we use user management service in Asset and tools service for Token authentication? -
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order
I have a problem with django. Actually I want to create a login panel in my new site but when I try to write address the debugger respond me a error: Page not found (404) Request Method: GET Request URL: http://localhost:8000/account/login Using the URLconf defined in firmowa.urls, Django tried these URL patterns, in this order: admin/ ^account/ The current path, account/login, didn't match any of these. My firmowa.urls is from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path(r'^account/', include('account.urls')), ] And the project urls.py is: from django.urls import path from . import views urlpatterns = [ path(r'^login/$', views.user_login, name='login'), ] I'm looking a solution from few hours but still nothing. -
Trying to upload multiple files, but getting str error
So I am trying to upload multiple files and get this error : __str__ returned non-string (type int) The thing is related to my str function. If I leave it like return self.file, then it will just show object, not real filname. Also, tried using os.basename but unsuccessfully. class FileUpload(models.Model): file = models.FileField(upload_to='documents', blank=True) def __str__(self): return self.file.name class AnotherClas(models.Model): file_upload = models.ForeignKey('FileUpload', on_delete=models.CASCADE, blank=True) -
Is there a limit for requests in db.sqlite3 in Django ?
I'm working with Django and I have a db.sqlite3 database. With my Django Website I want to add rows (Tweets collected with the Twitter API to be precised) to my database by clicking on a button. It works but it can't add more for than 100 rows for each click on the button. Here is the code : for tweet in tweets[:200]: q = Question(question_text=tweet.text, pub_date=timezone.now()) q.save() After I clicked on my button, there is 100 more rows in my database but not 200. So do you know if there is a limit of 100 rows by request in db.sqlite3 in Django ? And do you know how to remove that limit ? Thank you very much by advance for your answer :) -
Django model objects and Graphene get_node
So far I was able to play around with Graphene without needing DjangoObjectType. I try to avoid it as I'm not planning to stay too close to my Django model classes. However I'm having issues when implementing Relay with Graphene: class HouseholdNode(graphene.ObjectType): class Meta: interfaces = (graphene.relay.Node,) name = graphene.String() @classmethod def get_node(cls, info, id): return Household.objects.get(pk=id) This fails with the following error: Abstract type Node must resolve to an Object type at runtime for field Query.node with value "Test", received "None". "Test" comes straight from Household's __str__ function. Next try: @classmethod def get_node(cls, info, id): return cls(Household.objects.get(pk=id)) cls is Household (the node). However this yields the wrong result: "node": { "id": "SG91c2Vob2xkOlRlc3Q=", "name": null } The ID is actually "Test". Solution that works: @classmethod def get_node(cls, info, id): household = Household.objects.get(pk=id) return cls(name=household.name) However I highly doubt that this is all Graphene can do for me. Do I really have to wrap the real data object into HouseholdNode? I already have resolve functions, can't those simply be used instead? The documentation is highly lacking on those edges, please enlighten me. -
How can I link model in new app with specific model data in allauth?
In Django, I have installed allauth. Then I have created a new app, where user's actions will be. I want to link each of the actions with allauth's user data within EmailAddress model. My questions are: Normally, data is defined by user_action = models.CharField(max_length=200) and such. ForeignKey on user action does not allow defining field types, at least from what I've seen. How can I define it, or is it okay not to define it? How can I define the relationship with data in allauth's model that's not anywhere near this new app? For example, I have: from django.db import models import allauth.account.models class Button(models.Model): button_one = models.ForeignKey('EmailAddress', on_delete=models.CASCADE) def __str__(self): return self.button_one It does not work. The error shows: input.Button.comment: (fields.E300) Field defines a relation with model 'EmailAddress', which is either not installed, or is abstract. input.Button.comment: (fields.E307) The field input.Button.comment was declared with a lazy reference to 'input.emailaddress', but app 'input' doesn't provide model 'emailaddress'. The allauth model data ("user") in question is: class EmailAddress(models.Model): user = models.ForeignKey(allauth_app_settings.USER_MODEL, verbose_name=_('user'), on_delete=models.CASCADE) email = models.EmailField(unique=app_settings.UNIQUE_EMAIL, max_length=app_settings.EMAIL_MAX_LENGTH, verbose_name=_('e-mail address')) verified = models.BooleanField(verbose_name=_('verified'), default=False) primary = models.BooleanField(verbose_name=_('primary'), default=False) objects = EmailAddressManager() I'm using virtualenv and have allauth installed within the project. -
Django email sending: Attach zip file as well as HTML template
I am trying to email both html content and a zip file attached using EmailMultiAlternatives from django. Not sure why at a time only one of them can be attached. # import from django.core.mail import EmailMultiAlternatives mail = EmailMultiAlternatives('Subject', "", 'from emails', 'to emails') if file: mail.attach_file(file) mail.attach_alternative(html_content, "text/html") mail.send() -
Django. Get related field id
room = Reserved.objects.get(room=id) ?? I want to get id of that field exists in the one model. For example: models.py class Room(models.Model): number = models.OneToOneField(RoomNumber) class Reserved(models.Model): room = models.OneToOneField(Room, on_delete=models.PROTECT) Id of room that exits in Reserved table. How to get it? Thanks:) -
"Truncated incorrect DOUBLE value: X_XX"
Django's ORM just isn't clicking for me, but I intend to spend the weekend reading through the documentation in order to make it click. Meanwhile, I have an issue I need to resolve that I haven't been able to. The first I had was here, which was resolved with the answer provided: ValueError: invalid literal for int() with base 10 seems to be related to ForeignKey I have modified my query to: # data['product_id] = 78 # returns A_17 product_code = Products.objects.get(id=data['product_id']).code # this is where the error occurs print(ProductPositions.objects.filter(product_code__code=product_code)) /mnt/c/dev/current/client/.venv/client/lib/python3.6/site-packages/pymysql/cursors.py:166: Warning: (1292, "Truncated incorrect DOUBLE value: 'A_15'") result = self._query(query) I am not even sure why it is looking at A_15 because it should only be filtering on A_17, so that is one issue I don't understand To explain these tables because I don't think it is really intuitive. The Products will look something like this (with columns not relevant to this removed): -- Products table id code -------------- 77 A_16 78 A_17 81 M_15 There are multiple of the code in the ProductPositions. code is more like a line of products and and product_no (which I haven't got to yet and is the next step) are the products … -
Django restframework permissions
it is a basic api, I have 3 kinds of users -> admin, companies, employees. admin can view, edit and delete all of them, companies can view and delete it's employees and employees can only see the videos updated by it's companie. So each companie will have an admin panel that they can upload training videos and register it's employees, so each companie has it's own panel, they don't see other companies. Do I need to create a custom user model to do that? How would I create that model, How can I set those permissions? How can I manage the register form, login, urls that the companies and employees can or can't access -
'Mixed Content' warning when accessing localhost
I have a website backed by Nginx and Django using HTTPS. I also have a client program that runs locally on my computer. The website is accessed with HTTPS and makes Post requests to the client at http://localhost. I use jQuery for the request to localhost: jQuery.ajax({ url: "http://localhost:5555/command", data : data type : "POST", }); I get the following error message from Chrome: Mixed Content: The page at 'https://example.com/whatever/' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://localhost:5555/'. This request has been blocked; the content must be served over HTTPS. This warning is normally useful, but it seems kind of pointless for localhost. How can I allow this access? Note: this question is similar to this one, but different because I care about localhost in particular and not an arbitrary http website: "Mixed content blocked" when running an HTTP AJAX operation in an HTTPS page -
Django, listing the query-set of connected Models
I would like to list all conversations of a User. As seen from picture below, Conversation Model is not Directly connected to the User table. This is a freelancer site project, where users can register as workers to do jobs posted by users. The result I want is: my_conversations = User.Conversation.all() I'm adding this picture, since it paints everything that I will summarise below. Let's images I have 2 users, one of which is a registered worker. Then it looks as follows: **Users** id Name ... 1 John 2 Bob **Worker** id user_id ... 1 2 John posted some job. We add 1 new entry to the JOB table. **Job** id title user_id 1 Help me design a database 1 This is a M-to-M relationship (worker can apply for many jobs and one job can have many workers), we define a new table where job_has_worker. For each job_has_worker, there should be a way to communicate between worker and job poster. Now what I would like Django to do is load all conversations the user who is logged in e.g. load a list of my conversations for the jobs I posted. Views - My Posted Jobs User = request.user Jobs = …