Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ORM from queryset
Could someone please help me with converting below SQL query to django ORM SELECT tc.id, tc.cycle_time_target, tc.quality_target, tc.five_s_target, tc.recent_cycle_time, tc.actual_cycle_time, mc.press_name, tc.machine_id, p.number, tc.part_id, t.number, tc.tool_id FROM tech.computer_totalconfig tc INNER JOIN tech.computer_myconfig mc ON tc.machine_id = mc.id INNER JOIN tech.computer_part p ON tc.part_id = p.id LEFT JOIN tech.computer_tool t ON tc.tool_id = t.id; My ORM is TotalConfig.objects.prefetch_related('machine_id__part_id__tool_id') But I am not getting the desired output. -
Edit django wagtail promote tab fields
Hello I would like to ask you concerning editing default "promote" tab in django wagtail cms v.2.6.1 . I am doing bilingual website and I would like to put extra tranlation fields "Page title CZ" and "Search description CZ" between existing default fields. As you can see on attached image I know how to add extra field in another FieldPanel, but that is not exactly what I need. code of another FieldPanel: class BlogPage(Page): template = "blog/blog.html" subpage_types = ['blog.BlogPostPage','blog.PostAdvancedPage'] menu_order = models.IntegerField(default = 0) promote_panels = Page.promote_panels + [ FieldPanel('menu_order'), ] Image of problem description: -
If statement in django not working as expected
So I'm trying to show the user a list of attributes from objects in my database but only when the name of the object is the same as the group the user is in. In my code I have this: {% for page in object_list %} {% for group in request.user.groups.all %} {% if page.organisation == group.name %} {{group.name}} group name {{page.organisation}} page <li> {{page.page_name}} </li> <li> {{page.data_location}} </li> <li> {{page.organisation}} </li> {% endif %} {% endfor %} {% endfor %} when I run the list items do not show up as if the group name and page organisation variables do not match. However when I remove the if statement to compare the variables (as they should match with my test data) They show for example {{group.name}} = Abc {{page.organisation}} = Abc How can I get this list items to show when the two values are the same? Sample of my data: page{ page.name = "abc" page.data_location = "http://google.com" page.organisation = "abc" } The user in a group called abc I think it might be an issue with type and exact matches but I can't tell if thats the case when I show group.name and page.organisation.name directly. -
How to extract value from html tag attributes in Django
I am practicing scraping imdb new coming movies, to be more specific I like to get the name, src, title and so on of the movie list, however, what I'm getting is this.. [, ,...] I have tried to extract the value many ways but no success. m.img.title m['title'] m.get('title') and others similar << my views.py file >> def movies(request): import requests from bs4 import BeautifulSoup http = urllib3.PoolManager() headers = requests.utils.default_headers() headers.update({ 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0'}) url = "https://www.imdb.com/movies-in-theaters/?pf_rd_m=A2FGELUUNOQJNL&pf_rd_p=2413b25e-e3f6-4229-9efd-599bb9ab1f97&pf_rd_r=TVZT5ZEDG4QTR3X0H40R&pf_rd_s=right-2&pf_rd_t=15061&pf_rd_i=homepage&ref_=hm_otw_sm" req = requests.get(url, headers) soup = BeautifulSoup(req.content, 'html.parser') movies = soup.find_all('img', attrs={"class": "poster shadowed"}) return render(request, 'movies.html', {'movies': movies}) << my movie.html >> {% extends 'base.html' %} {% block content %} <table class="table table-hover table-bordered table-striped table-light"> {% for m in movies %} <tbody> <tr> <th width="10" scope="row">{{ how to extract the src }}</th> <th width="10" scope="row">{{ how to extract the alt }}</th> <th width="10" scope="row">{{ how to extract the title }}</th> </tr> </tbody> {% endfor %} </table> <br/> {{ movies }} {% endblock %} << my output from localhost:8000/movies/ >> [, ,...] I'd like to extract the value for src, alt, title and put it in each cell <tr> <th width="10" scope="row">{{ m['src'] }}</th> … -
Django - How to render ForeignKeyRawIdWidget in a form?
I have a form that has a field which is a ForeignKey since it makes sure that the ID # being entered is one that exists in the database. After making it be a ForeignKey, it changed my field to look like a dropdown in the form as shown below, that contains a bunch of options called "Salesman object ('a number')", instead of it being a text box like it was before. The user is supposed to be able to enter their "adp" number and it should only allow numbers in salesman. I tried following this Django: using ForeignKeyRawIdWidget outside of admin forms since I'm not using admin either, but once I made the field into a widget it just stopped showing on my page altogether and I'm not sure what needs to be changed. forms.py class WarehouseForm(AppsModelForm): class Meta: model = EmployeeWorkAreaLog widgets = { 'adp_number': ForeignKeyRawIdWidget(EmployeeWorkAreaLog._meta.get_field('adp_number').remote_field, site), } fields = ('work_area', 'station_number') models.py class EmployeeWorkAreaLog(models.Model): employee_name = models.CharField(max_length=25) adp_number = models.ForeignKey(Salesman, on_delete=models.SET_NULL, help_text="Employee #", null=True, blank=False) work_area = models.ForeignKey(WorkArea, on_delete=models.SET_NULL, null=True, blank=False, help_text="Work Area", related_name="work_area") station_number = models.ForeignKey(StationNumber, on_delete=models.SET_NULL, null=True, help_text="Station", related_name="stations", blank=True) enter_exit_area.html {% extends "base.html" %} {% block main %} <form id="warehouseForm" action="" method="POST" data-stations-url="{% url … -
Credit Card Payment(master Card and Visa) in Django
I need to integrate a visa or MasterCard payment methods into a Django Project. I already know how to integrate PayPal with my project, but I need to use Visa or MasterCard instead. -
How to fix 'Named Pipes Provider: Could not open a connection to SQL Server [53]'?
Cant connect mssql database to django. Whe I trying to do with python, It works well, but when I try to run server on Django I have got error. Pyodbc version : 4.0.27; Django version : 2.1.13; Microsoft SQL Server 2017 (RTM) - 14.0.1000.169 (X64). DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': '<djangoBanks>', 'HOST': '<DESKTOP-0FKB14V>', 'USER': '<test>', 'PASSWORD': '<12345>', 'OPTIONS': { 'driver': "ODBC Driver 17 for SQL Server", 'Trusted_Connection' : 'Yes', } } } When i trying to python manage.py runserver I got error: '08001', '[08001] [Microsoft][ODBC Driver 17 for SQL Server]Named Pipes Provider: Could not open a connection to SQL Server [53]. (53) (SQLDriverConnect); [08001] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0); [08001] [Microsoft][ODBC Driver 17 for SQL Server]Invalid connection string attribute (0); [08001] [Microsoft][ODBC Driver 17 for SQL Server]A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online. (53)' -
How to add fields dynamically to a form? - Implementing a django app to track order status
After a basic introduction to Python thanks to an edX course and a chat with a friend who told me about Django, I thought I could implement a solution for my laboratory. My goal is to keep track of every reagent order made by everyone of us researchers to the suppliers. After one month I have a pretty decent version of it which I'm very proud of (I also have to thank a lot of StackOverFlow questions that helped me). Nonetheless, there's one requirement of the ordering flow that I haven't been able to translate to the Django app. Let me explain: Users have a form to anotate the reagent or they need, and then it is passed to the corresponding manufacturer for them to send us an invoice. It's convenient that each invoice has several products, but they all have to: a) be sold by the same manufacturer, b) be sent to the same location and c) be charged to the same bank account (it's actually more complicated, but this will suffice for the explanation). According to that, administrators of the app could process different orders by different users and merge them together as long as they meet the … -
Unable to upload a csv file to Elastic Search in Django
I am trying to upload a CSV file to Elasticsearch in Django using below code: uploadfile.html <body> <form action="indexfile" method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="myfile"> <input type="submit"> </form> </body> where, indexfile is a path in urls.py file from django.urls import path from . import views urlpatterns = [ path('indexfile', views.indexfile) ] views.py def indexfile(request): from elasticsearch import Elasticsearch, helpers import csv es = Elasticsearch(<endpoints>) es.indices.create(index='demo', ignore=400) reader = csv.DictReader(request.FILES['myfile']) helpers.bulk(es, reader, index="demo", doc_type='mytype') return render(request, 'add/result.html') but, it gives me following error Error at /indexfile iterator should return strings, not bytes (did you open the file in text mode?) How can I solve this error ? -
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)