Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make python django website more effective for adds?
I tried google adds after coding but finding issues with them also. -
Problem in token generation with django rest framework for django-tenants
My django project is working properly with multi tenant architecture. I have implemented rest framework but it is giving me an error for token authentication. I tried multiple ways for generating token (admin panel, signals , custom token class, djoser package) but I get the same error(below). IntegrityError at /api/token/login insert or update on table "authtoken_token" violates foreign key constraint "authtoken_token_user_id_35299eff_fk_accounts_customuser_id" DETAIL: Key (user_id)=(3) is not present in table "accounts_customuser". I think this is because auth token table is created in public schema and users are in seperate schemas. My settings file - SHARED_APPS = [ 'django_tenants', 'accounts.apps.AccountsConfig', 'customer', 'api.apps.ApiConfig', #project containing rest api 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_filters', 'crispy_forms', 'rest_framework', 'rest_framework.authtoken', 'djoser', ] TENANT_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'accounts.apps.AccountsConfig', ' 'api.apps.ApiConfig', #project containing rest api 'rest_framework', 'rest_framework.authtoken', 'djoser', ] INSTALLED_APPS = list(set(SHARED_APPS + TENANT_APPS)) -
Saving profile instance when login
I am building a BlogApp I implement a feature and I am trying to save profile instance (Boolean) when user login. So I create a custom login page for saving profile instance, BUT User is successfully logging in BUT Profile instance (Boolean) is not updating. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) full_name = models.CharField(max_length=30,default='') email = models.EmailField(max_length=30,default='') send_notify = models.BooleanField(default=False) users/views.py def login_request(request): if request.user.is_authenticated: request.user.profile.send_notify = False request.user.profile.save() form = AuthenticationForm() return render(request = request, template_name = "registration/login.html", context={"form":form}) I have tried many times BUT is is still not updating, I also tried to change custom login but it is not even showing the login form. Any help would be much Appreciated. Thank You in Advance -
Which Django model should be used for staff members?
For a project (my own pet project) I am doing, I have an app called 'staff'. The ideas is 'staff' will contain list of all staff members in my organization. Now, they have to have an ability to login to the system and check what assets were assigned to them. The question is which built-in model (User, AbstractBaseUser, or AbstractUser) I should use for the 'staff' app? I've started with models.Model, however, I am thinking it might not be correct choice. -
Django ORM SQL Raw Mysql
select CONCAT(first_name,last_name)as broker_name,coupon_name, (select count(user_details.id)from user_details join user on user.id=user_details.user_id and user.role_id=3 where referral_coupon_id=coupons.id) as tenat_referrals, (select count(user_details.id) from user_details join user on user.id=user_details.user_id and user.role_id=2 where referral_coupon_id=coupons.id) as landloard_referrals from user LEFT JOIN coupons on coupons.user_id=user.id where role_id=4 -
I am new to Django and things i didnt understand are these can i get some insights
I have a problem or i am thinks that in which conditions do we write or to define functions like save and also in what condition do we need to write queryset -
Ignore changes to m2m relationship in post_save signal of django
I've got a question regarding django signals. Let's say I have these models: class Parent(models.Model): parent_name = (...) class Children(models.Model): child_name = (...) parent = models.ForeignKey(Parent, on_delete=models.CASCADE, related_name='children') And let's assume I have this signal connected to the post_save signal of Parent class: def handle(*args, **kwargs): (...) post_save.connect(handle, sender=Parent) Now, If I create a new child: some_parent = Parent.objects.get(...) new_child = Child.objects.create( ..., parent = some_parent ) Even though I'm just creating a new Child, Django will send a post_save signal from some_parent and thus handle will be invoked. Is there a way to ignore this signal? Something similar to this: def handle(*args, **kwargs): if <some_condition>: # check if the signal is sent just because a new child is created # Ignore the signal return # Do everything as usual ... -
how to use code block plugin in ckeditor5 cdn in python django?
it can't work... i cant find solution. please it can't work... i cant find solution. pleaseit can't work... i cant find solution. pleaseit can't work... i cant find solution. pleaseit can't work... i cant find solution. pleaseit can't work... i cant find solution. please <head> <script src="https://cdn.ckeditor.com/ckeditor5/29.1.0/classic/ckeditor.js"></script> </head> <body> strong text<textarea id="editor" name="queseditor"></textarea> <script> ClassicEditor .create( document.querySelector('#editor'), { codeBlock: { languages: [ { language: 'python', label: 'Python' } ] } } ) .catch( error => { console.error( error ); } ); </body> -
Why does this call to the Google Secret Manager API cause my Django application to hang?
In short: I have a Django application being served up by Apache on a Google Compute Engine VM. I want to access a secret from Google Secret Manager in my Python code (when the Django app is initialising). When I do 'python manage.py runserver', the secret is successfully retrieved. However, when I get Apache to run my application, it hangs when it sends a request to the secret manager. Too much detail: I followed the answer to this question GCP VM Instance is not able to access secrets from Secret Manager despite of appropriate Roles. I have created a service account (not the default), and have given it the 'cloud-platform' scope. I also gave it the 'Secret Manager Admin' role in the web console. After initially running into trouble, I downloaded the a json key for the service account from the web console, and set the GOOGLE_APPLICATION_CREDENTIALS env-var to point to it. When I run the django server directly on the VM, everything works fine. When I let Apache run the application, I can see from the logs that the service account credential json is loaded successfully. However, when I make my first API call, via google.cloud.secretmanager.SecretManagerServiceClient.list_secret_versions , the application … -
Django - After removing a table from models.py and migrations I get "relation "<table name> does not exist"
So I realized I could just remove a table and add it as a ManyToMany relation to another model and I removed the creation of the table from the migration files in the folder. But for some reason I'm getting the error below when I call python manage.py migrate django.db.utils.ProgrammingError: relation "<table name>" does not exist How do you properly remove tables and or add attributes to models in models.py without causing errors when you run python manage.py migrate? -
Right Way to inherit django form fields
EnquiryForm is a model form with many fields, I am not able to inherit fields of the Parent form using inheritance. class EnquiryForm(models.ModelForm): ... possession = forms.ChoiceField( required=True, choices=(('', '----Select----'),) + models.Enquiry._meta.get_field('possession').choices, widget=forms.Select(attrs={'class': 'form-control btn btn-primary'}) ) ... # It has several other fields and clean method to manipulate user inputs and form validation class EditForm(EnquiryForm): possession_month = forms.ChoiceField(label='Possession Month', required=True, choices=MONTHS.choices, widget=forms.Select( attrs={'class': 'form-control btn btn-primary', 'required':True}) ) possession_year = forms.ChoiceField(choices=possession_year_choices( datetime.now().year + 10, datetime.now().year), label='Possession Year', required=True, widget=forms.Select( attrs={'class': 'form-control btn btn-primary', 'required':True}) ) class Meta(EnquiryForm.Meta): model = models.Enquiry fields = EnquiryForm.Meta.fields + ('possession_month', 'possession_year', ) Notice here (last line), I am directly accessing EnquiryForm.Meta.fields. but I tried to access it by inheritance super().fields of the Meta class but no luck. Can we inherit fields through Meta inheritance such as super(EnquiryForm.Meta).fields. P.S. - Also I have to drop the field possession from parent Meta.fields in EditForm. -
Keep getting last value in for loop
I'm trying to get all the values in the variable roomnum, but the last value of roomnum keeps showing up. However, when I tried to print roomnum the values show up correctly. I'm not quite sure where the problem lies. roomnum = request.POST.getlist('polygon-names') print(roomnum) for k,v in unique_keys.items(): if category_in_excel == "Material": color_cell_format = workbook.add_format({'font_color': 'black', 'bg_color': v['color']}) color_cell_format.set_align('center') worksheet.write(row + 1, col, k, cell_format) worksheet.write(row + 1, col + 1, v['color'], color_cell_format) worksheet.write(row + 1, col + 2, convert_quantity_from_mm_squared_to(units, v['initialArea'], precision), cell_format) worksheet.write(row + 1, col + 3, units, cell_format) worksheet.write(row + 1, col + 4, ",".join(v['pages']), cell_format) else: for i in roomnum: print(i) worksheet.write(row + 1, col, i, cell_format) worksheet.write(row + 1, col + 1, convert_quantity_from_mm_squared_to(units, v['initialArea'], precision), cell_format) worksheet.write(row + 1, col + 2, units, cell_format) worksheet.write(row + 1, col + 3, ",".join(v['pages']), cell_format) Terminal when I print out the i value in roomnum: Values that I get in excel worksheet: As shown, the value keeps repeating for Polygon 3, when it should be Polygon 1,2,3. Any help would be greatly appreciated thanks! -
Where to learn to crop videos in django
I'm trying to crop video in my Django application, but I literally cannot find any resources or libraries on cropping videos, every time I search something up, image cropping recourses pull up and nothing about cropping videos. I'm using cropper.js to crop my images, but the library only does images and not videos. I want something like in the picture below that works for videos. If anyone could tell me where to start or recourses they recommend that would be much appreciated. -
ValueError at /result X has 118990 features per sample; expecting 103815
I am trying to make a fake news detector using scikit learn and I have deployed it on Django. I have made a front-end for inputting news descriptions from the user and display the result according to the prediction and I have used pickle to save the model. When I give input it shows the above error. Code for removing stop words and train test splitting def word_drop(text): text = text.lower() text = re.sub('\[.*?\]','',text) text = re.sub("\\W"," ",text) text = re.sub('https?://\S+www\.\S+','',text) text = re.sub('<.*?>+','',text) text = re.sub('[%s]' % re.escape(string.punctuation),'',text) text = re.sub('\n','',text) text = re.sub('\w*\d\w*','',text) return text news_total['text'] = news_total['text'].apply(word_drop) X = news_total['text'] # independent variable y = news_total['flag'] # dependent variable X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.1,random_state=0) 'flag' determines whether the news is fake or not and 'text' is the news description in the dataset. Vectorizer and classifier code vectorizer = TfidfVectorizer(stop_words="english",max_df= 0.7 ) X_train_vector = vectorizer.fit_transform(X_train) X_test_vector = vectorizer.transform(X_test) psa_classifier = PassiveAggressiveClassifier(max_iter = 100) psa_classifier.fit(X_train_vector,y_train) y_predict = psa_classifier.predict(X_test_vector) pickle.dump(psa_classifier,open('model_pickle.sav','wb')) Front end part Code of the views.py of the app of the project. Also model_pickle.sav is in the same directory as the app. loaded_model = pickle.load(open("model_pickle.sav", "rb")) news_total = pd.read_csv("final_dataset.csv") X = news_total['text'] # independent variable y = news_total['flag'] … -
Django Upload Images from Forms
I am trying to upload the images from django widget form. The rest of the form is filed correctly but the image field shows errors. Despite using the request.FILES is still getting the error. What could be the problem Here is my views.py file def addProduct(request): form = ProductForm() if request.method == 'POST': form = ProductForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('modifyAllProduct') context = { 'form': form } return render(request, 'products/Admin/addProduct.html', context) Here is my form.py class ProductForm(forms.ModelForm): class Meta: model = Product fields = ['image', 'title', 'category', 'price', 'description', 'is_published'] widgets = { 'image': forms.FileInput(attrs={'class': 'form-control'}), 'title': forms.TextInput(attrs={'class': 'form-control'}), 'category': forms.Select(attrs={'class': 'form-control'}), 'price': forms.TextInput(attrs={'class': 'form-control'}), 'description': forms.Textarea(attrs={'class': 'form-control'}), 'is_published': forms.CheckboxInput(attrs={'class': 'form-control'}), } Here is my model.py class Product(models.Model): image = models.ImageField(null=False, blank=False) title = models.CharField(max_length=2000, null=False, blank=False) category = models.ForeignKey( Category, on_delete=models.CASCADE, default=True, null=False) price = models.DecimalField(max_digits=5, decimal_places=2) description = models.TextField() delivery_time = models.DateTimeField(default=datetime.now, blank=True) is_published = models.BooleanField(default=True) created_at = models.DateTimeField(default=datetime.now, blank=True) digital = models.BooleanField(default=False, null=True, blank=False) -
JQuery UI autocomplete dropdown select change another field value and deselect dropdown clear field value
I am working on Django template. I am try to find solution that, when i select autocomplete dropdown then change value of this input field which (id=id_project_id). and if i deselect or any change on autocomplete input field, clear previous value of (id_project_id) input field and value set as (value = "00"). After lot of search & implementation, I found solution. Thats code work for me. <input type="text" name="package_name" id="id_package_name" placeholder="project...."> <input type="hidden" name="project_id" id="id_project_id" value="00"> Here is my solution script. $("#id_package_name").autocomplete({ source:'{% url 'autocomplete_project_name' %}', autoFocus: true, select: function( event, ui ) { $("#id_job_no").val(ui.item.job_no); // auto fill item code in id_code field $("#id_project_id").val(ui.item.project_id); }, // CHANGE INPUT FIELD change: function(event, ui) { $("#id_project_id").val(ui.item ? ui.item.project_id : "00"); }, minLength: 2, delay:500 }); }); -
UML diagrams to Django Models
I am a little bit confused about converting uml diagrams to django models. so I have decided to take help from you guys. so I am attaching a uml diagram so that you can guide me on how to convert it into django models. Your help would be ppreciated.enter image description here -
Do not saving when either of the 2 fields are not unique (Updated question)
I have the following codes models.py: class Device(models.Model): hostname = models.CharField(max_length=50, unique=True) ipaddr = models.GenericIPAddressField(protocol='ipv4', default='0.0.0.0') date_added = models.DateTimeField(default=timezone.now) def __str__(self): return self.hostname class DeviceDetail(models.Model): SUBNET_CHOICES = ( ('16','16'), ('17', '17'), ('18','18'), ('19','19'), ('20','20'), ('21', '21'), ('22', '22'), ('23', '23'), ('24', '24'), ('25', '25'), ('26', '26'), ('27', '27'), ('28', '28'), ('29', '29'), ('30', '30'), ) DEV_MODS =( ('Catalyst 9606R', 'Catalyst 9606R'), ('C9300L-48T-4X', 'C9300L-48T-4X') ) hostname = models.CharField(max_length=50) mgt_interface = models.CharField(max_length=50) mgt_ip_addr = models.GenericIPAddressField(protocol='ipv4', unique=True) subnetmask = models.CharField(max_length=2, choices = SUBNET_CHOICES) ssh_id = models.CharField(max_length=50) ssh_pwd = models.CharField(max_length=50) enable_secret = models.CharField(max_length=50) dev_mod=models.CharField(max_length=50, choices = DEV_MODS) ##device_model replacement DD2DKEY = models.ForeignKey(Device, on_delete=models.CASCADE) ##The key to link up the tables def __str__(self): return self.hostname class DeviceInterface(models.Model): MODULE_ID_CHOICES = ( ('TenGigabitEthernet','TenGigabitEthernet'), ('FortyGigabitEthernet','FortyGigabitEthernet'), ('GigabitEthernet','GigabitEthernet'), ('Ethernet','Ethernet'), ) moduletype = models.CharField(max_length = 50,choices = MODULE_ID_CHOICES) firstportid = models.CharField(max_length=50) lastportid = models.CharField(max_length=50) I2DKEY = models.ForeignKey(Device, on_delete=models.CASCADE) ##The key to link up the tables def __str__(self): return self.moduletype forms.py: class DeviceForm(ModelForm): class Meta: model= Device fields= ['hostname'] labels = { "hostname": "Hostname", } class DeviceDetailForm(ModelForm): class Meta: model= DeviceDetail fields= ['hostname', 'mgt_interface', 'mgt_ip_addr', 'subnetmask', 'ssh_id', 'ssh_pwd', 'enable_secret', 'dev_mod'] labels = { "mgt_ip_addr": "Management IP Address", } widgets = { 'enable_secret': forms.PasswordInput(), 'ssh_pwd': forms.PasswordInput() } def clean_hostname(self): hostname = self.cleaned_data['hostname'] if … -
How display custom error message above a model field in Django admin when a JSONSchemaValidationError occured?
I'm using JSONSchema validation but when an exception occurred it throw a validation error that will display the Validation Error message on a separate page. But I want to display an error message on the admin page next to that field displaying why the value is not saved. -
How to write create() function in DRF serializer for model with a many-to-many field by passing data through axios, and vue
I have vue at the frontend and I'm using axios to post user input to api. I have a Class model and a Student Model. In Student Model, I have a field named "classes" as many to many field. users will be able to input all the fields beside the class.id in the form(since I class.id can be retrieved using $router.params). I want to create the Student instance and add this class instance called clss to its relation. student.classes.add(clss). How am i supposed to implement the create() in serielizer class? I tied to come up with the following but it seems not working. class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = ( "id", "classes", "studentID", "lastName", "firstName", "gender", "dob", "ssn", "tel", "address", "email", "userName", "acctPass", "note" ) def create(self, validated_data): clss = self.request.query_params['class_id'] student = Student.objects.create(**validated_data) student.classes.add(clss) student.save() return student in AddStudent Vue i have the following: xport default { name: 'AddStudent', data(){ return { clss:{}, student:{} } }, async mounted(){ await this.getClass() }, methods:{ getClass(){ const classID = this.$route.params.id axios .get(`/api/v1/classes/${classID}`) .then(response => { this.clss = response.data }) .catch(error => { console.log(JSON.stringify(error)) }) }, submitForm(){ const classID = this.$route.params.id axios .post("/api/v1/students/", this.student, {params: {class_id: classID, } } ) … -
HTML format on Django text field model
I want to create a blog. I want to create blog content in admin panel and render the blog content with HTML format. models.py class Blog(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_created = models.DateField(auto_now_add=True) def __str__(self): return self.title In admin panel : Create blog content with HTML format in admin In template: {% extends 'base.html' %} {% block content %} <h1>{{ blog.title }}</h1> <p>{{ blog.content }}</p> {% endblock content %} Is there any template tags, model field, or anything to do this? -
Modal window retriving dynamic data by Django
I need a modal window that dynamically show post content. What i already have done: a post list which has title and some meta data. Some modal code when i click the title, it shows up. This is what i get so far. enter image description here But it is dead data, it is not retriving from database according to the pk of the post i clicked, which means i need to pass at least the prymary key of that post and get it show up in the modal window. -
Fields values do not display after detect error in form Django
The values filled in the form are not being shown after issuing a validation error. {{ object }} It is not shown. Form class EmpresaForm(forms.ModelForm): class Meta: model = models.Empresa fields = [ "fantasia", "razao", "cnpj", "seguimento" ] View class EmpresaCreateView(generic.CreateView): model = models.Empresa form_class = forms.EmpresaForm Template <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{form.errors}} <div class="form-group row"> <label class="col-sm-2 col-form-label" for="last_updated">last_updated: </label> <input class="form-control col-sm-10" id="last_updated" type="datetime-local" name="last_updated" value="{{ object.last_updated }}" disabled> </div> <div class="form-group row"> <label class="col-sm-2 col-form-label" for="created">created: </label> <input class="form-control col-sm-10" id="created" type="datetime-local" name="created" value="{{ object.created }}" disabled> </div> <div class="form-group row"> <label class="col-sm-2 col-form-label" for="fantasia">fantasia: </label> <input class="form-control col-sm-10" id="fantasia" type="text" name="fantasia" value="{{ object.fantasia }}"> </div> <div class="form-group row"> <label class="col-sm-2 col-form-label" for="razao">razao: </label> <input class="form-control col-sm-10" id="razao" type="text" name="razao" value="{{ object.razao }}"> </div> <div class="form-group row"> <label class="col-sm-2 col-form-label" for="cnpj">cnpj: </label> <input class="form-control col-sm-10" id="cnpj" type="text" name="cnpj" value="{{ object.cnpj }}"> </div> <div class="form-group row"> <label class="col-sm-2 col-form-label" for="seguimento">seguimento: </label> <input class="form-control col-sm-10" id="seguimento" type="text" name="seguimento" value="{{ object.seguimento }}"> </div> <input type="submit" value="Save" class="btn btn-primary"> </form> -
Django rest framework: read only views and serializers
As answers to this question suggested, to make a model readonly through drf, there're serializer level and view level solutions. Is it sufficient to make only one level readonly? readonly serializer readonly serializer + readonly view readonly view -
Django single query to count & use data on for loop?
I need to display total count & also use the queryset to loop on the template ! But the thing is its causing two queries to do this, is there any efficient way to manage this on single query ? data = Data.objects.filter(pk=pk) count = data.count // 1st query and then using data to iterate over loop on template // this makes second query Is there any other best way to do the same thing or it needs these two queries for sure ?