Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to reuse a function or class in Django
This is my class TimesheetListApiV2 there are lots of such kind of classes. class TimesheetListApiV2(APIView): def get(self, request): try: accesstoken=AccessToken.objects.get( token=self.request.META.get('HTTP_AUTHORIZATION').replace('Bearer ', '') ) except ObjectDoesNotExist: return Response ( { "status" : False, "error" : "Wrong Access Token", "error_message":"You have provided wrong access token.", } ) Now in all my classes this piece of code is there. try: accesstoken=AccessToken.objects.get( token=self.request.META.get('HTTP_AUTHORIZATION').replace('Bearer ', '') ) except ObjectDoesNotExist: return Response ( { "status" : False, "error" : "Wrong Access Token", "error_message":"You have provided wrong access token.", } ) I want to write a function or class where to reuse that code instead of writing it. But it should be workable even request should be pass. Even in future i am going to add more such code which should be reused. -
What is Celery Broker and Beat?
What is the use of Celery Worker and Beat ? Need basic concepts in a understandable way. Not fully answered What are the roles of celery-worker, celery-beat, message-broker? Celery: Definition Celery Worker Defintion Celery Beat Definition -
How do i access a triply nested dictionary in django templates?
I am trying to access a triply nested dictionary that i have defined in my view in my Django code , but im not able to access it in django templates This is my dictionary mydict={'apple':{'attributes':{'color':red,'shape':round},'type':fruit}, 'mango':{'attributes':{'color':yellow,'shape':irregular},'type':fruit}, 'carrot':{'attributes':{'color':orange,'shape':long},'type':vegetable}} And the code i have written to access attributes of each key is for key,value in mydict.items(): for key2,value2 in value.items(): for key3,value3 in value2.items(): print(value3) this prints all the attributes of all the keys while i want attributes of each key seperately -
How to fetch the information from the third party API and display on your website?
I need to fetch data from this "https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=ece95912ea3746e68826c8eb30e2eb66" API and display on my site using Class based views in django -
Images are not loading into the home page from static
I dont know why image is not display on the home page. Please see my code. I am on windows running python3 and Django 2.1. Is there any setting need to be done in files somewhere in Django folders like any config file? Please guide -
Serving separate database per user django
i am creating database according this now: Saperate PostgreSQL db for each client, with automated migrations on creating client on single Django app and on same server now i want to serve the db per user. we can return db from db routers only if they exists in DATABSES var in setiing file. Can any body have idea how to serve db which are created on server but not added on settings.py, which will be accoeding to the logged in user. There will be a main db for user,in which there relations with there db name is saved. -
Getting an assertion error when testing views in django
I am writing testcases to test my views. I am writing a class to test my registration view. I have tested the get method but the post seems to give an error. Kindly help me out: Here is my tests.py: class ViewsTest(TestCase): def setUp(self): self.client = Client() def test_register(self): url = reverse('register') response = self.client.get(url) self.assertEqual(response.status_code, 200) response = self.client.post('/', { 'first_name': 'john', 'last_name': 'doe', 'email': 'johndoe@gmail.com', 'password': 'johndoe' }) self.assertEqual(response.status_code, 302) Here is my urls.py: url(r'^register/', views.register, name='register'), Here is my views.py: def register(request): if request.method == 'POST': user_form = CustomUserCreationForm(data=request.POST) if user_form.is_valid(): ob = CustomUserCreationForm.register(user_form) if ob.is_active is False and ob.is_staff is False: return render(request, 'todoapp/waiting.html') else: return render(request, 'todoapp/admin_success.html') else: return render(request, 'todoapp/register.html', {'errors': user_form.errors}) return render(request, 'todoapp/register.html', {'form': CustomUserCreationForm()}) Here is the error I am getting: self.assertEqual(response.status_code, 302) AssertionError: 404 != 302 -
Which latest solr version does djagno-haystack support?
I am using Django-Haystack for implementing search functionality in my Django application. I use Solr backend search engine for Haystack. I have below questions related to search backend What latest Solr version does Haystack support? Are there any alternatives which could be used instead of Solr? -
How to fix 'NOT NULL constraint failed' when I'm sending data for this field from django form
I have a use-case for a django app where I need to save a form with some validation. Everything works fine until I hit the submit button. An integrity error is raised on the last_salary field. But what's weird is the fact that I'm passing data for that field in the form and I even confirmed it by checking request.POST in the view. I couldn't think of much to try since this behaviour is pretty weird. I did try to fill even the fields which aren't required to see if that worked but it didn't (obviously?). It should be noted that I'm using sqlite db. My model is as follows: class EmployeeTestModel(models.Model): full_name = models.CharField(max_length=50) post_code = models.CharField(max_length=8, blank=True) last_salary = models.PositiveIntegerField() uk_resident = models.BooleanField() resume_file = models.FileField( upload_to='media/', validators=[FileExtensionValidator(allowed_extensions=['pdf'])] ) My view is: class EmployeeFormView(FormView): form_class = EmployeeTestForm template_name = 'form_app/form.html' success_url = reverse_lazy('submission_success') def post(self, request, *args, **kwargs): form = self.form_class(request.POST, request.FILES) if form.is_valid(): form.save() return HttpResponseRedirect(self.success_url) else: return render(request, self.template_name, {'form': form}) With all the required fields filled, I expect it to save the form successfully but it raises the error: django.db.utils.IntegrityError: NOT NULL constraint failed: form_app_employeetestmodel.last_salary How do I fix it? -
Django image processing: word breaks into half to a new line
I have have python function for drawing text on an image. The text would break mid-word, so 1/2 the word was on one line and 1/2 on the other line. How can we make sure this doesn't happen? I want the whole word to go to a new line. Below is the image example This is my code: from PIL import ImageFont, Image, ImageDraw from django.contrib.auth import get_user_model from entities.obituary.forms import ObituaryForm User = get_user_model() def imprint(obituary_model, obiuary_sample_model): normal_font_path = 'static/fonts/PTF55F.ttf' heading_font_path = 'static/fonts/hind-regular.ttf' normal_font = ImageFont.truetype(normal_font_path, 18) normal_font2 = ImageFont.truetype(normal_font_path, 24) heading_font = ImageFont.truetype(heading_font_path, 30) text_color = ( obiuary_sample_model.text_color[0], obiuary_sample_model.text_color[1], obiuary_sample_model.text_color[2], 255) image = Image.open(obituary_model.image) text_layer = Image.new("RGBA", image.size, (0, 0, 0, 0)) text_draw = ImageDraw.Draw(text_layer) # Texts to imprint name_text = obituary_model.name life_span_text = obituary_model.date_of_birth.strftime( '%B %d, %Y') + ' to ' + obituary_model.date_of_death.strftime('%B %d, %Y') location_title_text = 'Funeral Services' viewing_title_text = 'Viewing Info' location_text = obituary_model.address # 'Areaxyz round about\nCity,State' viewing_location_text = obituary_model.viewing_address # 'Areaxyz round about\nCity,State' funeral_date_time_text = obituary_model.funeral_date.strftime( '%B %d, %Y,') + ' ' + obituary_model.funeral_time.strftime('%-I:%M%p') viewing_date_time_text = obituary_model.viewing_date.strftime( '%B %d, %Y,') + ' ' + obituary_model.viewing_time.strftime('%-I:%M%p') family_title_text = 'Surviving Immediate Family' family_detail_text = make_multi_line(obituary_model.family_info, 25) # donation_title_text = 'Ways To Contribute' # donation_info_text = … -
Access Django Media File by external scripts in Development
I have django project where I am asking user to upload the file. So I was able to successfully create the form and save the files to the generic MEDIA_ROOT = media/ folder in the django root for the project using FILESYSTEMSTORAGE method. However the files are typically are csv files I need to so some data manipulation. How do I go about passing this file to an external module that I created that will do the data manipulation. django_app/ media/ django_app/ settings.py apps/ app1/ manipulation_script.py -
Django Admin: How to change model name?
I would like to change the model name displayed in admin. The idea is to be able to register filtered versions of the model to the admin view. I know that I can add filter options when viewing the model. I am not interested in doing that. I don't think using the approach for solving admin plural naming is an option: Django fix Admin plural. I could be wrong. If so, please tell me how this can be done. I found this approach which seems to be the right solutions: Change 'Change model class name' in Django Admin || Change the 'Change' <h1>. However, I can't make it work. Is it just me not trying hard enough? It is also an option to make a number of models and then register each of them. However, I will prefer to rename and register filtered versions in admin. Any suggestions for solving this little issue? -
Do a full text search by using two models
I have two models Item and Owner; class Item(models.Model): name = models.CharField(max_length=255) owner = models.ForeignKey(Owner, related_name='owner_items', on_delete=models.CASCADE) is_featured = models.BooleanField(choices=CHOICES, default=BOOL_NO) .................................. I do a full text search (based on django docs) in the Item name and description fields. PostgreSQL version is 10. search_vectors = ( SearchVector('name', weight='A', config='english') + SearchVector('description', weight='B', config='english') ) terms = [SearchQuery(term) for term in keyword.split()] search_query = functools.reduce(operator.or_, terms) search_rank = SearchRank(search_vectors, search_query, weights=[0.2, 0.4, 0.6, 1]) qs = Item.objects.all().annotate(rank=search_rank).filter(rank__gte=0.2).order_by('-rank') I want to introduce also the Owner, name field in the equation, also give a little boost to the rank if is_featured is true. I have the Owner instance model before doing this search. -
urlpatterns not behaving as expected
I have specified a url to list students and a url to display the student details however the url for the student details doesnt seem to work. The ursl.py looks like this: urlpatterns = [ path('', views.IndexView.as_view()), path('', views.SchoolListView.as_view(), name='list'), path('<int:pk>/',views.SchoolDetailView.as_view(),name='detail'), path('create/', views.SchoolCreateView.as_view(),name='create'), path('update/<int:pk>/',views.SchoolUpdateView.as_view(),name='update'), path('delete/<int:pk>/',views.SchoolDeleteView.as_view(),name='delete'), path('students', views.StudentListView.as_view(), name='student_list'), path('students/<int:pk>/',views.StudentDetailView.as_view(),name='student_details'), ] but when I click on the actual student it doesnt take me to basic_app/students/1 (for example) but to basic_app/1 Also when I manually type /basic_app/students/1 I get an error which says: NoReverseMatch at /basic_app/students/1/ Reverse for 'update' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['basic_app/update/(?P<pk>[0-9]+)/$'] What have I done wrong?` -
What files to deploy from Django project
I want to deploy my Django project files to my web server from my local git location and I can't seem to find straight forward documentation on what files I should be deploying/copying to the web server. Is there anyone out there that can assist or point me to some good documentation. Thanks! -
Having trouble accessing static css files with Django
I can't access static files with Django in the cmd, I'm getting this error: "GET /'/static/blog/css/main.css HTTP/1.1" 404 2371 these are the code #settings.py STATICFILES_DIR = [ os.path.join(BASE_DIR, 'static'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' <-----------------------------------------------> #base.html {% load static %} <link rel="stylesheet" type="text/css" href="'{% static 'blog/css/main.css' %}"> <------------------------------------------------> this is my directory ├───blog │ ├───migrations │ │ └───__pycache__ │ ├───templates │ │ └───blog │ │ └───static │ │ └───blog │ │ └───css │ └───__pycache__ └───HelloDjango └───__pycache__ -
Advice on how to test DRF model permissions with TDD
I am writing a DRF API for an educational website where users can access data based on the permission groups and object level permissions they have. When I started writing the tests, I wondered whether it is necessary to test requests with all possible permission combinations. For example, say one endpoint of the API needs three permissions to give access to its data, then you could write up to 9 test methods to test all possible combinations of permissions the user could have. Only one combination, the one where the user has all three permissions, will result in data and the rest will most likely result in a 403 Forbidden Response. Is it necessary? Or should I test it in another way? Any advice or personal experience is welcome. Thanks in advance. -
django vs jsp for production scale applications
I have done large scale production grade web application using JSP, understand the difficulties of jvm tuning, web containers and how to scale content (static and dynamic). In the recent years there is not much development in JSP with the exception of JSTL and I am not sure whether this will change in near future; I am considering Django as an alternative to host production grade, high scaling application. Considering my java/JSP experience what are the pros and cons i should be aware of when it comes to DJango particularly when it comes to scaling and performance -
Need to help problem when start django with gunicorn, how to fix it?
I tried running my project using Gunicorn with the command gunicorn --bind 0.0.0.0:8000 myproject.wsgi:application, but the result was an error and gunicorn canceled the boot. please help me gunicorn --bind 0.0.0.0:8000 core.wsgi:application [2019-03-26 10:55:16 +0000] [8560] [INFO] Starting gunicorn 19.9.0 [2019-03-26 10:55:16 +0000] [8560] [INFO] Listening at: http://0.0.0.0:8000 (8560) [2019-03-26 10:55:16 +0000] [8560] [INFO] Using worker: sync [2019-03-26 10:55:16 +0000] [8565] [INFO] Booting worker with pid: 8565 [2019-03-26 10:55:16 +0000] [8565] [ERROR] Exception in worker process Traceback (most recent call last): File "/home/rofi/demo.protek/lib/python2.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker worker.init_process() File "/home/rofi/demo.protek/lib/python2.7/site-packages/gunicorn/workers/base.py", line 129, in init_process self.load_wsgi() File "/home/rofi/demo.protek/lib/python2.7/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi self.wsgi = self.app.wsgi() File "/home/rofi/demo.protek/lib/python2.7/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/home/rofi/demo.protek/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load return self.load_wsgiapp() File "/home/rofi/demo.protek/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp return util.import_app(self.app_uri) File "/home/rofi/demo.protek/lib/python2.7/site-packages/gunicorn/util.py", line 350, in import_app __import__(module) File "/home/rofi/demo.protek/core/core/wsgi.py", line 16, in <module> application = WSGIHandler() File "/home/rofi/demo.protek/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 151, in __init__ self.load_middleware() File "/home/rofi/demo.protek/lib/python2.7/site-packages/django/core/handlers/base.py", line 80, in load_middleware middleware = import_string(middleware_path) File "/home/rofi/demo.protek/lib/python2.7/site-packages/django/utils/module_loading.py", line 20, in import_string module = import_module(module_path) File "/usr/lib64/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/rofi/demo.protek/lib/python2.7/site-packages/django/contrib/auth/middleware.py", line 4, in <module> from django.contrib.auth.backends import RemoteUserBackend File "/home/rofi/demo.protek/lib/python2.7/site-packages/django/contrib/auth/backends.py", line 4, in <module> from django.contrib.auth.models import Permission File "/home/rofi/demo.protek/lib/python2.7/site-packages/django/contrib/auth/models.py", line … -
error ""The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty."
Getting improper secret key error I have added secret key in base.py which is located in settings folder, however it shows error. -
Django 2.1: is it possible to include Ngrok's Domain in an email instead of localhost's?
i am using Ngrok to run my website with https://, and when i send an activation email to myself, instead of seeing 'https://something.ngrok.io/...' i get 'http://localhost:8000/...'. This is the code responsible for sending the Activation Email which - to my opinion - it should send Ngrok's domain not the development domain ... ... current_site = get_current_site(request) mail_subject = 'Activate your customer account.' message = render_to_string('user_register_email/account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(), 'token': user_token.make_token(user), }) receiver = form.cleaned_data['email'] email = EmailMessage( mail_subject, message, to=[receiver] ) email.send() messages.info( request, f'An activation link has been sent to %s' % (receiver)) return redirect('accounts:login') is it possible ? -
How can I assign attributes to form elements in forms.py without using class Meta?
I have a django form setup like so: from django import forms class ContactForm(forms.Form): full_name = forms.CharField(max_length=20) phone = forms.CharField(max_length=20) email = forms.CharField(max_length=30) message = forms.CharField(max_length=400) class Meta: fields = ['full_name', 'phone', 'email', 'message'] widgets = { 'full_name': forms.TextInput(attrs={'class': 'sizefull s-text7 p-l-22 p-r-22', 'placeholder': 'Full Name'}), 'phone': forms.TextInput(attrs={'class': 'sizefull s-text7 p-l-22 p-r-22', 'placeholder': 'Phone Number'}), 'email': forms.TextInput(attrs={'class': 'sizefull s-text7 p-l-22 p-r-22', 'placeholder': 'E-Mail Address'}), 'message': forms.TextInput(attrs={'class': 'dis-block s-text7 size20 bo4 p-l-22 p-r-22 p-t-13 m-b-20', 'placeholder': 'Message'}), } Which works fine. However, I recently learned that class Meta can only be used with ModelForms. I need to assign attributes like the above in my form, in forms.py. I understand it is bad practice to mix business and presentation logic, but I am dealing with a complicated paid web template at the moment, and methods to apply attributes using template tags have not worked so far. Given I am on a deadline, I am postponing assigning attributes that way as a v2 feature. My question is, if class Meta can only be used with forms that have a corresponding model, how can I assign attributes to form widgets in forms that do not correspond to a model and thus cannot use class … -
Django-Admin TabularInline modify inline item attribute before save
Hi I need to be able to add the current user to an inline object as it is being saved or modified. I am using django-admin dashboard as this application is not public facing. class Med(models.Model): generic_name = models.CharField(max_length=33) last_updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.SET_NULL) def save_model(self, request, obj, form, change): try: obj.last_updated_by = request.user except AttributeError: obj.last_updated_by = None super().save_model(request, obj, form, change) class Comment(models.Model): text = models.TextField(("Comment"), max_length = 1000, null=False) med = models.ForeignKey(Med, related_name="comments", on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.SET_NULL) def save_model(self, request, obj, form, change): obj.user = request.user super().save_model(request, obj, form, change) class CommentInline(admin.TabularInline): model = Comment extra = 0 class Med(admin.ModelAdmin): inlines = (CommentInline,) I have tried to override the save_related function as well, but it seems that the CommentFormSet objects it contains are ALL of them vs just the one being modified or saved: '_queryset': <QuerySet [<Comment: test>, <Comment: another test>]>, A few of the SO posts on this topic were stale and didn't have enough information to extrapolate a working save_related implementation either. -
What is the meaning of CELERY_TIMEZONE variable in the settings.py file of a Django project?
I know that USE_TZ=True saves all the datetime objects in UTC in the database. In that case, when a task is scheduled to run at regular period of time (say every 2 days or every Monday) using django_celery_beat, why cant the scheduler directly take the values from the database in UTC and check is_due and run accordingly? My basic question is what is the purpose of CELERY_TIMEZONE variable? What does it do? -
Manejo de subdomains in django
Cual es la forma correcta, una guia para el manejo de subdominios en django 2.1.7. he seguido estos pasos https://martinpeveri.wordpress.com/2017/03/20/subdominios-en-django/ y en la guia oficial de django no hay pasos claros que me indiquen como hacerlo. Al seguir los pasos alli descritos, aparece el error en la consola luego de correr el runserver django.core.exceptions.ImproperlyConfigured: WSGI application 'mysite.wsgi.application' could not be loaded; Error importing module. Alguna idea? Gracias de antemano,