Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pass data from html to django view to use in URL?
I'm getting an error while working with django urls. I want to pass the value of Name input field after i hit the submit button. Let's say I've this html form- <form method='POST' action="{% url 'submittedform' slug=[firstname] %}"> {% csrf_token %} <div> <label for="name">Name</label> <input type="text" name="firstname" id="name"> </div> <div> <label for="email">Email</label> <input type="email" name="useremail" id="email"> </div> <div> <label for=phone>Phone</label> <input type="text" name="phonenumber" id="phone" maxlength="12" pattern="[0-9]{10}"> </div> <input type="submit" name="" id="btn" value="Submit"> </form> Here's my view that handling it- def submittedform(request, slug): if request.method == 'POST': # do something here return render(request,'myapp/welcome.html') return render(request,'myapp/welcome.html') and here's my view that's handling it- urlpatterns = [ path('index/',views.index ,name='index'), path('welcome/<slug:slug>/',views.submittedform, name='submittedform') ] I'm not using django forms. How can i get welcome/name working. -
Expand user model when fetching user data from Active Directory
I am using django_python3_ldap to connect to active directory. I can import users and sync them, making sure that the users that are already in the AD can log into the app without needing separate credentials. However, issue is that in addition to username, first_name, last_name and email, I want to import phone and office location from the AD. However, merely adding these fields causes the sync to break. I read from various tutorials that I should extend the Django user-model, but the import used by the library does not support extended one-to-one values. I am not confident in entirely replacing the django user model, so is there any good way to expand the user model to include these fields? -
Pycharm unresolved preference in Django project
I just created two projects by Django in virtual environment by python3 -m venv venv and pipenv, but they all report the unsolved reference warning in Pycharm. I have searched many methods on the internet, also changed the local interpreter, but all dont work. Current interpreter settings for my Pycharm in following images: The structure of project Also when I type from Django. in the Pycharm editor, it can not auto import modules. -
Web app framework advice for frontend page that works with backend MSSQL
I have a relic program at work with the backend that runs on Ms SQL, besides tables and views the programs business logic runs on stored procedures. These stored procs are executed by parsing xslt stylesheets that insert input fields and return results from tables which currently makes use of Internet Explorer's engine and runs as an executable desktop program. I would like to know from the community what framework I should consider using where I want to use the existing backend but control what appears on a modern browser, an example would be creating a new user. When the stored proc is called it is waiting for a username and password, I would like to control and force the user along a breadcrumb trail until they have completed the mandatory fields for the stored proc to update the table. I am comfortable with python and read up about using Flask, I have also dabbled in Angular. I would like to create these screens as quickly as possible and use Electron to publish it back as a desktop application. Typescript seems easier to understand than Javascript for me, or I am considering using Django and boxing myself into it. If … -
Django QuerySet return duplicate value on distinct, but does distinct on chaining count
I'm new to django, building a tiny project to get myself familiar with django, therefore still using default *qlite settings for storage. Here's the models defined, only with the fields related to this question: class Album(models.Model): id = models.CharField(max_length=32, primary_key=True) class Track(models.Model): name = models.CharField(max_length=128) album = models.ForeignKey(Album, on_delete=models.DO_NOTHING) Assume that I got: 2 albums: Album(id='a'), Album(id='b') 4 tracks: Track(name='a1', album='a'), Track(name='a2', album='a'), Track(name='b1', album='b'), Track(name='b1', album='b') When trying find out how many music albums are there in the selected music tracks, in this way. Track.objects.distinct('album').count() django complains that DISTINCT ON fields is not supported by this database backend. I thought this would be as easy as a sql statement like SELECT DISTINCT(album) FROM track; Then after some research, I found another way to achieve my goal, though something's kinda strange under the hood. Track.objects.values_list('album', flat=True).distinct().count() The query returns 2, the result I'm looking for, good. But without the count(), as below Track.objects.values_list('album', flat=True).distinct() The returned QuerySet contains 4 values, e.g. <QuerySet ['a', 'a', 'b', 'b']>. I'm curious about why this is happening, but didn't find any asked question similar to this, hope I could receive some help here, thanks. -
What does this error on Datepicker means? And how can it be resolved?
I am having this error after I click the update button from my modal. https://www.screencast.com/t/NOJr22Jyip Other data I submit is ok only this datepicker has an issue. <div class="row"> <div class="col-xl-12"> <div class="form-row"> <div class="col-md-4 mb-3"> <div class="form-group bmd-form-group is-focused"> <label class="bmd-label-floating" for="birthday">Birthday</label> <input type="text" class="form-control Dtpicker" id="birthday" name="birthday" value="{{employee.birthday}}" > </div> </div> </div> </div> </div> Views.py def save_employee_update(request): bday = request.POST['birthday'] employee = Employee.objects.get(employee_id=emp_id) employee.birthday = bday employee.save() # return render(request, 'index.html', {'form': form, 'successful_submit': True}) return render(request, 'index.html') JS for it. $(".Dtpicker").datetimepicker({ format: "YYYY-MM-DD", useCurrent: false, icons: { next: 'fa fa-angle-right', previous: 'fa fa-angle-left' } }) $(document).on("click", "#employee_update_btn", function () { if ($('#birthday').val() == ''){ return } }); After I click the update button the alert shows up but when I tried to print the value of birthday it does not contain anything. And That error show up. -
Failed to setup Postgresql in Django in namecheap
connection = Database.connect(**conn_params) File "/home/hatelsln/virtualenv/myunion/3.6/lib/python3.6/site-packages/psycopg2/init.py", line 126, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: FATAL: no pg_hba.conf entry for host "::1", user "hatelsln_hatelsln", database "hatelsln_myunion", SSL off -
Django: Get one to many data
I am current working on a project in Django where i have to get the information of the routers and the commands data. **Query that I want to apply** Select * From dashboard_routerdata, dashboard_alarmactive Where dashboard_routerdata.id = dashboard_alarmactive.routerID_id The method Im used is time consuming. Can you suggest any thing to how to apply this query. -
User can update or delete data which created by others
class StoryViewSet(viewsets.ModelViewSet): serializer_class = StorySerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,) I have viewset with all CRUD functions. The problem is that user can edit or delete stories of another user, I found DjangoModelPermissionsOrAnonReadOnly in permissions, but I cannot even create. I am using author as foreign key in Storymodel. Also I am using rest_framework.authtoken. So, I think there is two options, create own permission or rewrite some permission. Which one is better? -
How to clean the json output of a @property variable in Django Rest Framework
The issues is, when I do a get request for this model, the JSON response is not clean making it difficult to work with in Retrofit. Here is an example JSON output: [ { "id": 1, "restName": "Buddy's", "banner": "http://127.0.0.1:8000/media/buddysImg.jpg", "zipcode": 48212, "restRating": { "rating__avg": 4.0 }, "website": "Buddys.com", "phone": 3138929001, "restPrice": 0.0 } ] And this is how I'd like it to look: [ { "id": 1, "restName": "Buddy's", "banner": "http://127.0.0.1:8000/media/buddysImg.jpg", "zipcode": 48212, "restRating": 4.0, "website": "Buddys.com", "phone": 3138929001, "restPrice": 0.0 } ] Here is my model : class Rest(models.Model): restName = models.CharField(max_length=50, null=False, default = " ") zipcode = models.PositiveIntegerField( null=False, default = 0) #restRating = models.FloatField( null=False, default = 0) banner = models.ImageField( null=True) website = models.CharField(max_length=50, null=False, default = " ") phone = models.PositiveIntegerField( null=False, default = 0) restPrice = models.FloatField( null=False, default = 0) @property def restRating(self): avg = Rating.objects.filter(restId=self.pk).aggregate(Avg('rating')) return avg def __str__(self): return self.restName And here is my serializer : class restSerializer(serializers.ModelSerializer): restRating = serializers.FloatField class Meta: model = Rest fields = ['id', 'restName', 'banner', 'zipcode', 'restRating', 'website', 'phone', 'restPrice'] Thank you for the help. -
Collection, storage, and visualization of third party data using Django?
This question is based on a previous one I recently asked. I have tried to make this question as detailed as possible. My goal: I am creating a web app that allows for exploratory analysis of ocean buoys. User selects a buoy and some graphing options (e.g., monthly averages, filters to swell size, etc.) and a graph is made showing the resulting data for that buoy. Approach: User identifies a buoy through a web form or some type of selector and chooses options for the plot (e.g., monthly averages across all time). Data is queried for the selected buoy. Data is converted into a pandas dataframe of buoy time series data. Pandas processes the data based on the option selected by the user (e.g., calculates monthly averages). Plotly creates a chart The chart is sent to the templates.py in the views.py file, and the chart is rendered on the webpage. My problem: Collecting the data is difficult. The archived data for all buoys exists on NOAA's NDBC webpage and there is no simple API for accessing this archived data. Rather, it is stored on multiple pages in multiple CSVs. Thankfully, some open source code already exists for accessing this data. … -
Django templates: using include to pass a form template; how to write the form?
I simply would like to create a form, throw it in a template, and use the include keyword to include it in my home.html file. What am I doing wrong ? # forms.py class OrderForm(forms.Form): from_email = forms.EmailField(required=True) subject = forms.CharField(required=True) message = forms.CharField(widget=forms.Textarea, required=True) # views.py def orderView(request): template = 'orders.html' if request.method == 'GET': form = OrderForm() else: form = OrderForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] try: send_mail(subject, message, from_email, ['admin@example.com'] except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('success') return render(request, 'orders.html', {'form': form}) <!-- templates/orders.html --> <form method="post"> {% csrf_token %} {% form.as_p %} <button type="submit" class="btn btn-primary">Send</button> </form> <!-- templates/home.html --> ... <div class="orders"> {% include 'orders.html' %} </div> ... -
How to access selected data inside template in django?
I want to display selected user name. <select class="form-control" name="user_id"> {% for user in user_list %} <option value="{{ user.id }}">{{ user.id }}</option> {% endfor %} </select> <div> "I want to display name of selected user here" </div> How Can I access selected data in template? -
Importing excel data to django database in parent child format
My requirement is to save the excel data in the django DB using import which I could do using below code. But next I want to save the data in a one to many relationship. ie. I want a unique key to be generated and saved in Main_page model and corresponding to that my uploaded excel file data should share the same primary key in the Upload model. For eg. If the main_page has id 1, so for my complete excel data uploaded i want the data to share the same key. What changes or any link should i learn or go through. I am stuck since last few days but no luck. Thanks in advance models.py class Upload(models.Model): sheet_key = models.ForeignKey(Main_page) Student_Name = models.CharField(max_length=100) Total_Marks = models.IntegerField() Marks_Scored = models.IntegerField() class Main_page(models.Model): sheet_key = models.AutoField(primary_key=True) date = models.DateField() views.py class UploadFileForm(forms.Form): file = forms.FileField() def import_data(request): if request.method == "POST": form = UploadFileForm(request.POST, request.FILES) # Check if the form is valid if form.is_valid(): request.FILES['file'].save_to_database( # Save the file data to the database name_columns_by_row=1, model=Upload, mapdict=['Student_Name', 'Total_Marks', 'Marks_Scored', 'Status', 'Date', 'College_Name', 'Phone Number']) # Columns to be mapped return HttpResponse("OK") else: # If the form has errors show the error. … -
Django/Axios/React/Keras, upload image, classify image, return to user
class View(APIView): parser_classes = (MultiPartParser, FormParser) def get(self, request, *args, **kwargs): plants = Plants.objects.all() serializer = PlantSerializer(plants, many=True) return Response(serializer.data) def post(self, request, *args, **kwargs): plants_serializer = PlantSerializer(data=request.data) filename = request.FILES[request] logger.warning("test") img = image.load_img(filename, target_size=(224, 224)) img = image.img_to_array(img) img = np.expand_dims(img, axis=0) img = img/255 with sess.as_default(): with graph.as_default(): preds = model.predict(img) preds = preds.flatten() maximum_value = preds.max() for index, item in enumerate(preds): if item == maximum_value: classification = classification_list[index] Hi there, I'm working on a project that uses React front end and Django backend, and we cannot figure out how to pass in an image uploaded with the help of Axios in the front end for processing with Keras in the backend. We had it working when using Django, but we're having trouble reading the user uploaded file for processing. Any tips about how to handle this would be much appreciated. We took on a project without fully understanding backend or the complexity of many moving components. -
Tags containing spaces surrounded by quotes
I'm writing a simple notetaking app, and I have implemented tags on my notes. I'm using django-taggit for server-side implementation and bootstrap4 tag input plugin for front-end. I'm having an issue with something adding quotes around my tags that contain spaces and I cannot determine what, whether it is django-taggit or the bootstrap plugin. This is a pic of how my UpdateView looks like: so when I'm adding tags that contain spaces, they're added as they should (no quotes), however when I come back later to them (say, in UpdateView), the quotes are displayed. I have tried to print the tag in Django shell but I can't see the quotes that are being added: >>> Note.objects.get(pk=1).tags.all()[2].__str__() 'hello world' So I'm thinking the issue must be in the bootstrap plugin. How can I overcome the issue? There's quite a bit of code to this so I wasn't sure what pieces to include, if you need something, just let me know. Thanks. -
Django admin site get id to show in html
I just want that if the admin select the students, it will get the id and show in the html template admin.py @admin.register(studentDiscount) class studentDiscount(admin.ModelAdmin): list_display = ('Students_Enrollment_Records', 'Discount_Type','my_url_field') ordering = ('Students_Enrollment_Records',) search_fields = ('Students_Enrollment_Records',) def my_url_field(self, obj): return format_html("<a href='https://www.school.ph/enrollmentform/?StudentID=pk'>Report</a>", obj.Discount_Type) my_url_field.allow_tags = False my_url_field.short_description = 'Report' this is my models.py class studentDiscount(models.Model): Students_Enrollment_Records = models.ForeignKey(StudentsEnrollmentRecord, related_name='+', on_delete=models.CASCADE, null=True) Discount_Type = models.ForeignKey(Discount, related_name='+', on_delete=models.CASCADE, null=True,blank=True) -
Downloaded compressed data (`gz`) from django server using ajax is inflated and broken
I'm trying to download a .gz file from a django server (Python 3.7) using Ajax request. This is the minimal django view function and Ajax function to request download on client, compress a folder and send it (server) and receive the data on the client: from pathlib import Path def downloadfile(request): folder = Path().home().joinpath('workspace') tar_path = Path().home().joinpath('workspace.gz") tar = tarfile.open(tar_path.as_posix(), "w:gz") tar.add(folder.as_posix(), arcname='workspace') tar.close() try: with open(tar_path.as_posix(), 'rb') as f: file_data = f.read() response = HttpResponse(file_data, content_type='application/gzip') response['Content-Disposition'] = 'attachment; filename="workspace.gz"' except IOError: response = HttpResponse('File not exist') return response This is the Ajax function on the client side: $(function () { $('#downloadfile').submit(function () { $.ajax({ type: 'POST', url: 'downloadfile', success: function(response){ download(response,'workspace.gz', 'application/gzip'); } }); return false; }); }); function download(content, filename, contentType) { var a = document.createElement('a'); var blob = new Blob([content], {'type':contentType}); a.href = window.URL.createObjectURL(blob); a.download = filename; a.click(); } A sample gzipped folder that is 36.5 KB will be inflated to 66.1 KB when downloaded and it clearly can't be extracted. What I know: The file is healthy and extractable on server side. The data is transferred and downloaded on the client but inflated and broken. The respone variable in the JavaScript function looks like binary … -
Django signals post_save
class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, related_name='students', on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Discount_Type = models.ForeignKey(Discount, related_name='+', on_delete=models.CASCADE, null=True) Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, null=True) class studentDiscount(models.Model): Students_Enrollment_Records = models.ForeignKey(StudentsEnrollmentRecord, related_name='+',on_delete=models.CASCADE, null=True) Discount_Type = models.ForeignKey(Discount, related_name='+', on_delete=models.CASCADE, null=True,blank=True) @receiver(pre_save, sender=StudentsEnrollmentRecord) def get_older_instance(sender, instance, *args, **kwargs): try: instance._old_instance = StudentsEnrollmentRecord.objects.get(pk=instance.pk) except StudentsEnrollmentRecord.DoesNotExist: instance._old_instance = None @receiver(post_save, sender=StudentsEnrollmentRecord) def create(sender, instance, created, *args, **kwargs): if not created: older_instance = instance._old_instance if older_instance.Discount_Type != instance.Discount_Type: studentDiscount.objects.filter( Students_Enrollment_Records=instance ).delete() else: return None discount = studentDiscount.objects.filter(Discount_Type=instance.Discount_Type) if created: studentDiscount.objects.create( Students_Enrollment_Records=instance, Discount_Type=discount.first()) this is the picture of my (StudentsEnrollmentRecord) in my studentDiscount model why (Students_Enrollment_Records field) only save in my studentDiscount (just like in the picture shows) i want the result like this -
django-import-export - Importing ManyToMany from JSON file
I'm trying to import a JSON file that contains a many-to-many relationship but am hitting some problems. This is my code: book.json { "title": "The Lord of the Rings", "categories": [ "Fantasy", "Action", "Adventure" ] } models.py from django.db import models class Category(models.Model): guid = models.CharField(max_length=36) display_name = models.CharField(max_length=50) description = models.TextField() def __str__(self): return self.display_name class Book(models.Model): title = models.CharField(max_length=200) categories = models.ManyToManyField(Category) def __str__(self): return self.title resources.py from import_export import resources from import_export.fields import Field from import_export.widgets import ManyToManyWidget from .models import Book, Category class BookResource(resources.ModelResource): categories = Field(widget=ManyToManyWidget(Category)) class Meta: model = Book import_id_fields = ('title',) importer.py from resources import BookResource from models import Book with open("book.json", 'r') as f: book = '[' + f.read() + ']' result = BookResource().import_data(tablib.Dataset().load(book), raise_errors=True, dry_run=True) This seems to run through without errors, and adds the new book to the database. The problem is that it doesn't create a new entry in the book_categories table (PostgreSQL). I think I'm definitely missing a step somewhere because I haven't defined how to find the correct category database entries, given I the list of display_name strings. Am I on the right track here? -
How long did it take you to integrate Stripe (Django)?
This is a fairly general question. I'm integrating Stripe to my website to handle subscriptions / upgrades. I've never done it before, and it has taken me about 1.5 days to integrate it into my Django-based website, including all the templates, upgrade/downgrade pages and changing my User models in Django. My main bottlenecks have been JavaScript/jQuery as I have just no experience with it, and obviously figuring out the API, although I must say the documentation was excellent. How long should it have taken me? How long did it take you, for those who've done it before? Just asking out of interest/curiosity. Thanks! -
Custom Django Rest Framework authentication validating when 'None' is returned
I am working on implementing JWT for authentication. Of course, this means I have to do some custom authentication. According to the docs, "If authentication is not attempted, return None." So, I have code that checks for an authorization header (where the JWT resides) and returning "None" if an authorization header does not exist. This means that authorization was not attempted (and according to the docs) I should return None. However, Django is saying that the user is authorized: Root/authentication/TokenAuthentication/TokenAuthentication from rest_framework import status from django.http import HttpResponse from rest_framework.authentication import get_authorization_header, BaseAuthentication from django.contrib.auth.models import User import jwt, json class TokenAuthentication(BaseAuthentication): def authenticate(self, request): auth = get_authorization_header(request).split() if not auth: return None Login.py @api_view(['POST']) def login_view(request): if not request.data: return Response({'Error': "Please provide username/password"}, status="400") username = request.data['username'] password = request.data['password'] try: user = User.objects.get(username=username) if not user.check_password(password): raise User.DoesNotExist except User.DoesNotExist: # if user not found or password is wrong return Response({'Error': "Invalid username/password"}, status="400") if user.is_authenticated: print("user is authenticated") # THIS GETS PRINTED else: print("User is not authenticated") Settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ #'rest_framework.authentication.BasicAuthentication', 'Root.authentication.TokenAuthentication.TokenAuthentication' ] } The line if user.is_authenticated: print("user is authenticated") Is running everytime when None is being returned. Any help would be … -
passing multiple value from select element that has the same class to django views
I have a problem to pass multiple value that has the same class in select element(because i use ajax to load the value of the option element) example : <div class="form-group"> <button class="btn btn-theme" onclick="appendBox()">Add</button> <label class="control-label col-md-3">Column Name</label> <div class="col-md-4" id ="test"> <div class="input-group bootstrap-timepicker"> <div class="btn-group"> <select class ="columnselect" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;"> {% for data2 in obj %} <option value="{{data2}}">{{data2}}</option> {% endfor %} </select> </div> </div> </div> </div> <div class="form-group"> <button class="btn btn-theme" onclick="appendFilterBox()">Add</button> <label class="control-label col-md-3">Filter</label> <div class="col-md-4" id="filtbox"> <div class="input-group bootstrap-timepicker"> <div class="btn-group"> <select class="columnselect" style="width:125px;background-color:white;height:30px;font-size:15px;text-align-last:center;"> {% for data2 in obj %} <option value="{{data2}}">{{data2}}</option> {% endfor %} </select> </div> </div> </div> </div> How can i pass all this value that has the same class? because i want to pass 2 value to the views django , and want to print it in console -
Ignoring file in Github and Django
Me and my friend are both working on a project in Django. We are beginners with both GitHub as well as Django. We have managed to use .gitignore to ingore certain files. This is how the .gitignore looks like : .DS_Store groupProject/__pycache__ marketplace/__pycache__ marketplace/migrations/__pycache__ marketplace/templatetags/__pycache__ db.sqlite3 The only issue that we have is that when we try to push we get an error saying that there is a merge conflict for this file 'db.sqlite3' . I have added this file in .gitignore and for some reason it still decides to read it? What should we do? -
How to overwrite a file with same name when uploaded to Django FileField?
I want to overwrite the contents of a file if the filename is the same when an user uploads a file in Django. I have gone through many stackoveflow questions but haven't found what I wanted. Following is my model: class Upload(models.Model): profile = models.FileField(upload_to="uploads/") Code to upload files: files = {'newprofile': open('profiles/blah.jmx', 'rb')} x = requests.post(url, files=files) Any pointers would be appreciated.