Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot connect to celery signals from django
I have the default django integration from the celery docs. Also just added @before_task_publish.connect(weak=False) def before_task_publish_handler(*args, **kwargs): logger.error(f'Args {args}') logger.error(f'Kwargs {kwargs}') Running in the shell: debug_task.delay() There is no logging or breakpoint catching in pycharm. I do not think it connects to celery, but I do not know how to check. What am I missing? -
Using kong api gateway jwt plugin with django microservices
I am currently playing around with the Kong API Gateway and I would like to use it to validate the authentication and the authorization of users at the gateway and restrict access to services if the user is not logged in properly. I have already an existing authentication django microservice which issues JWTs whenever a user logs in but i cant share this tokens with the other microservices because each one of them have his own database. So i would now like to know if i can share the JWT secret produced by django and use it for jwt plugin of kong api and also do i need to create a consumer for every users and what is the right steps to achieve that ? Any hint would be highly appreciated. -
unable to create recs via foreign key association in django
I am completely new to django and python need your insights here I am trying to parse a list of csv files from a directory, storing the name and row_count in Files model and the content of the csv in Work model(associated with Files) I have two queries The recs are created in Files model , but no recs being created in Work model, below is my code and no error message is thrown Models class Files(models.Model): filename = models.CharField(max_length=100) work_count = models.IntegerField(default=0) class Work(models.Model): proprietary_id = models.IntegerField(default=0) iswc = models.CharField(max_length=1000) source = models.CharField(max_length=1000) title = models.CharField(max_length=1000) contributors = JSONField() file = models.ForeignKey(Files,on_delete = models.CASCADE) View root_dir="D:/Django/siva/files" for file in os.listdir(root_dir): with open(f'{root_dir}/{file}','r') as csv_file: csv_reader= csv.DictReader(csv_file,delimiter=',') Files.objects.create(filename=file, work_count=len(list(csv_reader))) for row in csv_reader: file_obj=Files.objects.get(filename=file) print(file_obj) Work.objects.create(proprietary_id=row['proprietary_id'],iswc=row['iswc'],source=row['source'],title=row['title'],contributors=row['contributors'],file_=file_obj) sample csv file title,contributors,iswc,source,proprietary_id Shape of You,Edward Christopher Sheeran,T9204649558,sony,1 Je ne sais pas,Obispo Pascal Michel|Florence Lionel Jacques,T0046951705,sony,3 And also is there any specific method to set the root_dir , so I don't need to change the filepath structure across OS's -
How to change the `frontend_domain` port in `GRAPHQL_AUTH` in the verification mail?
I'm working on a Docker-Django-Graphene-React stack where Django is the backend which receive GraphQL queries through Graphene from React which acts as the frontend. Everything runs in docker containers. Django on port 8000 and React on 3000. I'm currently working on the authentication with the python's django-graqhql-auth package. When a user register itself on the frontend form, the register mutation is correctly made to the backend and the account is created. A mail is sent at the same time to the user's registered mail address containing a verification link with a token that must be used with the veryifyToken mutation in order to flag the account as verified. Here is an example of the link: http://localhost:8000/activate/eyJ1c2VybmFtZSI6IkpvaG5zb2ZuZiIsImFjdGlvbiI6ImFjdGl2YXRpb24ifQ:1mQr0R:Wh25LJ6A1PRVCQT730kXXIk4i2QJgz1a4aNDe7RoZM0 The problem is that the port on the link is 8000, which redirects to the backend (Django). I would like to redirect the user on port 3000 which is the frontend (React). According to the documentation, I should be able to change the frontend_domain which I did. I also changed the path and the protocol values to see if it works: Here is what I put in my backend's settings.py file: GRAPHQL_AUTH = { "EMAIL_TEMPLATE_VARIABLES": { "protocol": "https", "frontend_domain": "localhost:3000", "path": "verify", } } … -
Django calculate sum of column after multiplying each row with a different value
I have three Django models defined as: class User(models.Model): name=models.CharField income=models.DecimalField expenditure=models.DecimalField group=models.DecimalField country = models.ForeignKey(Country) class Country(models.Model): name=models.CharField currency = models.ForeignKey(Currency) class Currency(models.Model): name=models.CharField value=models.DecimalField Users can be from different countries. Each country has a currency whose value is the exchange rate with USD. I am trying to calculate the sum of all the column after multiplying each value with the respective currency exchange rate. For example, for 3 Users: John:2:10:1:2 Jame:10:11:1:1 Mark:5:11:1:1 Country 1:USA:1 2:UK:2 Currency: 1:USD:1 2:GBP:1.5 I would like to print the sum after calculating income: (2*1.5) + (10*1) + (5*1) expenditure: (10*1.5) + (11*1) + (11*1) Final output: income: 18 expenditure: 37 I am thinking something like this might work but I could not quite get it: user=User.objects.filter(group=1).aggregate((Sum('income')*(country_currency_value),(Sum('expenditure')*(country_currency_value)) Any help is much appreciated -
Profiling database queries and latency of ordinary functions in django
We need some tool for analyzing non view functions of our django project particularly the celery-beat tasks. So, is there any tool for profiling queries and latency of running ordinary functions (not views) in a django app? Preferably, is there any decorators (or any other mechanism) that can add results of profiling an ordinary function to the output of tools like django-silk or django-debug-toolbar? -
What is this random key in Django form ? And how to get rid of it?
I am trying to create a form page but have no idea about this random key showing up below Enter details. Could anyone explain me about it and how do I get rid of it ? -
Django forms ValueError with HiddenInput widget
I have a weird problem. I have my model GameTask with fields like: activity = models.ForeignKey(Activity, verbose_name='Activity', related_name='activities', null=True, blank=True, on_delete=models.SET_NULL) distance = models.IntegerField(verbose_name='Distance [m]', default=0) I want to create form for this model and display activity and distance field only in specific category(field in GameTask) like: form.fields['activity'] = forms.CharField(widget=forms.HiddenInput(), required=False) form.fields['distance'] = forms.CharField(widget=forms.HiddenInput(), required=False) if category_slug == settings.GAME_TASK_SPORT_CATEGORY_NAME: form.fields['activity'] = forms.ModelChoiceField( required=False, queryset=Activity.objects.all(), widget=forms.Select( attrs={'placeholder': 'Aktywności', 'class': 'form-control'} ) ) and it works. These 2 fields display only with specific category.But when I want to save form I get error: Cannot assign "''": "GameTask.activity" must be a "Activity" instance. In addition I have defined structure like this: MODEL_PARAMS_TASK = { 'model': GameTask, 'fields': ['name', 'teams', 'activity', 'distance', 'description', 'button_text', 'cycle_type', 'self_confirm', 'confirm_attachment', 'attachment_options', 'points', 'max_points', 'image', 'multi_task_image', 'priority', 'attrs', 'private_attrs'], 'template_name': 'master/task_form.html', 'success_url': 'master_task_item', } I was thinking about refactoring this and create 2 forms (1 for specific category and 1 default), but maybe there is other solution to solve this problem. If something is not clear I will explain it more specific -
Django CK editor images not displaying, a quick F12 shows that images are comming from backend but not displaying, please help me to fix this
Hello , I am trying to develop a blog application using react and django and for description section i choose django ckeditor. when i upload a image using ck editor it's showing in adminpanel section no warnings because i double checked every path of django ckeditor . but those images are not dispalying in the front end it's just showing a blank image field. but it's working on a simple html file not working with React . images are totally blank where i am missing ? if i do a quick F12 to check if the image is coming from backend or not . it is coming there but just not showing, Text is showing just not image import React,{useState,useEffect} from 'react'; import {Link} from 'react-router-dom'; import axios from 'axios'; const BlogDetail =(props)=>{ const [blog,setBlog]=useState({}); useEffect(()=>{ const slug=props.match.params.id; const fetchFata=async()=>{ try{ const res=await axios.get(`${process.env.REACT_APP_API_URL}/api/blog/${slug}`); setBlog(res.data); } catch (err){ } }; fetchFata(); },[props.match.params.id]); const createBlog = () => { return {__html: blog.content} }; const capitalizeFirstLetter = (word) => { if (word) return word.charAt(0).toUpperCase() + word.slice(1); return ''; }; return( <div className='container'> <h1 className="display-2">{blog.title}</h1> <h2 className='text-muted mt-3'>Category: {capitalizeFirstLetter(blog.category)}</h2> <h4>Last commit {blog.updated}</h4> <div className='mt-5 mb-5' dangerouslySetInnerHTML={createBlog()}/> <hr/> <p className='lead mb-5'><Link to='/blog' className='font-weight-bold'>Back</Link></p> </div> … -
Forms and other component don't work with swup.js or barba.js
I'm currently coding a mobile app with a header and a footer common to all pages. I'm trying to add page transition to make the app smoother and avoid static reload each time an user move from one page to another. This is running on Django, and I only have a basic knowledge in javascript. So, I tried both swup and barba which work really great without so much complication except a specific point which simply kill the app functionalities. The main problem concern all my forms which doesn't work anymore if I go back to the concerned page without entirely refreshing the page. The be more precise, admitting I am on the 'home' page and moving to 'settings' page, if I now go back on 'home' none of the forms work anymore, including some other part of my html depending on css or javascript. I tried moving all css and javascript link tags in each swup/barba container of each page to get them reloaded each time but it doesn't work. Does anyone could tell me why is this not working ? Thank you in advance for your help ! -
How to get correct user?
How i can take a correct user? Let's assume I have a model named "MUSIC" in which it is located owner = models.ForeignKey(Profil, on_delete=models.CASCADE) I have a page on which i want display everything that is in the model "MUSIC". Views m = Music.objects.all() Okay i know that this display all project music. But the problem is how to assign the specific user from model named "Profile" to model named 'Music" Url path('profil_user/<int:pk>/',ShowProfilPage.as_view(), name='profil_user'), When i try: {% for x in m %} {{x}} <a href="{% url 'profil_user' x.pk %}> CLICK </a> {% endfor %} This take not a correct user profile but it doesn't get to the model called 'Profile' but to 'Music' http://127.0.0.1:8000/profile/profil_user/2/ it is http://127.0.0.1:8000/profile/profil_user/10/ http://127.0.0.1:8000/profile/profil_user/11/ -
celery autoscaling - determine optimum number of pool processes required
I need to determine the best possible combination of minimum and a maximum number of pool processes. Is there a way of testing and getting the optimum values? I'm using rabbitmq as a broker and this process is running on a machine with 8 cores -
Can't do a GET request using email as the primary key - "detail": "Not found."
I'm trying to do a GET request on an API that returns the relevant entry but keep getting not found. If I call: http://127.0.0.1:8000/bookings/booking/ I can GET all the entries but when I try GETing one entry based on the primary key (which is an email address (nested object) - yes I have considered changing this as I've read it's bad practice for many reasons). It just returns detail not found. Other endpoints where the primary key is ID work just fine. http://127.0.0.1:8000/bookings/booking/2customer%40business2.com/ Can someone explain to me why the email doesn't return an entry.` but I keep getting: "detail": "Not found." models.py class CustomerBookings(models.Model): completed = models.BooleanField() booking_startdate_time = models.DateTimeField() dynamic_slot = models.ForeignKey(DynamicSlot, blank=True, null= True, on_delete = models.SET_NULL, related_name="%(class)s_dynamicslot") customer = models.OneToOneField(Customer, primary_key=True, blank=True, on_delete = models.CASCADE, related_name="%(class)s_customer") views.py class BookingAPIViewSet(viewsets.ModelViewSet): # permission_classes= [DjangoModelPermissions] - disabled for testing serializer_class = CustomerBookingsSerializer queryset = CustomerBookings.objects.all() serializer.py class BookingSerializer(serializers.ModelSerializer): class Meta: model = CustomerBookings fields = ('__all__') -
Access model instance inside model field
I have a model (Event) that has a ForeignKey to the User model (the owner of the Event). This User can invite other Users, using the following ManyToManyField: invites = models.ManyToManyField( User, related_name="invited_users", verbose_name=_("Invited Users"), blank=True ) This invite field generates a simple table, containing the ID, event_id and user_id. In case the Event owner deletes his profile, I don't want the Event to be deleted, but instead to pass the ownership to the first user that was invited. So I came up with this function: def get_new_owner(): try: invited_users = Event.objects.get(id=id).invites.order_by("-id").filter(is_active=True) if invited_users.exists(): return invited_users.first() else: Event.objects.get(id=id).delete() except ObjectDoesNotExist: pass This finds the Event instance, and returns the active invited users ordered by the Invite table ID, so I can get the first item of this queryset, which corresponds to the first user invited. In order to run the function when a User gets deleted, I used on_delete=models.SET: owner = models.ForeignKey(User, related_name='evemt_owner', verbose_name=_("Owner"), on_delete=models.SET(get_new_owner())) Then I ran into some problems: It can't access the ID of the field I'm passing I could'n find a way to use it as a classmethod or something, so I had to put the function above the model. Obviously this meant that it could … -
Run or include gdal python scipt in Django
I am new (noobee) on Django. I have a python script that prints the times, X, Y of the dataset in a specific NetCDF file. import gdal netfile = gdal.Open('NETCDF:"E:/Jobs/statr.nc":tm25') print 'Band shape (T, Y, X): ', (netfile.RasterCount, netfile.RasterYSize, netfile.RasterXSize) How can I use this script in a Django project? For instance, if I have a button and an input box and on user click, show the script's output to the input box. Is there any way to include the script inside Django (view, template, etc)? Thanks in advance John -
?: (admin.E403) A 'django.template.backends.django.DjangoTemplates' instance must be configured in TEMPLATES in order to use the admin application
When i run my service using python manage.py runserver Then this error is occured. SystemCheckError: System check identified some issues: ERRORS: ?: (admin.E403) A 'django.template.backends.django.DjangoTemplates' instance must be configured in TEMPLATES in order to use the admin application. My settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', ], }, }, ] -
html tags in djnago email template
I am using django signals to send emails when a new record is assed to model : @receiver(post_save, sender=MeetingMember) def send_invited_emails(sender, instance, **kwargs): host = instance.meeting.host subject = "Mizban invition" # htmly = get_template('sendingemail.html') domain = Site.objects.get_current().domain context={'host':host,'meeting': instance,'domain':domain} html_content = render_to_string('sendingemail.html',context) send_mail(subject, html_content, settings.EMAIL_HOST_USER,[instance.email]) this code works but it sends html tags in email as well how can i sove this issue? -
Django ModelForm not valid (not saving to database)
I currently have a list of settings on my app, and if a user wants to update those settings I want them to be able to do that without going into the database. However, when the user clicks update , the page reloads but no changes are saved to the database. My code currently looks like this: Views.py: def viewSettings(request, settings_pk): setting = get_object_or_404(SettingsClass, pk=settings_pk) if request.method == 'GET': form = SettingUpdateForm(instance=setting) return render(request, 'main/viewSettings.html', {'setting': setting, 'form':form}) else: form = SettingUpdateForm(request.POST, instance=setting) if form.is_valid(): form.save() return redirect('settingsHome') return render(request, 'main/viewSettings.html', {'setting': setting, 'form':form}) Models.py: class SettingsClass(models.Model): Complex = models.CharField(choices=complex_list , max_length = 22 ,default='1' , unique=True) #Trial Balance Year To Date Trial_balance_Year_to_date= models.BooleanField(default = False) tbytd_Include_opening_balances=models.BooleanField(default = False) tbytd_Only_use_main_accounts=models.BooleanField(default = False) tbytd_Print_null_values=models.BooleanField(default = False) tbytd_Print_description=models.BooleanField(default = True) tbytd_Print_account=models.BooleanField(default = True) tbytd_Sort_by_account_name=models.BooleanField(default = True) #Trial Balance Monthly Trial_balance_Monthly=models.BooleanField(default = False) tbm_Only_use_main_accounts=models.BooleanField(default = False) tbm_Print_null_values=models.BooleanField(default = False) tbm_Print_description=models.BooleanField(default = True) tbm_Print_account=models.BooleanField(default = True) tbm_Sort_by_account_name=models.BooleanField(default = True) #Income Statement Year To Date Income_Statement_Year_to_date=models.BooleanField(default = False) isytd_Only_use_main_accounts=models.BooleanField(default = False) isytd_Sort_by_account_name=models.BooleanField(default = True) isytd_Print_null_values=models.BooleanField(default = False) isytd_Print_description=models.BooleanField(default = True) isytd_Print_account=models.BooleanField(default = True) #Income Statement Monthly Income_Statement_Monthly=models.BooleanField(default = False) ism_Only_use_main_accounts=models.BooleanField(default = False) ism_Sort_by_account_name=models.BooleanField(default = True) ism_Print_null_values=models.BooleanField(default = False) ism_Print_description=models.BooleanField(default = True) ism_Print_account=models.BooleanField(default = True) #Age … -
Generating automatic user registration number using django
What i wanted to achieve? I wanted to achieve {Company Letter}- {Country Code}-{1st Letter of 1st Name}{1st Letter of Last Name}-{000001-999999} For example: Company Name: Stack Overflow Username: Stack Overflow County is USA SO - 001 - SO - 000001 For that i have created a country, state and city model. I have created a custom user model. In the custom user model, i am using country, state, city drop down. So there is one field called registration numbers.. How can i generate registration number after registering one user.. Please guide me.. -
creating a database table for week schedule
i want to create a table for storing a weekly schedule for a doctor, my approach was like this: class ScheduleDay(models.Model): doctor = models.ForeignKey(Doctor, on_delete= models.CASCADE) #the name of the week day day = models.CharField(max_length=15) clinic = models.ForeignKey(Clinic, on_delete=models.SET_NULL, null = True) start_time = models.TimeField() end_time = models.TimeField() is it a good design to do this? -
How to update a particular field of a django model in class based views?
models.py class Grocery(models.Model): name = models.CharField(max_length=40) price = models.IntegerField(default=0) quantity = models.IntegerField(default=0) time = models.DateTimeField(default=datetime.now()) class Meta: verbose_name = 'grocerie' class Person(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) groceries = models.ManyToManyField(Grocery) my views.py class PersonSavedUpdateView(LoginRequiredMixin, UserPassesTestMixin,UpdateView): model = Person fields = ['groceries'] def test_func(self): person = self.get_object() if self.request.user == person.user: return True return False Here I want to update groceries field in the Person model through this updateView but i want to only delete a particular grocery from the logined User, How to do it -
React Django Application different ip adresses CORS issues
I try to deploy an APP1 application on an EC2 (whose IP address is app1_ip): the frontend is created with React and the backend is created with Django, django-rest-framework, gunicorn and nginx. The backend is the same as another APP2 application that is already deployed on a second EC2 (whose IP address is app2_ip). I have no trouble getting the second application to work and request its React frontend (located at port 3000 of app2_ip) on its backend (located at port 8000 of app2_ip). On the other hand, I have a lot of trouble requesting the backend of APP2 from the frontend of APP1. I'm missing something but I can't see what. I am looking to develop the cleanest production configuration possible. I have a login page that prompts the user to enter a password and a username. A request is then sent to the backend to verify these credentials. Fetch request from the login page used in the APP1 backend deployment : fetch(`https://{app2_ip}/token-auth/`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) nginx.conf file used in the APP2 backend deployment upstream django { server backend:8000; } server { listen 80; server_name my_server_name return 301 https://{my_server_name}$request_uri; } server … -
DJANGO - [Errno 30] Read-only file system: '/media'
I need your help because of an error regarding Media directory on Django forms.py from django.forms import ModelForm from .models import Mots from django import forms class CreeMot(ModelForm): mot = forms.CharField(max_length=50) level = forms.IntegerField(max_value=10) image = forms.FileField() class Meta: model = Mots fields = ["mot", "level", "image"] views.py def cree_mot(request): if request.method == "POST": form = CreeMot(request.POST, request.FILES) if form.is_valid(): form.save() return HttpResponseRedirect('/success/url/') else: form = CreeMot() return render(request, "cp/cree_mot.html", {'form': form}) settings.py STATIC_URL = '/static/' MEDIA_URL = '/media/' # Add these new lines STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_ROOT = os.path.join(BASE_DIR, 'staticfiles', 'media_root') And the error I have hen i submit my form [Errno 30] Read-only file system: '/media' Actually my /media/ directory is at the same place like /static/ cp /views.py /forms.py main_app /settings.py /... media static manage.py If you have a solution ... I put my /media/ in 777 chmod just in case ;) ... Thanks for your help ... Django is very usefull but regarding static and media it's not so easy to use ;) -
How can I use django-clever-selects for filters instead of forms?
I'm using ChainedChoiceField of django-clever-selets to automatically update a field if another field changes, in a form like this: class SomeForm(forms.Form): some_field = ChainedChoiceField( label=_("Field depending on parent field"), parent_field="some_parent_field", ajax_url=reverse_lazy('ajax:AjaxSomeView') ) Now I need the same functionality in a django rest framework FilterSet instead. Something like this: from django_filters.rest_framework import filters from django_filters.rest_framework import filterset class ChainedChoiceFilter(filters.ChoiceFilter): # This does not work, it's just a concept field_class = ChainedChoiceField class SomeFilterSet(filterset.Filterset): some_field = ChainedChoiceFilter( label=_("Field depending on parent field"), parent_field="some_parent_field", ajax_url=reverse_lazy('ajax:AjaxSomeView') ) Is there a way to do this? -
dj rest auth reset password sends raw html in email
I use dj rest auth package and i have overrided the reset password email like this in settings.py : REST_AUTH_SERIALIZERS = { 'JWT_TOKEN_CLAIMS_SERIALIZER': 'account.token.TokenObtainPairSerializer', 'USER_DETAILS_SERIALIZER': 'account_profile.api.userupdate.UserSerializer', 'PASSWORD_RESET_SERIALIZER': 'account_profile.api.customemail.CustomPasswordResetSerializer'} and in customemail.py : class CustomPasswordResetSerializer(PasswordResetSerializer): def save(self): request = self.context.get('request') # Set some values to trigger the send_email method. opts = { 'use_https': request.is_secure(), #'from_email': 'noreply@mizbans.com', 'from_email': getattr(settings, 'DEFAULT_FROM_EMAIL'), 'request': request, # here I have set my desired template to be used # don't forget to add your templates directory in settings to be found 'email_template_name': 'password_reset_email.html' } opts.update(self.get_email_options()) self.reset_form.save(**opts) and in email.py : class MyPasswordResetSerializer(PasswordResetSerializer): context={'domain':settings.WEBSITE_DOMAIN,'site_name':'mizban'} def get_email_options(self) : return { 'email_template_name': 'password_reset_email.html', 'context':'context' } I put a sample html code in password_reset_email : <html> <body> <p>welcome to{{domain}}</p> <p>site {{site_name}}</p> </body> </html> It works but it sends html tages codes as well in email template!