Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I use filter option in django rest framework using function based view
Here is my model: class Customer(models.Model): name = models.CharField(max_length=250) age = models.IntegerField() status = models.IntegerField() I want to use filter option for the Customer model with their age and status, which will pass by json format (not in the urls) using POST method. How can I implement the filter option? I am using function based view here. { "age": 20, "status": 2 } If I sent this json then it will filter out the Customer model. -
Migrate user accounts from old LAMP website to Django
We are rebuilding our old analytics website in Django. Our old website was built with LAMP stack. We have the usernames and passwords for all our accounts in un-hashed form. Now I want to migrate all those usernames and passwords to our Django website. All our users should be able to login to the new Django website using the same username and password. Can someone suggest some best practices to do this? How to achieve this objective efficiently? -
django - Searchview from two models using chain
I want to display search results combing two models. I am getting the search result from one model and not from the other. The field from the second model, datafile is not displayed. Not sure what I am missing. class SearchResultsView(ListView): #model = Metadataform model = Metadataform.objects.raw('SELECT "SSDatabase_metadataform".*, "SSDatabase_uploadmeta"."datafile" from "SSDatabase_metadataform" INNER JOIN "SSDatabase_uploadmeta" ON "SSDatabase_metadataform"."id" = "SSDatabase_uploadmeta"."path_id" order by "id"') template_name = 'searchresults.html' def get_queryset(self): # new query = self.request.GET.get('q') meta_list = Metadataform.objects.filter( Q(id__icontains=query) | Q(Authors_Name__icontains=query) | Q(Affliations__icontains=query) | Q(Methods__icontains=query) | Q(Instruments__icontains=query) | Q(Software__icontains=query)| Q(Models__icontains=query)| Q(Device__icontains=query) ) dataset_list = uploadmeta.objects.filter(Q(datafile__icontains=query) ) object_list = list(chain(meta_list, dataset_list)) return object_list <h1>Search Results</h1> <table class="table table-striped"> <thead> <tr> <th>Meta ID</th> <th>Author</th> <th>Download</th> </tr> </thead> <tbody> {% if object_list %} {% for a in object_list %} <tr> <td>{{ a.Authors_Name }}</td> <td> {{ a.datafile }} </td> </tr> {% endfor %} {% else %} {% endif %} </tbody> </table> -
django social auth extra argument and white listed domain not working
for my django project I'm using google social authentication which is working for me. now i want to allow particular email address which have my organizations domain only ( abc@example.com). hence only those mail allow to login who has suffix 'example.com' somewhere i read that i need to write SOCIAL_AUTH_GOOGLE_OAUTH2_WHITELISTED_DOMAINS = ['example.com'] in my settings.py, but still i'm able to login by other-then example.com mails. i also tried SOCIAL_AUTH_GOOGLE_OAUTH2_AUTH_EXTRA_ARGUMENTS = {'hd': 'example.com'} how can i fix this problem ? django version-2.2.7 -
social sign up with django-rest-auth and the custom user model (resources)
I am working on user authentication on my app using django-rest-auth. I also want to be able to connect to my custom model when the user is signing up with Google and Facebook signup. The problem is that the django-rest=auth documentation isn't clear enough. Please, can anyone share resources that have helped them with this? -
DeprecationWarning: Using or importing the ABCs from
I deleted all my migrations and then I try too add new migration but then it shows me a error. And now i'm not able to add migration. python manage.py migrate Operations to perform: Apply all migrations: contenttypes, core, sessions, admin, auth Running migrations: No migrations to apply. C:\ ...(path)...\.virtualenvs\File_compare-czl5peWG\lib\site-packages\django\db\models\fields\__init__.py:431: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working if name == "choices" and isinstance(value, collections.Iterable): -
How to build an instant messaging feature in already created django app between user and admin in django?
I am newbie to django I am having a user dashboard where I want to build an instant messaging feature like my requirement is admin should be able to message user which can be visible in frontend like a thread. Build a messaging feature in User Dashboard.How can I achieve this can you please guide me? -
Django Error Handling for Browser Support
I wanted to handle browser support. If the browser does not support the website, I would like to be redirected to a custom template. How do I find out if the browser supports it or not can anyone help me.? -
Render while pushing a button in Django
I have a simple HTML template in a django app: ... {% block analyze %} <br> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <button type="submit" name="run_script">Run Script</button> </form> {% if results %} <br> <a href="data:text/plain;charset=utf-8, {{results}}" download="results.json">download</a> {% endif %} {% endblock %} ... So when I push the button, the script in views.py should activate: def analysis(request): if request.method == 'POST' and 'run_script' in request.POST: ... # I get the variable finalresults here return render(request, 'template.html', { 'results' : finalresults, }) #in case the button is not pushed, I either want to render to #the template. But without running the script return render(request, 'template.html') The first time I enter there, it works. I push the button, and it runs my script. The problem is, when I reload the page, it automatically runs the script, without pushing the button. I just want the script to be run when I press the button, how could I do that? -
Disappear indexes on django template when i pass kwargs to modelformset_factory
Related to this post, passing extra kwargs to modelformset disappear indexes on template form.py class ConceptForm(forms.ModelForm): class Meta: model = app_models.Concept fields = '__all__' def __init__(self, *args, **kwargs): self.action = kwargs.pop('action', None) super(ConceptForm, self).__init__(*args, **kwargs) if self.action is not None: if self.action == 'detail': for field in self.fields: self.fields[field].widget.attrs['readonly'] = True ConceptModelFormset = modelformset_factory( model = model, fields = show_fields, extra = extra, min_num = min_num, max_num = 15, form = ConceptForm ) views.py form_kwargs = {} form_kwargs['action'] = action modelformset = ConceptModelFormset(queryset=queryset, prefix=model.__name__.lower(), form_kwargs=form_kwargs) template.html <div id="formset_{{ formset.prefix }}"> {{ formset.management_form }} {% for form in formset %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% for field in form %} <div class="form-group"> <label for="{{ field.id_for_label }}">{{ field.label }}</label> {{ field|add_class:"form-control" }} </div> {% endfor %} {% endfor %} </div> If i call to modelformset_factory method without specific form, the indexes appears but then the functionality of disabling the fields is not available. Anybody know what's happening. Thanks. -
Integrating Wagtail into a Saleor project
I have to make a Django e-commerce website for a client who need integrate regular news. For that, i would like to use Saleor and Wagtail but i'm not confortable whit Python and even if i succeed to install them separatly thanks to their documentation, i row to integrate Wagtail on Saleor's URLS, SETTINGS and VIEWS. I used the documentation and look for solutions on the internet but it seems very complex to me. My question is this, did any of you manage to make the two work together? Do you have any leads to give me? Thanks for your help. -
db query optimisation with alternate ways to handle expandable_fields
I am using ExpanderSerializerMixin as follows: class StateSerializer(ExpanderSerializerMixin): class Meta: model = State fields = ['name', 'population'] class CountrySerializer(ExpanderSerializerMixin): class Meta: model = Country fields = ('name', 'population') expandable_fields = { 'states': StateSerializer, } class PersonSerializer(FlexFieldsModelSerializer): country = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model = Person fields = ('id', 'name', 'country', 'occupation') expandable_fields = { 'country': CountrySerializer, } This created a performance overhead on the db. To enhance the performance of my serialiser, how can I override the expand or create my own mixin? -
how to get foreign key table field by name
throught this i am getting all the data fro the database context['Vehicle'] = Vehicle.objects.filter(user_id = hospital_id).filter(user_type = 1).filter(status = 1) Models I have class VehicleCategory(models.Model): category_name = models.CharField(max_length=50,unique=True) STATUS_CHOICES = ( (1, 'Active'), (0, 'Inactive'), (2, 'Deleted'), ) status = models.IntegerField( _('status'), choices=STATUS_CHOICES, default=1) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: db_table = "vehicle_category" verbose_name = 'Category' verbose_name_plural = 'Category' def __str__(self): return self.category_name class Vehicle(models.Model): user_id = models.IntegerField() vehicle_category = models.ForeignKey(VehicleCategory, on_delete=models.CASCADE) vehicle_no = models.CharField(max_length=25,unique=True) mileage = models.CharField(max_length=11,blank=False,null=False) STATUS_CHOICES = ( (1, 'Hospital'), (2, 'Vendor'), Through above query i am getting multiple records every record have their vehicle_category which i am getting the primary key of vehicle category i want the category name for the every record isntead of id relation of model is already given. please help me related to this i am facing this. how can i get thename fromthe single query with data -
Call command function from views.py [duplicate]
According to this [article][1], I made the Command class. myapp/management/commands/mycommand.py class Command(BaseCommand): def command_test(self): print("test command_test") Now I want to call this command_test from views.py like this below... Is it possible?? in myapp/views.py def index(request): Command.command_test() -
missing 1 required positional argument: 'user_id'
I am new in Django. When I click the link, I want the pdf to show user information, but when I click on the link it shows an error. Error it show is ticket_print() missing 1 required positional argument: 'user_id'. I think the error is caused by url, but I don't know how to fix it. My url.py urlpatterns = [ path("showticket/", ShowTicketListView.as_view(), name="show_ticket"), path("printticket/", views.ticket_print, name="ticket_print",), ] My View.py def ticket_print(request, user_id): user = get_object_or_404(Profile, user_id=user_id) template = get_template("user/ticket_print.html") html_result = render_template( template, {"username": profile.user, "phone": profile.phone_number, }, ) return html_to_pdf(html_result, name=f"Ticket_Print{user}") My models.py class Profile(models.Model): user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) birth_date = models.DateField(blank=True, null=True) phone_number = models.CharField(max_length=14, blank=True) Thanks. -
What is id value in the following code?What is exactly id generating?Does it generates choice 1 or only 1?
{% for choice in question.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br> {% endfor %} -
Javascript initially works, then fails after an Ajax call
What could be the reasons why js would work perfectly fine after a refresh, but not after an Ajax event ? I have a template from where I can create new object instances using intercooler.js ( a library using AJAX), Template A: <div id="page-content"> [stuff] <div> <a ic-get-from="{% url 'home' %}?add_new=True" ic-target="#page-new" > <i class='fa fa-plus'></i> </a> </div> </div> <div id="page-new"></div> and an other one that handle the actual creation of the new object instance, Template B: <form ic-post-to="{% url 'home' %}?add_new=True" method="post" ic-target="#page-content" ic-select-from-response="#page-content"> <div>{{new_object.name}}</div> <button type="submit" >Submit</button> </form> So far so good. Now I want to add my own js and added on Template A a listener on the div '#js-test': <div id="js-test"></div> and the js: $(document).ready(function() { console.log('js called !'); $('#js-test').click(function(){ console.log('Math.random():', Math.random()) }); }); Now, whenever I create new objects and refresh the page, the js works. But as soon as I create a new object with IC, then the console doesn't even log 'js called'. Any obvious mistakes to you ? -
Django inlineformset_factory in UpdateView formset data is not update
I'm using class based views in my project. In CreateView using multiple forms (inlineformset_factory) is working and I saved my both forms data successfully. But when I tried to edit my formset using using class based views (UpdateView) only first form data is updated successfully. But the formset (inlineformset_factory) data is not updated. Please help to find out problem in my (UpdateView). views.py class MaterialRequest_update(UpdateView): template_name = 'inventory/edit_files/material_request.html' form_class = MaterialRequestForm model = MaterialRequest success_url = reverse_lazy('inventory-material-request') def get_queryset(self): id = self.kwargs['pk'] return MaterialRequest.objects.filter(pk=id) def get_context_data(self, **kwargs): context = super(MaterialRequest_update, self).get_context_data(**kwargs) if self.request.POST: context['form'] = MaterialRequestForm(self.request.POST, instance=self.object) context['formset'] = MaterialRequestFormset( self.request.POST, instance=self.object) else: context['form'] = MaterialRequestForm(instance=self.object) context['formset'] = MaterialRequestFormset(instance=self.object) return context def form_valid(self, form): context = self.get_context_data() formset = context['formset'] if form.is_valid() and formset.is_valid(): form.save() formset.save() return super().form_valid(form) forms.py # Main Form class MaterialRequestForm(forms.ModelForm): class Meta: model = MaterialRequest fields = [ 'location', 'job', 'task_num', 'supervisor', 'entry_serialno', 'date', 'department', 'ref', 'other_info', 'attachment' ] labels = { 'location':'Location', 'job':'Job', 'task_num':'Estimate No', 'supervisor':'Supervisor', 'entry_serialno':'Entery No', 'date':'Date', 'department':'Department', 'ref':'Reference', 'other_info':'Other Info', 'attachment':'Attachment File' } widgets = { 'location': forms.Select(attrs={'class':'form-control select-search'}), 'job': forms.Select(attrs={'class':'form-control select-search'}), 'task_num': forms.TextInput(attrs={'class':'form-control'}), 'supervisor': forms.TextInput(attrs={'class':'form-control'}), 'entry_serialno': forms.TextInput(attrs={'class':'form-control'}), 'date': forms.DateInput(attrs={'class':'form-control pickadate'}), 'department': forms.Select(attrs={'class':'form-control select-search'}), 'ref': forms.TextInput(attrs={'class':'form-control'}), 'other_info': forms.Textarea(attrs={'class':'form-control', 'rows':3}), 'attachment': forms.ClearableFileInput(attrs={'class':'form-control'}) } … -
How to edit or add data on an extended Django User Model
I extended the Django User model but I am having issues trying to add or edit the data in the extended model I will need a practical help with code samples on this thanks. Here is the code below. on models.py from django.db import models from django.contrib.auth.models import User class ExtendUserModel(models.Model): url = models.URLField(blank=True, null=True, verbose_name='Website') age = models.PositiveIntegerField(blank=True, null=True) profile = models.ImageField(blank=True, null=True) user = models.OneToOneField(User, on_delete=models.CASCADE, default=None) def __str__(self): return 'Extend User on forms.py from django import forms from django.contrib.auth.models import User from backend.models import( ExtendUserModel) from django.contrib.auth.forms import(UserChangeForm, UserCreationForm) class RegisterForm(UserCreationForm): username = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Username'})) first_name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'First Name'})) last_name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Last Name'})) email = forms.CharField(widget=forms.EmailInput(attrs={'class':'form-control', 'placeholder':'Email'})) password1 = forms.CharField(label='Password', widget=forms.PasswordInput(attrs={'class':'form-control', 'placeholder':'Password'})) password2 = forms.CharField(label='Confirm Password', widget=forms.PasswordInput(attrs={'class':'form-control', 'placeholder':'Confirm Password'})) class Meta(): model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2') def save(self, commit=True): user = super().save(commit=False) user.email = self.cleaned_data['email'] user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] if commit: user.save() return user class ExtendUserForm(forms.ModelForm): url = forms.URLField(label='Website', required=False, widget=forms.URLInput(attrs={'class':'form-control', 'placeholder':'Website'})) age = forms.IntegerField(required=False, widget=forms.NumberInput(attrs={'class':'form-control', 'placeholder':'Age'})) profile = forms.ImageField(help_text='Image', required=False, widget=forms.ClearableFileInput(attrs={'class':'file-upload-default file-upload-info'})) class Meta(): model = ExtendUserModel fields = ('url', 'age', 'profile') on views.py from django.shortcuts import render from backend.forms import( ChangePasswordForm, EditForm, RegisterForm, ExtendUserForm) from … -
How to display in django admin readonly data from other model?
Why when i call instance of model from method car_name the method return - in Django admin. @admin.register(Invoice) class CarProductDataAdmin(admin.ModelAdmin): form = CarProductDataAdminForm def car_name(self, obj): # Call this instance car = Customer.objects.get(product__customer_id=self.request.user.person.id) return car.name readonly_fields = ('car_name', ) But when i just return string it is work. @admin.register(Invoice) class CarProductDataAdmin(admin.ModelAdmin): form = CarProductDataAdminForm def car_name(self, obj): # Doesn`t Call this instance # return string return "name" readonly_fields = ('car_name', ) -
I can't get return super().form_valid(form) to work
When I create or update a post the changes are saved to the sites database. But after clicking the submit button I get an error message. No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model. I want to be redirected to the current URL. I thought the line of code return super().form_valid(form) implied that. I could do success_url = '/'but I ideally don't want to be returned to the homepage. class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['title', 'content'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) -
Server-side querying of django models
I have been task with creating django class that will be customly querying all the models of a django application, depending on the parameters given to it and return paginated list of values This is a sample parameters used in the function for querying one of my models "parameters":{ page_size: "5" page_number: "1" order_column: "endpointName" search_query: "stackover" order_dir: "asc" } I have written a method for querying one model and realised that my code will be full of repetition for instance doing the query search I will have to do this for every model that exist. beats best code practices. anyone can give help or give suggestions of a way that i can re-write this so as to be able to re-use it with different models in my application Here is the sample code class TableData(object): """ class for getting data for table elements """ @staticmethod def get_endpoints(parameters, system_id): """ @param parameters: a dictionary containing parameters used for querying the endpoint model @type: dict @param system_id: Id of a system the endpoints will be attached to @type: int @return:a dictionary containing response code and data to be used for data table @rtype: dict """ try: if not parameters: return { … -
How to restrict the admin to not to login to the user dashboard in django?
I am having a user dashboard where users login and see their account details but the problem when I am logged in the admin site and then when I go to users dashboard the dashboard defaulty looging in with the admin credentials So,I want to restrict the admin to not to defaultly logging in the user dashboard in frontend My views.py: def login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username, password=password) if user is not None: if user.is_active: auth.login(request, user) return HttpResponseRedirect(reverse('modsy:dashboard')) else: messages.error(request,'Invalid Credentials') # return render(request,'dashboard.html') ## removed 1 # else: ## removed 2 return render(request, 'login.html') # This is a dashboard view def dashboard(request): return render(request, 'index1.html',); # This is a account view def account(request): return render(request, 'dashboard.html',); # This is a logout view def logout(request): messages.error(request,'You are now logged out') return render(request, 'login.html',); def edit_profile(request): if request.method == 'POST': form = EditProfileForm(request.POST, instance=request.user) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('modsy:account')) else: form = EditProfileForm() return render(request,'edit_profile.html',{'form':form}) def reset_password(request): messages.error(request,'You had updated your password ') return render(request, 'login.html',); @login_required def change_password(request): if request.method == 'POST': form = PasswordChangeForm(request.user, request.POST) if form.is_valid(): user = form.save() update_session_auth_hash(request, user) # Important! return HttpResponseRedirect(reverse('modsy:reset_password')) else: form = … -
How to create requirement.txt without all package versions
Actually i newbie at DJANGO development. Right now my requirement.txt contains following package list asgiref==3.2.3 beautifulsoup4==4.8.2 certifi==2019.11.28 chardet==3.0.4 Click==7.0 Django==3.0.2 idna==2.8 pytz==2019.3 requests==2.22.0 six==1.14.0 soupsieve==1.9.5 sqlparse==0.3.0 urllib3==1.25.7 i just want package name only, therefore i can install latest packages from pip3. -
since i want to process audio data , I have recorded and audio using javascript and passed it using ajax, but getting librosa error for unknown format
I need to perform speech recognition in the backend using users speech without transcribing using api. I am using Django and have successfully recorded the users voice in javascript but while loading the data in views using librosa its giving an error that the file contains data in unknown format my ajax request $.ajaxSetup({headers:{ "X-CSRFToken": token}}) $.ajax( { url:"{%url 'record:voice2pg'%}", type:'POST', contentType:false, processData:false, data:fd, processData:false, success:function(file){ alert('post successful') } } my django views.py file from django.shortcuts import render from django.http import HttpResponse import librosa def voice2(request): if request.method=='GET': return render(request,'record3.html') else: if request.method == 'POST' : print(request.FILES) audio=request.FILES.get("audioData") print(audio) audiodata=librosa.load(audio) return render(request, 'record3.html') the command prompt screen shows runtime error: Error opening : File contains data in an unknown format what exactly is the problem? Is it because the file is not in wav format but i tried using different audio format still the result is the same. what should i do?