Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I add displaying image in my home page
Am creating a site where I want to post some information with image, in my admin page I can add image and it works fine. But when I come to the homepage it doesn't appear Am using django and python. I know, the way I have used to call the image in the home template is not right, please help me how would I bring the image in my home page?? url from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static app_name = "main" urlpatterns = [ path("", views.homepage,name="homepage"), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Home template {% extends 'main/base.html' %} {% block content %} <a class="waves-effect waves-light btn" href="">button</a> <div class="row"> <div class="col s12 m9" > {% for Doc in documents %} <div class="card"> <div class="card-image"> <p>{{Doc.docs_name}}</p> <p>{{Doc.police_station}}</p> <p>{{Doc.docs_details}}</p> <img src = "{{Documents.docs_pic.url}}" width = "240"> </div> </div> {% endfor %} </div> </div> {% endblock %} views from django.shortcuts import render from django.http import HttpResponse from . models import Documents from main.models import Documents # Create your views here. def homepage(request): return render(request=request, template_name="main/home.html", context={"documents":Documents.objects.all} ) -
overwrite function with mock
Is it possible to overwrite functions behavior in class with mock? This is for python 3.6.8, django 2.2.2 views.py: YEAR_PATTERN = r"\(\d{4}\)\s*$" LOCKED_FROM_EXTERNAL_API = False class FetchFromExternalApi(APIView): @staticmethod def fetch_from_url(source): return urlopen('http://files.grouplens.org/datasets/movielens/%s.zip' % source, timeout=1) def post(self, request): global LOCKED_FROM_EXTERNAL_API, YEAR_PATTERN if LOCKED_FROM_EXTERNAL_API is False: LOCKED_FROM_EXTERNAL_API = True try: source = request.data['source'] except KeyError: LOCKED_FROM_EXTERNAL_API = False return Response('no source data in body', status=status.HTTP_400_BAD_REQUEST) if source in settings.AVAILABLE_SOURCES: try: response = self.fetch_from_url(request.data['source']) except URLError: LOCKED_FROM_EXTERNAL_API = False return Response("External server respond time out", status=status.HTTP_504_GATEWAY_TIMEOUT) I would like to write test that will overwrite behaviour of 'fetch_from_url' method, and fully simulate it. -
Django/PostgreSQL Full Text Search - Different search vectors when using SearchVector and SearchVectorField on AWS RDS PostgreSQL
I'm trying to use the Django SearchVectorField to support full text search. However, I'm getting different search results when I use the SearchVectorField vs. SearchVector on my AWS RDS PostgreSQL instance. Both perform the same on my laptop. Let me try to explain it with some code: # models.py class Tweet(models.Model): def __str__(self): return self.tweet_id tweet_id = models.CharField(max_length=25, unique=True) text = models.CharField(max_length=1000) text_search_vector = SearchVectorField(null=True, editable=False) class Meta: indexes = [GinIndex(fields=['text_search_vector'])] I've populated all rows with a search vector and have established a trigger on the database to keep the field up to date. I can't figure out why, but the search vector from the database looks different than the search vector that's generated using the SearchVector class. More importantly, it returns different results. # views.py query = SearchQuery('chance') vector = SearchVector('text') on_the_fly = Tweet.objects.annotate( rank=SearchRank(vector, query) ).filter( rank__gte=0.001 ) from_field = Tweet.objects.annotate( rank=SearchRank(F('text_search_vector'), query) ).filter( rank__gte=0.001 ) # len(on_the_fly) == 32 # len(from_field) == 0 The empty result prompted me to drop into the shell to debug. Here's some output from the shell using python manage.py shell: for tweet in qs: print(f'Doc text: {tweet.text}') print(f'From db: {tweet.text_search_vector}') print(f'From qs: {tweet.vector}\n') # Doc text: @Espngreeny Run your 3rd and long … -
How can I mock a function called from a dictionary?
test.py: @pytest.mark.django_db def test_b_called(mocker): b = mocker.patch('app.service.b') service.a('b') assert b.called service.py: def a(type): _actions[type]() def b(): pass _actions = { 'b': b } My test will fail as my patch does not work as I expected. What am I doing wrong here? This definitely works if a calls b directly and not using that dictionary. I have tested for this. -
API Root doesn't have has_permissions with JWT_Authentication
Trying to implement djangorestframework_simplejwt in accordance with DRF. After implementing everything based on: https://simpleisbetterthancomplex.com/tutorial/2018/12/19/how-to-use-jwt-authentication-with-django-rest-framework.html and when I'm logged in on localhost:8000, the API Root view is unavailable and the error is an attribute error. 'JWTAuthentication' object has no attribute 'has_permission' When I view the ModelViewSets themselves, they appear perfectly fine. It's just the API Root itself. When I logout and try to access the API Root, the page loads perfectly fine returning HTTP 403. Am I not supposed to access the API root when logged in or is there a loophole that I can implement (or extend) in views.py? -
How best to use multiple fields across multiple models?
Let's say I have these models and fields: class User(AbstractBaseUser): name_title name_first name_middle_initial name_last address_1 address_2 address_city address_state address_post_code class Order(models.Model): name_title name_first name_middle_initial name_last address_1 address_2 address_city address_state address_post_code class Shipment(models.Model): address_1 address_2 address_city address_state address_post_code Let's say, too, that none of these models are necessarily related -- an Order doesn't have to belong to a User, a Shipment doesn't have to belong to an Order, etc. I want all of the repeat fields to be identical -- to have the same verbose_name, validations, max_length, etc. I've tried taking a mixin approach: class AddressFieldsMixin(models.Model): address_1 address_2 address_city address_state address_post_code class NameFieldsMixin(models.Model): name_title name_first name_middle_initial name_last class User(AbstractBaseUser, AddressFieldsMixin, NameFieldsMixin): pass class Order(models.Model, AddressFieldsMixin, NameFieldsMixin): pass class Shipment(models.Model, AddressFieldsMixin): pass ...but this leads to model/inheritance collisions if my Mixin classes inherit from models.Model, and "unknown field" errors if they don't. What would be the correct way to re-use the 'name' fields and the 'address' fields across multiple models? Thanks! -
How to send password reset email from django using django-rest-framework and React
I'm creating a website in the backend i'm using (django,django-rest-framework) and frontend (React.js). I'm not clearly understand how do i create restfull api for password reset email. -
How can I pytest mock a function called from a dictionary?
test_service.py: @pytest.mark.django_db def test_some_other_function_called(mocker): cancel_showing = mocker.patch('app.service.some_other_function') service.some_function('some_other') assert some_other_function.called service.py: def some_function(type): _actions[type]() def some_other_function(): pass _actions = { 'some_other': some_other_function } My test will fail as my patch does not work as I expected. What am I doing wrong here? This definitely works if some_function calls some_other_function directly and not using that dictionary. I have tested for this. -
Cannot change URL of Django admin page
I am adding a second Django app to an Ubuntu Intranet application server. I am using Gunicorn/Nginx and both apps are available. However, I am running into problems with the admin pages. I should have changed the admin url for the second app before running it but I forgot, so both apps had the same admin URL. I changed the admin URL of the original app and it is now responding at it's new URL. I did the same for the new app but it was looking in the original app's urls.py so I added a location for it in NGINX/sites-available file. I saw strange behavior in the standard, Django URLconf "can't find URL" error page so I rebooted the server. Now strange behavior is gone, just a NGINX 502 Bad Gateway error. My NGINX set up must be wrong. How can I have admin sites for separate apps on two different URLs? urls.py (second app): urlpatterns = [ path('it-site-admin/', admin.site.urls), path('assets/', include('assets.urls')), path('', RedirectView.as_view(url='/assets/', permanent=True)), ] nginx/sites-available: server { listen 80; server_name server;; location = /favicon.ico { access_log off; log_not_found off; } location /staticfiles/ { root /var/www/.....path to staticfiles; } location / { include proxy_params; proxy_pass http://unix:/var/www/.......path to original … -
Django - Invalid Model Reference, but the model is not referenced
I can't find the source of this error: ValueError: Invalid model reference '......Tickets.models.SeatingGroup'. String model references must be of the form 'app_label.ModelName'. This is appearing after moving these models to a new app and subsequently attempting makemigrations. I've commented out the only Model reference to the SeatingGroup() model, but I'm still getting the same error. I don't see any of my files in the trace. from django.contrib.gis.db import models from django.db import models from Otherlane.UserAuth.models import OLUser TICKET_FEE = .99 TICKET_RESERVATION_LENGTH_IN_MINUTES = 15 class SeatingGroup(models.Model): user = models.ForeignKey(OLUser, on_delete=models.CASCADE) name = models.CharField(max_length=128) seat_index = models.CharField(max_length=1024) qty = models.IntegerField() class Ticket(models.Model): seat = models.CharField(max_length=12) # section = models.ForeignKey(SeatingGroup, on_delete=models.PROTECT) price = models.FloatField() event_instance = models.ForeignKey('Events.EventInstance', on_delete=models.PROTECT) sold = models.BooleanField(default=False) owner = models.ForeignKey(OLUser, null=True, blank=True, on_delete=models.SET_NULL) def __str__(self): return str(self.id) class TicketLock(models.Model): ticket = models.OneToOneField(Ticket, related_name='lock', on_delete=models.CASCADE) user = models.ForeignKey(OLUser, null=True, on_delete=models.CASCADE) session = models.CharField(max_length=32, blank=True, null=True) moment = models.DateTimeField() in_cart = models.BooleanField(default=False) This is the stack trace: (otherlane) C:\Projects\Otherlane>python manage.py makemigrations Traceback (most recent call last): File "C:\Users\Adam\Envs\otherlane\lib\site-packages\django\db\models\utils.py", line 11, in make_model_tuple app_label, model_name = model.split(".") ValueError: too many values to unpack (expected 2) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line … -
How to set the default selection of radio-button group on page load ( Django forms, ChoiceField )
Im trying to do a seemingly simple thing but cannot get this to work. Collection of fields in a Form class assinged ChoiceField class objects. The widget assigned to these ChoiceField is RadioSelect. choices attribute of these objects are assigned one list of value-text pairs. The form displays correctly and is hooked to the database, but I cant get the first radiobutton to be selected by default on page load. on page load there are no buttons selected. There were many questions that seem to be about an issue like this that people have, but none of the suggestions I read worked for me. Tried setting default attribute when the choice field is declared in the Form class, In the view that triggers when form-page url is entered (and handles the form submit), there is a IF ELSE condition that checks if request is 'POST' (or else). Im assuming the issue is at the else part. In the else-condition I have set initial attribute of the form object declared (with dictionary> declared_choicefield_attribute:'Unspecified' - the first default choice I need) In the pair I tried changing the 'Unspecified' to "-6" (-6 is the value of the radio button) and also the … -
Updating page elements immediately on input changes with django and AJAX inside GET request
I want to update elements in the page to tell a user in real-time how many objects will be affected by their choice of criteria in a form. For an example to work with, the form asks for a number and the django logic will delete any model instance with a pk less than that value once the submit button is clicked - but before clicking the user wants to know how many they will be deleting: <span id="number-changed">NULL</span> objects will be deleted so the end result I want is that #number-changed will be populated by a value like MyModel.objects.filter(pk__lt=input_number).count(). I have set up an AJAX call on changes to the input via: $("input").change( function() { $.ajax({ type: "GET", url: "{% url 'myapp:bulkdelete' %}", data: { csrfmiddlewaretoken: $("input[name='csrfmiddlewaretoken']").val(), }, success: function (data) { // code to update #number-changed } I am wondering how I implement in the view so that on successful GET the success function can use the value I retrieve. Some pseudo-code: # views.py class MyView(FormView): # ... def get(self, request, *args, **kwargs): input_number = ??? number_changed = MyModel.objects.filter(pk__lt=input_number).count() # presumably some super().get() call here return ??? Questions: Can I retrieve the current input_number via request or does … -
Django how i choice from template fields for my json
I want in my template to make a select multiple in which I select what fields I want to contain my JSON. How can I do that? I don`t have for the moment any source code. First step I must to think. Any advices? -
How to deploy Django asgi project to Heroku?
When I try to deploy to Heroku the build succeeds but it fails to work. In the Heroku logs --tail I get: Process exited with status 127 bash: daphne: command not found I tried finding the Daphne install directory but couldn't. My Procfile contains: web: daphne chatapp.asgi:channel_layer --port $PORT --bind 0.0.0.0 -v2 chatworker: python manage.py runworker -v2 In my settings.py for the CHANNEL_LAYERS I have: CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [os.environ.get('REDIS_URL', 6379)], }, }, } In my asgi.py file I have: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "chatapp.settings") django.setup() application = get_default_application() channel_layer = get_channel_layer() -
Django inline model: can I apply a different css to the header?
Django 2.2 I have inline mode which works fine as described here. Both main model and inline model are susing default Django templates, nothing is custom yet. I also have defined verbose_name_plural for it which shows as the header to the inline model table. My question is: is there a way to apply a css class to the header text class SomeForeignKeyInline(admin.TabularInline): model = SomeForeignKey verbose_name_plural = "My Header Text" #works css = "<some_css_class_I_want_to_apply_to_header_text>" I did not find anything reading this: Django docs on inline models Thanks -
Sending the logged on username to Sentry in Django
Trying to send the logged on username to Sentry. If hard coded in settings, I get the expected result on the Sentry dashboard. However I can't set the username in settings. #settings.py from sentry_sdk import configure_scope with configure_scope() as scope: scope.user = {"username": "Joe Soap"} So I am not sure where I should be doing this: with configure_scope() as scope: scope.user = {"username": request.user.username} I have tried my landing view and login view. But just get my IP Address back on the sentry dashboard. #views.py @login_required def landing(request): context={} with configure_scope() as scope: scope.user = {"username": request.user.username} return render(request,'paysched/landing.html',context) Python and Django are not my home language, so my questions really are A) can I do this? B) and if so, where/how. Thanks in advance for any assistance on this. -
Django ListVIew redirect if model has no records
I have built a class PlayerListView which uses class ListView for generic display of views. class PlayerListView(LoginRequiredMixin, ListView): model = PlayerSeason template_name = 'squad/players_list.html' context_object_name = 'players' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['test'] = 'test' context['season_name'] = PlayerSeason.objects.first().season.season_name return context Normally if there are no records for the PlayerSeason model, the template display html code with zero data to display. But as my template also needs additional data, I needed to put it in 'context' using get_context_data(). context['season_name'] = PlayerSeason.objects.first().season.season_name The problem occurs when there are no records for PlayerSeason and I want to set the context data for season_name. It checks for the fields in the relation field 'season'. Because it does not exist, it returns error: AttributeError: 'NoneType' object has no attribute (logical). What I want to avoid any errors is to redirect to the url for insertion of PlayerSeason records (lets say: '/create/playerseason'. One of the solutions I tried was checking that in the get() method if PlayerSeason.objects.count(): season_name = PlayerSeason.objects.first().season.season_name else: return redirect('blog-home') What is the correct/elegant solution in this case? -
I created registration form through django forms.But its not rendring?
I am trying to create blog app with django.I created registration form with django forms.In official django documentation for get request the code is form.classname().I also coded in that way.But its returning register() missing 1 required positional argument: 'request'? from django import forms class register(forms.Form): Email = forms.EmailField(required=True) Username = forms.CharField(label='Username', max_length=100,required=True) Password = forms.CharField(widget=forms.PasswordInput(),required=True) Confirm_Password = forms.CharField(widget=forms.PasswordInput(),required=True) views.py def register(request): if request.method == "POST": form = register(request.POST) email = form.cleaned_data['email'] User_name=form.cleaned_data['User_name'] Password1=form.cleaned_data['Password1'] Password2=form.cleaned_data['Password2'] if form.is_valid(): if User.objects.filter(username=User_name).exists(): messages.info(request,'Username Taken') return redirect('register') elif User.objects.filter(email=email).exists(): messages.info(request,'Email Taken') return redirect('register') else: user = User.objects.create_user(username=User_name, password=Password1,email=email) user.save(); return redirect('/') else: messages.info(request,'Password Not Matching') else: form = register() return render(request,'register.html',{'form': form}) models.py from django.db import models from django.conf import settings # Create your models here. class Post(models.Model): title=models.CharField(max_length=100) desc=models.TextField() date=models.DateField(auto_now=True) author=models.ForeignKey(settings.AUTH_USER_MODEL, to_field="username",on_delete=models.CASCADE) Showing error:register() missing 1 required positional argument: 'request' -
Django: AttributeError: module 'todo.views' has no attribute 'delete_item'
I'm trying to make a to-do app with Django. Users can add an item and now I'm trying to implement the functionality for deleting an item. When defining the view to delete an item I get his error: AttributeError: module 'todo.views' has no attribute 'delete_item'. I checked many forums and videos and to me the code seems right. Any suggestions please? Thank you. Models: from django.db import models class TodoItem(models.Model): content = models.TextField() Views: from django.shortcuts import render, redirect from .models import TodoItem from .forms import ItemForm def delete_item(request, todo_id): item = TodoItem.objects.get(pk=todo_id) item.delete() URLs: from django.urls import path from django.views.generic import TemplateView from . import views path('delete/<todo_id>/', views.delete_item, name='delete_item') HTML: <a href="{% url 'delete_item' things.id %}"> <button class="button is-danger is-outlined">Delete</button> </a> the error message I get when I run the server: AttributeError: module 'todo.views' has no attribute 'delete_item' -
com_error "Server execution failed" for Dispatch("Photoshop.Application")
I use win32com.client.Dispatch to manage Photoshop on a Windows server, I configured the address to connect to this server and now when I send a request from my local machine to the server, win32com.client.Dispatch gets com_error (-2146959355, 'Server execution failed', None, None) When it tried to use Dispatch("Photoshop.Application"). Everything works fine on the server itself without any problem with Dispatch. (This is all used to change layers in a psd file) I have got another com_error before (-2147024891, 'Access is denied.', None, None), but fixed this problem with the help of this Code that generates error app = Dispatch("Photoshop.Application") Photoshop location: "C:\Program Files\Adobe\Adobe Photoshop CC 2015" Help please! -
Dismissing a partially filled out form in ModelFormSet with a ManytoMany field
I have a Modelformset that contains a manytomany field. The M2M field, is rendered as a ModelMultipleChoiceField. The whole thing runs fine when all forms are filled out. In short, the only user input I receive are from the checkboxes on each form of the formset. There are other fields but they are pre-filled with user data. I want to save the forms where a checkbox was selected and ignore the form that none are selected from. I was able to get the partially filled forms to pass validation so all forms are saved but I'm having a hard time writing the test that would discard the partially filled (the form that no checkboxes we're selected from) form. Models.py customer_id = models.ForeignKey(CustomerDB, on_delete=models.CASCADE, default=None) services_manytomany = models.ManyToManyField(ContractorServices, blank=True) class ContractorServices(models.Model): service_parent = models.ForeignKey(User, on_delete=models.CASCADE, default=None) service_name = models.CharField(max_length=150, null=True, blank=True) archive = models.BooleanField(default=False, null=True) def __str__(self): return self.service_name forms.py services_manytomany = forms.ModelMultipleChoiceField( widget=forms.CheckboxSelectMultiple, queryset=ContractorServices.objects.all() ) def __init__(self, user, *args, **kwargs): super(AddJob, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_show_labels = False self.helper.form_show_errors = True self.helper.form_tag = False self.fields['services_manytomany'].required = False if user is not None: self.fields['services_manytomany'].queryset = ContractorServices.objects.filter(service_parent=user) class Meta: model = Jobs_DB fields = {'services_manytomany', 'frequency'} Relevant view.py code formset = … -
Python: .pop behaves different between same and different line
Can someone explain to me why these two code snippets behave differently? Here I get the expected output {datetime.date(2019, 6, 18): 12300} events_sales_gross_last_7_days = events_sales_gross_last_7_days_incl_today.get(event.pk, {}) events_sales_gross_last_7_days.pop(timezone.now().date(), 0) print(events_sales_gross_last_7_days) The next snippet however only gives me back 'int' object has no attribute 'get'. events_sales_gross_last_7_days = events_sales_gross_last_7_days_incl_today.get(event.pk, {}).pop(timezone.now().date(), 0) print(events_sales_gross_last_7_days) -
Django admin area causing Server Error (500) when logging in
I made a django application which I'm trying to deploy. It's a very small website on my home network on a Raspberry Pi. I have a domain pointed to the IP. When I set DEBUG to False and try to log into the admin area, it causes a "Server Error (500)". My settings.py ALLOWED_HOSTS = ["my domain", "my ip", "localhost", "127.0.0.1"] I am able to use the website and log view it remotely. Even when i put "*" it dos not work. -
Django view only renders first URL
I have the following code in my Django applicaton: View.py def Chart(request): #fusionchart code return render(request, 'dash.html', {'output' : column2D.render(),'output2' : doughnut3d.render(),'output3' : area2D.render()}) def view_name(request): #calculation code return render(request, 'dash.html', {'today': today}) def default_map(request): #map built code return render(request, 'dash.html', { 'mapbox_access_token': mapbox_access_token }) url.py urlpatterns = [ url(r'^$', views.Chart, name = 'Chart'), url(r'^$', views.view_name, name = 'view_name'), url(r'^$', views.default_map, name="default"), ] The issue that I am currently having is that the urlpatterns only show/render what is done in the first def (in this case def Chart) and skip the other two defs. How can I make sure that Django takes into account all three defs and renders all three of them on the same page? -
Django-Rest-Framework CreateAPIView not working
I am trying to implement a simple viewset from django-rest-framework, everything is working OK except for the Create view. The ulr (http://127.0.0.1:8000/api/create/) is loaded with the form to input data but when I hit PUT the data is not loaded in database. Terminal shows the following error: [19/Jun/2019 14:15:29] "GET /api/create/ HTTP/1.1" 404 10318 Not Found: /api/create/ I am following this tutorial to learn to integrate django and react. I've previously tried to implement CRUD views separately but got a circular reference error. I suppose there must be some sort of error with url definitions but I just can't figure out what is wrong. API urls.py: from articles.api.views import ArticleViewSet from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r'', ArticleViewSet, base_name='articles') urlpatterns = router.urls API views.py: from rest_framework import viewsets from articles.models import Article from .serializers import ArticleSerializer class ArticleViewSet(viewsets.ModelViewSet): serializer_class = ArticleSerializer queryset = Article.objects.all() API serializer: from rest_framework import serializers from articles.models import Article class ArticleSerializer(serializers.ModelSerializer): class Meta: model = Article fields = ('id', 'title', 'content') Project urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls')), path('api/', include('articles.api.urls')), ] With this code, when I access the List view the form to …