Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to dynamically add field in django form?
Suppose i made a form with fields name and email id and then i execute the code and page opens with the fields - name and email id and then i want to add contact field to that form without going back to add that contact field to models and form and without doing migrations. Can this is possible in django? -
Using Django or JS to turn on camera and scan QR-code
I am now working on a project that can scan QR-code which contains ID of a good. Is there any method that I can have my website to switch on iPhone camera for scanning? Please give me some information about this or link. -
Why doesn't djangorestframework template load on heroku?
I have a Django app meant to host a backend API using djangorestframework. Everything works fine save that the drf template refuses to load in production. The screenshot below is what I get no matter how many times I run python manage.py collectstatic. The app url is https://ethodoxy.herokuapp.com/api/v1/ -
Trigger an email to admin when new user registers in a Django app
I'd like to trigger a simple plaintext email to admin(s) when a new user registers for my Django app. What's the cleanest way to do this? -
Email sending CronJobs not working in Django
This is very little issue. My email sending cronjobs is not working from django_cron import CronJobBase, Schedule class MyCronJob(CronJobBase): RUN_EVERY_MINS = 1 schedule = Schedule(run_every_mins=RUN_EVERY_MINS) code = 'my_app.my_cron_job' def do(self): email = EmailMessage('hi', 'message', to=['test@gmail.com']) email.send() please tell me what is wrong with this code or what are the alternates I can use? -
How to render context values in generic list and detail views
I have a base template file (shared.html) contains Header and Footer, using on every page. I have some dynamic values from database in shared.html (e.g: Phone number, address, logos) and showing perfectly on index view page, but not showing on any of the generic views page. Please guide me how to do this to show all the dynamic values on every generic view page. Index view: def index(request): # Display all the Dynamic values form models num = TopBar.objects.get() addressISD = AddressIslamabad.objects.all() addressRWP = AddressRawalpindi.objects.all() alt = Logo.objects.all() YLP7Text = WhyLP7Text.objects.all() PMBG = BGimages.objects.all() lp7Features = LP7features.objects.all() locate = Locations.objects.all() events = Events.objects.all() memberLogo = LP7MembersLogo.objects.all() testi = LP7Testimonials.objects.all() promo = Promotions.objects.all() c = context = ({ 'topBarNumber': num, 'addressISD': addressISD, 'addressRWP': addressRWP, 'altText': alt, 'YLP7Text': YLP7Text, 'BG': PMBG, 'featuresLP7': lp7Features, 'LC': locate, 'evt': events, 'memLogo': memberLogo, 'testi': testi, 'promo': promo }) # Render the HTML template index.html return render(request, 'index.html', c ) Generic View: # Display the detail and generic views class EventListView(generic.ListView): model = Events class EventDetailView(generic.DetailView): model = Events class PromotionListView(generic.ListView): model = Promotions class PromotionDetailView(generic.DetailView): model = Promotions -
Should Important Metric be tracked in separate BooleanField, or is a CharField enough?
I want to track stats on messages in my application. An important metric is "initial message" as this means a new conversation started. Is it better to have the initial message as a separate BooleanField, or is it enough to have "initial message" being tracked as a string in the message category CharField. Please specify whether you recommend Model A, Model B, or another approach, and why. I want to use this model to power charts that I show in the user dashboard of my application. # Model A class Data(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) message = models.CharField(max_length=20) message_channel= models.CharField(max_length=20) #Facebook, Twitter, SMS message_category = models.CharField(max_length=20) #initial message, reply, feedback_reply initial_message = models.BooleanField() created_at = models.DateTimeField(auto_now_add=True) # Model B class Data(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) message = models.CharField(max_length=20) message_channel= models.CharField(max_length=20) #Facebook, Twitter, SMS message_category = models.CharField(max_length=20) #initial message, reply, feedback reply created_at = models.DateTimeField(auto_now_add=True) -
How to combine queryset via ManyToManyField in django
I'm trying to build an Instagram clone. I need to pass user's posts and follow's to the dashboard. I don't know how to combine a user with follow which is manytomanyfield of the user because ordering posts by created_at models.py class Insta(models.Model): title = models.CharField(max_length=255) body = models.TextField() image = models.ImageField(upload_to='images/', blank=True) video = models.FileField(upload_to='videos/', blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) likes = models.ManyToManyField(User, related_name='likes', blank=True, default='') owner = models.ForeignKey(User, on_delete=models.CASCADE) class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=100, unique=True) user_fullname = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) thumbnail = models.ImageField(upload_to='thumbnail/') follows = models.ManyToManyField('self', related_name='followers', symmetrical=False) views.py def list(self, request, *args, **kwargs): if not request.user.is_authenticated: return redirect('insta:signup') else: user = request.user response = Insta.objects.filter(owner=user.id) return Response({'posts': response, 'user': user}) Thank you in advance. -
User group is not creating?
Here I made a form for taking the group name from the user and then tried to create group name with that name entered by user but it is not giving me the expected result.It is neither throwing any error nor saving the data in the database. When i used group_name = request.POST['name'] instead of cleaned_data it throws: django.utils.datastructures.MultiValueDictKeyError: 'name' What I am doing wrong here ? forms.py class AddUserGroupForm(forms.Form): name = forms.CharField(max_length=255) views.py def add_user_groups(request): form = AddUserGroupForm() #group_name = request.POST['name'] #print(group_name,'group_name') if form.is_valid(): group_name = form.cleaned_data['name'] permissions = request.POST.getlist('user_permissions') new_group = Group.objects.create(name=group_name) new_group.permissions.add(permissions) messages.success(request,'New group added.') return redirect('organization:view_groups') return render(request,'organization/add_user_groups.html',{'user_permissions':user_permissions,'form':form}) template <form action="{% url 'organization:add_user_group' %}" method="post"> {% csrf_token %} <label> Group Name : </label> <input type="text" class="form-control required" placeholder="Enter group name" name="name"> <label>Permissions:</label> {% for permission in user_permissions %} <input name="user_permissions" type="checkbox" id="permission-{{permission.id}}" value="{{permission.id}}"> <label for="permission-{{permission.id}}"> {{permission.name}}</label> </div> {% endfor %} <button type="submit" class="btn btn-info">Submit</button> </div> </form> -
Is possible to get media_id from Instagram url?
I have an Instagram url: https://www.instagram.com/p/B2EtjT9hgvG/ and I need to obtain media_id of this url; something like: 1238578393243739028_1408429375 There is a way? -
django forms, categorizing a checkboxfield for better UI
I am using the widget forms.CheckboxSelectMultiple, but as there is too many data from the database, its too messy and would like to categorize them into category and display them out for the form, however i have no idea how to get about doing that. Form hobbies = forms.ModelMultipleChoiceField(required=True,queryset=Hobby.objects, widget=forms.CheckboxSelectMultiple()) Model class HobbyCategory(models.Model): name = models.CharField(max_length=50) class Meta: ordering = ('name',) def __str__(self): return self.name class Hobby(models.Model): name = models.CharField(max_length=50) category = models.ForeignKey(HobbyCategory, on_delete=models.CASCADE) class Meta: ordering = ('name',) def __str__(self): return self.name I been looking at the custom widget but i have no idea how to get started, is there any quick fix way for this? i want it to display something like: category 1 checkboxes checkboxes checkboxes category 2 checkboxes checkboxes checkboxes and so on. -
How to correctly pass parameters to a Class Based View instance in Django?
I'm trying to pass parameters in a Class Based View instance, but I can't figure out the proper way to do that. My api service works good in the REST Framework view and receive two mandatory parameters (user and language): I found similar answers but send parameters in return, that is not my situation. This is my call, _customdictionary = CustomDictionaryViewSet() _customdictionary.custom_dictionary_kpi(request) I've tried and fail with: _customdictionary.custom_dictionary_kpi(request) _customdictionary.custom_dictionary_kpi({'language': 1, 'user': 1}) # In both cases i receive status = 500 When I see my error.log, in this part: class CustomDictionaryViewSet(viewsets.ModelViewSet): ... def custom_dictionary_kpi(self, request, *args, **kwargs): try: import pdb;pdb.set_trace() Sending request, it shows me: AttributeError: 'WSGIRequest' object has no attribute 'data' And sending the dict, it shows me: AttributeError: 'dict' object has no attribute 'data' api/urls.py urlpatterns = [ url(r'^api/customdictionary/custom_dictionary_kpi/user/<int:user_id>/language/<int:language_id>', CustomDictionaryViewSet.as_view({'post': 'custom_dictionary_kpi'}), name='custom_dictionary_kpi') ] api/api.py class CustomDictionaryViewSet(viewsets.ModelViewSet): queryset = CustomDictionary.objects.filter( is_active=True, is_deleted=False ).order_by('id') permission_classes = [ permissions.AllowAny ] pagination_class = StandardResultsSetPagination def __init__(self,*args, **kwargs): self.response_data = {'error': [], 'data': {}} self.code = 0 def get_serializer_class(self): if self.action == 'custom_dictionary_kpi': return CustomDictionaryKpiSerializer return CustomDictionarySerializer @action(methods=['post'], detail=False) def custom_dictionary_kpi(self, request, *args, **kwargs): try: '''some logic''' except Exception as e: '''some exception''' return Response(self.response_data,status=self.code) serializers.py class CustomDictionarySerializer(serializers.ModelSerializer): class Meta: model = CustomDictionary … -
Django add files to model with Dropzone
I have a django bootstrap project and I want to add files to my Django model via a Dropzonejs.js. My problem is that the files don't get a name in the model. They are just blank files without any links/content to them. This is my model: class Studyplan(models.Model): name = models.CharField(max_length=100, null=True) description = models.CharField(max_length=1000, null=True) files = models.ManyToManyField(File, blank=True, null=True) This is my view: @login_required def teacher_assignment_add_files(request, assignment_id): if request.method == 'POST': file = request.POST.get('Assignment-File') file = File(file=file) file.save() assignment = Assignment(id=assignment_id) assignment.files.add(file.id) return redirect('teacher-detail-assignment', id = assignment_id) The Dropzonejs form: <form class="dropzone" action="{% url 'teacher_assignment_add_file' OBJECTID %}" method="POST"> {% csrf_token %} <span class="dz-message">Dra filer hit för att ladda upp</span> </form> -
Django allauth doesn't send any email
I'm using django_allauth for my django project. But no more email is sent (confirmation email, reset password). It successfully creates a new user, the message that confirms an email has been sent appears and there is also a the redirection to the confirm email page. However I don't receive this email in my inbox and I can't see any error. Moreover, I use in other app for a contact form the class send_email() and it works. I've tried to add some print() directly in the code if some variables could be wrong. I've also tried to enable fail_silently def send_mail(self, template_prefix, email, context): msg = self.render_mail(template_prefix, email, context) msg.send(fail_silently=False) My application is hosted on Digital Ocean. It is running on ubuntu with nginx/gunicorn I've run the shell in order to try sending some test email and I always received an email with the method send_email() and objects EmailMultiAlternatives.send(), EmailMessage.send(). here is Settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' # Email identification EMAIL_HOST = 'myhost' EMAIL_PORT = 465 EMAIL_HOST_USER = 'myuser' EMAIL_HOST_PASSWORD = 'mypassword' EMAIL_USE_SSL = True DEFAULT_FROM_EMAIL = 'myemail@email.com' # `allauth` config ACCOUNT_AUTHENTICATION_METHOD = 'username_email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = 'mandatory' ACCOUNT_LOGIN_ATTEMPTS_LIMIT = 5 ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 1 SOCIALACCOUNT_AUTO_SIGNUP = True LOGIN_REDIRECT_URL = '/' … -
How to display Uploaded file to the user who upload it in Django?
I am trying to build a system where users can upload their CSV file in the Django backend. But I am facing a problem, I want to display CSV file only to the user who uploaded it. I make a field in the models which can trace the user who uploaded the file. Here are some of my codes. CSV file model: class Data(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,default=1) filename = models.CharField(max_length=40,blank=False) csv_file = models.FileField(upload_to='documents/',blank=False) def __str__(self): return self.filename And the view logic: def accounts(request): user = Data.objects.values('user') if user == request.user: main_data = Data.objects.all() else: main_data = "" dict = {'main_data':main_data, 'name' : request.user.username} return render(request, 'accounts.html',dict) I am only getting that else value ' main_data=" " '. -
After installing spyder django is not working
I installed spyder on my ubuntu system From which django is not working. The error it is showing when i ran the server the error showing is is Traceback (most recent call last): File "manage.py", line 8, in from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 14, in import django ModuleNotFoundError: No module named 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 17, in "Couldn't import Django. Are you sure it's installed and " ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? I need both spyder for OpenCV and also Django. can anyone help -
Saving modelform vs use of rest api
If one has to use modelform for getting inputs for djano rest api, What way serialiser will help saving data. Because ModelForm can directly do that. Code for saving modelform as well as serialiser saving is almost same. Does this means wrt to django, rest api is for getting data for report generation only. Because I could not find any good tutorial (django based) which shows usage of serialiser / django forms for saving data to database. -
Deploy Django project with MSSQL DB in Local Server
I am new in Django and this will be my very FIRST Times web deploying. So I am trying to deploy my project to the local server and My project stack is Django with MSSQL so obviously I will need Window. I was read the documentation and I think I will need WSGI and As the documentation say to deploy with gunicron or uWSGI but both are supported for Unix and not for window. So How can I start this one? This will be the first question. I would like to know whether I am doing is correct or not. Now I copy my project to the local server and when I try to run my project like python manage.py runserver it asks me to install Django and other but I thought this environment is working at well my computer and all of the needed application is already installed in the environment. So I still need to install all of my needed apps like Django to this environment again? If u have any tutorial or can guide me to some useful site, I will be very very appreciated. Anything u want to know further, Just let me know. Thanks. -
Is it good to perform model checks on serializers method (create, update)?
I have the next code in my client/serializer.py and I don't know if it is a good practice to perform validation/checking of my models in the methods serializers. Is it a good practice? from rest_framework import serializers, exceptions from .models import Staff from django.contrib.auth import get_user_model from profession.models import Profession from django.db import IntegrityError class UserSerializer(serializers.Serializer): username = serializers.CharField(max_length=24, min_length=4, allow_blank=False, trim_whitespace=True) first_name = serializers.CharField(max_length=100, min_length=1, allow_blank=False, trim_whitespace=True) last_name = serializers.CharField(max_length=100, min_length=1, allow_blank=False, trim_whitespace=True) email = serializers.EmailField() class ProfessionSerializer(serializers.Serializer): url = serializers.URLField(read_only=True) id = serializers.IntegerField() name = serializers.CharField(read_only=True) class StaffSerializer(serializers.HyperlinkedModelSerializer): user = UserSerializer() profession = ProfessionSerializer() class Meta: model = Staff fields = ['url', 'id', 'commission', 'user', 'profession'] def create(self, validated_data): user_data = validated_data.pop('user') profession_data = validated_data.pop('profession') try: profession = Profession.objects.get(pk=profession_data.get('id')) except Profession.DoesNotExist: raise exceptions.ValidationError({'profession': ['profession with this id does not exists.']}) try: user = get_user_model().objects.create(**user_data) except IntegrityError: raise exceptions.ValidationError({'user': ['user with this username already exists.']}) staff = Staff.objects.create(user=user, profession=profession, **validated_data) return staff -
How to select and deselect options if multiselect option coming from ajax request
<div class="content-section"> <form method="POST" id="moviesForm" ajax_load_cast="{% url 'ajax_load_cast' %}" novalidate enctype="multipart/form-data" > {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">{{form_name|capfirst}}</legend> <div class="form-group"> <label for="id_cast" class="col-form-label requiredField">Cast<span class="asteriskField">*</span> </label> <div class=""> <input type="text" name="cast" value="" maxlength="50" class="textinput textInput form-control" required="" id="id_cast"> <select id="add_cast2" multiple style="width:100%" ></select> </div> </div> <div id="" class="form-group"> </div> </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Submit</button> </div> </form> </div> {% block js%} <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> var ajaxResult=[]; $("#id_cast").keyup(function () { var url = $("#moviesForm").attr("ajax_load_cast"); var text_input = $('#id_cast').val(); $.ajax({ url: url, data: { 'text_input': text_input }, success: function (data) { $("#add_cast2").html(data); // if (ajaxResult.indexOf(data) === -1) ajaxResult.push(data); } }); // var e = document.getElementById("add_cast2"); // var strcast_text = e.options[e.selectedIndex].text; // var strcast_id=e.options[e.selectedIndex].value // if (ajaxResult.indexOf(strcast_id) === -1) ajaxResult.push(strcast_id); // console.log(ajaxResult); // var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]; // for( var i = 0; i < arr.length; i++){ // if ( arr[i] === 5) { // arr.splice(i, 1); // } // } }); </script> {% endblock js%} {% endblock content %} I am implementing django multiselect option formField with basic html and ajax request so that it filter result before showing all the result .But I don't know how to implement select … -
Django - When unique constraint fails, do not allow to submit the form until user changes the field
I have a field in the model with unique constraint. class Profile(models.Model): user = models.OneToOneField(CustomUser,default=None, null=True,on_delete=models.CASCADE,) username = models.CharField(max_length = 200, blank = True, unique = True) summary = models.TextField(max_length = 5000, blank = True) I am using this model for below form. class ProfileForm(forms.ModelForm): class Meta: exclude = ['user'] model = models.Profile This is how I am using this form in the HTML page <form method="post" class="text-left subscription-form"> {% csrf_token %} {% bootstrap_form form %} <input type="submit" class='btn btn-default' value="Update Profile"> </form> When user enters the username that is already present in the database, I want form to not to submit but instead it should display a message that the username already exits. I think Django automatically used to do this, but now I am getting an error. Can you help me with this? Thanks! -
AttributeError __name__ when creating folium map in Django
View.py from django.http import HttpResponse from django.shortcuts import render from evadata.models import coord2_dj from django.views.decorators.csrf import csrf_exempt import json from django.views.decorators import csrf from django.http import JsonResponse import folium import pandas from folium import plugins def getvalue(request): # ctx = {} name = str(request.GET.get('gx')) print(name) # result_temp = coord2_dj.getmassege(name) with open('F:/pythonLine/shenzhen.json',encoding = 'utf-8') as f: san_geo = (json.loads(f.read())) data2 = read_frame({ 'lat': [22.54, 22.59, 22.57,22.53532129], 'lon': [113.95, 113.96, 114.14,114.0513112], 'name': ['sd', 'xl', 'tb','yt'], 'id': [x for x in range(4)] }) #center san_map = folium.Map(location=[22.54, 114.05], zoom_start=10,tiles='stamentoner') #load map folium.GeoJson( san_geo, style_function=lambda feature: { 'fillColor': '#1b1b1b', 'color': 'black', 'weight': 1, 'dashArray': '5, 5', 'fillOpacity': 0.5 } ).add_to(san_map) return render(request, 'shenzhen_Linemap.html') When running manage.py runserver, there was an error called 'AttributeError: name'. However, when I delete following lines, there has no error. import folium import pandas from folium import plugins How can I solve the problem and how to import packages above correctly? Thanks. -
Store assumptions of timezone in django model?
I have a MariaDB table with UTC datetimes in it. However, I cannot seem to get Django to use those without throwing a warning that I am feeding it naive datetimes when timezone support is active. Is there some way I can specify in the model that it is UTC datetimes stored in the database? I checked and it looks like MariaDB won't get a datetime column with timezone support (in a 2020-04-20 04:20:00-07:00 type of fashion) until the future. I've heard that Postgres doesn't have this problem but I am in no mood to migrate the database yet again. Code for the model is below—ideally, I'd convert into an aware datetime somewhere in the model rather than run the conversion every place the data is used. class NstRotationDate(models.Model): num = models.AutoField(primary_key=True) date = models.DateTimeField() special_note = models.CharField(max_length=123, blank=True, null=True) -
my Django form not validating when using __init__ for a dynamic Radio field
I have written a form which has a Radio Button, whose values I provide when I initialize the form. The form is being displayed perfectly but when I need to use the values submitted through the form, I cannot, because it is not validating. forms.py from django import forms class voteForm(forms.Form): def __init__(self,candidates, *args, **kwargs): super(voteForm,self).__init__(*args, **kwargs) self.fields['Candidate'] = forms.ChoiceField(choices=candidates, widget=forms.RadioSelect) views.py from django.shortcuts import render,redirect from register.models import Candidate, Voter from voting.models import Vote from voting.forms import voteForm from django.http import HttpResponse def index(request): context={} if request.method=='POST': form = voteForm(request.POST) if form.is_valid(): # do something with data return HttpResponse('Success') voterid=1 context['voter']=Voter.objects.get(id=voterid) request.session['id']=voterid candidates=Candidate.objects.filter(region=context['voter'].region).values_list('id','name') form = voteForm(candidates) context['form']=form return render(request,'voting/index.html',context) -
Calling a function within a view function in Django
Is 1 or 2 the correct way to call a function within a view function in Django. Or are both equally ok. Please explain. #1 def function1(request): [some api calls] #Once this process is done I want to call my second function return function2() def function2(): # some hard work return HttpResponse(...) #2 def function1(request): [some api calls] #Once this process is done I want to call my second function function2() def function2(): # some hard work return HttpResponse(...)