Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
compiled django application fails to run ASGI channels
I'm building a django application using Pyinstaller. When I run the application i get an error from dapne server. "daphne\server.py:13: UserWarning: Something has already installed a non-asyncio Twisted reactor. Attempting to uninstall it; you can fix this warning by importing daphne.server early in your codebase or finding the package that imports Twisted and importing it later on." In addition, when I compare the console log of the EXE application and a regular run of the django application I notice the following difference. In the regular run which works as expected I see the following print: "Django version 2.1.5, using settings 'cfehome.settings' Starting ASGI/Channels version 2.1.5 development server at http://0.0.0.0:8000/" however, when I run the application from the EXE I see: "Django version 2.1.5, using settings 'cfehome.settings' Starting development server at http://0.0.0.0:8000/" Appreciate any lead to understand this behavior and ways to fix it. -
Django not streaming properly when running in a virtual machine
I have an application which is using django as backend and react as UI. In the backend, it simply subscribe a remote publisher, and sending data to UI. If I run the application in host machine (mac OS), it works perfect. From the browser console, I can see the UI is receiving data and logged in the console. The total data size is larger than 2 MB. When I run it in a virtual machine (CentOS 7), and open it through host's browser, I can see the data is streaming, but with much smaller size, around 10 KB, and it never logged in the browser console. Initially I thought it may be caused by the connection, so I tested the connection speed between the host and the client. The speed test result is 3Gb/s so looks like the connection is fine. Then I also tried give more processor and memory to the virtual machine, but still the same. (I gave 6 processors and 12G memory) I tried search on the internet but couldn't find any solutions. Here are some code example: django def stream_data(request): context = zmq.Context() sock = context.socket(zmq.SUB) sock.setsockopt_string(zmq.SUBSCRIBE, '') ip_addr = get_public_ip() port = '5570' sock.connect('tcp://{0}:{1}'.format(ip_addr, port)) … -
How do I obfuscate data in variables in jinja2? e.g. variable = "John Smith", I want something like "Odsv Wgtvs"
So I am trying to create a page where details are only shown to users who are logged in. I am able to change the content statically using {% if user.is_authenticated %} So I can replace something like {{ celebrity.name }} with Dummy Name, but then every occurrence of this is the same. I'm hoping there is an easy way to mess with celebrity.name to obfuscate the actual data. If there is no easy way I'll happily write my own function, but at this point I'm not sure if I should be writing it in jinja2 in the html template or if I should do it in views.py so would appreciate some guidance. -
Retrieving all database objects and its related objects Django
I am currently learning Django, and im finding it a bit difficult wrapping my head around the ManyToMany fields. I am using an intermediate model to manage my relationships. I have three models; Ticket, User, and TicketUserRelation. I want to be able to query the ticket model, and retrieve both its corresponding user objects and the ticket object. How would I go about doing this? In Laravel I would do something along the lines of Ticket::where('id', '1')->with('contributors') But I can't really figure out how to do this in Django The models: class User(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Ticket(models.Model): contributors = models.ManyToManyField(User, through=TicketUserRelation, related_name='tickets') name = models.CharField(max_length=50) created_at = models.DateField() def __str__(self): return self.name class TicketUserRelation(models.Model): id = models.AutoField(primary_key=True, db_column='relation_id') ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) -
Django Front End Search
Currently using Django 2.1, PostgreSQL 11, and hosting the DB on Heroku. I would like to implement a user search on a device view that I have setup. Current Page Layout This page will list people in our DB and will provide a link to details about them. What I would like is for a user to be able to search for a particular person and have the list populate accordingly. Django documentation provides some steps to implement this but is not entirely clear about an action plan. Thanks for any help! -
ImportError: cannot import name 'Message' - django-messages
I forked https://github.com/arneb/django-messages/ and put it in my repo: https://github.com/mike-johnson-jr/django-messages/ As I am using the package, I get the error in the title. Full traceback: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/michael/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/michael/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/home/michael/.local/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/michael/.local/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/home/michael/.local/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/michael/.local/lib/python3.6/site-packages/django_messages/models.py", line 48, in <module> class Message(models.Model): File "/home/michael/.local/lib/python3.6/site-packages/django_messages/models.py", line 87, in Message get_absolute_url = reverse(get_absolute_url) File "/home/michael/.local/lib/python3.6/site-packages/django/urls/base.py", line 90, in reverse return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) File "/home/michael/.local/lib/python3.6/site-packages/django/urls/resolvers.py", line 562, in _reverse_with_prefix self._populate() File "/home/michael/.local/lib/python3.6/site-packages/django/urls/resolvers.py", line 413, in _populate for url_pattern in reversed(self.url_patterns): File "/home/michael/.local/lib/python3.6/site-packages/django/utils/functional.py", line 37, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/michael/.local/lib/python3.6/site-packages/django/urls/resolvers.py", line 533, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/michael/.local/lib/python3.6/site-packages/django/utils/functional.py", line 37, in __get__ res … -
Using Class Based View UpdateView with a 2 primary keys model
I'm building an aplication with two primary keys (it's a legacy database). Basically what I want to do is to click on table element and redirect to another page based on the primary keys on the model. I'm not finding anything about how to do this with Django Class Based Views Here is my code: models.py class RmDadoscarteira(models.Model): dtcalculo = models.DateField(db_column='dtCalculo', primary_key=True) # Field name made lowercase. cdcarteira = models.CharField(db_column='cdCarteira', max_length=50) # Field name made lowercase. nmcarteira = models.CharField(db_column='nmCarteira', max_length=255, blank=True, null=True) # Field name made lowercase. pl = models.FloatField(db_column='PL', blank=True, null=True) # Field name made lowercase. retornocota1d = models.FloatField(db_column='RetornoCota1d', blank=True, null=True) # Field name made lowercase. var = models.FloatField(db_column='Var', blank=True, null=True) # Field name made lowercase. var_lim = models.FloatField(db_column='VaR_Lim', blank=True, null=True) # Field name made lowercase. var_variacao1d = models.FloatField(db_column='VaR_Variacao1d', blank=True, null=True) # Field name made lowercase. var_variacao63d = models.FloatField(db_column='VaR_Variacao63d', blank=True, null=True) # Field name made lowercase. var_consumolimite = models.FloatField(db_column='VaR_ConsumoLimite', blank=True, null=True) # Field name made lowercase. stress = models.FloatField(db_column='Stress', blank=True, null=True) # Field name made lowercase. stress_lim = models.FloatField(db_column='Stress_Lim', blank=True, null=True) # Field name made lowercase. stress_variacao1d = models.FloatField(db_column='Stress_Variacao1d', blank=True, null=True) # Field name made lowercase. stress_variacao63d = models.FloatField(db_column='Stress_Variacao63d', blank=True, null=True) # Field name made lowercase. stress_consumolimite = models.FloatField(db_column='Stress_ConsumoLimite', … -
How can I have two objects from two models in one view
I am writing django blog app and I have problem how I can get Comment object in Post view. With post object there is no problem because I write self.get_object() and done. And the question is how I can get Comment object. Below is my code. Here is view. class PostDetail(generic.DetailView, FormMixin): template_name = 'post_detail.html' context_object_name = 'post' model = Post form_class = CommentForm Here is post model: class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = RichTextUploadingField() Here is comment model class Comment(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') text = RichTextUploadingField() -
TastyPie - filtering on related resources
Let's say I have two TastyPie resources: class LicenseResource(ModelResource): ... class UserResource(ModelResource): license = fields.ForeignKey(LicenseResource, 'license', full=False, null=True, blank=True) filtering = { "license": ALL_WITH_RELATIONS } ... Assume every user is assigned to a single license. Let's say a user (assigned to license with id=1) makes the following request to retrieve all users on License #2: /accounts/api/v1/user/?license__id=2 This user isn't assigned to this license, so they shouldn't be able to perform this query. How can I apply filtering to restrict users from only filtering on the license that they are assigned to? I've been reading the documentation but I'm having a hard time getting my head around how to handle this. Thanks -
UUID generating non unique strings
I've the following model, class PublicRoom(Base): name = models.CharField(db_index=True, max_length=255) hexcode = models.CharField(unique=True, max_length=255, default=gen_hex_code) This is the gen_hex_code function, def gen_hex_code(): return str(uuid.uuid4()) When I try to deploy(which runs migrations) I get the following error, django.db.utils.IntegrityError: could not create unique index "messenger_publicroom_hex_code_key" How can get past this. Any help appreciated. -
Django model admin panel multiple choice checkbox
I am wanting to implement an extension of the User model in django that allows for a field to be an array field of choices that is based on a field from another table. I only want the choices to be non null values from that table's field. I am using Postgres as my database. This is what I have so far: class UserLocations(models.Model): """ """ user = models.OneToOneField(User, on_delete=models.CASCADE) branches = ArrayField(models.ForeignKey(Locations.location_name, limit_choices_to={'is_null': False}, on_delete=models.SET_NULL)) class Meta: managed = True db_table = 'user_authorized_locations' Am I going about this correctly or am I doing this wrong? -
getting all the object related to the object added when using ModelMultipleChoiceField
i am trying to create a sign up form where the user can specify many categories and languages from a lists but when I signup up choosing one or two objects from the list I found that the new user is stored with all the objects. It is like i had checked all the objects. #forms.py class SignUpForm(UserCreationForm, ModelForm): categories=forms.ModelMultipleChoiceField(queryset=Category.objects.all(), widget=forms.CheckboxSelectMultiple(), required=True) languages = forms.ModelMultipleChoiceField(queryset=Language.objects.all(), widget=forms.CheckboxSelectMultiple(), required=True) class Meta: model = User fields = ['username', 'email','categories', 'languages'] #models.py class User(AbstractUser, models.Model): password1 = models.CharField(max_length=50) categories = models.ManyToManyField('Category') languages = models.ManyToManyField('Language') def __str__(self): return self.username class Category(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Language(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name #views.py class SignUp(CreateView): form_class = SignUpForm success_url = reverse_lazy('index') template_name = 'registration/signup.html' -
How do I use timedelta with a column in my Django ORM query?
I'm using Django and Python 3.7. I have the below two models ... class Article(models.Model): ... publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE, related_name="articles",) created_on = models.DateTimeField(default=datetime.now) class WebPageStat(models.Model): ... publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE, related_name="stats", ) elapsed_time_in_seconds = models.FloatField(default=0) score = models.BigIntegerField(default=0) I want to write a Django ORM query where given a publisher and an elapsed time in seconds (a WebPageStat record), I find all articles whose "created_on" date is not older than the elapsed time in seconds. Many have suggested using "timedelta," in other posts, but taht doesn't seem to be working for me here ... Article.objects.filter(created_on__lte=datetime.now(timezone.utc) - timedelta(hours=0, minutes=0, seconds=publisher__stats__elapsed_time_in_seconds)) Traceback (most recent call last): File "<input>", line 1, in <module> NameError: name 'publisher__stats__elapsed_time_in_seconds' is not defined Can I use timedelta with SQL column logic? Otherwise how do I do this? -
how to place a pre-existing web app from one django project to another
So basically, I created a user registration web app on django via a tutorial I watched. Recently, I've created a new django project and I was told that I could literally drag and drop that web app from one project to another and have it work. So far I've added the webapp "users" folder inside my django project directory and added it to my INSTALLED_APPS section as seen below When I run the server I receive the following error: "ModuleNotFoundError: No module named 'users.apps.UserConfig'; 'users.apps' is not a package" -
voice call ends right away, nexmo hangs up within a second
I have created an application in the Nexmo dashboard with an event url and answer url. I run the following code I got from Nexmo´s GitHub: client = nexmo.Client(key=api_key, secret=api_secret, application_id=application_key, private_key=private_key) response = client.create_call({ 'to': [{'type': 'phone', 'number': 'call_to_number'}], 'from': {'type': 'phone', 'number': 'call_from_number'}, 'answer_url': ['http://my_event_url'] }) And the phonenumber is called, but nexmo hangs up right away (within a second without saying anything). On my server I see Nexmo calls the answer url (with the ncco) what I do when the answer url is called: import nexmo import json from django.http import JsonResponse @csrf_exempt def answer(request): ncco = [{ "action": "talk", "voiceName": "Amy", "text": "Thank you for calling Nexmo. Please leave your message after the tone." }] d = json.dumps(ncco) j = is_json(d) if j: MyObject.objects.create(message="valid") else: MyObject.objects.create(message=user_ip + "json error") return JsonResponse(d, status=200, safe=False) def is_json(myjson): try: json_object = json.loads(myjson) except ValueError: return False return True This is what I do when my event_url is called: @csrf_exempt def event(request): d = json.dumps(request.POST) DataReceived.objects.create(answer=d) data = {"ok": True} return JsonResponse(data, status=200) The event url is called 5 times by Nexmo but the dictionaries are always empty. -
Use Vue attr inside render_field widget_tweaks django
file.html {% load widget_tweaks %} {%render_field set_pass_form.password v-on:blur="passwordOnBlur()" %} Gives error: 'render_field' tag requires a form field followed by a list of attributes and values in the form attr="value" But when I use v-on:blur in normal tag it works without error: <input type="email" name="email" v-on:blur="passwordOnBlur()" > How to use v-on:blur="" in {% render_field %} tag? Thanks -
django-filer: Resize images on upload
I' using django-filer to handle the uploads of images. I've been trying to resize an image after upload but before storing it in the 'media' folder. I think I should use a CustomImage model where I can override the save method, and do the resize there. However I don't really see how. More, If I printout the file path, I see the file is already uploaded at this stage! class CustomImage(BaseImage): class Meta(BaseImage.Meta): # You must define a meta with en explicit app_label app_label = 'tasks' if GTE_DJANGO_1_10: default_manager_name = 'objects' def save(self, *args, **kwargs): print(self.file.path) Any ideas where the resize should be implemented? TIA! -
Newbie Django blog with Mysql Following the Official Django Blog App Tutorial Need
Im following along with the official django blog tutorial. I have my own Vps Server that I pay for. I see most tutorials are showing if the developer is doing it on a home localhost system. I do know I have mysql on my hosting account. I'm trying to use mysql but soon as I add mysql info like DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'urbanpyt_polls', 'USER': 'urbanpyt_dbz', 'PASSWORD': 'shawn316566613' 'HOST': 'localhost', 'port': '', } } after putting this in my settings.py the virtual environment won't even load anymore. I don't know what todo. Every tutorial I watch is showing on a home server. not a vsp with mysql already installed. I hope someone can help me. I may delete and try all over again. since I'm new I know I might have something wrong. The only leads I've gotten is that people are saying don't use mysql to use the default. my only concern if I tried it this way will the default be really installed on the server or will it be virtual like running the virtual environment. -
"Forbidden 403 - CSRF verification failed" when using .submit(function) in Django form
I've been developing in application with Django that has a bunch of forms, each one in a different page. In one of the first views, I just ask the user a simple information, that is POST sent to Python and used to some formulas. The code I used to do so is show below, and it runs smoothly: <html> <head> <title>Data</title> </head> {% load staticfiles %} <link rel="stylesheet" href="{% static 'app/content/bootstrap.css' %}"> <link rel="stylesheet" href="{% static 'app/content/custom.css' %}"> <script src="{% static 'app/scripts/jquery-1.10.2.min.js' %}"></script> <script src="{% static 'app/scripts/jquery.validate.js' %}"></script> <script src="{% static 'app/scripts/jquery.maskedinput.min.js' %}"></script> <script src="{% static 'app/scripts/custom.js' %}"></script> {% if error == 404 %} <label>Who are you? Go away!</label> <br> {% endif %} Welcome! Give me your data! <body> <form action="/search/" method="post" id="myPrettyForm"> {% csrf_token %} <input type="text" name="q" id="q"> <input type="submit" value="Go!"> </form> </body> <script type="text/javascript"> $("#q").mask("00000000000"); </script> </html> As I said, this code runs nicely. However, I want to add a function, in which, once I click the "submit", the q input field is disabled. To do so, I tried adding this piece of code to the script above: $("#myPrettyForm").submit(function () { $("#myPrettyForm:input").prop("disabled", true); }); However, when I add this snippet to my code, everytime I try to … -
How to create django-filter custom filter for month/year for a dateField in model?
I am trying to filter date based on its month and year. Below is what i tried. In models.py class Expense(TimeStampedModel):date = models.DateField(_('date') in serailizer.py class ExpenseSerializer(serializers.ModelSerializer): class Meta: model = Expense fields = '__all__' in filters.py class ExpenseFilter(django_filters.FilterSet): date__month = django_filters.DateFilter(field_name='date', lookup_expr='month') date__year = django_filters.DateFilter(field_name='date', lookup_expr='year') class Meta: model = Expense fields = ('date__month', 'date__year') In views.py class ExpenseViewSet(viewsets.ModelViewSet): queryset = Expense.objects.all() serializer_class = ExpenseSerializer filter_class = ExpenseFilter When I try to hit http://127.0.0.1:8000/expense/?date__year=2019 i get empty result. Any help on this will be really appreciated. -
DJANGO template tags in plain text not displaying
I am making an app that displays questions. The question model has a text field and an image field. Each question has a template that is stored in my database in the text field. My problem is when I want to access images from the model, template tags are displayed as text and not rendering. My code: # question model class Question(models.Model): question_text = models.TextField() question_image = models.FileField(upload_to='static/images/questions', blank=true) # question view def question(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'questiontemplate.html', {'question': question}) # template {% extends 'base.html %} {% load static %} {% autoscape off %} {{ question.question_text }} {% endautoscape %} # in my database: question.question_text = '<p> some html {{ question.question_image.url }} some html </p>' question.question_image = 'image.png' This works fine and renders the html perfectly except the template tag is not rendered and does not not give the image url I want this to be the output: Some html static/images/questions/image.png some html But instead this is the output: some html {{ question.question_image.url }} some html Any suggestions to how the template tags could be render from the database text would be much appreciated. Thanks for reading -
Supervisord can't control celery workers, how to do the same using Monit
Supervisord cant controll my celery services(workers, flower, django and celerybeat). When system startup, I can see all processes running successfully, if 1 of processes fail and supervisor does not restart it, when I reload or restart supervisord, everything under supervisord fails and cant be re-launched. I have tried to move my celery services under monit. I created celery services in /etc/init.d/ and services run perfectly, I can start/stop them without problems, then I set up monit scripts for all of them. The problem is that monit is unable to start my celery-workers services, it is able to start/stop 'django', 'flower' and 'celerybeat' without problems, but workers services under init.d are unable to be started by monit. Could you please sugest me any idea how to fix this? Why other services can be managed by monit without problems, but workers not? Thank You in advance. -
Is there an implementation of a single instance blob store for Django?
I am new to Django so I apologize if I missed something. I would like to have a library that gives me a single-instance data store for Blob / Binary data. I want a library that masks whether or not the files are stored in the database, file system or some kind of back end like S3 on Amazon. I want a single API that lets me add files, and get back URLs to serve those files. Also it would be nice if the implementation supported some kind of migration if I had blobs in a database for a site when it just started out and then move those blobs to an S3 bucket behind the scenes without me needing to change how my application stores and serves the data. An important sub-aspect of this is that the files have to be only shown to properly authorized users (i.e. just putting them in an open /media/ folder as files is not sufficient). Perhaps I am asking too much - but I find this kind of service very useful in my applications. The main reason that I am asking is that unless I find such a thing - I will wander … -
How to get the user object from session in Django Rest Framework
I have just started with the DRF, and I'm going through implementing JWT within my REST API. Previously I have worked with Spring Security on Java based frameworks, where there is a concept of something known as Security Context Holder, so the User object is always be fetched from the context holderwithin the controllers or whereever required. Do DRF provide such functionality where I can get the details of currently logged in user without having to call the database? -
Change Default Password in Django Test Runner
I have a base test class (inheriting from from django.test import TestCase) that contains utility methods (eg generating a Django user with proper permissions). Within such a test, I can run user = self.make_user() # Utility function with a default username and password with self.login(user, password=settings.TEST_USER_PASSWORD): # do stuff However, if I omit the password=settings.TEST_USER_PASSWORD part of the login, I get authentication failures because the default password is password I know what the user's password is because I created the user and initialized the user in the setup method of my base test class (using a FactoryBoy factory). Nowhere am I setting the password to be password, but that's the default. I could override the login method within my CustomTestCase object, but I was hoping that there might be a settings variable (or attribute I can set on the base test class) that changes the default password to settings.TEST_USER_PASSWORD Any chance anyone knows if such a configuration exist? Thanks!