Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-Channels with 2 applications
I'm trying to make an example to test if it is possible to have 2 independent django apps connected to the same channel from django-channels. So far, I was able to make an example running on one machine and 2 other machines being able to access the first via a client. But the goal is to be able to connect separate applications in a single channel to communicate. Is that possible? If not, do you know an alternative? Note: I'm also using redis, if that helps. Thank you! -
Selenium keeps a cache?
I have a more complicate question but I'm trying to isolate the problem to avoid confusion. I'm testing a page using selenium. In this page there are two javascript external scripts. If you go there manually the page is working correctly but using selenium one of the javascript isn't loaded: The script from “http://localhost:55234/static/js/common.js” was loaded even though its MIME type (“text/html”) is not a valid JavaScript MIME type. 2 add-name Loading failed for the <script> with source “http://localhost:55234/static/js/common.js”. Checking the source (right click => view page source) gives me correctly the template with this two lines (and the others, off course): [...] <!-- load global javascript --> <script type='text/javascript' src="/static/js/common.js"></script> <!-- load app javascript --> <script type='text/javascript' src="/static/lists/js/lists.js"></script> [...] the src are clickable. Cliking the first one reload the source page without the line three and four, so without this lines: <!-- load app javascript --> <script type='text/javascript' src="/static/lists/js/lists.js"></script> Cliking the second one (lists.js) gives the javascript code. But! But this code looks an (very) old version of my code. Many days old (isn't too long to be cached?). At that time all the code was in one javascript file (lists.js) and the other one (common.js) didn't existed so … -
AttributeError in Serializer Django
I am developing an app, and one of its features is that it can recognize the device, but sometimes it doesn't get anything back. It maybe an error from the API that i'm using. The model Device is the following: class Device(models.Model): """ """ user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) deviceModel = models.CharField(max_length=128, verbose_name=_(u"Device Model")) deviceId = models.CharField(max_length=128, verbose_name=_(u"Device ID")) packageId = models.CharField(max_length=128, verbose_name=_(u"Package ID")) tokenId = models.TextField(verbose_name=_(u"Token ID")) platformId = models.CharField(max_length=10, verbose_name=_(u"Plataforma ID")) created_at = models.DateTimeField(auto_now=True, verbose_name=_(u"Created")) updated_at = models.DateTimeField(auto_now=True, verbose_name=_(u"Updated")) def __str__(self): return u'Device: {0}'.format(self.deviceId) def __unicode__(self): return self.__str__() def send_logout(self): """ Send logout Notification Message """ active_session = ActiveSession.objects.filter( device=self ).first() if active_session: push_service = FCMNotification(api_key=settings.FCM_API_KEY) data_message = { "action": "Logout", "token_id": active_session.token_jwt } push_service.single_device_data_message( registration_id=self.tokenId, data_message=data_message, content_available=True ) And the serializer is: class DeviceSerializer(ModelSerializer): def create(self, validated_data): # Check if exist device = Device.objects.filter(user=validated_data["user"], deviceId=validated_data['deviceId']).first() today = timezone.now() # If exist, update if device: device.tokenId = validated_data['tokenId'] device.updated_at = today device.save() logger.info("[Device] Updated deviceID {} with token {} for user {}".format( validated_data['deviceId'], validated_data['tokenId'], validated_data["user"].username )) else: device = Device(**validated_data) device.save() logger.info("[Device] Created deviceID {} with token {} for user {}".format( validated_data['deviceId'], validated_data['tokenId'], validated_data["user"].username )) # Associate Device to ActiveSession active_session = ActiveSession.get_active_session(self.context.get('request')) active_session.device = device active_session.save() return device … -
How to link your page to another page without using <a> tag
i have three Html page home.html, destination.html and login.html. Home.html only button my task is very simple if i click on this button if user is authenticated than go to the destination page otherwise go to the login page(i use builtin login function and that's working properly) my view.py is ``` from django.contrib import auth from django.shortcuts import redirect, render from rest_framework.permissions import IsAuthenticated """ this view section for home.html and destination.html, i have use builtin function for login """ def home(request): if request.method == 'POST': user = auth.authenticate() if user is IsAuthenticated: return render(request, 'destination.html') else: return redirect('login/') else: return render(request, 'home.html') def destination(request): return render(request, 'destination.html') ``` my urls.puy ``` from django.contrib import admin from django.urls import path from newapp import views from django.contrib.auth.views import LoginView urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home'), path('destination', views.destination, name= 'destination'), path('login/', LoginView.as_view(template_name='login.html')), ] ``` -
'CharField' object has no attribute split
i am creating an website where a user can search for recipes by their ingredients. I wish that when a user finally see recipe, ingredients there would be splited with ', ' in view. for now it is just space. I tried to do this in my model, but they i get error as in title - 'CharField' object has no attribute split. Models: from django.db import models class Ingredient(models.Model): ingredient_name = models.CharField(max_length=250) igredient_name1 = ingredient_name.split(', ') def __str__(self): return self.ingredient_name1 class Recipe(models.Model): recipe_name = models.CharField(max_length=250) preparation = models.CharField(max_length=1000) ingredients = models.ManyToManyField(Ingredient) def __str__(self): return self.recipe_name template: <div> <h1><a href="/">Drink drank drunk</a></h1> </div> {% for drink in results %} <div> <p>{{ drink.recipe_name }}</p> <p>Preparation: {{ drink.preparation }}</p> <p>Ingredients: {% for ingredient in drink.ingredients.all %} {{ingredient.ingredient_name}} {% endfor %} </p> </div> {% endfor %} view: def drink_list(request): template = "drinks/drink_list.html" return render(request, template) def search_results(besos): query = besos.GET.get('q') q = Q() for queries in query.split(', '): q |= (Q(ingredients__ingredient_name__icontains=queries)) results = Recipe.objects.filter(q) template = "drinks/search_results.html" context = { 'results' : results, } return render(besos, template, context) -
How from a Python variable to refer to <!-- Images. -- >?
There is a Python {{ object variable.background }}, which outputs the selected background from the database . When the background of the color ('#c6aa99', '#E1A600', it correctly displays the scene aframe. But when the variable is set to the image value 'mars',' star ' does not display the background of the image on the scene. How to make the value of a variable, when assigned to 'star', 'wars' refer to to upload pictures to the scene? <a-scene id="aframe" foo > <a-assets> <!-- Images. --> <img id="star" src="https://ucarecdn.com/30d7b1e6-2867-4396-a64d-8fb41e69ce0d/"> <img id="city" src="https://cdn.aframe.io/360-image-gallery-boilerplate/img/city.jpg"> <img id="cosmos" src="https://ucarecdn.com/34a5bbdb-1820-44c3-a848-26acd9356bbe/"> <img id="sechelt" src="https://ucarecdn.com/40714251-095c-407e-9b5f-76f361db3b78/"> <img id="blank" src="https://ucarecdn.com/fc2d2aa9-08b0-4d05-931c-85b78130d758/"> <img id="mars" src="https://ucarecdn.com/4496c535-1b3d-4c1c-a24f-8fa6bcfb895a/"> <img id="dey" src="https://ucarecdn.com/1bbbf75b-cc02-450a-91af-e528a6eaf8a1/"> <img id="blue" src="https://c1.staticflickr.com/3/2929/33929340355_1fb4ecf6e0_k.jpg"> <img id="wasteland" src="https://c1.staticflickr.com/5/4556/24549684008_5b18834af3_o.png"> </a-assets> <!-- General Enviornment --> <!-- Background selected when creating a new scene (taken from the database ) --> <a-sky id="sky" color="{{ object.background }}"></a-sky> <a-light type="ambient" intensity=".5" color="#FF54CA"></a-light> {% endblock %} <!-- Text written by the user when creating a new scene (taken from the database) --> <a-plane id="ground" position="0 0 0" rotation="-90 0 0" width="100" height="100" color="#00FF00" material="roughness: 1;"></a-plane> </a-entity> </a-scene> -
Using only gunicorn, django, and whitenoise how do I serve media?
I have my website finally working properly, but media files aren't served when debug = False what should I do? I've went through hell trying to make it work with nginx following this tutorial but it kept breaking and not serving static among other things, so I went with pure gunicorn and whitenoise. I really am not an expert at deploying, only development. Please help. Security isn't a problem with media files because only the admin can upload them, not end-users. Specifically I need to know if it's the end of the world leaving debug = True just for media files. Or if there's an easy way to serve them with debug = False. -
Error in SQL query with connection.cursor()
I am making a query with connection.cursor(), but I get the following error column does not exist LINE 1: SELECT u.id, u.addByAdmin FROM core_user AS u WHERE u.role... ^ HINT: You probably want to refer to the column «u.addByAdmin». This is my code @action(detail=False, methods=['get']) def registertalentsdetail(self, request,pk=None): cursor = connection.cursor() query = "SELECT u.id, u.addByAdmin FROM core_user AS u WHERE u.role = 'TA';" cursor.execute(query) conter = cursor.fetchall() print(conter) return Response(data=conter) Any idea how to fix this? -
How can to run task in 5 minutes after finish previous task using celery-beat?
I have a two tasks - a and b. Task a running in 5 minutes after finish previous task a. Task b running in 3 minutes after finish previous task b. How can I implement it? I'm use python 3.6.8, Django 2.2.6 and celery 4.3.0? -
Django - How to make a ForeignKey dropdown into a textbox?
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. Before I had made this change, I just had the adp_number under fields in forms.py, and not as a ForeignKey, which made me not be able to cross check with the Salesman model which contains all the valid adp_number's. 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 … -
how to add Paginator to search result using django?
hello i want add Paginator in search result page how to do this ? my code : views.py : def search(request): if request.method == 'GET': query= request.GET.get('q') submitbutton= request.GET.get('submit') # page = request.GET.get('page', 1) # the_home_page is the name of pages when user go to page 2 etc if query is not None: home_database= Homepage.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) pcprograms_database= PCprogram.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) androidapk_database= AndroidApks.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) androidgames_database= AndroidGames.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) antiruvs_database= Antivirus.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) systems_database= OpratingSystems.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) pcgames_database= PCgames.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) results= list(chain(home_database,pcprograms_database,androidapk_database,androidgames_database,antiruvs_database,systems_database,pcgames_database)) context={'results': results, 'submitbutton': submitbutton} return render(request, 'html_file/enterface.html', context) else: return render(request, 'html_file/enterface.html') else: return render(request, 'html_file/enterface.html') html page : {% if submitbutton == 'Search' and request.GET.q != '' %} {% if results %} <h1> <small> Results for {{ request.GET.q }} : </small></h1> <br/><br/> {% for result in results %} <label id="label_main_app"> <img style="margin-top:.3%;margin-left:.3%" id="img_main_app_first_screen" src="{{result.app_image.url}}" alt="no image found !" height="160" width="165" > {{result.name}} <br><br> <p id="p_size_first_page"> {{result.app_contect}} <br> <br> <a href="{{ result.page_url }}" type="button" class="btn btn-primary"><big> See More & Download </big> </a> </p> </label> {% endfor %} {% else … -
How should images used in jquery-ui be loaded in django admin?
I added an action to django admin which requieres a modal and some javascript interaction. I used jquery-ui for the modal and was able to load it following this instructions: django admin jQueryUI dialog However, the modal has a broken image (the closing button). The question is how can I reference that image so jquery-ui can find it. I put the images from jquery-ui library on the same folder where I put the .js and .css files I'm using for the action. The close image of the modal is broken, trying to find it on http://localhost:8000/static/admin/js/jquery-ui-1.12.1.custom/images/ui-icons_777777_256x240.png The project path is static/admin/js/jquery-ui-1.12.1.custom/images/ui-icons_777777_256x240.png The current code I have for referencing the assets is: admin.py class ReservationBaseAdmin: list_display = (..., 'action') # some more code (...) # Here I reference the jquery-ui library and the js code I wrote for the action class Media: css = { "all": ("admin/css/tables.css", 'admin/js/jquery-ui-1.12.1.custom/jquery-ui.min.css', 'static/admin/js/jquery-ui-1.12.1.custom/jquery-ui.structure.min.css') } js = ( 'admin/js/jquery-ui-1.12.1.custom/jquery-ui.min.js', 'admin/js/jquery-ui-1.12.1.custom/jquery-ui.structure.min.css', 'admin/js/front_iframe.js", "admin/js/force_sync.js' ) # some more code (...) def action(self, obj): front = env('FRONT_URL') url = reverse('admin:traveller_traveller_change', args=[obj.traveller.pk]) edit_button = format_html('<a class="button front_link" data-front="{}" target="_blank" href="{}">Ver Perfil</a>', front, url) refresh_button = format_html('<a class="button force_sync" data-confirmation-number="{}" >Forzar sincronización</a>', obj.reservation.confirmation_number) return edit_button + refresh_button action.short_description = "Acciones" static/admin/js/force_sync.js … -
Embedding seaborn generated plot image in Django Template
I am trying to embed the image generated by the seaborn plot dynamically into the Django HTML template. While when I am trying to save, the correct image gets saved in my directory. But my requirement is to pass this image in HTML page/Template without saving in the directory. I used BytesIO to stream the bytes and encoded the bytes with base64.b64encode encoding. But I get a blank white image on the page instead. fig = sb.pairplot(kpi) tmpfile = BytesIO() fig.savefig(tmpfile, format='png') encoded = base64.b64encode(tmpfile.getvalue()) return encoded Html file: <img src='data:image/png;base64,{{description}}'> {{description}} -
Django datadump and loaddata not working due to fixture error
Here is how I tried to dump mysql DB: python3 manage.py dumpdata > dumpdata.json Then, I tried to reload it: python3 manage.py loaddata dumpdata.json This is the error that I get: json.decoder.JSONDecodeError: Unterminated string starting at: line 1 column 226398200 (char 226398199) django.core.serializers.base.DeserializationError: Problem installing fixture '/home/JCDR77/HospitalThree/dumpdata.json': -
The current path, account/active/Z1s6IYaohOJWeRV4, didn't match any of these
enter image description here urls.py: path('active/(?P<active_code>.*)/$', ActiveUserView.as_view(), name='active_user'), views.py: class ActiveUserView(View): def get(self,request,active_code): users = UserProfile.objects.filter(code=active_code) if users: users.is_active = True users.save() else: users.delete() return HttpResponse('Fail!Register Again!') return HttpResponseRedirect(reverse("account:user_login")) -
Saving multiple text inputs from form into one field in django class-based view
I'm trying to save about 9 inputs from different textbox fields in template to one field on the django database, linking them each to another field. What can be done? What I'm trying to achieve is to get log input for each department and save in field log and linked to the department of the logged in user real_index.html (Template File) <script> function ch() { $(".div1").hide() $(".div2").show(); var a = document.getElementById("userInput").value; displayUserInput.innerHTML= a; } function cha() { $(".div2").hide() $(".div3").show(); var b = document.getElementById("userInpu").value; displayUserInpu.innerHTML= b; } ... <form action="" method="post" > {% csrf_token %} {{ form | crispy }} <table class="table table-bordered"> <thead class="table-primary"> <th>Time</th> {% for log in object_list %} {% if user.username == log.username%} <th>{{ log.dept }}</th> {% endif %} {% endfor %} </thead> <tbody> <tr class="table-success"> <td> 6:30AM-7:30PM </td> <td> <div id="div1" > <div class="div1" id="div1"> <input type="text" id="userInput" name="userInput"/><input class="btn2" class="btn2" type="button" value="Done" onclick="ch()"/> </div> </div> <span id="displayUserInput"></span> </td> models.py class Log(models.Model): ... dept = models.ForeignKey(Dept, null=True, on_delete=models.SET_NULL) log = models.CharField (max_length=50,null=True) forms.py ... class NewLogForm(forms.ModelForm): #class NewLogForm(forms.MultiValueField,forms.MultiWidget): class Meta(): model = Log fields = ('log','dept',) views.py class NewLogView(generic.CreateView): model = Log form_class = NewLogForm template_name = 'dutylog/real_index.html' def get_success_url(self, ): return reverse_lazy('index',) def form_valid(self, form): … -
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 ?