Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting JSON data from django rest api into react-admin app to fill drop downs not working
I have a react-admin app that uses a django api. I'm looking to read in the json data and fill the drop down values and other items from the the api. I'm having issues with accessing the data. I've tried dataProvider and tried accessing the data directly and the drop downs are basically structured like this: "type": { "type": "choice", "required": true, "read_only": false, "label": "point type", "choices": [ { "value": "ID", "display_name": "Point ID" }, { "value": "A_ID", "display_name": "Another ID" } ] }, export const PointGrid = props => ( <Datagrid title={<PointTitle />} /*rowClick="edit"*/ {...props}> <TextField source="id" label="ID"/> <TextField source="point" label="Point" /> <TextField source="address" label="Address"/> <SelectField source="type" label="Type" choices={CounterDropDowns} /> <CreateButton /> <EditButton /> </Datagrid> ); I want be able to access the data in the TextField, SelectField, SelectInput and so on. Any help would be appreciated. -
How to use gettext_noop with contextual markers?
I want to use gettext_noop to mark a string as a translation string without translating it so it's available in my .po files and I can use the translations later. Now I have the situation that I have the same string but it has another meaning based on the context so the translation is not the same. I know I can add context to a string with pgettext. Unfortunately I can't use this because I need to use gettext_noop but there is no version of gettext_noop which provides to add a context. Does someone know how to solve this problem? -
Django: collectstatic does not collect my app
I am going to deploy on IIS so all the following commands were executed on Windows (Server2016) This is the structure of my django project: $ C:\inetpub\wwwroot\djangoProject . ├── static ├── manage.py ├── websrv ├── __init__.py ├── admin.py ├── apps.py ├── models.py ├── tests.py ├── urls.py └── views.py └── djangoProject ├── __init__.py ├── settings.py ├── urls.py └── wsgi.p I set STATIC_ROOT in C:\inetpub\wwwroot\djangoProject\djangoProject\settings.py to: STATIC_ROOT = 'C:/inetpub/wwwroot/djangoProject/static' and obviously my app name (websrv) was added to the INSTALLED_APPS in settings.py too. but when I run python manage.py collectstatic, the result is that only admin folder is collected under C:\inetpub\wwwroot\Alsatex\static and there is no folder for my main app (websrv) -
TypeError: __init__() got an unexpected keyword argument 'attrs'
I am trying to add class to my CharFieldin forms.I am getting this error "__init__() got an unexpected keyword argument 'attrs'" forms.py class CommentForm(forms.ModelForm): content = forms.CharField( widget=forms.Textarea( attrs={ 'class': 'form-control', 'placeholder': 'Type your comment', 'id': 'usercomment', 'rows': '4' } ) ) class Meta: model = Comment fields = ('content', ) models.py class Comment(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) content = HTMLField('Content') post = models.ForeignKey( 'Post', related_name='comments', on_delete=models.CASCADE) def __str__(self): return self.user.username Plz, Help me -
How to pass a template tag from one template to another in django 2
I am new to Django, and template tags and HTML and have a template where I use a for loop to fill out bootstrap cards from a database. In the model I has a field Resume_link that has a PDF file. All I want to is have the PDF file displayed in a different template file and not in the card where it is too small to read. (Since I am in the loop when someone clicks the link, I just want the specific resume connected to that card to be shown in the new template.) So all I think I should need to do is somehow either pass the the index of the loop, or another variable that identifies the correct database entry. But I think I am missing something fundamental and don't understand how to pass the value of a template tag in one template another template. Is there some way to pass a variable along with the url to a view so the variable can be used to make a new template tag in the desired template? {% for key in myres %} ...fill out other parts of cards and create the below link... <a href="{% url … -
django-autocomplete-light: How to limiting the display results?
this is my form with a django-autocomplete-light widget on "species" and farmers ( I am using Django 2.2.2 & django-autocomplete-light 3.4.1) forms.py from django import forms # --- Import Autocomplete from dal import autocomplete # --- Import Models from datainput.models import Species, Animal class AutoForm(forms.ModelForm): class Meta: model = Animal fields = ('__all__') widgets = {'species': autocomplete.ModelSelect2( url='testa:species_autocomplete', attrs={ # Set some placeholder 'data-placeholder': 'choose a species ...', }), 'farmer': autocomplete.ModelSelect2( url='testa:farmer_autocomplete') } So far autocomplete works within my project. But i would like to limit the displayed choices in the autocomplete fields. For instance if a user sets a cursor into my "species" autocomplete Field all species are shown. But i would like to set a limit of 10 (species names). So my approach was to set a value in attr= like the data-placeholder but i could not find any options in the documentation. Is there something like limit_display: 10 ? -
How to fix 'reversemanytoonedescriptor' object has no attribute 'all' issue
I'm setting up Django reste framework in my web app, and getting some issue when i want to get some details with the api --------------Models----------------------------------- class Work (models.Model): work_name = models.CharField ('Work Name', max_length = 200 ) _box = models.ForeignKey (Box, related_name='works', on_delete=models.CASCADE) def get_absolute_url(self): return reverse('work_detail', kwargs={'work_pk' : self.pk}) class Task(models.Model) : task_name = models.CharField ('Task Name',max_length = 200) _work = models.ForeignKey (Work,related_name ='tasks_list',on_delete=models.CASCADE) _categorie = models.ForeignKey( Categorie, models.SET_NULL, blank=True, null=True, related_name = 'task_list', ) def get_absolute_url(self): return reverse('task_detail',kwargs={'task_pk':self.pk}) class Object (models.Model): _task = models.ForeignKey(Task,related_name='objects', on_delete=models.CASCADE) --------------Serializer---------------------- class ObjectSerializer(serializers.ModelSerializer): class Meta: model = Object fields = '__all__' class TaskSerializer(serializers.ModelSerializer): objects=ObjectSerializer(many=True) class Meta: model = Task fields = '__all__' class WorkSerializer(serializers.ModelSerializer): tasks = TaskSerializer(many=True) class Meta: model = Work fields = '__all__' view.py class WorkDetailView(RetrieveAPIView): queryset = Work.objects.all() serializer_class = WorkSerializer class TaskDetailView(ListAPIView): #-----TODO BUGS queryset = Task.objects.all() # that Task objects has'nt attributs all() serializer_class = TaskSerialize "in TaskDetailView queryset = Task.objects.all() AttributError :'ReverseManyToOneDescriptor' object has no attribute 'all' -
django email not being sent : ConnectionRefusedError WinError 10061
I am writing django application and trying to send email using it I have "Access to low security app" in gmail enabled and django setting are given below which I think are right. but I am still getting error as mentioned it title. I dont know the problem but I know I am not getting logged in to send email. searched on internet and find out that gmail does not allow low security app to login by default but I turned it off in setting of gmail. find out that my email backend was wrong so made it right. fail silently is False. settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 DEFAULT_FROM_EMAIL = 'testing@example.com' EMAIL_HOST_USER = 'syedfaizan824@gmail.com' EMAIL_HOST_PASSWORD = '******' views.py def post(self, request, *args, **kwargs): form = contact(request.POST) if form.is_valid(): name = form.cleaned_data['name'] email = form.cleaned_data['email'] phone = form.cleaned_data['phone'] organization = form.cleaned_data['organization'] message = form.cleaned_data['message'] ref_code = form.cleaned_data['ref_code'] plan = form.cleaned_data['plan'] message = message + ref_code send_mail( 'from website' + name + " " + organization, message, email, ['syedfaizan824@gmail.com'], fail_silently=False, ) print("sent") else: #print('something is wrong with forms!') return render(request, self.template_name, self.context) Error message is ConnectionRefusedError WinError[10061]. and statement of error is : No … -
Optimize QuerySets in a Loop with indexes and better SQL
I have a View that returns some statistics about email lists growth. The models involved are: models.py class Contact(models.Model): email_list = models.ForeignKey(EmailList, related_name='contacts') customer = models.ForeignKey('Customer', related_name='contacts') status = models.CharField(max_length=8) create_date = models.DateTimeField(auto_now_add=True) class EmailList(models.Model): customers = models.ManyToManyField('Customer', related_name='lists', through='Contact') class Customer(models.Model): is_unsubscribed = models.BooleanField(default=False, db_index=True) unsubscribe_date = models.DateTimeField(null=True, blank=True, db_index=True) In the View what I'm doing is iterating over all EmailLists objects and getting some metrics: the following way: view.py class ListHealthView(View): def get(self, request, *args, **kwargs): start_date, end_date = get_dates_from_querystring(request) data = [] for email_list in EmailList.objects.all(): # historic data up to start_date past_contacts = email_list.contacts.filter( status='active', create_date__lt=start_date).count() past_unsubscribes = email_list.customers.filter( is_unsubscribed=True, unsubscribe_date__lt=start_date, contacts__status='active').count() past_deleted = email_list.contacts.filter( status='deleted', modify_date__lt=start_date).count() # data for the given timeframe new_contacts = email_list.contacts.filter( status='active', create_date__range=(start_date, end_date)).count() new_unsubscribes = email_list.customers.filter( is_unsubscribed=True, unsubscribe_date__range=(start_date, end_date), contacts__status='active').count() new_deleted = email_list.contacts.filter( status='deleted', modify_date__range=(start_date, end_date)).count() data.append({ 'new_contacts': new_contacts, 'new_unsubscribes': new_unsubscribes, 'new_deleted': new_deleted, 'past_contacts': past_contacts, 'past_unsubscribes': past_unsubscribes, 'past_deleted': past_deleted, }) return Response({'data': data}) Now this works fine, but as My DB started growing, the response time from this view is above 1s and occasionally will cause long running queries in the Database. I think the most obvious improvement would be to index EmailList.customers but I think maybe it needs to … -
Search using date from to
Hello developers can you please tell me how to search query objects by date for example if anybody want to search it will show me date picker and then i will choose from 2019-3-11 to 2019-09-11 then it will print all results between these dates.. I am not looking for order by dat = example.objects.all().order_by('-date') models,py example class Sample(models.Model): date = fields.DateField(auto_now=True) -
Focus cursor to the end of an input value (CreateView, ModelForm) [Python Django]
I have a form with 2 inputs. I am using CreateView and ModelForm. And {% form %}. Problem: I need the second input (which already has an initial value) when "tabbed" to, to put the cursor at the end of the string. Current behavior: When "tab" to get to the second input, it highlights the entire string. What I have so far: I am able to autofocus by adding this line of code to my ModelForm init: self.fields['description'].widget.attrs['autofocus'] = 'on' . I was thinking that something like this: self.fields['inc_number'].widget.attrs['onfocus'] = 'INC'[:0] ("INC is the initial value) might solve the problem. I get no errors, but it still just highlights the entire string when I tab from the description input. For my code, I will try to focus on just the most relevant parts. models.py class ITBUsage(models.Model): """ ITB usage """ itb = models.ForeignKey(IncidentTriageBridge, related_name='itb', on_delete=models.DO_NOTHING, verbose_name="ITB name") description = models.CharField(max_length=100, verbose_name="Description", null=True) reserved_by = models.ForeignKey(auth_models.User, on_delete=models.SET_NULL, null=True, verbose_name="ITB reserved by") inc_number = models.CharField(max_length=20, verbose_name="Incident number", null=True) created_at = models.DateTimeField(null=False, auto_now_add=True) completed_at = models.DateTimeField(null=True) views.py class StartItb(CreateView): # class StartItb(CreateView): """ Start a bridge by adding a new row in ITBUsage """ model = models.ITBUsage form_class = forms.StartItbForm template_name = "itb_tracker/start_form.html … -
jQuery Steps Wizard with Django is not saving data to DB
I'm trying to use the jQuery Steps Wizard plugin with Django forms to create a form wizard. So far I can show the form, I can through the steps but when I press the finish button I get the POST request but it just reloads the page, shows no errors and nothing is saved into the database. What am I doing wrong here? I'm not that experienced in jQuery.. I think I went through all the posts related to my question and nothing worked so far. #views.py def add_bedroom(request, pk): get_property_id = pk data = {'property':get_property_id} property_reference = Property.objects.get(pk=get_property_id) if request.method == 'POST': bedroom_form = AddBedroomForm(request.POST, request.FILES, initial=data) lighting_form = LightingBedroomAddForm(request.POST) print('teste') if bedroom_form.is_valid() and lighting_form.is_valid(): bedroom = bedroom_form.save() print('error') add_lighting = lighting_form.save(commit=False) add_lighting.bedroom = bedroom add_lighting.save() print('Sucesso') return HttpResponseRedirect(reverse('properties:property_detail', args=[pk])) else: bedroom_form = AddBedroomForm(initial=data) lighting_form = LightingBedroomAddForm() context = { 'add_bedroom_form':bedroom_form, 'add_lighting_form':lighting_form, 'title':"Add Bedroom", 'reference':property_reference, } return render(request, 'properties/add-bedroom1.html', context) #steps.js var form = $(".validation-wizard").show(); $(".validation-wizard").steps({ headerTag: "h6" , bodyTag: "section" , transitionEffect: "fade" , titleTemplate: '<span class="step">#index#</span> #title#' , labels: { finish: "Submit" } , onStepChanging: function (event, currentIndex, newIndex) { // Always allow going backward even if the current step contains invalid fields! if (currentIndex > newIndex) … -
"Is there any way in Django to create dynamic menu and sub-menu ??"
" Using Django, i want to create menu and sub-menu(i mean drop-down menu) " " If you have any source code in django for creating menu and sub-menu, please give me a link **** thanks in advance................................................................................................................................ " ### models.py from django.db import models # Create your models here. class Category(models.Model): category_name = models.CharField(max_length=200) slug = models.SlugField(max_length=200) def __str__(self): return self.category_name class Sub_Category(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) Sub_category_name = models.CharField(max_length=200) slug = models.SlugField(max_length=200) def __str__(self): return self.Sub_category_name class Product(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) sub_category = models.ForeignKey(Sub_Category, on_delete=models.CASCADE) title = models.CharField(max_length=200) image = models.ImageField(upload_to='picture/') pub_date = models.DateTimeField(auto_now_add=True) description = models.TextField() def __str__(self): return self.title #### html page {% block content %} <h1 class="bg-success text-center">Home page </h1> <div class="row"> <div class="col-8"> {% for category in category_list %} <ul> <li>{{category.category_name}}</li> {% for sub_category in sub_category_list %} <ul> <li> {% if sub_category.category.id == id %} {{sub_category.Sub_category_name}} {% endif %} </li> </ul> {% endfor %} </ul> {% endfor %} </div> </div> </div> {% endblock %} ``` ### I want output will be like that... ### * Men Fashion * T-shirt * Pant * Men Fashion * Frog * beg -
how implement an efficient visits counter per page?
how implement an efficient visits counter per page? I've marketplace platform, but not a visits counter per product page, then, this is my question. what's is the better algorithm for implement this? I not think that this alghoritm is the better "update product set product.visits = (product.visits + 1) where ..." then, how? I'm accept sugestions Google Analytics? third party solutions? Alghoritm? thanks everyone Was developed in Django -
Send notification on post_save signal in django
I have a model called deposit and I am trying to send real time notification when a new row is added in table. Is it possible to do so using django-channels ? -
How to perform edit in inline_formset when its model contain multiple foreign key in it?
I used a form set to enter a schedule to course, When i try to edit the record it shows an error: inlineformset_factory() got multiple values for keyword argument 'form'. Model for that form contains multiple foreign key i tried to describe the foreign key fields in the inlineformset. views.py def edit_course_schedule(request,scheduleid): instance = CourseSchedule.objects.get(id=scheduleid) schedule_form = CourseScheduleForm() schedule_formset = inlineformset_factory( DynamicCoursePrice, CourseType, Course, CourseSchedule, can_delete=True, form=schedule_form, fk_name=('dynamic','course_type','course'), extra=0, max_num=1, fields= '__all__' ) schedule_form = CourseScheduleForm(instance=instance) scheduleformset = schedule_formset(prefix='schedule_formset',instance=instance) context = { 'scheduleid' : scheduleid, 'schedule_form' : schedule_form, 'schedule_formset' : schedule_formset, } return render(request,'myapp/edit_course_schedule.html', context) models.py class CourseSchedule(models.Model): dynamic = models.ForeignKey(DynamicCoursePrice, on_delete=models.CASCADE, blank=True, null=True) course_type = models.ForeignKey(CourseType, on_delete=models.CASCADE, blank=True, null=True) course = models.ForeignKey(Course, on_delete=models.CASCADE, blank=True, null=True) start_date = models.DateField("Start Date", blank=True, null=True) end_date = models.DateField("End Date", blank=True, null=True) hours = models.IntegerField("Hours", blank=True, null=True) time = models.CharField("Time interval", max_length=255,blank=True, null=True) day = models.CharField("Day", max_length=255,blank=True, null=True ) i want to edit schedule in formset view, so that i can add or remove new schedules to a course. please help me to find a way to solve this problem. -
How can I prefetch_related() everything related to an object?
I'm trying to export all data connected to an User instance to CSV file. In order to do so, I need to get it from the DB first. Using something like data = SomeModel.objects.filter(owner=user) on every model possible seems to be very inefficient, so I want to use prefetch_related(). My question is, is there any way to prefetch all different model's instances with FK pointing at my User, at once? -
How to serve static files for the frontend generated by ReactJs build in a django project?
I have a set of static files generated by ReactJs build command and which will serve as a front-end for my Django project. Both the Django application and react files will serve from the same server. How do I serve these static files as my front-end for the Django application and write urlpatterns properly - if required. I tried to copy all the files from the build folder to static/frontend folder My static/frontend folder has static/frontend /static /js /css index.html manifest.json ... settings.py is as follows STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'staticfiles'), ] -
The empty path didn't match any of these
enter image description here enter code here path('admin/',admin.site.urls) path('notes/', include('notes_app.urls') from django.contrib import admin from django.urls import include , path -
How to pass the user id to a custom password hasher in Django?
I have migrated password hashes, that are salted using the user id. I have a custom hasher that extends PBKDF2SHA1PasswordHasher. But the parameters of the methods do not include any user info. class MyHasher(PBKDF2SHA1PasswordHasher): def encrypt(self, password, salt, iters, keylen, digestmod): How do I retrieve the user id inside the encrypt method, so I can correctly verify the incoming password? -
How can the router path be accessed by html in "Django rest framework"?
I am trying to build a simple blog in Django Rest Framework. I want to add like count by pressing the button on the list page to send post method to the server. This is views.py class BlogListView(viewsets.ModelViewSet): serializer_class = BlogSerializer renderer_classes = [JSONRenderer, TemplateHTMLRenderer] def create(self, request, *args, **kwargs): user = request.user like_id = request.POST.get('pk', None) add_like = Like.objects.get(pk=like_id) if add_like.likes.filter(id=user.id).exists(): add_like.likes.remove(user) else: add_like.likes.add(user) context = {'likes_count': add_like.total_likes} serializer = BlogSerializer(context) return Response(serializer, content_type='application/json') This is url. router = DefaultRouter() router.register('dashboard', views.ImitagramListView) app_name = 'imitagram' urlpatterns = [ path('', include(router.urls)), ] This is HTML. <button type="button" class="like" name="{{ like.id }}"> <script type="text/javascript"> $.('.like').click(function () { var pk = $(this).attr('name'); $.ajax({ type: "POST", url: "{% url 'imitagram:dashboard' %}", data: {'pk': pk, 'csrfmiddlewaretoken': '{{ csrf_token }}'}, dataType: "json", success: function (response) { id = $(this).attr('name'); $('#count'+pk).html('count: ' + response.likes_count); alert('success'); }, error: function (request.status.error) { alert('error'); } }); }) </script> But this url spits out this error. Reverse for 'dashboard' not found. 'dashboard' is not a valid view function or pattern name. How can I get this resolved? -
update_or_create method raises IntegrityError
When using the update_or_create method, the error IntegrityError is raised. It also says "Violation of PRIMARY KEY constraint 'PK__Security__BCF928572A34AEAB'. Cannot insert duplicate key in object" I have tried adding the defaults=argument, adding the kwargs as a dict with **kwargs, and adding the Kwargs as parameters edit, created = MyTable.objects.update_or_create( SecurityIdentifier=places[0][0], EffectiveDate=places[0][1], defaults={places[0][2]: keyVals[0]} ) I am not sure why I am getting this error, Any help would be greatly appreciated! -
how to display foreign key value in django template?
Here I am filtering staffs by the joined year,month and organization name this code works fine also but the problem what i encountered is after selecting the year,month or organization option it performs the query well but in the select option there is not the value of selected month,year or organization. To display the selected organization,year or month in the select option I tried like this and with this it displays the organization pk but I want to display organization name instead of pk value. How can i display the organization name instead of pk in the select option here? Also i want to display month name instead of month value. It is working fine for year value. views.py year = request.GET.get('year') month = request.GET.get('month') # month_name = calendar.month_name[int(month)] organization = request.GET.get('organization') print('org',type(organization)) present_year = datetime.datetime.today().year year_list = range(2015, present_year + 1) organizations = Organization.objects.all() if not year and not organization and not month: messages.info(request, 'Nothing selected to filter.') return redirect('organization:view_staff_users') if year and month and organization: staffs = Staff.objects.filter(Q(joined_date__year=year) & Q(joined_date__month=month) & Q(organization=organization)) return render(request, 'organization/view_staff_users.html', {'staffs': staffs, 'year': year, 'month': month, 'organization': organization,'present_year':present_year,'years_list':year_list,'organizations':organizations}) template <form action="{% url 'organization:filter_staffs' %}" class='form-inline' > <select name="year"> <option {% if year %} … -
Deploy Django on Azure (Windows OS)
I try to deploy django web app about 1 month but it wasn't working. I can deploy it on Linux but Linux have no "MySQL in app". so I use Windows. Howerver, I can't fint "startup command" in Windows. Moreover, I have no permission to install package (i use cmd via kudu => i use python -m pip install -U --user -r requirements), so I can't run "gunircorn ...", I can't use pip install, .... Does anyone help me deploy Django on windows web app. I extremly tired ~~ it is difficult to deploy ~~ I deploy successfully on Linux (Azure webapp) -
TypeError at / context must be a dict rather than RequestContext. A bit strange case
I had an application that was build on Django 1.9 but now I have upgraded it to 2.2. Well, I have encountered a strange error and I'm unable to solve it using the existing similar solutions. In my case, we are fetching the templateResponse from a different file then the built in one [Say x.py]- class TemplateResponse(DefaultResponse): """A normal response involving data that can be sent to fill in a template. Since the template is specific to HTML responses, when a JSON response is desired, this class is indistinguishable from DefaultResponse.""" def __init__(self, template, data, status=200): self.data = data self.template = template self.status = status [Base.py]- def home(guts): return TemplateResponse(template, {'c_sk': c_nt, 'd_sk_count': d_sk_count} Traceback Error - response = get_response(request) … ▶ Local vars /home/gaurav/Desktop/a Upgrade Work/a/new_cl/lib/python3.6/site-packages/django/core/handlers/base.py in _get_response response = self.process_exception_by_middleware(e, request) … ▶ Local vars /home/gaurav/Desktop/a Upgrade Work/a/new_cl/lib/python3.6/site-packages/django/core/handlers/base.py in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars /usr/lib/python3.6/contextlib.py in inner return func(*args, **kwds) … ▶ Local vars /home/gaurav/Desktop/a Upgrade Work/a/new_cl/lib/python3.6/site-packages/django/contrib/auth/decorators.py in _wrapped_view return view_func(request, *args, **kwargs) … ▶ Local vars /home/gaurav/Desktop/a Upgrade Work/a/main/x.py in g response = seed.sprout(context, format) … ▶ Local vars /home/gaurav/Desktop/a Upgrade Work/a/main/x.py in sprout return self.sprout_html(context) … ▶ Local vars /home/gaurav/Desktop/a Upgrade …