Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
passing form arguments in django
I am trying to implement a simple search function in django but somehow I can't pass the argument from my template to my view function. I've got a key error: KeyError at /artdb/search/ because kwargs is empty: url.py: path('search/',views.Search.as_view(),name='search'), base,.html: <form class="form-inline my-2 my-lg-0" name="search" action="{% url 'artdb:search' %}" {{ form.as_p }} method="get">{% csrf_token %} <input class="form-control mr-sm-2" type="text" placeholder="Search" aria-label="Search" value="{{seastr}}"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit" value="{{seastr}}">Search</button> </form> views.py: class Search(ListView): print("class Search") model=Person template_name='artdb/search.html' context_object_name='ans' def get_queryset(self): Pdb().set_trace() self.seastr=get_object_or_404(Person,name=self.kwargs['seastr']) return Person.objects.filter(seastr=self.seastr) -
Django using an object in an ORM query, within its __init__ function
I have a model which exists only to combine a number of other models. There are a series of 'payable' objects, with need to be clubbed together into a 'payment' object, called 'ClubbedPayment'. The model is given a list of payable objects, and it uses them to calculate various attributes. This works fine, so far. These payable objects have a foreign key to ClubbedPayment. Rather than going through the payable objects and adding the new ClubbedPayment object to each of them as a foreign key, it seems easier to add them to ClubbedPayment.payable_set(). I've tried to do this, but it fails because in the __init__ function, the ClubbedPayment object is not yet saved: class ClubbedPayment(models.Model): recipient = models.ForeignKey(User, on_delete=models.PROTECT) paid_at = models.DateTimeField(null=True) is_unpaid = models.BooleanField(default=True) total = models.DecimalField(max_digits=6, decimal_places=2) payment_id = models.UUIDField(null=True, editable=False) response = models.CharField(null=True, max_length=140) payment_type = models.CharField(max_length=2, choices=PAYMENT_TYPES) def __init__(self, *args, **kwargs): super().__init__() objects = kwargs["objects"] recipients = set([x.recipient for x in objects]) types = set([type(x) for x in objects]) if len(recipients) > 1: raise Exception("Cannot club payments to more than one recipient") self.total = sum([x.total for x in objects]) self.recipient = list(recipients)[0] for x in objects: self.payable_set.add(x) Now, I know that overriding __init__ with non optional … -
Best practice for defining default app settings for custom django module?
Is there a defined best practice for defining custom settings that come with a django app. What I have at the moment is a separate file called app_settings.py that looks like this: from django.conf import settings # MY_SETTING_1 is required and will brake the application if not defined try: MY_SETTING_1 = str(getattr(settings, 'MY_SETTING_1')) except AttributeError: raise ImproperlyConfigured ('MY_SETTING_1 not defined in settings.py.') # MY_SETTING_2 is not required and has a default value MY_SETTING_2 = getattr(settings, 'MY_SETTING_2', ['default_value']) Then I am importing this in my views.py, and using it like this: from my_app import app_settings print (app_settings.MY_SETTING_1) print (app_settings.MY_SETTING_2) This works ok, but I am not quite happy with the design. I am assuming that I can somehow use the class defined in apps.py, but I am not sure how. Is there a best (or better) practice for this? -
Response ZIP file by Django
I try to download img from url, add it to zip archive and then response this archive by Django HttpResponse. import os import requests import zipfile from django.http import HttpResponse url = 'http://some.link/img.jpg' file = requests.get(url) data = file.content rf = open('tmp/pic1.jpg', 'wb') rf.write(data) rf.close() zipf = zipfile.ZipFile('tmp/album.zip', 'w') # This file is ok filename = os.path.basename(os.path.normpath('tmp/pic1.jpg')) zipf.write('tmp/pic1.jpg', filename) zipf.close() resp = HttpResponse(open('tmp/album.zip', 'rb')) resp['Content-Disposition'] = 'attachment; filename=album.zip' resp['Content-Type'] = 'application/zip' return resp # Got corrupted zip file When I save file to tmp folder - it's ok, I can extract it. But when I response this file I get 'Error 1/2/21' on MacOS or Unexpected EOF if I try to open in Atom editor (just for test). I also used StringIO instead of saving zip file, but it doesn't influence the result. -
Intertwined problems with Django Time fields force hacks to edit/display time
Django 2 There's alot of info here. I'll try to summarise the essence of the issues. Background fact: Setting a default for a Time field requires that a datetime.time be set in the model reference: https://code.djangoproject.com/ticket/6754 There are two problems here that are related. Problem 1: the data type of the time field changes First problem is that the initial GET of the Django page below returns a time field with a data type of <class 'datetime.time'>. This is fine and expected. BUT If you submit that form via POST, and there is a field validation error, then the data type of the Time field CHANGES to a string. Have a look at the server log at the bottom of this question to see. As a consequence, the format os the data changes too - note that the seconds are dropped. This can also be seen in the server log below. This leads to problem 2: Problem 2: Django's time formatting tag returns None when there are no seconds on the data passed into it. In the HTML template below you can see the line containing: time:'H:i' This is a formatting tag, which accepts a time and it should output … -
How to handle JSON Decode Error without getting Django typical html error in Python
I have Django application running. When I'm sending POST request with nothing in it or with wrong JSON I want to handle the error myself. But Django gives me html page with error rather than my custom try except block. Here is my code: if request.method == 'POST': temp_request = request.body if not isValidJson(temp_request): return JsonResponse({"Error": "Error"}) def isValidJson(received_json): try: json.loads(received_json) except ValueError as e: return False return True And I'm getting Django html error page with Json Decode Error than JsonResponse -
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 …