Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to get user latitude and longtitude
How to get users latitude and longtitude whenever click button Upload i want to autofill latitude and longtitude in models.py and stored in my database. How to solve this. strong text''' models.py enter code here class Raportimet(models.Model): latitude = models.CharField(max_length=200) longitude = models.CharField(max_length=200) data = models.DateTimeField(auto_now_add=True) photo = models.ImageField(upload_to='images/') ` -
Postgres has a lot of activity going on despite me not doing anything
I am running a local development server. I am working on the project until it is ready for deployment. I checked the postgres admin page and I noticed that I have a lot of transactions running in the background. I am not using the site/making queries, and am wondering what is causing this. (I am also the only user) Why is this? -
creating datetimefield without timezone
I need to create datetimefield without timezone, and I need that to be applied on postgres when the tables are created. I did set the USE_TZ = False. But still the field is created with timezone on postgresql. When I printed the value in django it has no timezone. But when store it does submitted_timestamp = models.DateTimeField(default=now) also I tried from django.utils.timezone import now submitted_timestamp = models.DateTimeField(auto_now_add=True) on the setting USE_TZ = False when I check the table, the column the column is with time zone. I deleted the database and recreated it 3 times and still same Any suggestion? -
keyerror in formset form field
i am making delivery note transiction form, i have created formset in which i wanted to django ignore item transiction in which item is not selectd and is empty forms.py class Delivery_note_transiction_form(forms.Form): item = forms.CharField(widget=Select2Widget(attrs={"class" : "item"}),label=False,required=False) description = forms.CharField(widget=forms.TextInput(attrs={ 'placeholder' : 'optionall','class' : 'description'}),label=False,required=False) quantity = forms.IntegerField(widget=forms.NumberInput(attrs={'class' : 'quantity'}),label=False,min_value=1) id = forms.CharField(widget=forms.HiddenInput,required=False) Delivery_note_transiction_form_formset = forms.formset_factory(Delivery_note_transiction_form,extra=1) views.py def feedback(request): if request.method == "POST" and request.is_ajax(): form = Deliver_Note_Main_Modelform(request.POST) formset = Delivery_note_transiction_form_formset(request.POST,request.FILES) if form.is_valid() and formset.is_valid(): ins = form.save(commit=False) ins.author = request.user result = Customer_data.objects.get(pk=form.cleaned_data['customer']) ins.customer_list = result ins.save() max_invoice = Invoice_max.objects.get(invoice_name='delivery') max_invoice.invoice_no = max_invoice.invoice_no + 1 max_invoice.save() print(formset) for instant in formset: if instant.cleaned_data['item']: item = Product.objects.get(pk=instant.cleaned_data['item']) description = instant.cleaned_data['description'] quantity = instant.cleaned_data['quantity'] Delivery_Note_Transiction.objects.create( item=item, description=description, quantity=quantity, delivery_invoice_no=ins ) return JsonResponse({'success':True, 'next' : reverse_lazy('delivery note:delivery note home page')}) else: return render(request,"delivery_note/ajax/delivery note error message.html",{"error" : form, "transiction_error": formset}) return HttpResponse("Hello from feedback!") template.html {% for delivery in delivery_transiction %} <tr class=" delivery_form "> <td class="col-sm-4">{{ delivery.item|as_crispy_field }}</td> <td class="col-sm-4">{{ delivery.description|as_crispy_field }}</td> <td class="col-sm-4">{{ delivery.quantity|as_crispy_field }}</td> </tr> {% endfor %} post data is sending by ajax and select option is created on template when it is load new row is added by ajax the problem is i want to it ignore … -
Changing the date format from JSON data
I'm currently trying to teach myself Django and I'm a little confused on how to modify data from a web API. For example I request an api with a url: api.example.com/events?location=.... And I get JSON data {'data': [ { 'name': 'blah' 'date': '2019-03-22' }, { 'name': 'blah2' 'date': '2019-03-23' }, ] } The date is outputted as "yyyy-mm-dd" and I want to change it to "mm dd yyyy". Would I have to put the JSON data into a model? If so, how would I go about doing so? -
How do I return a class-based view method with super from a function within that very same class-based view method?
Is it even possible? I can't find anything or figure it out by myself since I'm a beginner, so I turn to you guys. Here's an example (don't worry about the use case, I just want to know if it's possible and how): When I run this code I get that *args is not defined. What's wrong? views.py: class MyCreateView(CreateView): def get(self, request, *args, **kwargs): slug = kwargs['slug'] helper_method(self, slug) helpers.py: def helper_method(self, slug): if slug == "random": return super(self.__class__, self).get(request, *args, **kwargs) -
Python Django working with multiple database simultaneously
I'm still a noon Django developer.kindly excuse the silly. I've been trying to add in a functionality to my already existing Django application. Currently my application only services multiple users belonging to an organization. I'm trying to accomplish a task where in: 1. Multiple organizations can work with my application by having separate database. This way organization specific data is private to individual organization. 2. For every organization that wants to subscribe to the web app services, the web app shall use a database template to create the database for. The new organization and commission it. 3. The web app should handle/service all organizations simultaneously. Is this possible? I have tried performing multiple research. Unfortunately, I have not gotten any substantial breakthrough. Any kind of help is much appreciated. Cheers! -
Use django-filters on multiple models
I'm trying to create a search capability in my Django project that will filter multiple models (currently 3). It worked great for one model, worked when I added a second, but when I tried to add a dropdown menu for the third model, I got an error saying they keyword was unavailable (because it wasn't looking in the model): Cannot resolve keyword 'rooms' into field. Choices are: DateBegin, FAN, IS, Location, PI, holdings, id Models: #models.py class rooms(models.Model): ContainerLocation = models.CharField(max_length=100, blank=True, null=True) Database = models.CharField(max_length=100, blank=True, null=True) Name = models.CharField(max_length=100, blank=True, null=True) Datatype = models.CharField(max_length=100, blank=True, null=True) class holdings(models.Model): Contents = models.CharField(max_length=700, blank=True, null=True, default='No description') FAN = models.ForeignKey('surveys', on_delete=models.SET_NULL, blank=True, null=True) Database = models.ForeignKey('rooms', on_delete=models.SET_NULL, blank=True, null=True) ...(more fields)... class surveys(models.Model): FAN = models.SlugField(max_length=100, blank=True, null=True) PI = models.CharField(max_length=100, blank=True, null=True) IS = models.CharField(max_length=100, blank=True, null=True) DateBegin = models.DateField(blank=True, null=True) Location = models.CharField(max_length=200, blank=True, null=True) Filter: #filters.py from django import forms from datalibrary.models import surveys, rooms, holdings import django_filters class MultiFilter(django_filters.FilterSet): FAN = django_filters.CharFilter(lookup_expr='icontains', distinct=True) PI = django_filters.CharFilter(lookup_expr='icontains', distinct=True) Location = django_filters.CharFilter(lookup_expr='icontains', distinct=True) Contents = django_filters.CharFilter(field_name='holdings__Contents', lookup_expr='icontains', label='Contents', distinct=True) Room = django_filters.ModelChoiceFilter(queryset=rooms.objects.all(), label='Room', distinct=True) class Meta: model = surveys fields = ['FAN', 'PI', 'Location', 'Contents', 'Room'] Views: #views.py … -
How to render json to html?
I've JSON file: [ { "key1": "value1", "key2": "value2" }, { "key3": "value3", "key4": "value4" }] Output should be: <h1>value1</h1><p>value2</p><h1>value3</h1><p>value4</p> I'm trying like that: import json with open('file.json') as f: data = json.load(f) for key in data: for k, v in key.items(): print(k.replace(k, '<h1>') + v + (k.replace(k, '</h1>'))) But it's horrible and stupid :( Also, I have another JSON file: [ { "h1": "value1", "div": "value2" } ] Output should be: <h1>value1</h1><div>value2</div> My solution: with open('file2.json') as f: data = json.load(f) for key in data: for k, v in key.items(): print(f"<{k}>" + v + f"</{k}>") This one is work, it's possible to make it better? And the last one: If JSON have a list, each element it's has should be <ul> tag, and each <ul> element should contain <li> element: JSON: [ { "h1": "value1", "div": "value2" }, { "h1": "value3", "div": "value4" }] Output should be: <ul><li><h1>value1</h1><div>value2</div></li><li><h1>value1</h1><div>value2</div></li></ul> How can i solve these task? Please give me some advice which way i can dig it. With Python or Django -
How do I save records to the right schema/tenant?
I'm working on a multi-tenant application in Django, using django-tenant-schemas. However, when I save users, they don't seem to be properly attached to their tenants. When I query the list of users on a tenant I get a list of all the users in the database. I can see that the records have the right foreign keys but they all appear to have been lumped together in the same schema. I looked through this Multi-tenant schema with django and this User doesn't exists and no redirect to created tenant in django project, but I can't get mine to work properly Here's my tenant model(estates/models.py): from django.db import models from tenant_schemas.models import TenantMixin from .managers import EstateManager # Create your models here. class Estate(TenantMixin): name = models.CharField(max_length=100, unique=True) slug = models.CharField(max_length=20, unique=True) is_active = models.BooleanField(default=True) created_on = models.DateField(auto_now_add=True) auto_create_schema = True objects = models.Manager() tenancy = EstateManager() Here's my custom user model (authentication/models.py): from django.core.mail import send_mail from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.base_user import AbstractBaseUser from estates.models import Estate from .managers import UserManager class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField('email address', unique=True) phone = models.CharField('phone', max_length=50) first_name = models.CharField('first name', max_length=100) last_name = models.CharField('last name', max_length=100) created_at = models.DateTimeField('date created', auto_now_add=True) is_active … -
How do I fix the following piece of code in django?
My model entries are not getting displayed in the HTML file. I am trying to get the database entries from the models and running a for loop to print the entries in HTML. My views.py look like this: from django.shortcuts import render from .models import Post def blog(request): posts = Post.objects.all() return render(request, 'saunterer/blog.html', {'posts': posts}) I getting all the entries in Post table. My models.py looks lie this: class Post(models.Model): title = models.CharField(max_length = 150) subtitle = models.CharField(max_length = 150) body = models.TextField() date = models.DateTimeField() img_1 = models.FileField() img_2 = models.FileField() def __str__(self): return self.title Html file: {% for p in posts %} <div class="container"> <div class="row"> <div class="col-lg-8 col-md-10 mx-auto"> <div class="post-preview"> <a href="post.html"> <h2 class="post-title"> {{ p.title }} </h2> <h3 class="post-subtitle"> {{ p.subtitle }} </h3> </a> <p class="post-meta">Posted by <a href="#">something</a> on September 24, 2018</p> </div> <hr> {% endfor %} Nothing is getting printed. I am new to django and unable to spot the error. -
Django - In app urls not working properly
I am trying to include the url of my app to my project's url as stated below but there seems to be a problem, please help me figure out what is the problem. My project name is trydjango and this is urls.py file in it urlpatterns = [ path('teacher/', include('teacher.urls')), path('admin/', admin.site.urls), path('', homeView, name='home'), ] and this is teacher.urls file from django.urls import path from .views import addTeacherView, listTeacherView, teacherIndexView, deleteTeacherView, editTeacherView app_name = "teacher" urlpatterns = [ path('addTeacher/', addTeacherView, name='add-teacher'), path('listTeacher/', listTeacherView, name='list-teacher'), path('teacherIndex/<int:my_id>/', teacherIndexView, name='teacher-index'), path('deleteTeacher/<int:my_id>/', deleteTeacherView, name='delete-teacher-view'), path('editTeacher/<int:my_id>/', editTeacherView, name='edit-teacher'), ] and in models.py I included the app name at reverse method class Teacher(models.Model): firstName = models.CharField(max_length=72) email = models.EmailField() salary = models.DecimalField(max_digits=100000, decimal_places=2) def get_absolute_url(self): return reverse('teacher:edit-teacher', kwargs={'my_id': self.id}) Please help me find the problem Thanks in advance! -
is there something like that in django=2.1 , self.cleaned_data.get('ForeignKeyField.FieldName') to get a specific field's data
$self.cleaned_data.get('ForeignKeyField.FieldName') im try to make a validation error in my model form i need to get a specific field'data from another models.py based on the foreign key is it possible? i try it with cleaned_data.get() but it will give error or if there another solution i appreciate it -
My templates/index.html is not rendering (django 2.1.7 and python 3.7.2)
I'm setting up a new app in django and my index.html template is rendering. I'm getting below error. -
Eroor django-urls
from django.urls import path, re_path from . import views app_name="home-app" urlpatterns = [ path('nueva-url', IndexView.views(), name='index')#this synthesis does not work, it gives me an error. ][enter image description here]1 -
How can I use the jwt token for authentication that i get from my login view
I need to create JWT token authentication, but I don't know how, could you explain me how to do it better or put some examples? my view: class UserLogin(generics.CreateAPIView): """ POST auth/login/ """ # This permission class will overide the global permission # class setting permission_classes = (permissions.AllowAny,) queryset = User.objects.all() serializer_class = TokenSerializer def post(self, request, *args, **kwargs): username = request.data.get("username", "") password = request.data.get("password", "") user = auth.authenticate(request, username=username, password=password) if user is not None: auth.login(request, user) return Response({ "token": jwt_encode_handler(jwt_payload_handler(user)), 'username': username, }, status=200) return Response(status=status.HTTP_401_UNAUTHORIZED) -
Dispatching requests from one uwsgi to another uwsgi instance running Django Channels
I am currently using Django channels for websocket communication. I read this article and it states that I should split the project into two uwsgi instances. It states that "The web server undertakes the task of dispatching normal requests to one uWSGI instance and WebSocket requests to another one" Now I have two uwsgi instances running. This is how I am running both. This uwsgi handles the normal django site requests uwsgi --virtualenv /home/ec2-user/MyProjVenv --socket /home/ec2-user/MyProjVenv/MyProjWeb/site1.socket --chmod-socket=777 --buffer-size=32768 --workers=5 --master --module main.wsgi This uwsgi handles the websocket requests uwsgi --virtualenv /home/ec2-user/MyProjVenv --http-socket /home/ec2-user/MyProjVenv/MyProjWeb/web.socket --gevent 1000 --http-websockets --workers=2 --master --chmod-socket=777 --module main.wsgi_websocket Now the websocket uwsgi launches main.wsgi_websocket The code for main.wsgi_websocket one is this import os import gevent.socket import redis.connection redis.connection.socket = gevent.socket os.environ.update(DJANGO_SETTINGS_MODULE='main.settings') from ws4redis.uwsgi_runserver import uWSGIWebsocketServer application = uWSGIWebsocketServer() Now after spinning up the two uwsgi instances I am able to access the website fine.The websocket uwsgi instance is also receiving data however I am not sure if its passing that data to the django website uwsgi instance which basically uses django channels. I am using Django Channels here and this is the configuration I have specified in my settings for Django Channels CHANNEL_LAYERS = { "default": { … -
Am I legally allowed to use the backend from this place that shut down a while ago, and their code got out to people for them to download
So there is this company that shut down, and they released their source code on the website some people downloaded it and now sell it I managed to get my hands on it. I was wondering if I am legally allowed to use the website and the backend they made. Like will I have to get permission from the owner (if so going to be hard as the owner scammed thousands of dollars from people). So I just want to be in the clear if I can use it or not. Also I 100% have the rights to use the front end as the front end developer released it as open source. -
Unsupported grant type with Django Oauth Toolkit
I'm using the Django Rest Framework with django-oauth-toolkit, When I make a request on POSTMAN, with this body it works fine, { "username":"username", "password":"password", "client_id":"something", "client_secret":"somethingelse", "grant_type":"password" } When I make the same request using requests, I get unsupported_grant_type This is my request code, data = {"username": username, "password": password, "client_id": client_id, "client_secret": client_secret, "grant_type": "password"} r = requests.post(url, data=data) I'm using the string "password" as grant_type. It works in Postman, just doesn't work in code. Any help appreciated. -
Django Allauth signup form POSTs but no redirect, no email sent
This was all working fine for weeks, I haven't changed anything except taken a few fields off of the signup form (password which I've tried putting back and still same problem). I'm using Allauth with Django and the generic signup form /accounts/signup/ isn't redirecting to verification_sent.html. An email_confirm.html is also not being sent to confirm the account. I've set up an email backend to test on localhost and normally the emails come through fine via the terminal window. Now when I submit the form and request.POST, nothing happens. No emails, no verification_sent.html page redirection. The terminal isn't throwing any errors and says HTTP POST /accounts/signup/ 200 How can I go about debugging this? signup.html <form method="POST"> {% csrf_token %} {{ form.email|as_crispy_field }} {{ form.first_name|as_crispy_field }} {{ form.last_name|as_crispy_field }} <button type="submit" value="submit" id='signup_button'>Sign Up</button> </form> forms.py # User signup form class UserRegisterForm(forms.Form): email = forms.EmailField() first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) def signup(self, request, user): user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.save() settings.py ACCOUNT_SIGNUP_FORM_CLASS = 'users.forms.UserRegisterForm' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_EMAIL_VERIFICATION = 'mandatory' ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS=7 ACCOUNT_LOGIN_ATTEMPTS_LIMIT = 5 ACCOUNT_LOGIN_ATTEMPTS_TIMEOUT = 86400 # 1 day in seconds -
React in Django or React as a standalone?
I have been researching how to create django react application and the best way to go about implementing it. From this link on creating a django react app states a few way to go about implementing it. One way is to generate a webpack and using django to load the webpack another is to run it as 2 separate applications. What are the obvious benefits of "React in its own “frontend” Django app: load a single HTML template and let React manage the frontend" vs "Django REST as a standalone API + React as a standalone SPA" Because I do not see a need of generating a webpack and loading the application in django template where you could create a standalone react app and use Django REST for communication? -
How to save new Django database entries to JSON?
The git repo for my Django app includes several .tsv files which contain the initial entries to populate my app's database. During app setup, these items are imported into the app's SQLite database. The SQLite database is not stored in the app's git repo. During normal app usage, I plan to add more items to the database by using the admin panel. However I also want to get these entries saved as fixtures in the app repo. I was thinking that a JSON file might be ideal for this purpose, since it is text-based and so will work with the git version control. These files would then become more fixtures for the app, which would be imported upon initial configuration. How can I configure my app so that any time I add new entries to the Admin panel, a copy of that entry is saved in a JSON file as well? I know that you can use the manage.py dumpdata command to dump the entire database to JSON, but I do not want the entire database, I just want JSON for new entries of specific database tables/models. I was thinking that I could try to hack the save method on … -
API not sending email
I am trying to build a rest API that will ask for an email, subject and message from the user and send that subject and message to the email provided in the email field, from the email registered in the settings.py file. My models.py is as follows: class Email(models.Model): email = models.EmailField(null=False) subject = models.CharField(max_length=250, null=False) message = models.CharField(max_length=500, null=False) def __str__(self): return self.email my views.py is as follows: class EmailView(viewsets.ModelViewSet): serializer_class = EmailUser def get_queryset(self): queryset = Email.objects.all() return queryset serializer.py file looks something like this: class EmailUser(serializers.ModelSerializer): class Meta: model = Email fields = ('id', 'email', 'subject', 'message') def send_email_user(self, subject, message, from_email=None, **kwargs): return send_mail(subject, message, from_email, [self.email], **kwargs) and urls.py is as follows: url(r'email-user/', csrf_exempt(EmailView.as_view({'post': 'create', 'get': 'list'}))) I expect that it will send the email to the provided email address but as I do POST call the email, subject and Message is stored in the database but email isn't sending to the provided email. I am newbie in django rest framework if someone could tell me exact what I am doing wrong in this will be quite helpful. -
Pass Parent Model Value to Inline Model When Saving
I'm setting up a inline model using generic foreign key. There is a common value called "client" in both child and parent model. When adding a child item, i want it to take automatically the "client" value in its parent and save. Could anyone kindly give some help? #Filestorage management model class ChildModel(models.Model): object_id = models.PositiveIntegerField() content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) of = GenericForeignKey('content_type', 'object_id') # fileName = models.CharField(max_length=50) client = models.ForeignKey(ClientCtrl, on_delete=models.CASCADE) #Filestorage management inline class ChildModelline(GenericTabularInline): model = ChildModel ct_field_name = 'content_type' id_field_name = 'object_id' fieldsets = ( (None, { 'fields': ('id','client','fileName',...), }), ) readonly_fields = ('id','client') class ParentModelAdmin(admin.ModelAdmin): inlines = [ChildModelline] ... def save_formset(self, request, form, formset, change): instances = formset.save(commit=False) for instance in instances: if not instance.pk: instance.oper = request.user instance.client = self.ParentModel.client instance.save() formset.save_m2m() When adding a inline item, i want to pass the existing client value in parent to child, like this: instance.client = self.ParentModel.client which doesn't work at all: -
How to handle an image upload before creating the entry for the account in the database?
I'm building a single page application. On the client side I'm using Nuxt.js (which includes Vue.js and Vuex). To send and receive data to the server I use axios. The API was built with the Django REST framework. I have the following scenario: If a user wants to register, he starts on Page 1. Here he has the possibility to upload a profile picture. As soon as he has selected the picture it will be uploaded automatically into an S3 bucket. During or after the upload he can fill in the other fields First Name and Last Name. All these fields are temporarily saved in the Vuex store which means if the user reload the page the data is gone. If he clicks on Next Page he will be taken to another page (another URL; no page reload -> Single Page Application) where he can enter the remaining data. After clicking on the button Create Account the entry is created in the database. Now to my question... How should I handle the image upload? As already said, the picture should be uploaded directly after the selection and not only when you click on the button Create Account. At some point …