Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Could anyone please write the code in django to get a csv file as an input from user and then displaying number of rows and columns in it [on hold]
Please help me with the contents of template,views, URL(outer and inner) file. I just want to create a simple web application in django where i get a user input in the form of a csv file(I also want to put a check so that the file should only be a .csv) and then simply displaying the number of rows and columns in that file to the user. Thank you in advance. -
Reward Points to Currency Conversion
I am currently building a Django app where a user gets a point referrals. And these points could be converted to "real" money which can later be used for "shopping" real items on specific stores BUT cannot be withdrawn as cash. My problem is the conversion part of the points. For example: the equivalent of 1 point is $30. I am really new to these kinds of applications and also new in using python so please bear with me. How should I approach this then? Should I store the $30 to a "wallet" in my database after it was converted? Or should I use a 3rd party to process the conversion and the payment of the users whenever they use the "money" to shop? I am open to any suggestions besides these things that I have in mind. And honestly, I barely have enough knowledge to execute these things, but I am currently studying it. Your inputs will help a lot. Thank you. -
Django Error: "You are trying to add a non-nullable field 'author' to entry without a default"
I was trying to make migrations after adding an author field in my models.py file but Django asked me this: You are trying to add a non-nullable field 'author' to entry without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py My Models.py File: from django.db import models from django.utils import timezone from django.urls import reverse from django.contrib.auth.models import User class Entry(models.Model): title = models.CharField(max_length=50, default=timezone.now) date = models.DateTimeField(default=timezone.now) content = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) def get_absolute_url(self): return reverse('diary:index') def __str__(self): return self.title I wanted to add the user who's currently active as the author, so I did this on my views.py file: class EntryCreate(CreateView): model = Entry fields = ['title', 'content'] def form_valid(self, form): form.instance.author = self.request.author return super().form_valid(form) What Should I Do To Avoid This? Thanks In Advance! -
Trouble getting the localhost using webdriver selenium 3.141.0 for firefox 69.0.1
I'm trying to test my django application using selenium and Mozilla Firefox 69.0.1 on Ubuntu 16.04, but I get an error message: "selenium.common.exceptions.WebDriverException: Message: Reached error page". It seems like Firefox cannot establish a connection to the server 127.0.0.1:8000. I built a virtual environment where everything is installed (python 3.5.2, django 2.2.6, selenium 3.141.0, urllib3 1.25.6, etc.). I downloaded geckodriver 0.25.0, which is installed in /usr/local/bin/. I ran the following code: from selenium import webdriver browser = webdriver.Firefox() browser.implicitly_wait(10) browser.get("http://127.0.0.1:8000") browser.quit() I also tried: from selenium import webdriver firefox_capabilities = DesiredCapabilities.FIREFOX firefox_capabilities["marionette"] = True browser = webdriver.Firefox(executable_path="/usr/local/bin/geckodriver", capabilities=firefox_capabilities) browser.implicitly_wait(10) browser.get("http://127.0.0.1:8000") browser.quit() But it did not work. The first piece of code works when I use "https://www.python.org/" instead. I suppose there is a problem with the local host, but I cannot figure out what is wrong though. -
Ouput ping status on django template
I have a model that contains domain names which I need to ping. I was able to create the view but I couldn't figure out how to output it on the template. def pingDomain(request, page): domain = Table.objects.filter(page) try: subprocess.check_call(['ping', '-c', '1', "domain"]) except subprocess.CalledProcessError: host_online = False else: host_online = True context = { 'online': host_online } return render(request, 'home.html') the model class Table(models.Model): page = models.URLField(verbose_name=None) and this is how I call it on the template {{t.page.status.url}} Can anyone guide me? -
Getting error response in ajax from my Django view
i am getting the error in ajax from my view in Django and I cannot figure out why : // AJAX GET $(document).ready(function(){ // AJAX GET $('#btnx').click(function(){ console.log('start'); $.ajax({ type:"GET", url:"profile_bit", dataType:"json", data: {'counter': 'counter'}, success: function(data) { console.log('ok')}, error: function(data){ console.log('why?') // << I keep getting this }}) }) }); // django view , my url is all good too def profile_bit(request): if request.is_ajax(): data ={ 'key': 'value', } return HttpResponse(json.dumps(data), content_type='application/json') else: return Http404 I would like to get a success response so I could just continue to work with my DB. Thx so much -
OperationalError at /add-to-cart/test-product-4/ table core_order has no column named shipping_address_id
after i changed class BillingAddress To class Address. and tried these stages Deleted all the migration records from your app's migration directory. Also Deleted the db.sqlite3 file. And Then, I did following commands python manage.py makemigrations core python manage.py migrate After migrated, Instead of showing data inserted ,it is shown No migrations to apply. in Terminal PS C:\Users\Dell\project5> python manage.py makemigrations core Migrations for 'core': core\migrations\0001_initial.py - Create model Address - Create model Coupon - Create model Item - Create model Order - Create model Refund - Create model Payment - Create model OrderItem - Add field items to order - Add field payment to order - Add field shipping_address to order - Add field user to order PS C:\Users\Dell\project5> python manage.py migrate Operations to perform: Apply all migrations: account, admin, auth, contenttypes, core, sessions, sites, socialaccount Running migrations: No migrations to apply. PS C:\Users\Dell\project5> when i click add to cart button, it shown error as OperationalError at /add-to-cart/test-product-4/ table core_order has no column named shipping_address_id -
request.FILES is empty
I have a form with an <input type="file"> for selecting images to upload, and once upload button is clicked, a POST XMLHttpRequest is sent which calls the upload_view that should save the images on the server. However, my request.FILES is empty for some reason. When I console.log(document.getElementById('fileToUpload').files I can see the files there. And my request.POST looks like this: <QueryDict: {'fileToUpload': ['[object FileList]'], 'csrfmiddlewaretoken': ['bOjUFzTnMVbHOWOQURj2egJuRizsVJIBMSfQra4yuz7MX3DOEaRPHbMVnY8xyIsU']}> My view: def upload_view(request): key = f'{request.user}-{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}' for file in request.FILES.getlist('fileToUpload'): TemporaryImage.objects.create(image=file, key=key) return HttpResponse('complete') My JS: function uploadFile() { var fd = new FormData(); fd.append("fileToUpload", document.getElementById('fileToUpload').files); var value = []; document.getElementsByName('csrfmiddlewaretoken').forEach(function(x) { value.push(x.value); }) fd.append('csrfmiddlewaretoken', value[0]); var xhr = new XMLHttpRequest(); xhr.open("POST", Urls['upload-view']()); xhr.send(fd); } My form: <form id="form1" enctype="multipart/form-data" method="post"> {% csrf_token %} <label for="fileToUpload">Select a File to Upload</label> <input type="file" multiple="multiple" name="fileToUpload" id="fileToUpload"> <input type="button" onclick="uploadFile()" value="Upload"> </form> -
Custom 500 error getting blank page sometimes
When I try to test the custom 500 error page. If the test works, the I get a blank page with nothing on it ("Internal Server Error") in my error logs. If an error occurs, I get custom error page. In views: def handler500(request): response = render_to_response("errors/500.html") response.status_code = 500 return response def my_test_500_view(request): # Return an "Internal Server Error" 500 response code. return HttpResponse(status=500) In Urls.py: my path is : path('test500/', views.my_test_500_view, name='test500') Also: handler500 = 'myapp.views.handler500' If I actually create an error like by removing the import line for the HttpResponse from the my_test_500_view above, the custom 500 error page actually loads and I get this error on the server, i.e. the actual error. NameError: name 'HttpResponse' is not defined What's wrong with my test that it returns a blank page. Is my 500 page actually working? I think it's not working right, since I got a email warning from google search about failure of 500 error page and I often get this error: TypeError: view must be a callable or a list/tuple in the case of include(). Please help, what's going on. -
django Sum values for loop in template
I have this template that is a search engine. I need all the searched items to be added, but as i did it sums up all the database items. and I need it to show only the sum of the searched items. sum all loop items {{images.price | mul:images.pictures}} views.py def search(request): sales_list = Images.objects.all() sales_filter = ImagesFilter(request.GET, queryset=sales_list) places_count = Images.objects.all().annotate(total=Sum('pictures')) return render(request, 'paneladmin/sales_list.html', {'filter': sales_filter, 'places_count': places_count}) filter.py class ImagesFilter(django_filters.FilterSet): checkin = django_filters.NumberFilter(widget=DatePickerInput(format='%d'),field_name='checkin', lookup_expr='day' ) checkin1 = django_filters.NumberFilter(widget=DatePickerInput(format='%m'),field_name='checkin', lookup_expr='month' ) checkin2 = django_filters.NumberFilter(widget=DatePickerInput(format='%Y'),field_name='checkin', lookup_expr='year' ) # usando o name__photographers eu estou dizendo que quero busca o name da tabela photographes, desse modo terei um boxlistt em meu template name__photographers = django_filters.CharFilter(lookup_expr='icontains', field_name='name') class Meta: model = Images fields = ['name', 'checkin'] sales_list.html {% load mathfilters %} {% for images in filter.qs %} {{images.price | mul:images.pictures}} {{ places_count }} {% endfor %} -
How to use Python Keyring from Django without user interaction?
I need to store some third party server passwords in Django, in views.py to be more specific. Those are used for Paramiko SFTP (machine-to-machine communication) and it's not possible to use keys instead of passwords. For sure I don't like to write those passwords directly to source code. I have figured out that Python Keyring would be good way to store passwords and following short code works ok: import keyring try: keyring.get_keyring() keyring.set_password("system", "user", "passWORD") pword = keyring.get_password("system", "user") print pword except Exception as e: print e I moved the code to Django (views.py): from django.http import HttpResponse import keyring def index(request): try: keyring.get_keyring() keyring.set_password("system", "user", "passWORD") pword = keyring.get_password("system", "user") return HttpResponse(pword) except Exception as e: return HttpResponse(e) Then I asked Django to run built-in development server by typing: sudo python manage.py runserver Finally I browsed to correct localhost url. Result: browser was showing dialog requesting me to create (on first try) and then open (on next tries after I have created it) kdewallet. Is it possible to use Keyring from Django without need for user interaction (= without those dialogs)? -
How to remove a field from modelform model instance?
I have a question related this one: How to handle the validation of the model form when the model has a clean method if the model form excluded some fields? This is my model: class StudentIelts(Model): SCORE_CHOICES = [(float(i/2), float(i/2)) for i in range(0, 19)] IELTS_TYPE_CHOICES = [('General', 'General'), ('Academic', 'Academic'), ] student = OneToOneField(Student, on_delete=CASCADE) has_ielts = BooleanField(default=False, ) ielts_listening = FloatField(choices=SCORE_CHOICES, null=True, blank=True, ) ielts_reading = FloatField(choices=SCORE_CHOICES, null=True, blank=True, ) ielts_writing = FloatField(choices=SCORE_CHOICES, null=True, blank=True, ) ielts_speaking = FloatField(choices=SCORE_CHOICES, null=True, blank=True, ) ielts_overall = FloatField(choices=SCORE_CHOICES, null=True, blank=True, ) ielts_exam_type = CharField(max_length=10, null=True, blank=True, choices=IELTS_TYPE_CHOICES, ) ielts_exam_date = DateField(null=True, blank=True, ) ielts_file = FileField(upload_to=student_directory_path, null=True, blank=True, ) student_ielts_non_empty_fields = \ { 'ielts_listening': 'please enter your listening score', 'ielts_reading': 'please enter your reading score', 'ielts_writing': 'please enter your writing score', 'ielts_speaking': 'please enter your speaking score', 'ielts_overall': 'please enter your overall score', 'ielts_exam_type': 'please enter your exam type', 'ielts_exam_date': 'please specify your exam date', } def clean(self): errors = {} if self.has_ielts: for field_name, field_error in self.student_ielts_non_empty_fields.items(): if getattr(self, field_name) is None: errors[field_name] = field_error if errors: raise ValidationError(errors) class StudentIeltsFilterForm(ModelForm): class Meta: model = StudentIelts fields = ['has_ielts', 'ielts_listening', 'ielts_reading', 'ielts_writing', 'ielts_speaking', 'ielts_overall', 'ielts_exam_type', ] def __init__(self, *args, **kwargs): … -
objects.create(...) does not create the objects
For some reason my objects aren't being created: def upload_view(request): key = f'{request.user}-{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}' for file in request.FILES.getlist('fileToUpload'): TemporaryImage.objects.create(image=file, key=key) return HttpResponse('complete') TemporaryImage.objects.all() returns an empty QuerySet, and when I inspect the database, nothing is there, yet I can see the HttpResponse being returned successfully. I don't see any errors. The same is true when I do: tmp_img = TemporaryImage(...) tmp_img.save() What could be the cause? -
How to view local webpage in iframe of public webpage?
I've been working on a security camera project where I have a raspberry pi that hosts a local webpage with the live video feed from its camera. I also have a server running at home whitch hosts a public webpage. I want to be able to view the local webpage from the raspberry pi from the public webpage. Is there a way I can use an Iframe or something to view the local webpage from everywhere from within the public webpage? -
Django Users Default Profile Image not showing
I am trying to add set the default profile picture for the users who doesn't add their profile. I am following this tutorial but for some reason default picture isn't showing up on the profile tab. I have mentioned all the code I can below but click here to check complete code. About Project There are two apps blog and users along with main project directory django_project. Click here to check complete code. But main profile.html {% extends 'blog/base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <div class="media"> <img class="rounded-circle account-img" src='{{ user.profile.image.url }}'> <div class="media-body"> <h2 class="account-heading">{{user.username}}</h2> <p class="text-secondary">{{user.email}}</p> </div> </div> <!-- FORM HERE --> </div> {% endblock content %}` admin.py from .models import Profile from django.contrib import admin admin.site.register(Profile) apps.py from django.apps import AppConfig class UsersConfig(AppConfig): name = 'users' forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserRegisterForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] models.py from django.contrib.auth.models import User from django.db import models class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default="default.jpg", upload_to="profile_pics") def __str__(self): return f"{self.user.username} Profile" views.py from django.contrib.auth.decorators import login_required from .forms import UserRegisterForm from django.shortcuts import … -
How to add more data when registering a user by python-social-auth
I already implemented a successful Facebook register form in my django project with python-social-auth. However, now I need to create the registered user with additional data in the register form of my page. I mean allowing to retrieve the necessary data from Facebook to create the new user, but also use the data from the form (the user could fill this data before or after redirecting to Facebook, but that is not my concern here). How can it be done in general terms? -
How to monkey patch django function?
I want to customize django admin change_list_result row content, so i guess override related to change_list_result function. And I found to konw call display_for_field via items_for_result in django.contrib.admin.templatetags.admin_list. admin_list.py I put following code to the manage.py, but doesn't work. from django.contrib.admin.utils import display_for_field from warehouse.monkey_patching import _display_for_field_mod display_for_field = _display_for_field_mod -
Django - how to store different parsing techniques for different XML formats?
Every user has different csv/xml feed url. Some users feeds are "standardized" so the parsing techniques/scripts can be shared. But some users has very unique feed formats and I need to write custom script. I'm trying to figure out way to store such scripts so either I choose existing parsing technique inside admin or I write code and assign it to the object. How would you do that? My idea is to have a folder with these scripts and every object would have FilePathField so I can choose or create a new script. Is there another way? class Feed(BaseTimeStampedModel): url .... name = models.CharField(max_length=64) template = models.FilePathField(path='feeds/parsers/', recursive=True, match='tparser__.*') -
Class views in Django, Html not showing
Im quite confused with why my html template is not showing up. Im trying to learn Class base views instead of functions on Django. I know the url is working because {% extend base.html %} is showing, but anything else like the h1 tags aren't showing up in the render? Can anyone help please. views.py from django.shortcuts import render from django.views import View from django.views.generic import ( CreateView, DetailView, ListView, UpdateView, ListView, DeleteView ) from .models import Article class ArticleListView(ListView): template_name = 'article/article_list.html' queryset = Article.objects.all() url.py from django.contrib import admin from django.urls import path from .views import ( ArticleListView ) app_name = 'article' urlpatterns = [ path('', ArticleListView.as_view(), name = 'article_list'), article_list.html {%extends 'base.html'%} <h1> Test </h1> <h1> Test </h1> {%block content%} {% for instance in object_list %} <p>{{instance.id}} - <a href = '{{instance.get_absolute_url}}'> {{instance.title}} </a></p> {%endfor%} {%endblock%} -
how to group records by hour and return instances
this is my model and i am using postgresql: class TripRequest(models.Model): passenger = models.ForeignKey('user.Passenger', on_delete=models.DO_NOTHING) beginning_point = models.PointField() destination_point = models.PointField() trip_beginning_time = models.DateTimeField() ... i'm not very familiar with advance orm queries i want to group trip requests that have nearest (for example in a specific hour) beginning time and after that filter it furthermore like nearest beginning point or nearest driver. now there are answers on SO that group the query and return the count or other information of all the group items but i want to just group the instances by hour and have a collection of instances for further filtering how can i do that? -
I am not getting any errors in my terminal yet my contact page doesn't display my email fields
I am not getting any errors in my terminal yet my contact page only displays the header "Contact Form" and a "Send Message" button without the fields required for my form. The fields are (Username, Email, Subject & Content). If i can get my form to display the required fields so that users can enter the required details and post their queries id be happy. Kindly assist and if i have left an important bit kindly tell me and i will update my question. Thanks in advance. MY forms.py file looks like this from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm # contact form class ContactForm(forms.Form): contact_username = forms.CharField() contact_email = forms.EmailField() contact_subject = forms.CharField() content = forms.CharField() class Meta: model = User fields = ['contact_username', 'contact_email', 'contact_subject', 'content'] My views.py file looks like this from django.shortcuts import render, redirect from django.contrib import messages from .forms import UserRegisterForm # contact form view def contact(request): Contact_Form = Contact_Form if request.method == 'POST': form = Contact_Form(data=request.POST) if form.is_valid(): contact_username = request.POST.get('contact_username') contact_email = request.POST.get('contact_email') contact_subject = request.POST.get('contact_subject') contact_content = request.POST.get('content') template = get_template('buyer/contact_form.txt') content = { 'contact_username' : request.POST.get('contact_username'), 'contact_email' : request.POST.get('contact_email'), 'contact_subject' : request.POST.get('contact_subject'), 'contact_content' : request.POST.get('contact_content'), … -
Django Error: "TypeError: join() argument must be str or bytes, not 'Path'" when running manage.py migrate with cookiecutter-django installed
I have been trying to set up Django with a cookiecutter-django project and I'm getting this error output when I run python3 manage.py migrate TypeError: join() argument must be str or bytes, not 'Path' -
How to actually make a PATCH request to DRF
So I've been looking around and researching a bit and still couldn't figure out how to make a PATCH request to the DRF. Here's my view: class AttendanceView(viewsets.ModelViewSet): queryset = Attendance.objects.all() serializer_class = AttendanceSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,) parser_classes = (MultiPartParser, FormParser) def patch(self, request, *args, **kwargs): att = self.request.query_params.get('id', None) att_obj = get_object_or_404(Attendance, pk=att) serializer = AttendanceSerializer(att_obj, data=request.data, partial=True) if serializer.is_valid(): att_obj = serializer.save() return Response(AttendanceSerializer(att_obj).data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def post(self, request, *args, **kwargs): file_serializer = AttendanceSerializer(data=request.data) if file_serializer.is_valid(): file_serializer.save() return Response(file_serializer.data, status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) And I have all the standard serializers and urls set. I am using the Python requests library. How do I send a PATCH request to my API so I can update a field in my attendance object? Also please let me know if there's something missing in or for my patch method. I appreciate your time in reading this. Thank you so much. -
Django caching (?) HTML
I'm using Django==2.2.6 (haven't kept up with the later releases, I don't know what's new) and it seems like it is caching my html-files, somehow? Currently, at the index-page is says: SHISH There are NO references to "SHISH" in the code, whatsoever. -
AttributeError: 'bytes' object has no attribute '_committed'
I have a form with an <input type="file">, and I'm getting an error when I try to save the uploaded image. The image is uploaded via POST XMLHttpRequest. I have no idea why this is happening. views.py: import datetime from django.shortcuts import render from .models import TemporaryImage def upload_file(request): key = f'{request.user}-{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}' for file in request.FILES.get('file'): img = TemporaryImage(image=file, key=key) img.save() def home_view(request): return render(request, 'products/home.html', {}) models.py: from django.db import models def get_temp_image_path(instance, filename): return os.path.join('tmp', str(instance.id), filename) class TemporaryImage(models.Model): image = models.ImageField(upload_to=get_temp_image_path, blank=True, null=True) key = models.CharField(max_length=100) urls.py: from django.contrib import admin from django.urls import path from products.views import upload_file, home_view urlpatterns = [ path('admin/', admin.site.urls), path('', home_view, name='home'), path('upload/', upload_file, name='upload_file') ] template 'home.html': <!DOCTYPE html> <html> <head> <title>SO Question</title> <script> function uploadFile() { var fd = new FormData(); fd.append("file", document.getElementById('file').files[0]); var value = []; document.getElementsByName('csrfmiddlewaretoken').forEach(function(x) { value.push(x.value); }) fd.append('csrfmiddlewaretoken', value[0]); var xhr = new XMLHttpRequest(); xhr.open("POST", '/upload/'); xhr.send(fd); } </script> </head> <body> <form enctype="multipart/form-data" method="POST"> {% csrf_token %} <label for="file">Select a File to Upload</label> <input type="file" id="file" name="file"> <input type="button" onclick="uploadFile()" value="Upload"> </form> </body> </html> full stack trace: [06/Oct/2019 12:05:40] "GET / HTTP/1.1" 200 968 request.FILES is <MultiValueDict: {'file': [<TemporaryUploadedFile: 20190615_193154.jpg (image/jpeg)>]}> image is b'\xff\xd8\xff\xe1\\\xd5Exif\x00\x00II*\x00\x08\x00\x00\x00\x0c\x00\x00\x01\x04\x00\x01\x00\x00\x00 \x10\x00\x00\x01\x01\x04\x00\x01\x00\x00\x00\x18\x0c\x00\x00\x0f\x01\x02\x00\x08\x00\x00\x00\xae\x00\x00\x00\x10\x01\x02\x00\n' …