Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unusual error occurring when attempting to remove user from Django admin page
I am creating a simple endpoint in my project, where a user can delete their account. When I send this request, it successfully works: However when I attempt to remove a user from my admin page, this error occurs: Error: IntegrityError at /admin/users/user/ insert or update on table "django_admin_log" violates foreign key constraint "django_admin_log_user_id_c564eba6_fk_auth_user_id" DETAIL: Key (user_id)=(1) is not present in table "auth_user". My code: models.py: from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): pass def __str__(self): return self.username views.py: def deleteuser(request, username): user = User.objects.get(username=username) user.delete() return JsonResponse({"message": "User successfully removed"}, status=200) -
Why is bar blacklisted in pylint
I have an error while linting my django project with pylint. Pylint shows an error while linting my django project "C0102: Black listed name "bar" (blacklisted-name)" It's correct that I have a function called bar, but why is this name blacklisted? I don't know of a built-in with that name. -
gunicorn vs celery for concurrency in django
In Django webapp that's deployed, I get a POST request from external source in views.py As soon as post request is received, I modified post function to do certain action and deliver results(1.1.1.1 is endpoint) in views.py def post(self, request, *args, **kwargs): #do some action #deliver results to 1.1.1.1 In this case, I'm currently running task as the request comes. For instance, if 5 requests come in at once, it's currently processing one by one. But, I'd like to process all requests at once(assuming there are enough server load) and deliver results back. Would increasing workers in gunicorn solve the issue of concurrency or would it be better to utilize job queue like celery? I need something lightweight. If gunicorn is enough, how many workers would need to be set? And what is best practice method? -
Assign value to one-to-many field through django code
I am trying to assign value to a database entry that is defined using the models.ForeignKey. How should I refer to the variables in the referred model? In the code below, the assignment update_user.appointments.requester_name = requesting_user does not work. Googling has not helped me find the right solution. How should one refer to such variables from django/python? Below is my models.py class AppointmentRequest(models.Model): my_name = models.TextField(default='') requester_name = models.TextField(default='') meeting_year = models.TextField(default='') class CustomUser(AbstractUser): firstname = models.TextField(default='') lastname = models.TextField(default='') appointments = models.ForeignKey(AppointmentRequest, on_delete=models.CASCADE, default='', blank=True, null=True) I want to modify the value of appointments entry, i.e., my_name, requester_name, etc. Below is the code in views.py def book_appointment(request): requesting_user = request.GET['requesting_user'] update_user = CustomUser.objects.get(username=requested_user) update_user.appointments.requester_name = requesting_user -
ModuleNotFoundError: No module named 'mylife.wsgi'
So I'm trying to deploy my website in heroku. It gets deployed successfully but when i open the site, it displays application error. When I ran the logs, it displayed no module name mylife.wsgi. Here is the full error that I got. Starting process with command `gunicorn mylife.wsgi --log-file -` Process exited with status 3 State changed from starting to crashed. Also __import__(module) ModuleNotFoundError: No module named 'mylife.wsgi' I tried changing wsgi file, even added middleware, but no luck. Here is my wsgi.py file import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mylife.settings') application = get_wsgi_application() Here is my middleware from settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] Here is my Procfile web: gunicorn mylife.wsgi --log-file - Here is my requirements.txt Django==2.0 dj-database-url==0.5.0 dj-static==0.0.6 gunicorn==19.9.0 Pillow==3.3.0 psycopg2-binary==2.7.7 whitenoise==4.1.2 django_ckeditor Here is the file structure └───mylife ├───accounts │ ├───migrations │ │ └───__pycache__ │ ├───templates │ │ └───accounts │ └───__pycache__ ├───daily │ ├───migrations │ │ └───__pycache__ │ ├───static │ │ ├───css │ │ └───js │ ├───templates │ │ └───daily │ └───__pycache__ ├───mylife │ └───__pycache__ └───staticfiles ├───admin │ ├───css │ │ └───vendor │ │ └───select2 │ ├───fonts │ ├───img │ │ └───gis │ └───js │ ├───admin │ └───vendor … -
What are the directives available in django similar to angular directives?
Do we have any directives in django similar to Angular directives like ng-show, ng-if, ng-for etc? When I worked on Angular, those directives are very helpful to me to finish my work faster. For example: how will you use a for loop in templates of django? -
Quiero que todos los navegadores acepten la coma para decimales
Tengo un formulario que en Firefox me acepta la coma para separar los decimales pero con Chrome me acepta el punto. Quisiera que los dos navegadores me acepten siempre coma; quiero que sólo se pueda ingresar números como 560,25 o 1250,75, por ejemplo. Estamos usando HTML5, en un proyecto con Python/Django. -
How to filter models efficiently in Django?
I have a website which will have many companies (model instances) and each company will have many users (model instances). What is the best way to separate the users by company so that the users of each company are all segregated from each other? All the ways I am currently thinking about doing this seems to use some sort of filtering in every section of the site which seems very inefficient. I already used Django's Groups for different employee types. Should groups be applied at the top of the chain (i.e. companies)? Even if I applied companies to groups I would probably be filtering at the template level quite often which seems inefficient and "un-pythonic". What are the best practices here? -
call a method in views.py from template
I want to call a method in views.py from my html file in templates when the user is authenticated. I don't know what html syntax should I use here. I don't think a form or button should work since I want to simply call that method without letting user click any button. {% block content %} {% if user.is_authenticated %} <!-- I want to call the method here--> <div id="user-logout">Hi {{ user.username }}! <a href="{% url 'logout' %}">logout</a></div> {% block chess_page %} {% endblock %} <!-- else redirect to the login page --> {% else %} <meta http-equiv="REFRESH" content="0; {% url 'login' %}"> {% endif %} {% endblock %} -
different response in django unittestcases in windows and linux
I am running django unittest in windows and linux at same PC. In one testcase , I am using submit() to submit a form. From the response of submit, when I am using regex search to search a text. In linux it is giving result but same code and same test giving none result in windows. I have tried in window10 and python3.7 response_report = response_query.forms[2].submit() datasheet = re.search(f'Datasheet_72222_003_002_input.xlsx'.encode(self.encoding), response_report.body).group(0).decode(self.encoding) In windows, testcase is failing but in linux same testcase is passing. I am expecting it to run on windows -
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!!