Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cyclic Connection in Database for easy lookup
I have the following model for student assessment: It will implemented this in Django with MySQL. I want to lookup for a given Student's SkillLevel quickly. But it takes too many links (queries) to go there (Blue line below). Also, I'd like to lookup what Skills does a SkillLevel belongs to. It takes even more queries (Red line below). I'm worried about the performance and difficulty to implement these queries. I am ruminating about shortcuts below (marked with question marks below). With some basic constraints and checks, I believe it will work without a problem. But I wonder whether there is a strong case against it that I can't see at this point. I don't want my database to collapse unexpectedly, for example. -
Django Admin Logo not Loading
I have created a new file base_site.html as per the books and in it i put this code: {% extends "admin/base.html" %} {% load staticfiles %} {% block title %}{{ title }} | {{ site_title|default:_('ADP site admin') }}{% endblock%} {% block branding %} <h1 id="site-name"> <a href="{% url 'admin:index' %}">My site <img src="{% static '/parcare/images/logo.png' %}" height="40px" /> </a> </h1> {% endblock %} {% block nav-global %}{% endblock %} This is from settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') And this is my static folder situation What am I doing wrong here? -
Django Action Stream error No Module named 'actstreamdjango'
I am building a Django app, and wrote in the code as it exists on the documentation to use Action Streams. This means: 'actstream' is in my INSTALLED_APPS I copied ('^activity/', include('actstream.urls')) into my urlpatterns and I copied the text in the Settings documentation to settings.py and I get the error: No Module named 'actstreamdjango' There is nothing else in the Get Started guide... what am I missing? -
headers and boundary included in uploaded file django rest framework
I'm uploading a csv file to Django via ajax, using Django Rest Framework. I have everything working, but data from the request headers is included with the file content. I was expecting these headers to have been stripped from the file content, so the file would look exactly like the uploaded file. Any ideas? ... Django View class FileUploadView(APIView): parser_classes = (FileUploadParser, ) def post(self, request, format=None): file = request.FILES['file'] fs = FileSystemStorage() fs.save('output.csv', file) input.csv: Date,Customer,Team Member,Services 09-25-2018 03:30 PM,Suzy16 Neil16,Suzy,Men's Haircut | Legs 09-25-2018 03:30 PM,Suzy16 Neil16,Suzy,Men's Haircut | Legs 09-25-2018 03:30 PM,Suzy16 Neil16,Suzy,Men's Haircut | Legs ... output.csv: ------WebKitFormBoundarycaNCidFSnOuN1u0G Content-Disposition: form-data; name="file"; filename="input.csv" Content-Type: text/csv Date,Customer,Team Member,Services 09-25-2018 03:30 PM,Suzy16 Neil16,Suzy,Men's Haircut | Legs 09-25-2018 03:30 PM,Suzy16 Neil16,Suzy,Men's Haircut | Legs 09-25-2018 03:30 PM,Suzy16 Neil16,Suzy,Men's Haircut | Legs ... ------WebKitFormBoundarycaNCidFSnOuN1u0G-- Relevant Headers From HTTP Request: Content-Disposition: attachment; filename=services.csv Content-Type: multipart/form-data; boundary=----WebKitFormBoundarycaNCidFSnOuN1u0G -
(gcloud.app.deploy) Error Response: [7] Access Not Configured. Cloud Build has not been used in project
I am running into this error while deploying my django(2.1) app with python(3.5) to appengine. Before, I was using python 2 and python27 in app.yaml, there was no such error, but now when I have python 3.5.2 and python37 in my app.yaml, I am running into this error after "gcloud app deploy". Do I really have to enable billing or am I doing something wrong? Is there a way out? The full error is ERROR: (gcloud.app.deploy) Error Response: [7] Access Not Configured. Cloud Build has not been used in project chaipani-217815 before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/cloudbuild.googleapis.com/overview?project=chaipani-217815 then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry. -
why after login in my site again i can see login page?
i have a question. 1. in Django i created a login page after login successfully. if i enter /accounts/login again i can see the this url and i can login again. how can disable login page after that user was login and if user enter url for login page get another page. views.py def user_login(request): if request.method == "POST": username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request,username=username,password=password) if user is not None: login(request,user) return redirect("home") else : messages.error(request,"Bad username or password") return render(request,"login.html",context={}) tnx for help -
Problem to make first migrate using Oracle in Django
I am trying to connect Oracle in my Django Project, but with no success. My versions: Python 3.7 x86 Django 2.1.1 Oracle Client 12.2.0.1.0 x86 Oracle Database 12.2.0.1.0 x64 cx-Oracle 7.0.0 settings.py file: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.oracle', 'NAME': 'lopestrc', 'USER': 'django', 'PASSWORD': 'django', 'HOST': '192.168.0.208', 'PORT': '1521' } } My tnsping response just fine and I can connect on database from my client station. But, when I try to migrate for the first time, I receive this error below: django.db.utils.DatabaseError: ORA-00955: name is already used by an existing object I haven't found any help on internet. Don't know what to do anymore. Does anyone can help? Thanks -
Django. DRY. Same context in get request
I am trying to make a voting app in django. Here the view that display a vote. class DetailVoteView(View): """ Displays the vote If vote is active allows to vote If vote is completed shows winners and top 5 """ vote = None vote_for_chars = None page_title = '' def dispatch(self, request, *args, **kwargs): self.vote = Vote.objects.get(id=kwargs['id']) self.vote_for_chars = self.vote.voteforcharacter_set.all() self.page_title = self.vote.title return super(DetailVoteView, self).dispatch(request, *args, **kwargs) def get(self, request, id): if is_active_vote(self.vote): nominates = self.vote_for_chars return render(request, 'vote_detail/active_vote_detail.html', context={ 'page_title': self.page_title, 'vote': self.vote, 'votes_name': self.page_title, 'nominates': nominates, }) else: winners = [] top_fives = [] if self.vote.voteforcharacter_set.count() != 0: sorted = self.vote.voteforcharacter_set.order_by('-votes_number') winner_number_votes = sorted[0].votes_number winners = self.vote_for_chars.filter(votes_number__exact=winner_number_votes) top_fives = sorted[winners.count():5 + winners.count()] return render(request, 'vote_detail/completed_vote_detail.html', context={ 'page_title': self.page_title, 'vote': self.vote, 'votes_name': self.page_title, 'winners': winners, 'top_fives': top_fives }) def post(self, request, id): vote_for_chars = self.vote_for_chars id_to_vote = request.POST.get("id_to_vote") char_to_vote = vote_for_chars.get(character__id=id_to_vote) char_to_vote.votes_number += 1 char_to_vote.save() return HttpResponseRedirect('/') The code is not DRY as I suppose. Because, there is the same context in get reuqest. I need to use a mixins feature? How can I improve it? Thanks. -
Django - upload both png or jpeg image and compress it
Im trying to compress images using django. The issue is im not able to compress png images. its raising 4.2.0 - IOError cannot write mode RGBA as JPEG error. I found snippet to convert png to jpeg. But how do I let the users upload both jpeg or png and convert it to jpeg only if the uploaded file is png. And the compress it. def compressImage(self,uploadedImage): imageTemproary = Image.open(uploadedImage) outputIoStream = BytesIO() imageTemproaryResized = imageTemproary.resize("RGB", imageTemproary.size, (500,500) )#1020,573 imageTemproaryResized.paste(imageTemproary, mask=imageTemproary.split()[3]) imageTemproary.save(outputIoStream, format='JPEG', quality=60) # change quality according to requirement. outputIoStream.seek(0) uploadedImage = InMemoryUploadedFile(outputIoStream,'ImageField', "%s.jpg" % uploadedImage.name.split('.')[0], 'image/jpeg', sys.getsizeof(outputIoStream), None) return uploadedImage This code is raising unknown resampling filter error what's the edit needed to get it work? -
Heroku: Deploying Django Rest Framework + Vue
I have a project made with Django (only DRF API) and Vue js. I have this project structure: root_directory/ βββ project_name/ β βββ settings.py β βββ ... βββ front_end/ β βββ ... vue files generated with CLI 3 ... βββ api/ βββ ... api app files ... I want to deploy this project using heroku and my biggest problem is: I don't know how to serve static files. In heroku docs is specified that I should use django staticfiles serving with whitenoise package (apart from hosting them in S3). But here comes another problem: vue-cli provided me a index.html file where everything gets injected when I run npm run build, so I can't access {% static 'example.js' %} in index.html directly, cause it is not the index.html that I should use, it is the one in dist/ folder, of course. But there everything gets minified and complicated for me to handle. I think npm run build would throw an error if it sees something like {% %} in public/index.html. I can't figure out how can I manage to deploy this project with heroku. What would be the best practice to deploy it in this situation? Thanks in advance. -
Changing default pop-up error message for default login form Django > 2.0
I created a html login page with Django (version > 2.0) using Django's in-build, default login form. It being the default form I don't have anything in my views.py or models.py files and I didn't even create a forms.py. I am generating the login form by calling it in my urls.py file like this: from django.urls import path from django.contrib.auth import views as auth_views urlpatterns= [ path('login/', auth_views.LoginView.as_view, {'template_name': 'log_in/log_in.html'}, name='login'} I then call the login view in my login.html file with Django's templating language like this: {% extends 'base.html' %} {% block head %} {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'auth_log/style.css' %}"> <title>Login</title> {% endblock %} {% block body %} <form method="post"> <div class="centered_err" align="center"> {% if form.errors %} <p class="alert">Username and password do not match.</p> {% endif %} </div> <div class="container" id="login_div"> <div class="centered">Login</div> {% csrf_token %} {{ form.username.label_tag }} </div> <div class="usr"> {{ form.username }} </div> <div class="pwd"> {{ form.password.label_tag }} </div> <div class="pwd"> {{ form.password }} </div class="centered"> <div class="centered_button"> <button class="button" type="submit">Submit</button> </div> </div> </form> {% endblock %} As you can tell from the html code I managed to create a custom error message if the user name and the password don't β¦ -
404 100 Error while connecting JS File to DJANGO App
Settings.py file in Project directory : I already added following : STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] I have a directory static under project directory. home.js is under validateurl directory under static. Referring JS File using following in template html file : Please advise what am I missing here. Errors below : -
Installed virtualenv drops some errors
Trying to run virtualenv with my project, but it shows some errors. Couldn't find a right solution, unfortunately. Maybe someone has dealt with the same issue before. (base) Organic:djangoproject organic$ mkvirtualenv py1 Using base prefix '/anaconda3' New python executable in /Users/organic/.virtualenvs/py1/bin/python3 Traceback (most recent call last): File "/anaconda3/bin/virtualenv", line 11, in <module> load_entry_point('virtualenv==16.1.0.dev0', 'console_scripts', 'virtualenv')() File "/anaconda3/lib/python3.6/site-packages/virtualenv.py", line 712, in main symlink=options.symlink) File "/anaconda3/lib/python3.6/site-packages/virtualenv.py", line 928, in create_environment site_packages=site_packages, clear=clear, symlink=symlink)) File "/anaconda3/lib/python3.6/site-packages/virtualenv.py", line 1234, in install_python shutil.copyfile(executable, py_executable) File "/anaconda3/lib/python3.6/shutil.py", line 121, in copyfile with open(dst, 'wb') as fdst: OSError: [Errno 62] Too many levels of symbolic links: '/Users/organic/.virtualenvs/py1/bin/python3' -
Images and Thumbnails in Django
I want to store the images along with the thumbnails of it. I am storing the images in file system in django. At first, the user will be able to see the thumbnails and after clicking it original images can be seen. I am using postgres database. Thumbnail size will be approx 200*200. Now my questions are: How should I store the thumbnails ? (in Database or in file system) How to convert the images to it's thumbnails ? (python library or something else) If anything better is possible for the mentioned feature please let me know. P.S.: High performance and lesser page load time is required. -
Django - was queryset filtered using some parameters or not
The question related to python - django framework, and probably to experienced django developers. Googled it for some time, also seeked in django queryset itself, but have no answer. Is it possible to know if queryset has been filtered and if so, get key value of filtered parameters? I'm developing web system with huge filter set, and I must predefine some user-background behavior if some filters had been affected. -
Upload files to s3 using celery tasks
I am trying to upload video file to s3 but after putting in task queue with celery. While the video is being uploaded, user can do other things. My views.py to call celery tasks def upload_blob(request, iterator, interview_id, candidate_id, question_id): try: interview_obj = Interview.objects.get(id=interview_id) except ObjectDoesNotExist: interview_obj = None current_interview = interview_obj if request.method == 'POST': print("inside POST") # newdoc1 = Document(upload=request.FILES['uploaded_video'], name="videos/interview_"+interview_id+"_candidate_"+candidate_id+"_question_"+question_id) # newdoc1.save() save_document_model.delay(request.FILES['uploaded_video'],"videos/interview_"+interview_id+"_candidate_"+candidate_id+"_question_"+question_id) # newdoc2 = Document(upload=request.FILES['uploaded_audio'], name="audios/interview_"+interview_id+"_candidate_"+candidate_id+"_question_"+question_id) # newdoc2.save() save_document_model.delay(request.FILES['uploaded_audio'],"audios/interview_"+interview_id+"_candidate_"+candidate_id+"_question_"+question_id) iterator = str(int(iterator) + 1) return HttpResponseRedirect(reverse('candidate:show_question', kwargs={'iterator': iterator,'interview_id':current_interview.id,'question_id':question_id})) else: return render(request, 'candidate/record_answer.html') Actual celery tasks.py @task(name="save_document_model") def save_document_model(uploaded_file, file_name): newdoc = Document(upload=uploaded_file, name=file_name) newdoc.save() logger.info("document saved successfully") return HttpResponse("document saved successfully") Document Model def upload_function(instance, filename): getname = instance.name customlocation = os.path.join(settings.AWS_S3_CUSTOM_DOMAIN, settings.MEDIAFILES_LOCATION, getname) # Add other filename logic here return getname # Return the end filename where you want it saved. class Document(models.Model): name = models.CharField(max_length=25) uploaded_at = models.DateTimeField(auto_now_add=True) upload = models.FileField(upload_to=upload_function) Settings.py AWS_ACCESS_KEY_ID = '**********************' AWS_SECRET_ACCESS_KEY = '**************************' AWS_STORAGE_BUCKET_NAME = '*********' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'static' AWS_DEFAULT_ACL = None MEDIAFILES_LOCATION = 'uploads/' DEFAULT_FILE_STORAGE = 'watsonproj.storage_backends.MediaStorage' # CELERY STUFF BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE β¦ -
Django request session cannot read the django-session table
I have two simple views, one is log in and the other one is just check the session. I added 'user_id' into the request.session and it did create a new entry in django_session table. But when I try to get the request session in a new request. It returns an empty one.enter image description here -
how to emble realtime in play chess in django
I see creat chess mutilplayer by nodejs (from: https://github.com/dwcares/RealTimeWeb-HOL) and I create a web chess by django, and I use js from chessboardjs.com. I wanna emble realtime in django, I read the guide chatbox by django channel, but I don't undertand to able it to django. what should I do? my project: https://github.com/ilove3q/webChess -
Adding note in Django Admin site's TubularInline
Currently my django admin site's setup looks like Topic submit_date: 2018/09/25 submit_user: blah Topic-category1 sub-topic field1 field2 --------------------------------- bleh bleh1 bleh2 mlem mlem1 mlem2 Topic-category2 something something1 something2 --------------------------------------- asd asd1 asd2 asd2 asd2-1 asd2-2 I want to add a note section in between Topic-category1 and the table, so it looks like Topic-category1 <this is where the note goes, functions like description> sub-topic field1 field2 --------------------------------- bleh bleh1 bleh2 mlem mlem1 mlem2 Is there a way for django admin to do it? I'm not using any of the custom form. Only using ModelAdmin and modify variables here and there -
How do I hide or remove message after it has been displayed for a certain amount of time?
html: {% if messages %} {% for message in messages %} <div class="message">{{ message }}</div> {% endfor %} {% endif %} js: <script> $(document).ready(function() { setTimeout(function() { $('.message').fadeOut('slow'); }, 2000); } </script> Here is my html and javascript. Right now the script does nothing to my message and it just stays on the page. I have tried moving the div container outside the for loop and if statement but nothing works. Is there a way around this or an alternate method? -
Schedule task for one year from now
What is the best way to schedule an event for a month or a year from now? For example, I want my program to send a notification one year after a customer's registration. I try to use celery with redis using the eta option but, at some point, the task multiplies and sends the same notification to the same customer (like 600 times). I also think that using a cronjob is not the best option. Any suggestions? -
Why might django_content_types be rebuilt?
When I edit an object (user 276) in django-admin, I get a foreign key error: IntegrityError at /admin/auth/user/276/change/ (1452, 'Cannot add or update a child row: a foreign key constraint fails (`my_db_name`.`django_admin_log`, CONSTRAINT `django_admin__content_type_id_c4bce8eb_fk_django_content_type_id` FOREIGN KEY (`content_type_id`) REFERENCES `django_content_type` (`id`))') On checking the records against user 276 in the django_admin_log table, I see that the field content_type_id is 126. mysql> select id, object_id, content_type_id, user_id from django_admin_log order by id; +----+-----------+-----------------+---------+ | id | object_id | content_type_id | user_id | +----+-----------+-----------------+---------+ | 1 | 276 | 126 | 276 | | 6 | 276 | 126 | 276 | | 8 | 276 | 126 | 276 | | 9 | 276 | 126 | 276 | | 10 | 276 | 126 | 276 | | 11 | 276 | 126 | 276 | | 13 | 1 | 144 | 276 | | 16 | 1 | 182 | 276 | | 19 | 276 | 126 | 276 | +----+-----------+-----------------+---------+ 9 rows in set (0.00 sec) When I look at the django_content_types table, I see id 126 is indeed there and relates to the correct type: mysql> select * from django_content_type order by id; +-----+---------------+---------------------------------+ | id β¦ -
Invalid character in identifier (SyntaxError)
cmd traceback: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' ^ SyntaxError: invalid character in identifier settings.py: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' Curious as I have been advised to do this to fix a problem I have with my project..(previous Q I have asked). -
Django from Python VS SQL for making database
Basically do you guys know which one would it be better to use between Django and SQL for database? And in terms of effectivity which one would be better? -
Django pyinstaller error Import error myapp
I developped myproject with Django 1.11.8 and all it's ok Now I trying to generate the "myproject.exe" file by pyinstaller 3.4 This is the structure: myproject\ manage.py myproject\ settings.py urls.py myapp\ models.py views.py urls.py [Settings.py] INSTALLED_APPS = [ 'django.contrib.admin', ... ... 'myapp', ] [myapp/views.py] from django.views.generic import ListView, TemplateView from myapp.models import ModelOne, ModelTwo .... [myapp/urls.py] from django.conf.urls import url from myapp import views from django.conf import settings ... I receive the error ImportError generate by the function: get_module_file_attribute(package) where I investigated that the package is "myapp" like the following: File "...\lib\site-packages\PyInstaller\utils\hooks__init__.py", line 340, in get_module_file_attribute raise ImportError ImportError