Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
It does not work when copying and creating image of a server running a live Django app in the new server
I have a live Django server running. It is running in one of the servers made from a virtual machine, with IP that ends with 13. From VMWare, I copied the image of server 13 and created a copy in a server with an IP that ends with 14 just to avoid the IP crash. As far as my understanding goes, because the whole image was copied, I should not be having any problems when I access the copied IP address but even after restarting the apache2, it is giving me the internal server error. According to log, it says django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on '34.xxx.xx.xxx' (101)") Because all our servers, once it leaves the firewall, uses one IP address, connection to AWS RDS should not be a problem as it the Django app in server 13 is working flawlessly. What could be the problem? Thank you! -
How to set views in django restframework
I am experimenting with django rest framework. I want to build a simple CRUD to post products to the database. However, I get an error when i visit the url to post the product. serializers.py from rest_framework import serializers from .models import Product class ProductSerializer(serializers.ModelSerializer): model = Product fields = ("id", "name", "brand", "specs", "price", "stock", "picture") views.py from rest_framework import viewsets from .serializers import ProductSerializer from .models import Product class ProductViewSet(viewsets.ModelViewSet): serializer_class = ProductSerializer queryset = Product.objects.all() This is the error i get when I got to the url to post product 'tuple' object has no attribute 'values' -
Mock out a model field validator in Django
According to the patch documentation to mock out a certain function. We have to mock it from the module in which it is being used/called. a.py def function_to_mock(x): print('Called function to mock') b.py from a import function_to_mock def function_to_test(some_param): function_to_mock(some_param) # According to the documentation #if we want to mock out function_to_mock in a # test we have to patch it from the b.py module because that is where # it is called from class TestFunctionToTest(TestCase): @patch('b.function_to_mock') def test_function_to_test(self, mock_for_function_to_mock): function_to_test() mock_for_function_to_mock.assert_called_once() # this should mock out function to mock and the assertion should work I got myself in a situation where I cant tell exactly how to mock the function in question. Here is the situation. # some application validators.py def validate_a_field(value): # do your validation here. models.py from . validators import validate_a_field class ModelClass(models.Model): a_field = models.CharField(max_length=25, validators=[validate_a_field]) forms.py class ModelClassModelForm(forms.ModelForm): class Meta: model = ModelClass fields = ['a_field',] Finally in my tests.py tests.py class TestModelClassModelForm(TestCase): @patch('models.validate_a_field') <<< What to put here ??? def test_valid_data_validates(self, validate_a_field_mock): data = {'a_field':'Some Text'} validate_a_field_mock.return_value = True form = ModelClassModelForm(data=data) is_valid = form.is_valid() validate_a_field_mock.assert_called_once() <<< This is failing From my little understanding even though validate_a_field is called in models.py. It is never … -
How to grab images from URLs
I have a model in django with url field, I want to do something similar to Facebook, when you add a link to post, Facebook grap image preview from that link. So what I want to do is display a url from URL field in HTML template along with image from that URL.. I don't know if this something I can do with django/python or javascript. Thanks -
class view error "name 'context' is not defined" when passing model to template
I am trying to access model data in a template using the view class method (that I have done before), however the "NameError: name 'context' is not defined" continues to arise. from django.views.generic import TemplateView from django.shortcuts import render, redirect from .models import Email class MapView(TemplateView): template_name = 'Map/map.html' email = Email.objects.all() context = {'email': email} def get(self, request): return render(request, self.template_name, context) if I replace "context" with an empty dictionary "{}" then I can display the template, but even if i declare "context = {}" and try to return "render(request, self.template_name, context)" I still get the context is not defined error. -
Hashing an element received in a FileField in django
My objective is to make a custom create function that can make a hash in the sha256 format, but I keep running into problems with it in the different methods I try. Currently, if I run my application, it says the following: AttributeError at /sped_create/ FieldFile object has no attribute 'encode'. I vaguely understand what's causing the issue here. But I don't know how to fix it. Even after researching some different methods, I found nothing that'd suit my needs. Here's the code I have: models.py def hash_generator(file_bearer): integrity_hash = hashlib.sha256(file_bearer.encode('utf-8')).hexdigest() return integrity_hash class Sped (models.Model): json_file = models.FileField(upload_to='json_sped') # sped_file = models.FileField() integrity_hash = models.CharField(max_length=256, blank=True, null=True) # line_counter = models.CharField(max_length= 15000000) created_at = models.DateTimeField(auto_now_add=True) def save(self, *args, **kwargs): file_bearer = self.json_file self.integrity_hash = hash_generator(file_bearer) super(Sped, self).save(*args, **kwargs) (Indentation is correct, but for some reason the code snippet is turning out like this here) views.py def sped_create(request): if request.method == 'POST': form = SpedForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect(sped_list) else: form = SpedForm(request.POST, request.FILES, None) return render(request, 'sped_form.html', {'form': form}) forms.py class SpedForm(ModelForm): class Meta: model = Sped fields = ['json_file'] def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) sped = Sped.objects.all() context['sped'] = sped return context -
Django all related data
class Docs(models.Model): doc_id = models.BigIntegerField(primary_key=True) journal = models.CharField(max_length=50, blank=True, null=True) year = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'docs' class Assays(models.Model): assay_id = models.BigIntegerField(primary_key=True) doc = models.ForeignKey('Docs', models.DO_NOTHING) description = models.CharField(max_length=4000, blank=True, null=True) class Meta: managed = False db_table = 'assays' class Activities(models.Model): activity_id = models.BigIntegerField(primary_key=True) assay = models.ForeignKey(Assays, models.DO_NOTHING) doc = models.ForeignKey(Docs, models.DO_NOTHING, blank=True, null=True) record = models.ForeignKey('CompoundRecords', models.DO_NOTHING) class Meta: managed = False db_table = 'activities' I apologize in advance if this answer is easily found elsewhere. I have searched all over and do not see a simple way to query my data as intuitively as I feel like should be possibe. These are classes for 3 tables. The actual dataset is closer to 100 tables. Each doc_id can have one or many associated activity_ids. Each activity_id is associated with one assay_id. My goal is to obtain all of the related data for each of the activities in a single doc. For instance: query_activities_values = Docs.objects.get(doc_id=5535).activities_set.values() for y in query_activities_values: print(y) break >>> {'activity_id': 753688, 'assay_id': 158542, 'doc_id': 5535, ..... This returns 32 dictionaries (only part of the first is shown) for columns in the Activities table that have doc_id=5535. I would like to go … -
How to convert UTC time to local time in Javascript
My backend is in Django. I used Django's auto_now_add feature on model to add the current time when that model was created. For example: This is 2019-10-08 09:16:20.666754+00:00. How to convert this in local time in Javascript? I have not coded JS. So the line's a bit blurry for me. I tried the following method: function localize_time(date) { date = new Date(date); date = date.toString(); } Then I saw another SO post to add "UTC", that's not working either. when I am calling a said function from Django's template, it's showing following error: Uncaught SyntaxError: missing ) after argument list It's on that function. In Django's template, I am calling the function like this: <script type="text/javascript"> localize_time({{ user.created_on | safe}}); </script> If I don't add safe, then the error is: Uncaught SyntaxError: Unexpected number Thanks in advance. -
Implementing Beautiful soup in Django
views.py def home(request): context={ 'posts':Post.objects.all(), 'testrankings':cricket_rankings.teams_test, } return render(request,'cricbee/home.html',context) home.html {% for teams in test_rankings %} <h4>{{teams}}</h4> {% endfor %} cricket_rankings.teams_test is a list within a list with each list containing 5 items. When I try to print the contents of the teams, it doesn't get printed. Can someone please help!! -
Django Admin User Permission in database object
I have a models how look like this : class Article(models.Model): # Créé une entrée titre dans la table Article de max 100 caractères titre = models.CharField(max_length=100) # créé une entrée auteur dans la table Article de 50 caractères max auteur = models.CharField(max_length=50) # créé une entrée contenu dans la table Article sans limite de caractères contenu = models.TextField(null=True) # céé une entrée date dans la database en date type field date = models.DateField(default=timezone.now, verbose_name="Date de parution") # créé une entrée image dans la table Article à l'aide du path stocké dans un varchar # L'image est stocké dans la string définie par upload_to. image = models.ImageField(upload_to='image/article', null=True) # céé une entrée preview_text dans la database preview_text = models.CharField(max_length=500, null=True) # créé une entrée slug dans la table Article. Le slug sert à définir l'url de l'article # Il est rempli automatiquement en fonction du titre grâce au prepopulated-field dans admin.py slug = models.SlugField(max_length=100) # Ajout de la clef étrangère catégorie à la table Article. models.PROTECT empèche la supression de la catégorie # si utilisé par un article categorie = models.ForeignKey('Categorie', on_delete=models.PROTECT) # Ajout de la clef étrangère Flag à la table Article. models.PROTECT empèche la suppression du Flag si … -
Python pyminizip package requires password only once
I am using pyminizip to password protect my zip. I am zipping a file using the mentioned package in python. When I try to extract or read, it asks for a password. Till here is fine. However, once I have entered the password and read or extracted the file, then when I again try to read or extract the file, it does not ask for a password. Even when I again compile the code to create a zip, it will run fine but it wont ask for a password again even though the properties of the zip shows that it is password protected. I am on python 3.7.4 Here is my code: import pyminizip compression_level = 5 # 1-9 pyminizip.compress(src, None, dest.zip, "password", compression_level) -
Python is already installed within virtual env
When I created a virtual Environment , in that I am already getting Python 3.7 which is on my local Machine . But I need Python 2 for my Project . How should I install that in my virtualenv And Also why python is already there? -
Django:How to store images in database instead of media file?
I want to store images in database for various users.Its just like famous blog app but instead of blogs i want to store images in database.How can i implement my idea? -
Django runserver throws error during boot
Am trying to run a django server, the server was running fine, but after reverting to old git commit, it started to throw the below error when I do python manage.py runserver Error (venv_prd) D:\projects\rd-portal\rdportal>python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\Python36\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Program Files\Python36\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "D:\projects\rd-portal\rdportal\venv_prd\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "D:\projects\rd-portal\rdportal\venv_prd\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "D:\projects\rd-portal\rdportal\venv_prd\lib\site-packages\django\utils\autoreload.py", line 77, in raise_last_exception raise _exception[1] File "D:\projects\rd-portal\rdportal\venv_prd\lib\site-packages\django\core\management\__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "D:\projects\rd-portal\rdportal\venv_prd\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "D:\projects\rd-portal\rdportal\venv_prd\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "D:\projects\rd-portal\rdportal\venv_prd\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "D:\projects\rd-portal\rdportal\venv_prd\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Program Files\Python36\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "D:\projects\rd-portal\rdportal\venv_prd\lib\site-packages\django\contrib\auth\models.py", line 95, in <module> class Group(models.Model): File "D:\projects\rd-portal\rdportal\venv_prd\lib\site-packages\django\db\models\base.py", line 156, in __new__ new_class.add_to_class(obj_name, obj) File … -
How can I integrate a function based view into a Class Based View?
In my site I have 2 sections for users. The user posts page and the profile page. The profile page has all their info on it, so username, description, first/last name, etc. And the user posts page has all their posts on it. However, I want to integrate them together somehow. Here is some of the code. Here is the view for the User Posts class UserPostListView(ListView): model = Post template_name = 'mainapp/user_posts.html' context_object_name = 'posts' def get_queryset(self): user = get_object_or_404(User,username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-published_date') As you can see, I am returning the specific users posts. And now here is my profile view def view_profile(request,pk=None): if pk: user_profile = User.objects.get(pk=pk) else: user_profile = request.user context = {'user':user_profile} return render(request,'mainapp/profile.html',context) It returns all the user's info. Here is the HTML code for both the profile and user posts page {% block content %} <div class="profile-page-container"> <div class="profile-page-info"> <div class="profile-page-banner"> <div class="profile-page-banner-background"> <!-- <img src="https://cdn.pixabay.com/photo/2017/08/30/01/05/milky-way-2695569_960_720.jpg" alt="{{ user }}'s Background Image" > --> </div> <div class="profile-page-banner-text"> <h2 title="{{ user }}" id="username-profile-page">{{ user|safe|linebreaksbr|truncatechars_html:25 }} {% if user.userprofileinfo.verified %} <span class="image-profile-verified"><img draggable="false" title="Verified User" class="verifed" src="{% static 'images\verified.png' %}" alt="verified" width="25" height="25" srcset=""></span> {% endif %}</h2> <p>{{ user.first_name }} {{ user.last_name }}</p><br> </div> </div> <div class="profile-page-user-desc-box"> <p>{{ … -
Django social-auth-app-django always redirects to LOGIN_ERROE_URL
social-auth-app-django always redirects to LOGIN_ERROR_URL after the google authentication completes. I am using the custom user model I tried with default settinga, changing the pipelines and created my own, but none of them works. MIDDLEWARE = [ .... 'social_django.middleware.SocialAuthExceptionMiddleware', ] SOCIAL_AUTH_PIPELINE = [ 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.social_user', 'accounts.views.fetch_social_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ] def fetch_social_user(backend, user, response, *args, **kwargs): global SOCIAL_USER_EMAIL, SOCIAL_USER_FNAME, SOCIAL_USER_LNAME, SOCIAL_USER_IMAGE SOCIAL_USER_EMAIL = response['email'] SOCIAL_USER_FNAME = response['given_name'] SOCIAL_USER_LNAME = response['family_name'] SOCIAL_USER_IMAGE = response['picture'] I need to redirect it to login_success url -
django auth ldap | Add LDAP user in admin-panel
Maybe, anybody know... I need add LDAP user inside admin panel. My autentithication LDAP in Django works, but I have to add users very strange. First they log in and they are not allowed. Then I go to admin panel and see user is added, but without the Staff status flag. I activate the flag. The user can log in with his LDAP account. Question: Is it possible to first add an LDAP user in the admin panel itself and activate everything that is needed so that the user does not have to log in twice? -
How to partiallly update a model in django rest framework?
I built an api with django and I have a picture model that comprises an imagefield. I'm trying to perform a partial update I already tried setting partial = Trueto the Serializer's definition the serializer is class PictureSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Picture fields = ("id", "name", "picture", "button_1", "button_2", "button_3", "button_4") partial = True the model is class Picture(models.Model): name = models.CharField(max_length=250) picture = models.ImageField(upload_to="pictures/", null=True, blank=True) button_1 = models.BooleanField(default=False) button_2 = models.BooleanField(default=False) button_3 = models.BooleanField(default=False) button_4 = models.BooleanField(default=False) printed = models.IntegerField(default=0) the view is class PictureViewSet(viewsets.ModelViewSet): queryset = Picture.objects.all() serializer_class = PictureSerializer -
How to save the data from the post request in django?
I was trying to implement a comment in a blog using a POST method. I want to save get the data by POST method of name, email, text and save it to the database. Also, the date field should get the date.now() and blog field should get the Blog or id of the Blog. The code looks like this - models.py : from django.db import models class Blog...... class Comment(models.Model): id = models.AutoField(primary_key=True, default=0) blog = models.ForiegnKey(Blog_tables, on_delete=models.CASCADE) name = models.CharField(max_length=200) email = models.EmailField() Text = models.TextField() date = models.DateField() def __str__(self): return self.Text views.py from .models import Blog, Comment from django.shortcuts import render, get_object_or_404, redirect from django.template import loader, RequestContext from django.http import HttpResponse, HttpResponseRedirect def blog_detail(request, blog_id): blog = get_object_or_404(Blog, pk=blog_id) return render(request, 'home/detail.html', {'blog': blog}) def post_comment(request, blog_id): # Here's a post code to be implemented. Please read the commented text # 'blog' field of models will get the id of the blog # 'name' field will get the POST method value of input name="name" # 'email' field will get the POST method value of input name="email" # 'text' field will get the POST method value of input name="text" # 'date' will get the current Date # … -
Include foreign keys to modelform
I have two models: class A(models.Model): name = models.CharField() class B(models.Model): a_object = models.ForeignKey(A) value = models.PositiveIntegerField() I have a ModelForm for object A and I'm trying to create a select field for that relation: class AForm(ModelForm): b_types = ModelChoiceField(queryset=B.objects.all()) but I keep getting the error AttributeError: type object 'B' has no attribute 'all' What am I doing wrong here? -
When running djangos dbshell command, error you appear not to have the sqlcmd program installed or on your path
When I first started the project, I had access to the dbshell command, but now I don't because apparently I don't have the sqlcmd program installed or on my path. I must have somehow accidentally deleted it from the path or unistalled it. Do you know where it would be located, and/or where I could download an older version? (I am using sql server 2014, so the new one doesn't work) -
Django How to gather HTML for {% include %} and assign to JS variable
I am using JSPDF to convert HTML to a PDF. This is extremely simple if I have a rendered page and then clicking a button just exports the appropriate PDF, however, I am attempting to create a receipt via JSPDF and rendering the page prior to providing the PDF is not a good option. With this, I am using Django and basically what I want to do is use a template's html to render the receipt I need: For example: <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.0.272/jspdf.min.js"></script> let doc = new jsPDF(); $('#click').click(function () { let a = {% include 'receipt_template.html' with data=payment_data %}; doc.fromHTML(a, 0, 0, { 'width': 170 }); doc.save('receipt.pdf'); }); But this is not working as I am not gathering the template's HTML, I am literally rendering it on the page. Is what I am trying to do possible? -
How to do Delete Confirmation in Django
I am working on a project in django. I'm trying to do delete Confirmation alert before deleting data. How to do. Any advice would be much appreciated. views.py def del_data(request, obj_id): del_data = Order_data.objects.filter(order_no=obj_id) if len(del_data) > 0: del_data.delete() return redirect('/home/') return render(request, 'delete_conf.html', {}) urls.py urlpatterns = [ path('delete/<int:obj_id>/',views.del_data,name="del_data") ] delete_conf.html <table id="order_view_table"> <tr> <th>Name</th> <th>Email</th> <th>ACTION </th> {% for i in result %} <tr id="get_data"> <td id="name">{{ i.name }} </td> <td>{{ i.email}} </td> <td><a href="{% url 'app:edit_data' i.order_no %}" > <i class='fas fa-edit' ></i></a><a href="{% url 'app:del_data' i.order_no %}"><i class='fas fa-trash-alt' ></i></a> </tr> {% endfor %} </table> -
AWS Upgrading site Django site from Python 2.7 to 3.6
I've a Django project running on AWS with Django1.11 and Python 2.7. I am upgrading it to Django 2.2 and Python 3.6 I have it running locally and all tests pass. I am not trying to load it onto an AWS elasticbeanstalk instance. When I do eb deploy, I am getting the following error in the eb activity log Traceback (most recent call last): File "<string>", line 1, in <module> File "/opt/python/run/venv/local/lib/python3.6/site-packages/setuptools/__init__.py", line 5, in <module> import distutils.core File "/opt/python/run/venv/lib64/python3.6/distutils/__init__.py", line 4, in <module> import imp File "/opt/python/run/venv/lib64/python3.6/imp.py", line 27, in <module> import tokenize File "/opt/python/run/venv/lib64/python3.6/tokenize.py", line 33, in <module> import re File "/opt/python/run/venv/lib64/python3.6/re.py", line 142, in <module> class RegexFlag(enum.IntFlag): AttributeError: module 'enum' has no attribute 'IntFlag' The Python2.7 version was using enum34 (in requirements.txt) which I've deleted/uninstalled so I don't believe that is the issue. Can anyone help? -
How to fix "Project with ID "some id" doesn't exist" Django FileField model error
I have a model which I can edit from admin page. I want to upload the file, let the server do some changes to it, then download the file back. In models: class Project(models.Model): project_title = models.CharField(max_length=200) project_content = models.TextField() project_published = models.DateTimeField("date published", default=datetime.now()) project_file = models.FileField(default="Null",upload_to='Files') def __str__(self): return self.project_title In admin: class ProjectAdmin(admin.ModelAdmin): #fields = ["project_title", # "project_published", # "project_content", # "project_funded",] fieldsets = [ ("Title/date", {"fields": ["project_title", "project_published"]}), ("URL", {"fields":["project_slug"]}) ("Content", {"fields":["project_content", "project_file"]}), ] FileField generates 2 sub-fields: an upload button, and a "current" field with the link to the current file if one exists. File upload works just fine, and the file is stored in "Files" directory, but when I click the link I get redirected to homepage and get the "Project with ID "1/change/Files/somefilename" doesn't exist. Perhaps it was deleted?" error. I have tried adding to admin: def file_link(self, Project): if Project.project_file: return "<a href='%s' download>Download</a>" % (Project.project_file.url,) else: return "No attachment" file_link.allow_tags = True file_link.short_description = 'File Download' but it just prints the href as plain text, containing the "Files/somefilename" url.