Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Passing List to Manytomany field in APIVIew having error "Incorrect type. Expected pk value, received str."
I made APIs to create update case But the problem is with task if I pass only one pk like(task=1) while updating or creating through postman then it works fine and case will be created with referencing that task but a task is a manytomany field I need to assign multiple task pk to a case like task = [1,2] Then it is giving error like "Incorrect type. Expected pk value, received str." ] class Case(models.Model): name = models.CharField(max_length=200) task = models.ManyToManyField('task.Task',blank=True, null=True) assigned_to = models.ForeignKey("account.User",null=True, blank=True, on_delete=models.SET_NULL) class CaseSerializer(serializers.ModelSerializer): class Meta: model = Case fields = ('id', 'name', 'task', 'assigned_to') -
How I can create category and subgategory in Django
I am new to Django and I know how to implement theme and pages in Django but now I want to add category and subcategory in my projects, if a user clicks on subcategory then he can see a new page where he can check all the information related to subcategory service. Please let me guide how I can create these features on my website. I have already install Django and created an admin panel. -
Overriding PasswordChangeView
I'm trying to override the PasswordChangeView in Django Allauth. I'd like to implement everything, except override the template name. However, I'm having a hard time with the render_to_response method, it keeps redirecting to the old /password/set/ template. Here's how my method looks like: class PasswordSettings(PasswordChangeView): template_name = 'oauth/password-change.html' success_url = reverse_lazy('oauth:password-settings') def render_to_response(self, context, **response_kwargs): return super().render_to_response( context, **response_kwargs) What am I doing wrong? Why can't it redirect correctly to my template? Here's the source code: https://github.com/pennersr/django-allauth/blob/master/allauth/account/views.py -
How to return pagination with djando framework?
How to return pagination with djando framework? I'm trying to use the class LimitOffsetPagination. Where am I going wrong? Thank you guys class Sellers(APIView): pagination_class = LimitOffsetPagination def get(self, request): transactions = Transactions.objects.all() page = self.paginate_queryset(transactions, request) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(transactions, many=True) return Response(serializer.data) page = self.paginate_queryset(transactions, request) AttributeError: 'Sellers' object has no attribute 'paginate_queryset' -
How to make the number of range working in generator
How to make this range working in function. Whenever I limit n, it gives every result without limit. def generator(f, n, *args, **kwargs): return [f(*args, **kwargs) for __ in range(n)] -
'list' object has no attribute 'filter'
def g_view(request): header_category = Category.objects.all() m = Type1.objects.all() r=Type2.objects.all() g=Type3.objects.all() from itertools import chain orders=list(sorted(chain(m,r,g),key=lambda objects:objects.start)) mquery = request.GET.get('m') if mquery: orders = orders.filter( Q(name__icontains=mquery) | Q(game__name__icontains=mquery) | Q(teams__name__icontains=mquery)).distinct() (Type is abstract and type1 type2 type3 are inherited classes) I got this error 'list' object has no attribute 'filter' -
html doc not using external css style sheet
I am starting to learn CSS and after trying to implement an external stylesheet, i found I was unable to change the color of my html document. I am using Visual Studio Code and my html templates are using Djangos inheritance. I have tried double checking that everything is saved, I have checked spelling for the href, and i even restarted VSC. So far nothing. Here is the base html sheet <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> {% block style %} {% endblock %} <title> {% block title %} {% endblock %} </title> </head> <body> {% block content %} {% endblock %} </body> </html> Here is an html sheet that should use the styling: {% extends 'student_view_base.html' %} {% block title %} Socrates Home Page {% endblock %} {% block style %} <link rel="stylesheet" type="text/css" href="css/sidebar.css"> {% endblock %} {% block content %} <h1>Socrates Home Page</h1> <div> <a href="{% url 'login' %}">Login</a> </div> <a href="{% url 'admin:index' %}">Admin Login</a> {% endblock %} Here is the css sheet: h1{ color: blue; } As you can tell, I am pretty new to Web Dev in general and this was mostly to experiment and make sure I could implement it properly. As … -
folium map not displaying on django page
I am reading data from postgressql to get a dataset of latitude, longitude and name of a jpeg file. I'm iterating through the dataset to create markers on a map. I'm not getting an error message, but the map does not display. I'm displaying data on the index.html page. I'm using iframe to display map.html. I've read a number of threads on the subject, but none of the answers are working for me. views.py: from django.shortcuts import render from django.http import HttpResponse from .models import PhotoInfo import folium # Create your views here. def index(request): VarPhotoInfo = PhotoInfo.objects.order_by('DateTaken') context = {'PhotoInfo': VarPhotoInfo } return render(request,'natureapp/index.html',context) def show_map(request): PhotoInfo1 = PhotoInfo.objects.order_by('DateTaken') m = folium.Map([33.571345, -117.763265], zoom_start=10) test = folium.Html('<b>Hello world</b>', script=True) popup = folium.Popup(test, max_width=2650) folium.RegularPolygonMarker(location=[33.571345, -117.763265], popup=popup).add_to(m) fg = folium.FeatureGroup(name = "MyMap") for i in PhotoInfo1: fg.add_child(folium.Marker(location=(float(i.Lat),float(i.Long)),popup = str(i.DateTaken) +' file: '+ i.PhotoName, icon = folium.Icon(color='green'))) m.add_child(fg) m.get_root().render() context = {'MyMap': m} return render(request, 'natureapp/map.html', context) map.html: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>NatureMapper</title> </head> <h1>Map goes here </h1> {{ my_map.render }} </html> index.html: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>NatureMapper</title> </head> <h1>Here it is! </h1> {% if PhotoInfo %} {% for Photo in PhotoInfo %} <p>there is info.</p> <p> … -
UserCreationForm KeyError 'email' in Registration page
Im learning django and im trying to understand the registration progress with an UserCreationForm and a CreateView, I want to use an email as field on the registration form but they keep poping an error about KeyError 'email' on my form. forms.py from django import forms from accountApp.models import Profile from django.contrib.auth import get_user_model from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserForm(forms.ModelForm): class Meta: model = User fields = ('username','first_name', 'last_name', 'email') class CreateUserForm(UserCreationForm): fields = ('username', 'email', 'password1', 'password2') model = get_user_model() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['username'].label = 'Usuario' self.fields['email'].label = 'Email' views.py from django.urls import reverse, reverse_lazy from . import forms class RegistrationPage(CreateView): template_name = 'accountApp/register.html' success_url = reverse_lazy('accApp:profilepage') form_class = forms.CreateUserForm models.py from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) def __str__(self): return self.user.username -
How to query a query using date field inside a metadata of type JSONField?
How to query a query using date field inside a metadata of type JSONField? In the field metadata of my line contains the following content [ { "id": "57400265c48f4ae16ea6f719bb360", "method": { "id": "be32754f6c3643c49c308a4526646", "expiration_date": "2019-06-12T00:00:00+00:00", "accepted": false, "printed": false, "downloaded": false, "created_at": "2019-06-12T11:49:00+00:00", "updated_at": "2019-06-12T14:48:59+00:00" }] I tried to use a query with range to return values of data between two dates. Transac.objects.filter(id=request.user.id, metadata__method__expiration_date__range=(datetime.date(2019, 7, 1), datetime.date(2019, 7, 30)) ) I also tried using the gte Transac.objects.filter(id=request.user.id, metadata__method__expiration_date__gte=datetime.date(2019, 6, 1) ) Nothing worked. The error follows. TypeError: Object of type 'date' is not JSON serializable If anyone can help, I'm very grateful. -
Django : How to link model one objects with model two in form?
I trying to link one model objects with other model in forms but ending up with invalid form Models.py: class Patient(models.Model): name = models.CharField(max_length=200); phone = models.CharField(max_length=20); address = models.TextField(); Patient_id = models.AutoField(primary_key=True); Gender= models.CharField(choices=GENDER,max_length=10) consultant = models.CharField(choices=CONSULTANT,max_length=20) def __str__(self): return self.name class Rooms(models.Model): name = models.CharField(max_length=200) room_num = models.IntegerField() def __str__(self): return str(self.name) class Ipd(models.Model): reason_admission = models.CharField(max_length=200, blank=False) presenting_complaints = models.CharField(max_length=200,) ipd_id = models.AutoField(primary_key=True) rooms = models.OneToOneField(Rooms,on_delete=models.CASCADE, blank=False) investigation = models.CharField(max_length=300) patient = models.ForeignKey(Patient,on_delete=models.CASCADE,null = False) Forms.py: from .models import Patient,Ipd class PatientForm(forms.ModelForm): class Meta: model = Patient fields = ['name','phone','address','Patient_id','consultant','Gender'] class IpdForm(ModelForm): class Meta: model = Ipd fields = ['patient','reason_admission','presenting_complaints', 'rooms','investigation'] views.py: @login_required def ipd (request,patient_id): patient = Patient.objects.get(pk=patient_id) if request.POST: data = dict(request.POST) data['patient']=Patient.Patient_id formtwo = IpdForm(request.POST) if formtwo.is_valid(): if formtwo.save(): return redirect('/', messages.success(request, 'Patient is successfully updated.', 'alert-success')) else: return redirect('/', messages.error(request, 'Data is not saved', 'alert-danger')) else: return redirect('/', messages.error(request, 'Form is not valid', 'alert-danger')) else: formtwo = IpdForm(request.POST) return render(request, 'newipd.html', {'form2':formtwo ,'form':patient}) i have Patient model that is used to create patient , and Ipd model which takes additional information from Patient before getiing admitted. so i am trying to link Ipd model with Patient to create New Ipd List -
AttributeError at /map creating folium map in Django
I am reading gps coordinates from a postgressql database, and I am using folium to create a map. I use iframe to embed the map in index.html. The data is being read and displayed in index.html, but the embedded map.html throws an error saying ''QuerySet' object has no attribute 'Lat'' - but my recordset does have a field called Lat and I use it in index.html I am displaying the data (latitude, longitude, a picture taken at those coordinates) in index.html. I've created a model and have data in a postgressql database. I created a function in views.py where I'm looping through the dataset to create markers in a folium map. Then I'm using iframe to embed it in an index.html views.py from django.shortcuts import render from django.http import HttpResponse from .models import PhotoInfo import folium # Create your views here. def index(request): VarPhotoInfo = PhotoInfo.objects.order_by('DateTaken') context = {'PhotoInfo': VarPhotoInfo } return render(request,'natureapp/index.html',context) def show_map(request): #creation of map comes here + business logic PhotoInfo1 = PhotoInfo.objects.order_by('DateTaken') m = folium.Map([33.571345, -117.763265], zoom_start=10) test = folium.Html('<b>Hello world</b>', script=True) popup = folium.Popup(test, max_width=2650) folium.RegularPolygonMarker(location=[33.571345, -117.763265], popup=popup).add_to(m) fg = folium.FeatureGroup(name = "MyMap") for lt, ln, el, fn in zip(PhotoInfo1.Lat,PhotoInfo1.Lon, PhotoInfo1.DateTaken, PhotoInfo1.PhotoName): fg.add_child(folium.Marker(location={float(lt),float(ln)},popup = str(el) … -
Django - Forbidden (CSRF token missing or incorrect.)
I have a problem with creating a simple form that uses {% csrf_token%}. Template with form: <form action="{% url 'library:my_view' %}" method="post"> {% csrf_token %} <input type="submit" value="Submit"> </form> urls.py urlpatterns = [ # ... path('some_page', views.my_view, name='my_view'), ] views.py #... def my_view(request): used_method = str(request.method) return render(request, 'library/some_template.html', {'test': used_method}) Template with result (some_template.html): {{test}} The server gives me the message: Forbidden (CSRF token missing or incorrect.): / Library / some_page "POST / library / some_page HTTP / 1.1" 403 2513 or (when i use a different browser): Forbidden (CSRF cookie not set.): /library/some_page "POST /library/some_page HTTP/1.1" 403 2868 The form works correctly when I disable protection (@csrf_exempt before the view). Where is a problem? I will be grateful for any help. -
How to POST variables js to Django
I have 3 variables in js. I need post to views.py I use Python 2.7 and django 1.11 i try with ajax but i dont understand. <head> <meta charset="UTF-8"> <title>Prueba de actualización de forma</title> <script type="text/javascript"> function addEvidence(form) { idAlumno = document.getElementById('idAlumno').value; competencia = document.getElementById('Competencia').value; var radios = document.getElementsByName('Calificacion'); for (var i = 0, length = radios.length; i < length; i++) { if (radios[i].checked) { calificacion = radios[i].value break; } } alert(idAlumno + " " + competencia + " " + calificacion); } </script> </head> views.py def Evidences(request, idAlumno,competencia,calificacion): return render(request, 'resultados_app/resultados.html') i need post idAlumno, competencia and calificacion but i dont know -
How to assert the user is logout in django.test.TestCase?
I'm new to Django and now I'm strugging writing test code. In a test case I want to check if the user is logout successfully. Then how can I write assert? Below is the tiny sample code. from django.test import TestCase class TestLogin(TestCase): fixtures = ['myuserdata.json'] @classmethod def setUpClass(cls): super().setUpClass() def setUp(self): self.USER_ADMIN = { 'email': "foo1@bar.com", 'password': "foobar1234", } self.USER_PLAIN = { 'email': "foo2@bar.com", 'password': "foobar1234", } def test_login_success(self): login_result = self.client.login( email=self.USER_ADMIN['email'], password=self.USER_ADMIN['password'], ) self.assertTrue(login_result) login_result = self.client.login( email=self.USER_PLAIN['email'], password=self.USER_PLAIN['password'], ) self.assertTrue(login_result) self.client.logout() # self.assertFoobar(???) def tearDown(self): pass #... -
How to fix upload file from angular 7 to djago rest
I'have rest api devlopped with djago and application front devlopped with agular7 and i try to upload image to my rest api when i try to send it with form data the form data is empty in the api. for angular i try to send form data with file. Angular: getPredictionImage(file): Observable<any> { const HttpUploadOptions = { headers: new HttpHeaders({ 'Content-Type': 'multipart/form-data'}) } const f = new FormData(); f.append('image', file, file.name); console.log(f); return this.http.post(this.urlapiimage, file, HttpUploadOptions); } Django: def post(self, request, format=None): print("heloooo") print(request.data) serializer = MammographySerializer(data=request.data) print(serializer) if serializer.is_valid(): result='hi' serializer.save() return Response(result,status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) the request.data is empty -
What is the difference between these two methods of serving static files in Django?
I have a Django app that uses different static files such as images, css files, and js files. That being said, the documentation https://docs.djangoproject.com/en/2.2/howto/static-files/ shows two different ways to serve static files, and I've also seen developers follow both methods. I'm currently doing it like this: #settings.py STATIC_URL = '/static/' # whatever.html {% load static %} <img src="{% static "my_app/example.jpg" %}" alt="My image"> With all my images inside the same folder as my main.css file. But I've also seen developers following the second method of the documentation: #settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' #urls.py from django.conf import settings from django.conf.urls.static import static urlpatterns = [ # ... the rest of your URLconf goes here ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) When using the second method, they'll have a different folder called media that is located at the same level as all main apps. Supposedly I'd leave my images in there. I'm wondering if it's okay to follow the first method (using {% load static %}) which is what I'm doing, and what the difference between the two methods is. Thank you! -
How does one create a Factory with foreign key instances that share certain attributes - but that attribute does not exist on parent?
I'm looking to use FactoryBoy to ensure that a model with foreign keys to other models that indirectly share foreign keys are generated with the same instances (I realize that’s pretty hard to grok, here’s a code example): from django.db import models import factory class Foo(models.Model): name = models.CharField(max_length=32) class Bar(models.Model): foo = models.ForeignKey(Foo, on_delete=models.PROTECT) class Baz(models.Model): foo = models.ForeignKey(Foo, on_delete=models.PROTECT) class HasBarAndBaz(models.Model): bar = models.ForeignKey(Bar, on_delete=models.PROTECT) baz = models.ForeignKey(Baz, on_delete=models.PROTECT) class HasBarAndBazFactory(factory.django.DjangoModelFactory): class Meta: model = HasBarAndBaz bar = factory.SubFactory(BarFactory) baz = factory.SubFactory(BazFactory) The desire here would be to ensure that the following occurs has_bar_and_baz = HasBarAndBazFactory() has_bar_and_baz.bar.foo === has_bar_and_baz.baz.foo # should be True I can think of a couple solutions, but I’m curious to know if there’s a “FactoryBoy” way to do this, without needing to write a wrapper function that accepts a product_line kwarg and passes it. I thought about using a RelatedFactory, and then referencing that as the default foo kwarg to the SubFactories, but a RelatedFactory gets generated after the base factory. -
Filling MS Word Template from Django
I found some python docs relating to docxtpl at this link: https://docxtpl.readthedocs.io/en/latest/ I followed the instruction and entered the code found at this site into a view and created the associated URL. When I go to the URL I would like for a doc to be generated - but I get an error that no HTTP response is being returned. I understand I am not defining one, but I am a bit confused about what HTTP response I need to define (I am still very new to this). The MS word template that I have saved is titled 'template.docx'. Any help would be greatly appreciated! VIEWS.PY def doc_test(request): doc = DocxTemplate("template.docx") context = { 'ultimate_consignee' : "World company" } doc.render(context) doc.save("generated_doc.docx") I would like accessing this view to generate the doc, where the variables are filled with what is defined in the context above. -
{% load static %} Shown as a text line in html opened on browser
Im trying to use templatetags, but when i write {% load static %} on top of html document and run, it takes this as a text, and does not load the static. I set the static config in settings.py but stills not working {% load static%} <!DOCTYPE html> <html> ... </html> when i open the file on browser or when i send the template via email, as expected in the proyect, the css works, but the images doesnt. I realized i'd use the static dir, but the line: {% load static %} is shown in the browser as text. -
Invalid credentials raises exception on auth mutation
I'm using graphene-django and django-graphql-jwt in my django project. When I set invalid credentials server raises 'Invalid credentials' exception. Are invalid credentials supposed to raise an exception on the server? When I test tokenAuth mutation with wrong data Django server raises exception. Django server log: File "/Users/cgf/.local/share/virtualenvs/testdjangoauthbackend-183R1gMP/lib/python3.7/site-packages/promise/promise.py", line 487, in _resolve_from_executor executor(resolve, reject) File "/Users/cgf/.local/share/virtualenvs/testdjangoauthbackend-183R1gMP/lib/python3.7/site-packages/promise/promise.py", line 754, in executor return resolve(f(*args, **kwargs)) File "/Users/cgf/.local/share/virtualenvs/testdjangoauthbackend-183R1gMP/lib/python3.7/site-packages/graphql/execution/middleware.py", line 75, in make_it_promise return next(*args, **kwargs) File "/Users/cgf/.local/share/virtualenvs/testdjangoauthbackend-183R1gMP/lib/python3.7/site-packages/graphql_jwt/decorators.py", line 106, in wrapper result = f(cls, root, info, **kwargs) File "/Users/cgf/.local/share/virtualenvs/testdjangoauthbackend-183R1gMP/lib/python3.7/site-packages/graphql_jwt/decorators.py", line 89, in wrapper _('Please, enter valid credentials')) graphql.error.located_error.GraphQLLocatedError: Please, enter valid credentials -
Channels 2 uWSGI/Daphne/Workers configuration
Trying to get a uWSGI ini file to bring up Channels 2 properly. Channels 1, looked like: attach-daemon = %(release)/env/bin/daphne -u /opt/sock.ws --ws-protocol "graphql-ws" --proxy-headers -v 1 asgi:channel_layer attach-daemon = %(release)/env/bin/python manage.py runworker --thread=2 --only-channels=websocket.* With Channels 2, I tried: attach-daemon = %(release)/env/bin/daphne -u /opt/sock.ws --ws-protocol "graphql-ws" --proxy-headers -v 1 asgi:channel_layer attach-daemon = %(release)/env/bin/python manage.py runworker websocket Of course asgi:channel_layer now points to the application as I've fixed up asgi.py, but it seems the workers never seem to receive the messages (websocket is of course the name of my route) Any ideas? -
Why is Django app redirect_uri = 'web' and not my domain?
I'm setting up Oauth sign in on my django web app and am getting a redirect_uri error because my django app is using 'web' instead of my domain. How can I change the redirect uri of my django app? I think it has to do with nginx and my configuration file but I'm not too sure what to change. Here's my mydjango.conf file: upstream web { ip_hash; server web:8000; } server { location /static/ { autoindex on; alias /src/static/; } location / { proxy_pass http://web/; } listen 8000; server_name localhost; client_max_body_size 1000M; } For slack authentication, expecting the passed URI to be http://[my domain]/accounts/slack/login/callback/ but instead am getting http://web/accounts/slack/login/callback/ -
django messages after dataframe export to excel
I have a Django view that perform a long qry in the back-end. Once the qry result is available, it exports the data to a csv file. I am using this logic, which is working fine: response = HttpResponse(content_type='text/csv') # Format response as a CSV filename = 'some_file_name' + '.csv' response['Content-Disposition'] = 'attachment; filename="' + filename + '"' # Name the CSV response df.to_csv(response, encoding='utf-8', index=False) return response I need to add a response message that displays on the current page without needing to refresh the page: for that I have the following: if df is None or df.shape[0] ==0: messages.warning(request, 'failure message.') else: messages.success(request, 'success message.') and in the html I have: {% if messages %} <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %} id="export_messages">{{ message }}</li> {% endfor %} </ul> {% endif %} The problem that I am facing is that the message appears only if I refresh the page after export button is clicked and the file is successfully exported. I am looking for an advise or guidance how to make the message appears right after the button click event. Please note that the action is a form … -
TypeError: getattr() takes no keyword arguments
here my models.py @python_2_unicode_compatible class TaggedItem(models.Model): content_type = models.ForeignKey( ContentType, related_name=getattr( settings, 'USER_TAGS_RELATED_NAME', 'user_tags_tagged_items', on_delete=models.CASCADE), ) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') user_tags = models.ManyToManyField( 'user_tags.UserTag', verbose_name=_('User tag'), ) def __str__(self): return str(self.content_object)