Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
autocomplete for python commands in django template
I want to autocompletion in Django template while I'm working with python commands in the template. For example, I have the code below in the test.html: <div id="content-main"> {% if app_list %} {% for app in app_list %} <div class="app-{{ app.app_label }} module"> {% endfor %} {% endif %} I want to have autocompletion popup for all variables but I have it for some part of the commands. For instance when I write {{ app.app_label }} I don't have any autocomplete popup for app_label. Is there any way to have it? thanks. -
How to implement favourite list in django for a user
I was following this question asked here Django query to get User's favorite posts? But how to select the favourites through the template? -
How to make model migration for different apps in different db in Django
I have used DB routers for apps, but after running migrate command tables are created in default DB, why?? -
django-haystack with elasticsearch's more_like_this always returns empty list
The more_lik_thismethod of SearchQuerySet of django-haystack always returns empty list, even when I created some duplicate items. What could be the issue? I am using django-haystack==2.3 with elasticsearch==1.6 as backend. My index looks like: class NoteIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField( model_attr="description", document=True, boost=1.0, ) title = indexes.EdgeNgramField( model_attr="title", boost=1.1 ) I currently have only 15 items and more_like_this always returns empty list while normal searches are working fine, even when the item passed to more_like_this() is very similar (almost duplicate in content) to other items in database. note_1 = Note.objects.first() SearchQuerySet().more_like_this(note_1) # returns [] -
Changing the WSGI application Django
I am trying to build a server in Django for an application for FLockOS, which requires me to build a new WSGI application, and replace it with the existing one get_wsgi_application(). A WSGI application in general takes a environ argument and a start_response argument, the general get_wsgi_application() on the other hand works in a more complex method. I wanted to know if I could combine the WSGI application I made with the pre-existing one so that, for the functions apart from those needed to serve my application can be built normally like how normal Django applications are made. Thanks in advanced! Here is my modified WSGI application def application(event_handler_client, get_wsgi_application): def inner(environ, start_response): try: return event_handler_client.handle(environ, start_response) except: return app(environ, start_response) return inner -
How to incorporate Twitter API into ModelForm and save
AIM I have a ModelForm in which a User enters the search_text and then returns all the locations associated with that search_text in the Hashtag model. For present purposes, the locations are manually created through the Admin. However, instead of manually entering the locations, the aim is for the locations to be scrapped from Twitter. As a beginner, I am considering achieving it in the following flow: A User enters search_text in the HashtagSearch FormView, A function is run within HashtagSearch FormView that searches Twitter for tweets using the search_text as a hashtag ('the applicable tweets'). Searches 'the applicable tweets' for whether the tweeter has a location saved on their profile. If so, save that location to a txt file, Performs regex on the txt file to filter out 'non-genuine' locations, Saves the locations to the locations object associated with the search_text in the Hashtag model. Render results.html with the locations object associated with the search_text in the Hashtag model. QUESTION As a beginner, I have one specific question and one broader question: First, how do I perform #2 (above)? I have attempted to: Incorporate the functions: scrap_locations and save_locations within HashtagSearch FormView, and then call them within form_valid and … -
Reverse for 'user_logout' not found, though it was configured well
I have such a navbar: <ul class="nav navbar-nav navbar-right" style="margin-right:10px" > <li><a href="{% url 'account:user_logout' %}">Logout</a></li> </ul> It report error: Exception Value: Reverse for 'user_logout' not found. 'user_logout' is not a valid view function or pattern name. However, the user_logout was configured finely. url(r"^logout/$",auth_views.LogoutView.as_view(template_name="account/logout.html"), and the namespace: url(r"^account/", include("account.urls", namespace='account', app_name='account')), It seems that there's no reasons to report error Reverse for 'user_logout' not found. What's might be the problem? -
Wagtail site is failing to load media files using DigitalOcean Spaces
I am building a Wagtail site, using DigitalOcean Spaces. The static files are loading OK, but when I try to upload an image from the admin, it can't upload the image into the media folder at Spaces, showing error. This is my config for the storage: AWS_ACCESS_KEY_ID = config('SPACES_ACCESS_KEY') AWS_SECRET_ACCESS_KEY = config('SPACES_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = 'BUCKET_NAME' AWS_S3_ENDPOINT_URL = 'https://nyc3.digitaloceanspaces.com' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'my_app/static'), ] STATICFILES_LOCATION = 'spaces-folder/static' STATICFILES_STORAGE = 'custom_storages.StaticStorage' MEDIAFILES_LOCATION = 'spaces-folder/media' DEFAULT_FILE_STORAGE = 'custom_storages.MediaStorage' I am also using a custom_storages.py file with the two following classes to use static and media files in the same Spaces bucket, following this tutorial: # custom_storages.py from django.conf import settings from storages.backends.s3boto3 import S3Boto3Storage class StaticStorage(S3Boto3Storage): location = settings.STATICFILES_LOCATION class MediaStorage(S3Boto3Storage): location = settings.MEDIAFILES_LOCATION -
IOPS brush and blocking access to my cloud services
I encounter the following situation and I have no clue to find out the source of the problem. The followings are the services I am running in my cloud instance: I am running a Django application in my cloud service. I use uWSGI to conenct Django with Nginx like this: nginx <---> uWSGI <---> Django I am running a MySQL docker container (version:5.7) in the same instance, it serves as the database for Django. It's just a development server. Problem: Sometimes when I am testing some functions of my service, the loading time is extremely slow. And soon, all my remote access to the instance are disconnected, and I can no longer access to my service. I check the monitor panel of my cloud service. It gives me the below diagram IOPS diagram from cloud's monitor panel As you can see, the blue line is the IOPS(read) and the orange line is IOPS(write). From 13:00 to 17:00, IOPS(read) was unreasonably high, and it blocked me from accessing my cloud instance. The followings are my assumptions to this incident: I suspect there is sth mis-configured in Django or uWSGI. (because this incident happens when i am testing functions of Django. I … -
Filtering fields with a file
I want to get only songs with a file models.py This includes the song model song_genre = ( (1,"Jazz"), (2,"Pop "), (3,"Rock"), (4,"Hip Hop / Rap"), (5,"R&B / Soul"), ) class Songs(models.Model): name = models.CharField(max_length=1000,blank=True, null= True) genre = models.CharField(choices=song_genre) file = models.FileField() def __str__(self): return str(self.name) views.py i have tried using the file__isnull filter but the template comes empty yet the sample data has files with no songs(song files) from .models import Song def song_with_file(request): songs = Song.objects.filter(file__isnull=True) return request(render, 'song_with_file.html', {'songs':songs}) templates/song_with_file.html {% include 'base.html' %} {% block content %} {% for song in songs%} {{song}} {% endfor %} {% endblock %} -
Haystack elasticsearch is case-sensitive
How to configure haystack elasticsearch for case-insensitive queries? this is the field in django of my model: text = indexes.EdgeNgramField(document=True, use_template=True) isn't it because of the EdgeNgramField? should it be just CharField? I didn't found any information in the docs about this? or should I set a custom analyzer for this purpose? -
Django REST Framework generics.RetrieveUpdateDestroyAPIView return all records instead of one
I'm new to DRF and trying to build a rest API, I have set up my models, URLs, views, and serializers as: model.py: services = ( ('Single', 'Single'), ('Multiple', 'Multiple'), ) class DeploymentOnUserModel(models.Model): deployment_name = models.CharField(max_length=256, ) credentials = models.TextField(blank=False) project_name = models.CharField(max_length=150, blank=False) project_id = models.CharField(max_length=150, blank=True) cluster_name = models.CharField(max_length=256, blank=False) zone_region = models.CharField(max_length=150, blank=False) services = models.CharField(max_length=150, choices=services) configuration = models.TextField() routing = models.TextField() def save(self, **kwargs): if not self.id and self.services == 'Multiple' and not self.routing and not self.configuration: raise ValidationError("You must have to provide routing for multiple services deployment.") super().save(**kwargs) From urls.py: path('deployments/', apiview.DeploymentsList.as_view(), name='deployment-list'), path('deployments/<int:pk>', apiview.DeploymentDetail.as_view(), name='deployment_detail') From apiview.py: class DeploymentDetail(generics.RetrieveUpdateDestroyAPIView): def retrieve(self, request, *args, **kwargs): pk = self.kwargs.get('pk') return Response(DeploymentOnUserModel.objects.get(pk=kwargs['pk'])) From serializers.py: class DeploymentOnUserSerializer(serializers.ModelSerializer): class Meta: model = DeploymentOnUserModel fields = '__all__' When I try access: http://127.0.0.1:8000/api/v1/deployments/?pk=1/ it should return a single object of id=1 but it returns all objects. -
Implementing 4 column Composite Foreign Key
I have looked at the documentation and installed the module as instructed [https://pypi.org/project/django-composite-foreignkey/][1] but I'm struggling to get this implemented, if the following is correct I'm getting an error "get() returned more than one Samples -- it returned 217!" So obviously the multi-key is only working on one column. I'm guessing the issue is with post = get_object_or_404(Samples, pk=pk) only returning one variable rather than a list/dictionary? Any help is very much appreciated since I need to get this ready for our archaeological expedition while I'm here in the field. My view.py def editsample(request, pk): post = get_object_or_404(Samples, pk=pk) if request.method == "POST": form = SamplesForm(request.POST, instance=post) if form.is_valid(): post = form.save(commit=False) post.save() return redirect('allsamples') else: form = SamplesForm(instance=post) return render(request, 'samples/create_samples.html', {'form': form}) My model.py: class Container(models.Model): #columns for composite fkey area_easting = models.IntegerField() area_northing = models.IntegerField() context_number = models.IntegerField() sample_number = models.IntegerField() container_name = models.CharField(max_length=50, blank=True, null=True) container_type = models.CharField(max_length=50, blank=True, null=True) #foreign keys location_id = models.ForeignKey(Location, db_column='location_id', on_delete = models.PROTECT) icon_desc = models.ForeignKey(Icon, db_column='icon_desc', on_delete = models.PROTECT) def __str__(self): return self.container_name class Meta(): managed=False db_table = 'samples\".\"container' unique_together = [('area_easting', 'area_northing', 'context_number', 'sample_number'),] class Samples(models.Model): #Composite Key area_easting = models.IntegerField() area_northing = models.IntegerField() context_number = models.IntegerField() sample_number … -
where does the defenition of custom permission exist?
In the docs, it says that the below given way can be used to give custom permissions.The permission required decorator is used to check user permissions. But it does not say where these permissions are defined or what they do. Do i not need to define them ? If yes where and how do i do it? Thanks for all the helps. class Task(models.Model): ... class Meta: permissions = ( ("view_task", "Can see available tasks"), ("change_task_status", "Can change the status of tasks"), ("close_task", "Can remove a task by setting its status as closed"), ) -
django Users and Registration
Django 2 - python3 my model: simplified class School_info(models.Model): school_name = models.CharField(max_length=25) school_address = models.CharField(max_length=40) school_sector = models.CharField(max_length=20, choices=) school_field = models.CharField(max_length=10,choices='') school_size = models.CharField(max_length=10, choices='') school_phone = PhoneField(blank=True, help_text='Contact phone number') school_email = models.EmailField(max_length=50,blank=True) def __str__(self): return self.school_name class Course(models.Model): course_name = models.CharField(max_length=200, default='') course_description = models.TextField(default='') course_scope = models.CharField(max_length=2000, default='') def __str__(self): return self.course_name class Homework(models.Model): homework_name = models.CharField(max_length=20, default='') homework_type = models.CharField(max_length=20, default='') homework_address = models.CharField(max_length=20, default='') assst_description = models.CharField(max_length=700, default='') assst_avaliablility = models.CharField(max_length=8, choices='') homework_criticality = models.CharField(max_length=8, choices='') def __str__(self): return self.homework_name This is My needed data, I want the Admin to create 2 type of Users, and he is only able to Create Courses and HomeWorks. Teacher and Student. The Teacher can view the Course and the homework. The Student can view the Assigned Homework and the School info Without the Course Info. Only the Admin Can Create A Teacher Account And Assign it to the Course and Can view the School Info and HomeWork. The Student Can View The Assigned Homework and and Submit it the Teacher can request the Homework to be RE-DO. I got confused where I would put the Account Creation and How to make Sure that no Other Teacher or … -
Does Django 1.11 still support function base view for auth module?
It has been written in release notes of Django 1.11 that auth module will now support class base view and not function base view. Since we're migrating from 1.10 to 1.11 we can see that our older function base view is still working with django 1.11. we've referred below link https://docs.djangoproject.com/en/1.11/releases/1.11/ Whether the behavior are expected or not ? Do we need to rewrite class base view ? -
How to resolve Plotly url issue?
why url issue is showing in django while making bar chart by python Plotly module. Request URL: http://127.0.0.1:8000/%3Cplotly.tools.PlotlyDisplay%20object%20at%200x00000000035B8DA0%3E.embed?width=200&height=200&link=false&showlegend=false The current URL, <plotly.tools.PlotlyDisplay object at 0x00000000035B8DA0>.embed, didn't match any of these. I am making bar chart and rendering in django template. There i am getting above error. Actually this error comes if url doesn't exist. but i am not calling this url. It is predefined url by plotly. Waiting for response. Any help will be appreciate. -
Pyhton Django overite uploaded file
I want to overwrite/replace a file whenever a new file is uploaded. Currently the app can upload the file to a specific folder but its not overwriting files in an event that a new file has been uploaded. I need assistance to resolve that. #views.py def uploadfunc(request): if request.method=='POST': form =uploadfileform(request.POST,request.FILES) if form.is_valid(): form.save() return render_to_response('upload_successful.html') else: form=uploadfileform() return render(request, 'upload.html',{'form':form}) #models.py class uploadfolder(models.Model): """ my application """ File_to_upload = models.FileField(upload_to='') #forms.py class uploadfileform(forms.ModelForm): class Meta: model=uploadfolder fields=('File_to_upload',) -
Authentication on specific method for generic API views
I have used ListCreateAPIView and RetrieveUpdateDestroyAPIView for a model. Now I want to add JWT authentication to only the Update and Destroy part in the RetrieveUpdateDestroyAPIView. How can I do that? -
request.POST.get() is empty
In views.py @login_required(login_url='lab_3:login',redirect_field_name="next") def myorders(request): pass I used login_required to redirect to login with parameter "next". class user_login(View): def post(self,request): from_order = request.POST.get('next','') username = request.POST.get('username','') password = request.POST.get('password','') user = authenticate(username=username, password=password) current_time = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time())) if user: if user.is_active: login(request, user) request.session['last_login'] = current_time request.session.set_expiry(60*60) if from_order: order_list = Order.objects.filter(client=user).all() return render(request,'myapp/myorders.html',{ 'order_list':order_list, }) return render(request,'myapp/index.html',{ 'user':user, }) else: return HttpResponse('Your account is disabled.') else: return HttpResponse('Invalid login details.') def get(self,request): from_order = request.GET.get('next', '') return render(request, 'myapp/login.html') I used Debug to check the user_login view and I find request.GET.get() can get the parameter from myorders view. But the request.POST.get is always empty. -
Why is the form not being displayed?
I am using django and ajax to submit a form, but when the form is invalid then it's not been displayed. # views.py class ProductCreateView(LoginRequiredMixin, CreateView): model = Product template_name = "products/my_products.html" form_class = AddNewProductForm() def form_valid(self, form): obj = form.save(commit=False) obj.user = self.request.user obj.save() return JsonResponse({"msg": "Your product was created successfully."}) def form_invalid(self, form): return render(self.request, "products/add_new_product.html", {"form": form}, status=400) saveNewProductButton.on("click", function () { var addNewProductForm = $(".add-new-product-form"); $.ajax({ type: 'POST', url: '/product/new/', data: addNewProductForm.serialize(), success: function(res){ alert(res['msg']); location.reload(); }, error: function (res) { var newProductPlaceHolder = $("#new-product-form-placeholder"); newProductPlaceHolder.html(res); }}); }); The res is shown in the console using Chrome, but not on the page. -
How does this snippet work exactly? "pk=request.POST['choice']"
This comes from part 4 of the polls application tutorial from the Django documentation. I am told that it fetches the id of the of the selected choice as a string. I would like to know exactly how it does this. Here is some context: from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import get_object_or_404, render from django.urls import reverse from .models import Choice, Question # ... def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'polls/detail.html', { 'question': question, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) -
AWS Elastic Beanstalk django project
I made this tuttorial https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html, and i try to do an Django application on AWS Elastic Beanstalk, but when click Image Could some one helpme please, I have phyton 3.6. Thanks. Regards -
How to make form.cleaned_data[] with m2m field, string + manytomanyfield?- Django
I changed a CharField of teacher into ManyToManyField, now my UserMessage and EmailMessage are broken, models as below: class UserMessage(models.Model): user = models.ManyToManyField(User,related_name="recipent") send_user = models.ForeignKey(Use,null=True, blank=True, on_delete=models.SET_NULL, related_name="sender") message = models.CharField(max_length=500) test_name =models.CharField(max_length=800, default='', blank=True) test_date = models.DateField(default=datetime.now) test_time = models.TimeField(default=datetime.now) `# when teacher is not ManyToManyField, the EmailMessage of body works well with test.teacher.user` teacher = models.ManyToManyField(User, related_name="+") test.teacher.username is for CharField, how to define a ManyToManyField? body="Name of test:" + test.name + ",Date :" + str(test.date) + ",Time:" + str(test.time) + ", Teachers:" + test.teacher.username And My UserMessage views as below, how to change form.cleaned_data['teacher'].name into a ManyToManyFiled? Thank you so much for any advice. user_message.test_name = form.cleaned_data['name'] user_message.teacher = form.cleaned_data['teacher'].username user_message.test_time = form.cleaned_data['time'] user_message.test_date = form.cleaned_data['date'] -
python django json.dumps() and javascript cookies
6.5 and django 2.1.a1. I am having trouble with what I thought might be a simple cookie build. I create a dict for the cookie payload. I end up with two string keys, each with a string value. An example is: >>> cookie_payload = dict() >>> cookie_payload["whereAmI"] = "index" >>> cookie_payload["account_number"] = "123456789" >>> json.dumps(cookie_payload, ensure_ascii=True) '{"whereAmI": "index", "account_number": "123456789"}' The result of the set_cookie below however is: '{"whereAmI": "index"\054 "account_number": "123456789"}' when it reaches my javascript. JSON.parse() barfs on the "054". The comma is obviously being escaped but it is not being url encoded. How do I force that comma to stay a "," or should I decode the string differently in javascript? @verified_email_required def index(request): cookie_payload = dict() try: cookie_payload["whereAmI"] = "index" my_profile = Profile.objects.get(user=request.user) profile_in_groups = Group.objects.all().filter( grouplist__profile__account_number=my_profile.account_number) \ .order_by('name') cookie_payload["account_number"] = my_profile.account_number.__str__() my_render = render(request, 'App/index.html', { 'profile': my_profile }) my_render.set_cookie("Session", value=json.dumps(cookie_payload, ensure_ascii=True)) except ObjectDoesNotExist: my_render = redirect('profile-create') my_render.set_cookie("Session", value=json.dumps(cookie_payload, ensure_ascii=True)) return my_render