Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Python Testing: How do I assert that some exception happened and was handled
I'm trying to test a Django view using the client post method. Inside the view I catch an exception and return a 500 response My test that checks the 500 response passes however I would also now like to test what actual Exception class was raised during the view call. Is there a way to do that? I've tried self.assertRaises(SpecificException) as a context manager but since it is already handled and caught, it won't do what I'm looking for: with self.assertRaises(SpecificException): response = self.client.post( path=reverse("stock:getstockinvt"), data={'product_id': 1}, content_type='application/json' ) If this can't be done then so be it, I am just wondering if this can. The alternative is to unit test the function that raises the exception. -
Filter model using many to many field as criteria Django
I want to get all objects that contain the certain many to many field id.i go through a whole lot of SO Post I didn't get it at all. my question is class Pizza(models.Model): name = models.CharField(max_length=30) toppings = models.ManyToManyField('Topping') def __str__(self): return self.name class Topping(models.Model): tp_id = AutoField(primary_key=True) name = models.CharField(max_length=30) def __str__(self): return self.name i want to get all pizzas objects which has tp_id = x.i tried something like this in view filterdObjects = Pizza.objects.filter(toppings = 1) -
How to select specific tables from related tables(Django)?
I have a query that links five tables. In some of them I need one (name from contractor) field. Therefore, I want to optimize this and select only one field), and not the entire table. How can I edit this code? paymentsss = Transaction.objects.all().select_related('currency', 'payment_source__payment_type', 'deal__service','deal__service__contractor') -
Saving images to ImageField that are crawled by a background task
I have a program running in the background that will output images to a specific folder on my server, and this can happen at different intervals. I need to be able to show these images on a template, so I want to save them to the db using ImageField. My question is how would I go on saving them to the DB? Can I just do something along os.listdir(dir) on a background task and save that directly to the DB, or does it need the full path to the image? I have already created the Model for this class Usertasks(models.Model): TaskID = models.CharField(max_length=55) user = models.ForeignKey(User, unique=False, on_delete=models.CASCADE) TaskStatus = models.CharField(max_length=15, default="missing") class TaskImages(models.Model): UserTasks = models.ForeignKey(UserTasks, related_name='images') image = models.ImageField() -
Download the HTML template page filled with Django form
I have a template page on which one I access when I filled my Django form. This page is a simple HTML page with data coming from my form. I would like to be able to download the filled template. That's to say, get a browser window which let to download the template or by clicking on a button which will save the HTML template somewhere. This is my code in my views.py file: class TemplateGenerator(TemplateView): ''' This class displays the form and lets to save data into my database. It redirects users to the filled HTML template ''' form_class = CommunicationForm template_name = 'form.html' success_url = '/HTML_Result/' def get(self, request): form = self.form_class() return render(request, self.template_name, {'form': form}) def post(self, request): form = self.form_class(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('HTML_Result') args = {'form': form} return render(request, self.template_name, args) class HTMLResult(TemplateView): ''' This class displays the template filled thanks to the form from TemplateGenerator() class ''' template_name = 'template_1.html' def get(self, request): data = Communication.objects.values().latest('id') self.donwload_html() return render(request, self.template_name, {'data': data}) def donwload_html(self): file_path = os.path.join(settings.MEDIA_ROOT, 'media') if os.path.exists(file_path): with open(file_path, 'rb') as fh: response = HttpResponse(fh.read(), content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") response['Content-Disposition'] = 'inline; filename=' + 'test' return response raise Http404 I got … -
How can I check from the frontend if a dropdown is empty to not show it?
I was seeing this could be achieved using AJAX, but I'm not very familiar with it and I'm not sure how to approach it since my html is limited. I have a form, which has ForeignKey dependent dropdowns. Some of the options in the first dropdown cause the second to not have any options, in which case I'd like for it to not appear, without having to refresh the page. My page has an ajax request from a tutorial on how to make these dependent dropdowns, but I couldn't figure out how to create a request to check whether station_number is empty or not, to maybe hide/unhide from the div, or something of that sort, not sure what's possible enter_exit_area.html {% block main %} <form id="warehouseForm" action="" method="POST" data-stations-url="{% url 'operations:ajax_load_stations' %}" novalidate > {% csrf_token %} <div> <div> {{ form.adp_number.help_text }} {{ form.adp_number }} </div> <div> {{ form.work_area.help_text }} {{ form.work_area }} </div> <div> {{ form.station_number.help_text }} {{ form.station_number }} </div> </div> <div> <div> <button type="submit" name="enter_area" value="Enter">Enter Area</button> <button type="submit" name="leave_area" value="Leave">Leave Area</button> </div> </div> </form> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> $("#id_work_area").change(function () { var url = $("#warehouseForm").attr("data-stations-url"); var workAreaId = $(this).val(); $.ajax({ url: url, data: { 'work_area': workAreaId }, … -
How to generate a quiz with a limited number of questions in Django
I want to generate a quiz with a pre-set number of questions, and have these questions drawn at random. Currently, it is only generated one at a time. How to make? views.py def quiz(request): qtd = request.GET.get('qtd',None) questao = Questao.objects.annotate(resp_count=models.Count(models.Case(models.When(resposta__usuario=request.user, then=1),output_field=models.IntegerField()))).filter(resp_count=0,tipoQuestao=1,statusQuestao=1).order_by("?").first() q = request.POST.get('idQuestao',None) respostas = Resposta.objects.filter(usuario=request.user,idQuestao=questao) respostaform = RespostaForm(request.GET,request.POST or None) if request.method == 'POST': if respostaform.is_valid(): resp = respostaform.save(commit=False) resp.resposta = request.POST.get('resposta','') resp.usuario = request.user resp.idQuestao_id = q resp.save() return HttpResponseRedirect(request.path_info) else: respostaform = RespostaForm() quiz.html {% if not respostas %} <h3>Questão {{questao.idQuestao}}</h3> {% if questao.textoQuestao %} <p>{{questao.textoQuestao}}</p> {% endif %} {% if questao.perguntaQuestao %} <p>{{questao.perguntaQuestao}}</p> {% endif %} <form id="respostaform" name="respostaform" action="" method="POST"> {% csrf_token %} {{respostaform.resposta}} <input class="btn btn-primary btn-block" type="submit" value="Responder"> </form> {% endif %} -
trying to deploy a poll app on heroku but i keep getting problems
i dont get any problem using my localhost i have add the Procfile but still can't deploy it C:\Windows\System32\POLLSTER-PROJECT>heroku ps:scale web=1 Scaling dynos... ! ! Couldn't find that process type (web). -
How to filter/get with 2 word __str__
Model has: def __str__(self): return '%s %s' % (self.first_name, self.last_name) I want to do a objects.get where the first name and last name are the same to allow users to have the same first name but still specifiy. Tried having the __str__ as the id but can't be an int apparently. Also tried splitting the name with .split() but it gave the error object has no attribute 'split'. How I tried the split: full_name = interaction_info.candidate_id split_name = split() candidate_first = split_name[0] candidate_last = split_name[1] candidate_link = Candidate.objects.filter(first_name__exact=candidate_first).filter(last_name__exact=candidate_last) I want to be able to find the entry where the first name and last name match the return self string. But cannot get it to work. -
Pycharm can't auto complete some modules
Pycharm works well at most time. But it can't auto complete code sometimes. The following "objects" can't be completed. Who knows why? class SnippetList(APIView): """ List all snippets, or create a new snippet. """ def get(self, request): snippets = Snippet.objects.all() # The objects can't be auto completed. serializer = SnippetSerializer(snippets, many=True) return Response(resp) -
looping of functions with pauses
There are two functions. Both should start when the server (nginx) starts and work throughout its life. The first function should run every 5 minutes, the second - every 3 minutes (for example). It is possible that the function will run longer than the pause between its starts. It is necessary to start the pause counting from the moment the previous function ends. If any of the functions breaks with an error, need to restart it. How can this be implemented? At the moment, this has been decided in a very crutch-like manner. Through while True in celery and try / except to check for a "break" function. It is clear that this needs to be rewritten. So far, the thought comes to my mind with writing a management team with a cron and a supervisor. Or celery beat. -
Username and ID shown in the address bar
I am trying to create a website using Django and python ,which asks user for the Login ID and password and then makes an API call to verify the credentials now my problem is than whenever the user inputs the ID and password and logs in the ID and Password is shown in the address bar -
How to mimic unique_together behaviour for many-to-many fields?
I need to treat three fields from model as unique . The problem is that one of them is ManyToManyField so i can't use Django built-in unique_together functionality. How would you handle this problem? Database i'm using is MySQL. Example: class A(models.Model): name = models.CharField(max_length=255) class B(model.Model): name = models.CharField(max_length=255) other_field = models.CharField(max_length=255) a_m2m = models.ManyToManyField(A, blank=True) And i want name, other_field and all fields from m2m relation unique together. So following "rows" for B are treated as a whole and are unique (with m2m): name: 1, other_field: 1, a_m2m: (1, 2, 3) name: 1, other_field: 1, a_m2m: (1, 2) name: 1, other_field: 2, a_m2m: (1, 2, 3) name: 1, other_field: 1, a_m2m: (1, 2, 4) How would you do it in Django/MySQL? -
Django FileField uploads files to S3 bucket but location of the files is not stored to database
My Django application is running on Elastic Beanstalk. I want to store some files using FileField. Storing is done using default Django admin. On local installation my application works fine. When I run the app on AWS, the files are uploaded correctly to a S3 bucket after save, but Django admin shows that photo fields are empty. Why aren't location of the files stored to database? settings.py: if 'AWS_STORAGE_BUCKET_NAME' in os.environ: # Running on AWS DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_STORAGE_BUCKET_NAME = os.environ['AWS_STORAGE_BUCKET_NAME'] AWS_S3_REGION_NAME = os.environ['AWS_S3_REGION_NAME'] AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID'] AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY'] DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' else: # Running locally MEDIA_ROOT = os.path.join(BASE_DIR, 'photos/') MEDIA_URL = 'http://localhost:8000/photos/' models.py: def start_photo_directory_path(instance, filename): return 'photos/{0}/begin-{1}'.format(instance.id, filename) def completion_photo_directory_path(instance, filename): return 'photos/{0}/completion-{1}'.format(instance.id, filename) class Scenario(models.Model): start_photo = models.FileField(blank = True, editable = True, upload_to=start_photo_directory_path) completion_photo = models.FileField(blank = True, editable = True, upload_to=completion_photo_directory_path) -
Django CreateView with get_success_url not working for this specific case
I'm using Django 2.1. I'm having a problem with a CreateView because I need to redirect to the update url, but that url contains one argument that is created manually after verifying that the form is valid. This is the view code: class ProjectCreateInvestmentCampaignView(LoginRequiredMixin, SuccessMessageMixin, generic.CreateView): template_name = 'webplatform/project_edit_investment_campaign.html' model = InvestmentCampaign form_class = CreateInvestmentCampaignForm success_message = 'Investment campaign created!' def get_success_url(self): return reverse_lazy('project-update-investment-campaign', args=(self.kwargs['pk'], self.object.campaign.pk, self.object.pk)) def form_valid(self, form): project = Project.objects.get(pk=self.kwargs['pk']) form.instance.investment_type = "A" form.instance.contract_type = "CI" form.instance.history_change_reason = 'Investment campaign created' valid = super(ProjectCreateInvestmentCampaignView, self).form_valid(form) if valid: campaign = CampaignBase.objects.create(project=project, ) form.instance.campaign = campaign form.instance.campaign.project = project form.instance.campaign.creation_date = timezone.now() form.save() return valid As you can see, on the form_valid I validate first the form, and then I create the object campaign and assign all the related data. This is working fine. The problem came when I changed the get_success_url to fit my use case, that is redirecting to the update view. I debugged and saw that at the moment I create the variable valid on the form_valid, it checks the success url, and that triggers me the following error: Exception Type: AttributeError Exception Value: 'NoneType' object has no attribute 'pk' Exception Location: /Volumes/Archivos/work/i4b/webplatform/views/investor_campaign_views.py in get_success_url, line … -
Django form with modelchoicefield always is invalid
I created the form to which I submit queryset.Everything is displayed well, but the form does not pass validation. As I noticed, the entire selector is transmitted immediately. views.py if search_form['contractorName']: contractor = search_form['contractorName'] paymentsss = paymentsss.filter(deal__service__contractor__name=contractor) forms.py class SearchForm(forms.Form): date1st = forms.DateField(required=False) date2st = forms.DateField(required=False) numberPayment = forms.CharField(required=False) numberPhone = PhoneNumberField(region='RU', required=False) contractorName = forms.ModelChoiceField(queryset=Contractors.objects.values_list('name', flat='True'), required=False) status = forms.CharField(required=False) -
Django QuerySet filter field in JSONField list
I've got two models. On that is not relevant except the fact that it has id and the other has a JSONField with a serialized list of first model's id's. I want to get a QuerySet of first model's objects that id's are in a JSONField's list of second model object. What I've managed to do is: @property def variant_id_list(self): return json.loads(self.variant_ids or "[]") @property def variants(self): return Variant.objects.filter(id__in=self.variant_id_list) But aboves aproach forces Django and Postgres to get variant_ids from DB then convert it to python list and then again request DB to check if an id is in a list, whereas (I think) DB could handle whole operation itself. Is there a way to do this simplier? I can't change JSONField to ArrayField or any other, it has to be JSONField. -
How to print current details of a logged in user django
I have used oneToOneField to connect username to the sellerdetails model. In the dashboard, I print the username with {{ request.user }} and now I want to print the name of the user, which is stored in the SellerDetail model in models.py, linked to the current user. I have tried using {{ request.name }} But it does not return any value. name here is a field defined in my model SellerDetails. How can I print the deatils of the currently logged in user? -
What is shallow key transformation
I was reading about CVE-2019-14234 Detail.There it is mentioned about shallow key transformation.Can you please tell me what is shallow key transformation.It would be better if someone can explain about this CVE also.Please ignore this if this question is at wrong place. -
TimeRotated logging in Python/Django not working as expected
i have the following handler configuration: "handlers": { 'system_file': { 'level': 'DEBUG', 'class': 'logging.handlers.TimedRotatingFileHandler', 'filename': os.path.join(LOG_FOLDER, "all.log"), 'formatter': 'verbose', 'when': 'midnight', 'backupCount': '30', } } Now based on this configuration my logs should get rotated every midnight. In the all.log file, everything gets logged properly with correct timestamp, but when the rotation happens, I see a strange content in the backup log files. For example: Let's say today is 2019-10-29, the all.log file starts storing all the logs from 2019-10-29 00:00:00 to 2019-10-29 23:59:59. The next day i.e. on 2019-10-30 (when rotation would have happened), when I go and check all.log.2019-10-29, it contains log from 2019-10-30 00:00:00 till 2019-10-30 01:00:00, instead of the log of 2019-10-29 and the all.log file starts storing logs of 2019-10-30 from 00:00:00 onwards. So basically all my backup files only contain log of the next day from 00:00:00-01:00:00. all.log as on 2019-10-30 [DEBUG 2019-10-30 00:00:07,463 cron.py:44] ..... [DEBUG 2019-10-30 00:00:11,692 cron.py:44] .... [DEBUG 2019-10-30 00:00:13,679 cron.py:44] .... . . . . *Till current time* all.log.2019-10-29 as on 2019-10-30 [DEBUG 2019-10-30 00:00:07,463 cron.py:44] ..... [DEBUG 2019-10-30 00:00:11,692 cron.py:44] .... [DEBUG 2019-10-30 00:00:13,679 cron.py:44] .... . . . [DEBUG 2019-10-30 00:00:52,463 cron.py:44] ..... [DEBUG 2019-10-30 00:00:55,692 cron.py:44] … -
Enabling logging for OpenLDAP client?
I'm trying to do some authentication inside a Django application using django-auth-ldap via the OpenLDAP client. It's not working so how do I enable some logging? I CAN make LDAP queries using ldapsearch so fundamentally my config is correct and I tried enabling logging for django-auth-ldap but it just reports an Error(0) which is completely unhelpful. So how do I enable logging for the OpenLDAP client part of the equation? Ideally I would like to see what queries it is making and using which config is being passed down from django-auth-ldap. I did find ldap.conf but the syntax man page implies there is no logging or debug option. -
for loop is not working in one template and different request ( just first loop shown )
I have model and passed content base on each dashboard slug but item of dashboard for first one just create and other item not shown , what is my problem code? View: def dashboards(request,slug): domain_list = Domain.objects.all() category_list = Dashboard.objects.all() widget_list = Widget.objects.filter(dashboard_list__Dashboard_name__contains=slug) return render(request, "Dashboards.html", {'domain_list': domain_list, 'category_list': category_list, 'widget_list': widget_list }) class DashboardList(generic.ListView): queryset = Widget.objects.filter(status=1).order_by('-created_on') template_name = 'Dashboards.html' class DashboardDetail(generic.DetailView): model = Widget template_name = 'Dashboards.html' url : urlpatterns = [ path('dashboards/<slug:slug>/',dashboards, name='dashboard_list'), ] Dashboard.html: {% for Post in widget_list.all %} {{ Post.title }} {% endfor %} I have menu and slug call from them: {% for Category in domain.categorys.all %} <ul class="treeview-menu"> <li><a href="http://127.0.0.1:8000/dashboards/{{ Category.slug }}#"><i class="fa fa-adjust"></i> {{ Category.Dashboard_name }}</a></li> </ul> {% endfor %} Model : class Widget(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) dashboard_list = models.ForeignKey(Dashboard, on_delete=models.CASCADE, related_name='Widget_category') def __str__(self): return self.title class Dashboard(models.Model): Dashboard_name = models.CharField(max_length=20) slug = models.SlugField() Domain=models.ForeignKey(Domain,related_name='categorys',on_delete=models.CASCADE) -
Delete user image from S3 and update his profile with default one also stored on S3
I'm creating user profile page in Django and I want to give users ability to delete previously uploaded avatar and replace it with default one. What I have done is that after pressing delete button the image on AWS S3 is deleted, but I don't know how to update user.image in database. If it was a string or int type, there would be no problem. But the question is how do I get the image from AWS, transform it to whatever object type is needed and update database? models.py: class Patient(models.Model): image = models.ImageField(default='default.jpg', upload_to=get_file_path) I have also implemented an ability to update an old image with new one, so I've create an UpdateForm for that. On a page with that form is also a button that calls delete_image from views.py forms.py class PatientUpdateForm(forms.ModelForm): image = forms.ImageField(required=False) class Meta: model = Patient fields = ['image'] views.py @login_required def delete_image(request): old_image_name = request.user.patient.image.name # refers to the specific user # don't know what's next Patient.objects.filter(pk=request.user.patient.pk).update(??) storage.delete(old_image_name) return redirect('profile') -
How to: Django Parler CRUD Forms
I am using Parler for localizing my models. Django Admin works fine, but now I want to recreate the admin forms in the frontend. So far, I can create a new model but it is always created in the default language. The question now is, how can I set the language? Best case scenario would be, that I can select the language via <select> in the form, but the default value would be set by a get param language=iso_code or if it is way easier using the language tabs like in Django Admin. Model class Category(MPTTModel, TranslatableModel): title = TranslatedField(any_language=True) description = TranslatedField() slug = TranslatedField() parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children', db_index=True) objects = CategoryManager() def save(self, *args, **kwargs): super(Category, self).save(*args, **kwargs) class CategoryTranslation(TranslatedFieldsModel): title = models.CharField(max_length=200) description = models.TextField(null=True) slug = models.SlugField() master = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='translations') class Meta: unique_together = ( ('language_code', 'slug'), ) View @method_decorator(login_required, name='dispatch') class CategoriesCreateView(TranslatableCreateView): model = Category context_object_name = 'categories' template_name = 'categories/update.html' form_class = CategoryForm object = Category() def get(self, request, *args, **kwargs): request.DEFAULT_LANGUAGE = LANGUAGE_CODE request.meta_title = _('Create Category') return super().get(request, *args, **kwargs) def post(self, request, *args, **kwargs): request.DEFAULT_LANGUAGE = LANGUAGE_CODE request.meta_title = _('Create Category') return super().post(request, *args, **kwargs) … -
how to redirect after logging in django admin page to home page if user is staff
Give me any links or idea about how to redirect from Django admin login page to other pages.