Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Blank column created in some html table rows while displaying dynamic data in django templates
I want to display the dynamic data in html table and export the table in excel format. But the blank column created between the columns in some table rows and the data shifts to right in html table whereas the heading remains constant. -
fields from foreignkey is not showing data in django admin
I am trying to show fields from foreignkey, So my fields are showing but with empty value, i have value for these field. I have following code for admin.py @admin.register(OrderDetail) class OrderDetailAdmin(admin.ModelAdmin): list_select_related = ('category', 'industry', 'user') fieldsets = ( ('User Information', {'fields': ('first_name', 'last_name', 'email',),}), ) readonly_fields = ('first_name', 'last_name', 'email',) def first_name(self, obj): obj.user.first_name first_name.short_description = 'First Name' def last_name(self, obj): obj.user.last_name def email(self, obj): obj.user.email and related model code is here: class OrderDetail(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) -
can we use modelform to update an existing instance of a model?
i know that modelform in django is a form which is used to generate a model instance but suppose if we want to update an already present model instance through a modelform, then will it update a model or create a whole new instance. -
Issue in adding Current user to user field in Django Serializer
I am using APIView and I would like to provide the authenticated user as logged_in_user in my model. My post method: def post(self, request, format=None): serializer = ContactUsSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=HTTP_201_CREATED) return Response(serializer.errors, status=HTTP_400_BAD_REQUEST) And serializer: class ContactUsSerializer(serializers.ModelSerializer): def validate_logged_in_user(self, data): """ Check that the start is before the stop. """ # Get authenticated user for raise hit limit validation return self.context['request'].user class Meta: model = ContactUsQuery fields = ('company', 'email', 'phone', 'message','vehicle','category','logged_in_user') Still, a logged_in_user is saved null. Can anyone help me with this issue? -
Different results on using django app from local development server and heroku
I just started using heroku today. I was testing a web application, and got different results on using django app from local development server and heroku. From my local django webserver, the following search yields correct results: from django.db.models import CharField from django.db.models.functions import Lower CharField.register_lookup(Lower, "lower") import logging logger = logging.getLogger('testlogger') logger.info('This is a simple log message') items_set = [] if request.method == 'POST': print(request.POST.get) form = CGHSMetaForm(request.POST) name = request.POST.get('name').lower() items_set = CGHSRates.objects.filter( name__lower__contains=name).order_by('name') print(items_set) logger.info(items_set) else: form = CGHSMetaForm() return render( request, 'app/cghs_search.html', { 'rnd_num': randomnumber(), 'form': form, 'items': items_set, }) I get the following results: Code Name Rate 1098 After Mastectomy (Reconstruction)Mammoplasty Rs 13800.0 364 Local mastectomy-simple Rs 14548.0 251 Mastoidectomy Rs 17193.0 On heroku, however, I receive an empty result. The database is the default heroku database, a postgre db, defined by the following settings in settings.py: import dj_database_url DATABASES = {'default': dj_database_url.config(default='postgres://kpnbcpyqtxxjqu:2c86exffsdff0d789e7f3b29d70sfsfsffs7be197sffsfsffb233@ec2-53-22-46-10.compute-1.amazonaws.com:5432/dful1l3ra7nknn')} Why does the same database when accessed on different servers yield different queries? -
Django App logging INFO level logs to , HTTPD log file as error
I have a couple of Django Apps running and here is my configuration. The problem is that from the app named one.app all the INFO level logs are being logged as ERROR in the HTTPD log file. Should just add propogate = False for the one.app configuration ? Or is it something related to the Httpd configurations ? LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'file_log_formatter': { 'format': '%(levelname)3.3s %(asctime)22.22s [%(module)s:%(name)s::%(funcName)s] {%(process)d} %(message)s' }, 'verbose': { 'format': '%(name)-15s : %(asctime)s %(levelname)-8s %(pypath)s:%(funcName)s:%(lineno)d [%(process)d:%(thread)d] %(message)s' }, 'simple': { 'format': '%(levelname)s %(message)s' }, 'django.server': DEFAULT_LOGGING['formatters']['django.server'], }, 'filters': { 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, }, 'handlers': { 'app_file': { 'level': 'INFO', 'class': 'logging.handlers.RotatingFileHandler', 'filename': APP_LOG, 'formatter': 'verbose', 'backupCount': 1, # keep at most 1 backup log file 'maxBytes': 1024 * 1024 * 100, # 100MB }, 'monitor_file': { 'level': 'INFO', 'class': 'logging.handlers.RotatingFileHandler', 'filename': MONITOR_LOG, 'formatter': 'verbose', 'backupCount': 1, # keep at most 1 backup log file 'maxBytes': 1024 * 1024 * 100, # 100MB }, "celery_console": { "level": "DEBUG", "class": "logging.StreamHandler", "formatter": "verbose", }, 'console': { 'level': 'DEBUG', 'filters': ['require_debug_true'], 'class': 'logging.StreamHandler', 'formatter': 'verbose' }, 'syslog': { 'level': 'DEBUG', 'filters': ['require_debug_true'], "class": "logging.handlers.SysLogHandler", 'formatter': 'verbose' }, 'sentry': { 'level': 'ERROR', # … -
Modal login in navbar, I cant define it is authenticated
I want to log in with bootstrap_modal_forms via ajax, everything works, but I can not define in the navbar so that if the user is logged in, he added the field and changed it to others, I will add that the main page works, but I do not want to do subpages This is my header.html -> https://pastebin.com/FuUXKkWu So someone can tell me what is wrong ? in my LOGOWANIE is changed then another, bc i was try fix it but its not working, on Home Page, everythink working, but in subpages like {% url 'anime:anime_list' %} i have problem because showing all hidden links and show Login not picture and username -
How to represent subdomain.domain type url in django urls
I am coming across web. i notice that some websites represent different pages of a website like: https://play.google.com not https://google.com/play How to achieve same through django urlpatterns? -
render_to_response() - KeyError: 'object'
I'm working on Django. I'm getting the error below. I didn't find the solution despite the much increased. I'd appreciate it if you could help. /core/views.py class CreateVote(LoginRequiredMixin, CreateView): form_class = VoteForm def get_initial(self): initial = super().get_initial() initial['user'] = self.request.user.id initial['movie'] = self.kwargs[ 'movie_id' ] return initial def get_success_url(self): moive_id = self.object.moive.id return reverse( 'core:MovieDetail', kwargs = { 'pk':moive_id } ) def render_to_response(self, context, **response_kwargs): movie_id = context['object'] movie_detail_url = reverse( 'core:MovieDetail', kwargs = {'pk':movie_id } ) return redirect( to=movie_detail_url) I could not find movie.id from render_to_response returns context dic. -
How To Serve Django Applications with Apache and mod_wsgi on LXLE
I am trying to sever pages through Apache 2.4.18 from Django using mod_wsgi and receive error 403 Forbidden when I access local host. System: LXLE Unix Apache 2.4.18 Django version 1.11.17 libapache2-mod-wsgi-py3i Procedure followed:www.digitalocean.com Configuration: /etc/apache2/sites-available/000-default.conf # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName www.example.com ServerAdmin webmaster@localhost DocumentRoot /var/www/html # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. #LogLevel info ssl:warn ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # For most configuration files from conf-available/, which are # enabled or disabled at a global level, it is possible to # include a line for only one particular virtual host. For example the … -
Upload and retrieve files from Google Cloud Storage/ Buckets in Python/Django
I want to upload and retrieve file (that includes image and csv) for my django application. My project is currently hosted on Google App Engine Flexible. From my understanding, I need to use Google Cloud Buckets for the process. But I could not find relevant material online for the process. GoogleAppEngineCloudStorageClient API also provides the feature of writing a file and reading it (https://cloud.google.com/appengine/docs/standard/python/googlecloudstorageclient/functions#open) Please point me to the relevant resources for the same. Since I am new to Django and Google Cloud, I would really appreciate if you could share code snippets with me. Thanks in advance. -
How to append dyanmic url pattern at the beginning of fixed tail in django urls?
I want to give ajax call to dyanmic urls in django to get images. An individual profile can have it's own photos. Then team of individuals will display photos of all members and main page may highlight different random images from different teams. So, I can have following set of urls in django: 1. ^home/images/ 2. ^home/teams/1/images/ 3. ^home/teams/1/user/2/images/ I'll be using AJAX request to send details like team id, user id etc. So, there'll be only one view that'll handle any request related to viewing images. How can I route all above url request to this single view with single url pattern. To be specific, How can I construct dynamic urlpattern in django which will allow me to append '/images/' to any url at the run time? Means visitor should be routed to the same view whether he visits any of the above url? If there is any flaw in my logic or approach, please correct me as I am not expert in django. -
Django Admin UI add and edit objects in table form
I have a Django app that displays tables on the user end of database queries. I would like the admin to be able to edit those models and objects in table form. Ex: click a value and type in the new value instead of having to click the object and hit save. I’m unsure if there is an easy/conventional way to do this. Thanks! -
Add field to django auth user?
I am trying to add a new field to the built in auth user. Here is my code from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth import get_user_model from django.contrib.postgres.fields import ArrayField class Profile(models.Model): user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) newField = ArrayField(models.CharField(max_length=16)) @receiver(post_save, sender=get_user_model()) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=get_user_model()) def save_user_profile(sender, instance, **kwargs): instance.profile.save() And in my view I have the following: current_user = User.objects.get(username=request.user) current_user.save() And i am getting the error Exception Type: RelatedObjectDoesNotExist Exception Value: User has no profile. Am i doing this wrong? I creates a profile table in the db but that didnt seem to be the issue -
Creating dynamic reports based on location specific using Django , postures and other frameworks
Please suggest me , if any tools or framework , which can help in building reports table which should be dynamic , user friendly , and location specific , with Shango , postures as database. Suggestions will be welcome if data from postgres is returned as json format and render it as a dynamic customized report tables. -
django exclude urls using regular expression in list
I'm working on Middleware in django version 2.1. It is LoginMiddleWare where i need to exclude some urls if the requested url exits it returns None below is the portion of middleware code : middleware.py def process_view(self, request, view_func, view_args, view_kwargs): exclude_urls = [r'[admin]', r'[login]', r'[register]', r'[demo]'] if(request.path_info in exclude_urls): print('BELOW IS EXCLUDED URL') print(request.path_info) return None else: print('BELOW IS NOT EXCLUDED URL') print(request.path_info) The above code must identify the url requested by user request.path_info and must check exits in exclude_urls EXAMPLE : if requested url is https://www.example.com/login?query=1 this must identify login in that particular url and must return None THANKS IN ADVANCE -
Django Full Text Search Optimization - Postgres
I am trying to create a Full Text Search for an address autocomplete feature, leveraging Django (v2.1) and Postgres (9.5), but the performance is not suitable for an auto-complete at the moment and I don't get the logic behind the performance results I get. For info the table is quite sizeable, with 14 million rows. My model: from django.db import models from postgres_copy import CopyManager from django.contrib.postgres.indexes import GinIndex class Addresses(models.Model): date_update = models.DateTimeField(auto_now=True, null=True) longitude = models.DecimalField(max_digits=9, decimal_places=6 , null=True) latitude = models.DecimalField(max_digits=9, decimal_places=6 , null=True) number = models.CharField(max_length=16, null=True, default='') street = models.CharField(max_length=60, null=True, default='') unit = models.CharField(max_length=50, null=True, default='') city = models.CharField(max_length=50, null=True, default='') district = models.CharField(max_length=10, null=True, default='') region = models.CharField(max_length=5, null=True, default='') postcode = models.CharField(max_length=5, null=True, default='') addr_id = models.CharField(max_length=20, unique=True) addr_hash = models.CharField(max_length=20, unique=True) objects = CopyManager() class Meta: indexes = [ GinIndex(fields=['number', 'street', 'unit', 'city', 'region', 'postcode'], name='search_idx') ] I created a little test to check performance based on number of words in the search: search_vector = SearchVector('number', 'street', 'unit', 'city', 'region', 'postcode') searchtext1 = "north" searchtext2 = "north bondi" searchtext3 = "north bondi blair" searchtext4 = "north bondi blair street 2026" print('Test1: 1 word') start_time = time.time() result = AddressesAustralia.objects.annotate(search=search_vector).filter(search=searchtext1)[:10] #print(len(result)) time_exec … -
python manage.py runserver error : ModuleNotFoundError: No module named 'settings'
I am in the process on getting started with python and have run into a problem using django 2.1 and python 3.7 that many other people seem to have had as well. Below is my process for getting here: started a virtual environment started a django project attempted to run: python manage.py runserver I consistently get the error : ModuleNotFoundError: No module named 'settings' I've researched extensively to and came across a few solutions in the following SO questions, none of which were effective solutions for me. Has anyone come across this issue? First question researched Second Question researched Any insight would be helpful. Thanks in advance. -
Django python-accept two images from post method, combine those images in opencv and then json response the final image
I got the code for post face detection api in django. It sends an image, detect face in it and return an json data. from django.views.decorators.csrf import csrf_exempt from django.http import JsonResponse import numpy as np import urllib.request import json import cv2 import os define the path to the face detector FACE_DETECTOR_PATH = "H:/01Python/APItest/cv_api/haarcascade_frontalface_default.xml" @csrf_exempt def detect(request): # initialize the data dictionary to be returned by the request data = {"success": False} # check to see if this is a post request if request.method == "POST": # check to see if an image was uploaded if request.FILES.get("image", None) is not None: # grab the uploaded image image = _grab_image(stream=request.FILES["image"]) # convert the image to grayscale, load the face cascade detector, # and detect faces in the image image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) detector = cv2.CascadeClassifier(FACE_DETECTOR_PATH) rects = detector.detectMultiScale(image, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30), flags= cv2.CASCADE_SCALE_IMAGE) # construct a list of bounding boxes from the detection rects = [(int(x), int(y), int(x + w), int(y + h)) for (x, y, w, h) in rects] # update the data dictionary with the faces detected data.update({"num_faces": len(rects), "faces": rects, "success": True}) # return a JSON response return JsonResponse(data) def _grab_image(stream=None): if stream is not None: data … -
Load URL without Search Query
DJANGO/PYTHON I am trying to load http://127.0.0.1:8000/catalog/. If the user enters data into the on this page, the form sends a search_query to the database. My problem is that http://127.0.0.1:8000/catalog/ does not load – it leads to a 'MultiValueDictKeyError' exception type with exception value 'search_query'. However, when the user submits data into the form, (i.e. http://127.0.0.1:8000/catalog/?search_query=biography+of) the page loads. I am trying to make it so that http://127.0.0.1:8000/catalog/ loads without the user having to submit a search query. Here is my view function: def index(request): . . . num_of_word = [] bookInstance_titles = [] bookInstance_ids = [] num_of_word = BookInstance.objects.filter(status='a', book__title__contains=request.GET['search_query']).count() bookInstances = BookInstance.objects.filter(status='a', book__title__contains=request.GET['search_query']) for i in bookInstances: bookInstance_titles.append(str(i.book)) bookInstance_ids.append(str(i.id)) context = { . . . 'num_of_word': num_of_word, 'bookInstance_titles': bookInstance_titles, 'bookInstance_ids': bookInstance_ids, } I believe the problem is that the variables (num_of_word and bookInstances) are trying to access the request's search_query, yet the /catalog/ request does not have a search query. After research, I am still not sure how to solve this. Thank you! -
Heroku :Application error An error occurred in the application and your page could not be served. If you are the application owner
i pushed my django app to heroku but when i tried to access the application i got this error here is my logs 018-12-16T04:16:53.837508+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=sreeman-billing.herokuapp.com request_id=2acfa8c0-2eb7-410b-acc5-69917ad1d4a7 fwd="103.80.12.116" dyno= connect= service= status=503 bytes= protocol=http i couldnt figure out what the error is all about -
In Django, pass parameters in href when a href uses the urlpattern not the url tag
I am trying to pass a parameter in a urlpattern not the url tag. In urls.py, re_path(r'^send/(?P<uidb64>[0-9A-Za-z_\-]+)/$', views.send_email, name='send_email'), In views.py, error_messages = { ... 'inactive': _('<a href="/send/">Please get a new email</a>.'), } I have to send a parameter in /send/ how can I set it up? -
How to check new posts since users last login Django
Intro: I have a 3 models user, post, group. User is able to make posts however each post has to belong to a group. Users have to choose from the existing groups for their posts. Users cannot add, delete, update group's. Furthermore: Users can become a member of groups and when they click on a certain group. They see all the posts in that group. What I want When Users come on the home page they see posts that were added since the last time they logged in My Models class Post(models.Model): user = models.ForeignKey(User, related_name='posts') group = models.ForeignKey(Group, related_name='posts') title = models.CharField(max_length=250, unique=True) message = models.TextField() created_at = models.DateTimeField(auto_now=True) My Views class Homepage(TemplateView): template_name = 'home.html' def get_context_data(self, **kwargs): context = super(Homepage, self).get_context_data(**kwargs) context['object_list'] = Group.objects.all() context['post_list'] = Post.objects.order_by("-created_at") #What am I doing wrong in the below code new_posts = Post.objects.filter(created_at__gt(self.request.user.last_login)) context['new_posts'] = new_posts.count() return context In my templates I have <div class="list-group"> {% for group in object_list %} {{group.name}} {% if new_posts > 0 %} {{new_posts}} new {% endfor %} </div> NameError: name 'created_at__gt' is not defined -
Django app + 3rd party' s template directory
I' ve a django application to which i' m writing a 3rd party application which is getting placed in the virtualenv' s lib/python2.7/site-packages/appname directory . It has also template files, but the django application itself does not find it by default. What is the best way to write the 3rd party app in a way that the django app will find the template directory (in the easiest way)? The 3rd party app has the following structure: appdir/ views.py forms.py templates/ . The django app has the following related settings: TEMPLATES['APP_DIRS'] = True . Of course it' s an easy workaround to add the 3rd party app' s location to TEMPLATES['DIRS'], but i' m rather interested in the best technique. -
Internal Server Error when posting image via jquery, ajax and django
I'm trying to post a cropped image via Jquery and ajax. I've been following the solution to this question crop image using coordinates, however I've had no luck in receiving the image on Django's end, despite the CSRF token and image being handled by the ajax request fine. I haven't done anything in my views.py, just attempted to print request.FILES and request.POST to see if anything got returned but no luck. Not sure how or if I should be handling that a different way. JS function readURL(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function(e) { $('#image').attr('src', e.target.result) }; reader.readAsDataURL(input.files[0]); setTimeout(initCropper,1000); } } function initCropper() { console.log("initializing") var image = document.getElementById('image'); var cropper = new Cropper(image, { aspectRatio: 16/9, viewMode: 1, autoCropArea: 0.8, cropBoxResizable: false, minCropBoxWidth: 640, minCropBoxHeight: 360, minContainerWidth: 720, minContainerHeight: 405, crop: function(e) { console.log(e.detail.x); console.log(e.detail.y); } }); document.getElementById('crop_button').addEventListener('click', function(){ var imgurl = cropper.getCroppedCanvas().toDataURL(); var img = document.createElement("img"); img.src = imgurl; cropper.getCroppedCanvas().toBlob(function(blob){ var formData = new FormData(); formData.append('croppedImage', blob); formData.append('csrfmiddlewaretoken', '{{csrf_token}}') $.ajax({ url: '/campaigns/create/', method:"POST", data: formData, processData: false, contentType: 'multipart/form-data', success: function () { console.log("Upload success"); }, error: function () { console.log('Upload error') } }); }); }) }; HTML <div class="col-xl-9 …