Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Single modelAdmin for multiple apps
My project has multiple apps. Users runs processess inside these apps. I want to record the starting time and the ending time for each process. I would like to display these information in a single view at django admin. Is it possible to build a modelAdmin with data from multiple apps? Should I use models to achieve this? Thanks in advance. -
Wrap a Django serializer in another serializer
I need a nested serializer in django. I have the following serializer that works: class LocationSerializer(serializers.ModelSerializer): coordinate = serializers.SerializerMethodField() message = serializers.SerializerMethodField() def get_message(self, instance: models.Location): if len(instance.message) > 1: return instance.message return None def get_coordinate(self, instance: models.Location): if instance.point: return {"latitude": instance.point.y, "longitude": instance.point.x} class Meta: model = models.Location fields = ('id', 'street', 'zip', 'phone', 'coordinate', 'message') The json this serializer produces needs to be wrapped in a a json object like this: { "locations": //here comes the serialized data } I tried it the following way with another serializer that has the serializer above in a field: class LocationResponseSerializer(serializers.Serializer): locations = LocationSerializer(many=True) But when I trie to use this serializer I always get the following error: The serializer field might be named incorrectly and not match any attribute or key on the `Location` instance. Original exception text was: 'Location' object has no attribute 'locations'. What am I doing wrong? Just wrapping it in a response object works, but is not a solution because it looks like this is not supported by the swagger frameworks that work with Django. Thanks for the help! -
Django geting request in signal post_save
I am trying to access Django built-in request to get some important data and most of them coming through my custom middleware, that is why i need to access the request at any means. this is my signal: @receiver(post_save, sender=MyModel) def create_journal(sender, instance, created, **kwargs): if created: # request.finance_data # Do something But there is no argument like request so I need to extend whatever needed to get request here.. in the request, I have finance_data and I access that like this: request.finance_data I know i can access it from view but my case will not solve in view, i need to access it in signal at any means Can anyone help me please to get this? -
HTML image not found
I have the code below: <body> <div class="team-section"> <h1>Our Team</h1> <span class="border"></span> <div class="ps"> <a href = "#"></a><img src = "p1.jpg" alt=""></a> </div> <div class="section" id="p1"> <span class="name">name</span> <span class="border"></span> <p> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. </p> </div> </div> </body> Can someone explain me why I have error: Not Found: /about/p1.jpg . I try to put p1.jpg in many places and the final was the same. file tree -
django rest use an url that does not go through the frontend
I'm working on a project angular and django (2.0.13). Currently the application is available in localhost:4200, and I can also reach admin with localhost:4200/admin/. But for an url that I defined localhost:4200/other/, I have the error: Error: Cannot match any routes. URL Segment: 'other' it works with the url localhost:8000/other/. my goal will be to do as for admin is to be able to use port 4200 to display url /other/ I did not find how it works for the url /admin/ thank you -
I want to load a template from the templates folder but I get an error that says the included URLconf does not appear to have any patterns in it
I am trying to load a template in my templates/pages folder and get the error: django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'pages.urls' from 'D:\\django\\pages\\pages\\urls.py'>' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. I have tried putting the templates folder in both the project and the app directory but still get the same error. In my settings.py I have: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] and: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'pages', ] my urls.py file in the root project folder named pages_project looks like: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('pages.urls')), ] and my urls.py in my app folder named pages looks like: from django.urls import path from . import views path('', views.HomePageView.as_view(), name='home') my views.py looks like: from django.shortcuts import render from django.views.generic import TemplateView class HomePageView(TemplateView): template_name= 'home.html' I have a template file named home.html in the path pages/templates/pages/home.html and looks like: <h1>Homepage</h1> -
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 # …