Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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! -
getting the count of a query set in Django
i am making a doctor appointment system, and i want to get the count of how many appointment i have in a specific day, so instead of doing it this way: appointments_count = Appointment.objects.filter(user = user, date = specific_date).count() will it be more efficient if i make another table for keeping track of the count of the appointments for each date, to avoid more i/o disk operations class Date_Counter(models.Model): doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE) date = models.DateField() count = models.PositiveIntegerField(default=1) and thanks everyone -
Django : Set is_active flag for User created by social-auth-app-django and google_oauth2
I am using social-auth-app-django for signup-signin of new users using google oauth2 authentication. after signup a new user is created in my db but the is_active is set as false, I want to set is_active as true only for users created by this social_auth google authentication (for other users who sign up using email-password I activate them by sending an account activation email) I have tried setting is_active = True for all users with no password , but I feel this way is insecure and hackish . How do I modify the social_auth_login flow to activate users as well ? I am using a custom User model : class UserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): if not email: raise ValueError('The Email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) if password: user.set_password(password) # else: # user.is_active = True <-------- tried this , worked too user.save() return user def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_active', True) extra_fields.setdefault('user_type', user_constants.SUPERUSER) if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self.create_user(email, password, **extra_fields) .. class User(AbstractUser): username = None # remove username field, we will use email as unique identifier email = models.EmailField(unique=True, null=True, db_index=True) client_id = … -
Don't return forms in context if they are not altered?
In my HTML-file I have a submit button (click_button) to do stuff and a submit button for a Django form (form_submit). All submits are redirected to one View-function (get_post_from_submit). If using the return render() function, I always have to return the context including the form, but I have no information of the form when I pressed the click_button. Is there any way to not return the form again? def get_post_from_submit(request): if request.method == 'POST': if "form_submit" in request.POST: # Do Stuff form = form_book(request.POST) if "click_button" in request.POST: # Do Stuff # Here the form always gets a reset, because I have no Info about the form in POST but it is needed as context... form = form_book() return render(request, 'home.html',{"form": form}) -
Vehicle rental system Database Structure [closed]
Vehicle Allotment The vehicle Allotment should be done automatically.A particular vehicle may have multiple quantities, hence if one vehicle is alloted for a duration of 2 hours the other vehicle must accept booking for that duration, if no vehicles are available then show "out of stock". The price of vehicles can change on weekends or on special occations. This is a project that I am currently working on and I am stuck at this. I am building this project with python Django. and Database MySql. Please Help. -
How to filter results and manytomany childs?
I am making a web page that display a "Kanban". I have columns as well as cards. I want to filter the results according to a field (priority) in the cards (Sale). My models: class PipelineColumn(models.Model): name = models.CharField(_("Name"), max_length=80) order = models.PositiveIntegerField(_("Order of column"), unique=True) default_probability = models.PositiveSmallIntegerField(_("probability")) class Meta: verbose_name = _("PipelineColumn") verbose_name_plural = _("PipelineColumns") ordering = ["order"] def __str__(self): return self.name class Sale(models.Model): name = models.CharField(_("name"), max_length=255) expected_income = models.FloatField(_("expected income")) probability = models.PositiveSmallIntegerField(_("probability")) contact = models.ForeignKey( "crm.Person", verbose_name=_("person"), related_name="sale_person", on_delete=models.PROTECT, ) date = models.DateField(_("date"), auto_now_add=True) scheduled_closing_date = models.DateField(_("scheduled closing date")) priority = models.PositiveSmallIntegerField(_("priority"), default=0) column = models.ForeignKey( "crm.PipelineColumn", verbose_name=_("column"), related_name="sale_column", on_delete=models.CASCADE, ) class Meta: verbose_name = _("Sale") verbose_name_plural = _("Sales") ordering = ["scheduled_closing_date", "-priority"] def __str__(self): return self.name For example, I would like to display only the columns and cards that have a priority of 2. If I try with PipelineColumn.objects.filter(sale_column__priority=2) it filters the columns well, only the columns with a sale with a priority equal to 2 are displayed. On the other hand, in the displayed columns all the sales are displayed even those whose priority is not equal to 2. I would also like to be able to filter the sales returned by my … -
django queryset filter many2many
In django i have two model classes that both of them have a many2many field. I want filter objects from this models that have subscription in their two many2many fields. How can I do that with queryset?