Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Group private messages in Django by users
I have built a private messaging system for registered users in Django, and I have a small issue. I cannot think of a way to group the messages by users. The image below shows the messages between two users. This is the conversation as seen by the user karolann. You can see that it does not group the messages correctly. The sentences "Hello Susan" and "Those two modules are quite challenging" should come after the last sentence - "Text me when you online.". Right now, the messages are grouped by the sender. If I group them by the receiver, it still does not work properly. It would need something that is common for both like a conversation id or something. So my question is: How do I create conversations? I want all the messages between two users to be in the same place. My models.py is as follows: My views.py is as follows: And lastly, my template: -
Suspicious Operation trying to upload local image to S3 in Django
I'm developing a Django project where my Users have a profile picture saved as an ImageField, which I currently store in S3. class MyUser(models.Model): user = models.OneToOneField(User, unique=True) picture = models.ImageField(max_length=255, upload_to=get_user_pic_path) def get_user_pic_path(instance, filename): return os.path.join('user_pics', instance.user.username, filename) with the relevant settings.py: # Amazon S3 stuff AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID'] AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY'] AWS_STORAGE_BUCKET_NAME = os.environ['AWS_STORAGE_BUCKET_NAME'] AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_LOCATION = 'static' MEDIAFILES_LOCATION = 'media' # URL prefix for static files. STATIC_ROOT = '/%s/' % AWS_LOCATION STATIC_URL = '//%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] # Media urls MEDIA_ROOT = '/%s/' % MEDIAFILES_LOCATION MEDIA_URL = '//%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION) DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' The project works in production, which allows users to create accounts by taking a webcam photo and saving that to S3, but I get a SuspiciousOperation when trying to set up a local user for testing purposes. I have a command that is invoked by python manage.py create_test_user, which does: def handle(self, *args, **options): pic_path = os.path.join(settings.BASE_DIR, 'static', 'img', 'test_img.jpg') user_list, pic_list = [], [] for i in range(5): # create user objects associated with each MyUser u = User.objects.create_user( username='bickeree_'+str(i), email=str(i)+'@gmail.com', password='1234' ) u.first_name = 'Test User' u.last_name = … -
Django Form Doesn't Save to Table
Here is the issue - when the user presses the 'Save' button, the settings they entered SHOULD be saved to the table. However, this doesn't happen. After you are redirected, you can check the 'Settings' page again or the admin site and the changes will not appear. I even put in several print statements which ALL run, but I can't figure out why this is happening. Here is the code (I only included what is necessary) views.py class SettingsView(LoginRequiredMixin, FormView): template_name = 'example/settings.html' form_class = ExampleSettingsForm success_url = reverse_lazy('example:index') def get_context_data(self, **kwargs): context = super(SettingsView, self).get_context_data(**kwargs) context['page'] = 'settings' return context def get_initial(self): initial = super(SettingsView, self).get_initial() initial['example1'] = self.request.user.example.example1 initial['example2'] = self.request.user.example.example2 initial['example3'] = self.request.user.example.example3 initial['example4'] = self.request.user.example.example4 initial['example5'] = self.request.user.example.example5 initial['example6'] = self.request.user.example.example6 initial['example7'] = self.request.user.example.example7 return initial def form_valid(self, form): form.save_to_example(self.request.user) print("Form valid.") return super(SettingsView, self).form_valid(form) @method_decorator(shelter_login_required) def dispatch(self, *args, **kwargs): return super(SettingsView, self).dispatch(*args, **kwargs) forms.py class ExampleSettingsForm(forms.Form): example1 = forms.CharField() example2 = forms.TimeField() example3 = forms.TimeField() example4 = AddressField() example5 = forms.IntegerField() example6 = forms.RegexField(regex=r'^\+?1?\d{9,15}$') example7 = forms.BooleanField() def save_to_example(self, user): user.example.example1 = self.cleaned_data['example1'] user.example.example2 = self.cleaned_data['example2'] user.example.example3 = self.cleaned_data['example3'] user.example.example4 = self.cleaned_data['example4'] user.example.example5 = self.cleaned_data['example5'] user.example.example6 = self.cleaned_data['example6'] user.example.example7 = self.cleaned_data['example7'] user.save() print(user.example.example1) -
Django REST API not returning response to angular 7 http.post call
I have been trying to call API, I created in Django it works fine in Postman application gives the right results, but when I call it in my Angular 7 app it returns status code 200 ok! but I don't get any response !! ** ANGULAR 6 ** return this.http.post(`http://localhost:8000/scheduler/FCFS/`, body, { headers: headers }).pipe( map((response) => { return response; }) ) Django (view file) @api_view(['GET', 'POST']) def FCFS(request): return Response({'foo':'boo'}) Here are some screenshots Angular response -
How can I build a Django template filter that displays text surrounding a certain word? (Django 2.1)
I am building a search engine and want my search results to contain a short text blob that shows the keyword highlighted in its context, just like Google. For example, if the keyword is "Linux", I want my text blob to be something like "Get a Linux computer: no need to remove (and pay for) all the software you can't trust! The following vendors sell machines preinstalled with ..." So far, I've only found a filter mechanism to limit the amount of characters shown in the text blob, but I don't know how to restrict these characters to the characters surrounding the keyword. Any idea? My template: <div id="results-list" class="container"> <ul> {% for article in articles %} <li><a href="{% url 'search:article_detail' article.ArticleID %}">{{ article }}</a></li> <p> {{ article.Content|slice:":255" }} </p> {% endfor %} </ul> </div> My code for the search engine: def query_search(request): articles = cross_currents.objects.all() search_term = '' if 'keyword' in request.GET: search_term = request.GET['keyword'] articles = articles.annotate(similarity=Greatest(TrigramSimilarity('Title', search_term), TrigramSimilarity('Content', search_term))).filter(similarity__gte=0.03).order_by('-similarity') -
Server Error 500 in deploy Django to Heroku
So, I have a problem with a Django project I deployed to Heroku. I have finally been through the whole process of deploying the project resolving loads of errors. Now that the site is correctly deployed i have difficulties with my login app (that works perfectly fine on local host). Whenever I try to Register or login a user (or login in the admin page), i get a Server 500 error (You can try yourself at the link Universalvvfamily.herokuapp.com), but i can't understand why... What should I show you about my code so that you can help me? Thank you very much in advance -
Django send_mail giving NoneType Error with RequestFactory, But Not When Running Code Outside of Views (Test Code Included)
So I am having issues with my website in production and figured it was something with Nginx while in production. But I have boiled it down to another issue, that I am not quite sure how to define. The issue at hand is when using the send_mail function in Django (1.10.x). I can send emails perfectly when I run my function code from the terminal, just by typing it out while in a python shell. But when I try to run it using RequestFactory and running the given function with the request, I get an odd error. This error on my terminal screen is much more clear than the blank 500 server error I receive on my website. I have tried different email setups, even changing the email backend to console in the settings, and nothing is working. Code that works, after opening up my shell ./manage.py shell_plus >>> from django.core.mail import send_mail >>> name = 'Test User' >>> contact_email = 'testing@test.com' >>> contact_phone = '123-456-7890' >>> subject = 'Message from: %s, %s' % (name, contact_phone) >>> message = 'This is a test being sent from the backend console.' >>> to = 'user@test.com' # changed for anonymity >>> send_mail(subject, message, … -
Django: access from different network
I made a django server, which I ran by the command: python3 manage.py runserver 0.0.0.0:8000 When I try to connect to the server from the same computer using the localhost:8000 everything works fine :) However, when I try to connect to the server using server_ip:8000 from another computer, I get the response: ERR_CONNECTION_TIME_OUT. ( The server ip is configured in ALLOWED_HOSTS ) Any ideas how to solve this problem or what might be causing it? :) -
Django: how do i get values from <div> of HTML into django views and use the value?
so I have used leaflet and Javascript for rendering maps and calculate distance. the calculated distance is passed to and I need to extract the value and use it in django views to sort the object by distance in another page. How do I do it? -
TypeError: type CombinedExpression doesn't define __round__ method
I'm using the ipython (Python 3.7) console in PyCharm. I'm trying got run a Django ORM query where I want to do some date math specifically calculating number of seconds and comparing that to another field. I tried Article.objects.filter(article_stat__elapsed_time_in_seconds=(round(datetime.now(timezone.utc) - F("created_on")) / 300) * 300) but I'm getting the following error Traceback (most recent call last): File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/IPython/core/interactiveshell.py", line 3267, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-18-607b95229a28>", line 1, in <module> Article.objects.filter(article_stat__elapsed_time_in_seconds=(round(datetime.now(timezone.utc) - F("created_on")) / 300) * 300) TypeError: type CombinedExpression doesn't define __round__ method Here is the model in question ... class Article(models.Model): ... created_on = models.DateTimeField(default=datetime.now) How do I overcome this "TypeError: type CombinedExpression doesn't define round method" error? -
Manager isn't accessible via __ instances when getting model objects
I'm just transitioning to python. I just cant populate my html list from data in models. here's my model just to show details but i think there's nothing wrong here from django.db import models class Student(models.Model): student_id = models.CharField(max_length=10, primary_key = True) first_name = models.CharField(max_length = 30) middle_name = models.CharField(max_length = 30) last_name = models.CharField(max_length = 30) course = models.CharField(max_length = 50) year = models.IntegerField(default=1) section = models.CharField(max_length=1) Here is the view and the html file that I'm not sure where I messed up view: from django.shortcuts import render from django.contrib.auth.decorators import login_required from .models import Student @login_required def home(request): student = Student return render(request, 'studentapp/studenthome.html', { 'student':student, }) studenthome.hmtl {% extends 'base.html' %} {% block content %} <h2>Student Home</h2> <ul> {% for students in student.objects.all %} <li>{{students.first_name }} {{students.middle_name}} {{ students.last_name }}</li> {% endfor %} </ul> {% endblock %} I think the error is related to the for statement here in html file but I really have no idea Error: Manager isn't accessible via Student instances -
Compare naive time with aware datetime object in Django
One my models has DateTimeField which get assigned at some point in the flow of the app. class SomeModelWithAwareDateTimeField(models.Model): timestamp = models.DateTimeField(...) Yet another model has unaware TimeField which represents time slot, unrelated to date or specific day, just plain time like 17:00. class SomeModelWithNaiveTimeField(models.Model): time = models.TimeField(...) At some point I need to filter SomeModelWithAwareDateTimeField objects by time stored in time field of SomeModelWithNaiveTimeField object. SomeModelWithAwareDateTimeField.objects.filter( timestamp__time=instance_of_some_model_with_naive_time_field.time ) But because I'm using time zone support USE_TZ = True values mismatch, although both represent the same time. How do I convert time field to aware time object and compare two? -
Django: Searching with __icontains Across All Fields Produces Duplicates
I have a Django model called Books(models.Model) that has a variety of fields including author, title, and year created. I want to filter this list across all fields of the Book model. For example, if I search for "Winnie," I want all Book instances with "Winnie" in the title, author, or year created to come up, but do NOT want to same instance of a model to come up. For instance, if "Winnie" is in the title AND author of a specific instance, I only want that instance to appear once. I have tried using the following code to accomplish this: books = Books.objects.filter(Q(title__icontains=search_query) | Q(author__icontains=search_query) | Q(year_created__icontains(search_query)) where search_query is a variable that represents the search query. However, I am getting duplicate results as explained earlier. How do I prevent these duplicate results? Any help is greatly appreciated! Thanks! -
Is Django Channels supported in Google App Engine?
I saw that now GAE supports WebSocket... I would know if this include Django Channels (I use the standard GAE, not Flex one). Fonts (scroll down the page): https://issuetracker.google.com/issues/35886348 -
DRF serialize and save model with user FK
models.py class UserContentItem(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=200) created_date = models.DateTimeField(default=timezone.now) views.py class UserContentItemView(APIView): permission_classes = (permissions.IsAuthenticatedOrReadOnly, ) def post(self, request, format=None): data = request.data data['owner'] = request.user.id serializer = UserContentItemSerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers.py class UserContentItemSerializer(serializers.ModelSerializer): class Meta: model = UserContentItem fields = ('id', 'owner', 'title', 'created_date') I am building an API with Django Rest Framework and simple jwt. I want to allow authenticated users to POST a new UserContentItem that has a FK dependency on the User but the User is not part of the POST payload. The only way I've been able to figure out how to do this is as above, adding the request.user.id to the request data before passing it to the serializer. Is there a better way to serialize the UserContentItem and achieve the same goal? -
Getting an error while trying to perform the python manage.py migrate command
When I am trying to run the python manage.py migrate , I am getting the attached error. raise MigrationSchemaMissing("Unable to create the django_migrations table (%s)" % exc) django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table (ORA-00907: missing right parenthesis) I am using the below packages cx_oracle 6.3.1 django 2.1.5 backend Oracle 10g XE DATABASES = { 'default': { 'ENGINE': 'django.db.backends.oracle', 'NAME': 'xe', 'USER': 'django', 'PASSWORD': 'oracle', 'HOST': 'localhost', 'PORT': '1521', } } enter image description here -
Making a button group dynamic
I have data coming from a 3rd part API which I can parse using JQuery into multiple arrays which I want to display in a chart. I have taken this out to simplify the code and I'm using two fixed arrays newData1 and newData2 I have successfully created buttons that switch between the two data arrays and change the chart so the chart is dynamic and changes on the button click What I can't work out is how to make the number of buttons dynamic and populate them from a list - the length of which could vary and is taken from the array called button_list The function printBn does create a dynamic list of buttons, but I doesn't appears as a button group and take the Bootstrap styling that I've tried to apply like this <div class="btn-group-vertical" role="group" aria-label="First group"> <button id="btn1" type="button" class="btn btn-secondary">1</button> <button id="btn2" type="button" class="btn btn-secondary">2</button> </div> I basically want a way to make that Bootstrap html dynamic charts.html {% extends 'base.html' %} <script> {% block jquery %} var endpoint = '/api/data/'; var newData1 = [0.9, 0.9, 0.9]; var newData2 = [0.2, 0.2, 0.2]; var data = []; var button_list = ['Test1', 'Test2', 'Test3', 'Test4']; … -
NameError: name 'F' is not defined in Django ORM query
I'm using the ipython (Python 3.7) console in PyCharm. I'm trying got run a Django ORM query Article.objects.filter((round(datetime.now(timezone.utc) - F("created_on")) / 300) * 300) but I'm getting the following error Traceback (most recent call last): File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/IPython/core/interactiveshell.py", line 3267, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-12-53618885441a>", line 1, in <module> Article.objects.filter((round(datetime.now(timezone.utc) - F("created_on")) / 300) * 300) NameError: name 'F' is not defined I thought "F" was the way to reference a field in my model in an expression but I get the error above. My Article model contains the field as below ... class Article(models.Model): ... created_on = models.DateTimeField(default=datetime.now) -
How to run JS inside an if block in django templates?
I want to run an alert, but only if there are messages, and with all the messages in a single alert. I'm trying this way: {% if messages%} <script type = "text / javascript"> alert {% for message in messages%} {{message}} {% endfor%} ); </ script> {% endif%} But the alert does not run on the page, and when I inspect the element, this appears: <script type = "text / javascript"> alert Wellcome, marcosr00t ); </ script> obs: the script is inside the main > section element -
Multiple periodic long running tasks
I have multiple websocket feeds which i'm trying to run continuously. My idea was to use celery beat to run these automatically with a task lock to not run multiple instances. I've scheduled the task to run every 1 second incase they die so they automatically restart with little interruption. Currently I can only get one running at a time. Where am I going wrong or is there a better way to approach this? @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): sender.add_periodic_task(1.0, task1.s(), name='task1') sender.add_periodic_task(1.0, task2.s(), name='task2') LOCK_EXPIRE = 60 * 10 @contextmanager def task_lock(lock_id, oid): timeout_at = monotonic() + LOCK_EXPIRE - 3 status = cache.add(lock_id, oid, LOCK_EXPIRE) try: yield status finally: if monotonic() < timeout_at and status: cache.delete(lock_id) @app.task(bind=True) def task1(self): with task_lock("task1-id", self.app.oid) as acquired: if acquired: start_socket("socket1") @app.task(bind=True) def task2(self): with task_lock("task2-id", self.app.oid) as acquired: if acquired: start_socket("socket2") -
Django-Oscar: Adding slugs to url
I would like to be able to add a the following: [(?P<slug>[-\w]+)] after /dashboard/' between that and the rest of any possible url that comes after, i.e. '/dashboard/ (?P<slug>[-\w]+) /catalogue/. The point of this would be to make it 'partner-specific' for my particular project. How would I go about doing this? I currently am working directly with Oscar code for several reasons, meaning that I do not have to 'fork' any apps - I just change the Oscar code within my project. The strategy I am trying to accomplish this URL-change is to go into app.py and adding it there after 'dashboard', or going into dashboard/app.py and adding it before each url defined there. Whenever I change I keep getting 'NoReverseMatch at ---' and errors like: Reverse for 'MY-URL-IS-HERE' with no arguments not found. 1 pattern(s) tried: ['dashboard/(?P<slug>[-\\w]+)/logout/$'] I am familiar with this error, but now seem unable to ever locate the exact location of the error message. And whenever I do get the page to load (was able to when adding it before 'reviews'), I still get an error something like the following in the terminal: Invalid URL name dashboard:reviews-list Traceback (most recent call last): File "/Users/myname/Desktop/Developer/wybe-all/wybe/apps/oscar/dashboard/nav.py", line 83, … -
How can I set specific HTML-tags with Jinja as safe / unsafe? [duplicate]
This question already has an answer here: Sanitising user input using Python 7 answers I'm trying to replace specific text in user generated content with fully working HTML using Jinja2. I'm using this code: {{content | replace("\n", "<br/>") | safe}} The problem is that the user can now submit any HTML he want. So how can I set only specific HTML-tags with Jinja as safe / unsafe? -
Django Abstract Class change behaviour according to actual class
I think following code explains what I'm trying to do from django.db import models class MyBaseClass(models.Model): type = models.IntegerField() class Meta: abstract = True def save(self, *args, **kwargs): self.type = #What Should I write here?# self.type = self.class.type ? super().save(*args, **kwargs) class Model1(MyBaseClass): TYPE = 1 class Model2(MyBaseClass): TYPE = 2 I want to make sure following assertions work: instance1 = Model1.objects.create() assert(instance1.type, 1) instance2 = Model2.objects.create() assert(instance1.type, 2) How can I make this work? Thanks. -
Checkbox input in form disappearing after submit
Created a form that enters boolean values on submit using checkbox inputs. When the form is submitted and the page reloads, the checkbox form inputs disappear. This is on Django and I have tried changing the views function to potentially keep it there, but I haven't found a solution. HTML <form action="{% url 'student:account_notifications' %}" method="POST" autocomplete="off"> {% csrf_token %} <div class="email"> <p>Email notifications</p> </div> <!-- Check Boxes --> <div class="checkbox"> {{ form.schedule }} <label>When you schedule a lesson</label> </div> <div class="checkbox"> {{ form.cancel }} <label>When a lesson is cancelled</label> </div> <div class="checkbox"> {{ form.day_reminder }} <label>24 hour reminder before your lesson</label> </div> <div class="checkbox"> {{ form.half_hour_reminder }} <label>30 minute reminder before your lesson</label> </div> <div class="bottom"> <button type="submit" name="submit" class="btn blue_button">Save</button> </div> forms.py class ChangeNotificationsForm(forms.ModelForm): schedule = forms.BooleanField(widget=forms.CheckboxInput(attrs={'checked' : 'checked'}), required=False) cancel = forms.BooleanField(widget=forms.CheckboxInput(attrs={'checked' : 'checked'}), required=False) day_reminder = forms.BooleanField(widget=forms.CheckboxInput(attrs={'checked' : 'checked'}), required=False) half_hour_reminder = forms.BooleanField(widget=forms.CheckboxInput(attrs={'checked' : 'checked'}), required=False) class Meta: model = Notifications fields = ('schedule', 'cancel', 'day_reminder', 'half_hour_reminder') views.py def account_notifications(request): if request.method == 'POST': form = ChangeNotificationsForm(request.POST) if form.is_valid(): schedule = request.POST.get('schedule', '') == 'on' cancel = request.POST.get('cancel', '') == 'on' day_reminder = request.POST.get('day_reminder', '') == 'on' half_hour_reminder = request.POST.get('half_hour_reminder', '') == 'on' notifications_obj = Notifications(schedule … -
Dependant fields in Django admin
I have a model which must be able to save information about when/what actions must be executed by a task (the task-related stuff are out of the scope of this question, so I won't get into details about that). The actions are divided into at least 3 sections. The first section is "when" (before or after the task has been executed), so that should show up in the django admin like a dropdown (this one is easy). The second section is what action should be executed (perform a click, transform a text, get regex match, etc...), which should also show up as a dropdown in django's admin (this one is easy too). Here comes the difficult part. Depending on the selection of the second section, I must show another input field(s) of some sort. For example, if I select perform a click in the second section, the third section would show a text field in which I should type the CSS selector for the element I want the task to click. But if I select transform a text in the second section, then the third section should show me a dropdown with several options such as uppercase, lowercase, append, etc... …