Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to build a ModelForm edit form with a multiple select field populated with data from a different models in Django?
I have a Django application with a dabatase backend. I need to render an HTML multiple select field with a ModelForm form (select field which allow to select multiple items). Data used to populate this multiple select field is gathered from a different tables/models than the one referenced in the Meta class of my ModelForm. I don't know what would be the best strategy in that case to implement this 'edit' form. Values to populate most of my form are stored in model 'Items' Values to populate the multiple select field are stored models 'Item_Usage' and 'Usage' This form is aimed at editing existing data of those 3 Models/database tables Items can have multiple usages, for instance 'Wood' can have 'Stove combustor' and 'Boat construction' usage. How should I build my multiple select field so that user could retrive current 'usage' for an item and add or remove usage within this form so that 'item_usage' model is updated accordingly? Database tables 'items' table +----+-------------------------+-------------+ | id | name | quantity | +----+-------------------------+-------------+ | 1 | Wood | 20 | | 2 | Steel | 5 | | 3 | Asphalt concrete | 80 | 'item_usage' table +----+---------+---------------+ | id | … -
How to reference a slug from a different model in get_success_url?
Setup I have two models in my app. One is for a Journal and the other one is for entries to that journal. I wrote a CreateView class that will allow user to create a Journal entry for any Journal id currently located in. Ideally I want the class to "refresh" with the updated entry or in other words the get_success_url should lead the page we are currently located at. views.py class ToJournalEntriesList(LoginRequiredMixin, CreateView): model = to_journal_entry template_name = 'to_journals/to_journal_entries_list.html' fields = ('body',) def get_success_url(self): return reverse('to-journals', kwargs={'slug':self.object.slug}) def form_valid(self, form): current_journal = to_journal.objects.get(journal_user=self.request.user, slug=self.kwargs['slug']) form.instance.journal_user = self.request.user form.instance.journal_name = current_journal return super(ToJournalEntriesList, self).form_valid(form) def get_context_data(self, **kwargs): context = super(ToJournalEntriesList, self).get_context_data(**kwargs) context['to_journal_entries'] = to_journal_entry.objects.all() return context models.py class to_journal(models.Model): journal_name = models.CharField(max_length = 40) slug = AutoSlugField(populate_from='journal_name') date_created = models.DateTimeField(auto_now_add=True) journal_user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE,) def __str__(self): return str(self.journal_user) + " " + self.journal_name def get_absolute_url(self): return reverse('to-journals') class to_journal_entry(models.Model): body = models.TextField() entry_date = models.DateTimeField(auto_now_add=True) journal_name = models.ForeignKey(to_journal, on_delete=models.CASCADE,) journal_user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE,) def __str__(self): return str(self.journal_name) + " " + str(self.entry_date) def get_absolute_url(self): return reverse('to-journal-entries', args=(self.slug)) urls.py urlpatterns = [ path('', CreateToJournal.as_view(), name='to-journals'), path('<slug:slug>', ToJournalEntriesList.as_view(), name='to-journal-entries'), ] Error With the current setup that I have I get: Which makes … -
Django - Custom Login Page on index
I'm using Django and I'm creating an backend web application. I would like to ask fellow Django users if it is possible to create the urls and functions for the login page but on index. Without using default Django auth framework for authentication/login. I'm just about to write the function for this, but I have got no idea if it will work. I have also looked at other tutorials but I do tend to find these are out of date. Any information would be much appreciated. ''' path('', views.index.login_user, name='index'), ''' -
Django - How to update check-out time based on another field?
I have an app that sort of works in a check-in/check-out manner. People just enter their ID, area, and click check in and it sends the timestamp to the db with their info. There is also a "check-out" button that currently does nothing. It's supposed to work so that, once the person fills the form and submits, it'll will either do one of these things: Find the previous check in entry based on the ID and Area entered and update the check out from NULL to timestamp. If the person forgot to previously check in, then it will create a new record with just the check out timestamp and the ID/Area. I thought that trying to find the user by matching both ID AND Area would be better since the same person can check in/out of different areas several times a day so matching only by ID could generate the problem of the program updating the wrong field at one point. models.py class WorkArea(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class StationNumber(models.Model): work_area = models.ForeignKey(WorkArea, on_delete=models.CASCADE) name = models.CharField(max_length=50) def __str__(self): return self.name class EmployeeWorkAreaLog(TimeStampedModel, SoftDeleteModel, models.Model): employee_number = models.IntegerField(max_length=50, help_text="Employee #", blank=False) work_area = models.ForeignKey(WorkArea, on_delete=models.SET_NULL, null=True, blank=False, … -
Using the command " django-admin startproject ", doesn't create anything
I am new to Django, command line and Stackoverflow. I installed python and django. On running the following commands, nothing happens. As per some tutorials, I should get a folder made inside the Django_Practice folder. When I re-run the same command, it says, the folder already exists. I am on Windows 10, version 1903. C:\Users\Arjit Raj>python Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 19:29:22) [MSC v.1916 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> ^Z C:\Users\Arjit Raj>python -m django --version 2.2.6 C:\Users\Arjit Raj>cd desktop C:\Users\Arjit Raj\Desktop>cd Django_Practice C:\Users\Arjit Raj\Desktop\Django_Practice>django-admin startproject djangotrial C:\Users\Arjit Raj\Desktop\Django_Practice>dir Volume in drive C is Windows Volume Serial Number is E21B-45DC Directory of C:\Users\Arjit Raj\Desktop\Django_Practice 18-Oct-19 07:06 PM <DIR> . 18-Oct-19 07:06 PM <DIR> .. 0 File(s) 0 bytes 2 Dir(s) 32,418,140,160 bytes free C:\Users\Arjit Raj\Desktop\Django_Practice>django-admin startproject djangotrial CommandError: 'C:\Users\Arjit Raj\Desktop\Django_Practice\djangotrial' already exists C:\Users\Arjit Raj\Desktop\Django_Practice> -
d3.js pan zoom issue
I am working on a django project in which I use intensively d3.js. I have a javascript function that works well: function three_lines_pan_zoom_chart(id, data, options) { var plotChart = d3.select(id).classed('chart', true).append('svg') .attr('width', options.w + options.margin.left + options.margin.right) .attr('height', options.h + options.margin.top + options.margin.bottom) .append('g') .attr('transform', 'translate(' + options.margin.left + ',' + options.margin.top + ')'); var plotArea = plotChart.append('g') .attr('clip-path', 'url(#plot_Area_Clip)'); plotArea.append('clipPath') .attr('id', 'plot_Area_Clip') .append('rect') .attr({ width: options.w, height: options.h }); var navChart = d3.select(id).classed('complex_chart', true).append('svg') .classed('navigator', true) .attr('width', options.nav_w + options.margin.left + options.margin.right) .attr('height', options.nav_h + options.margin.top + options.margin.bottom) .append('g') .attr('transform', 'translate(' + options.margin.left + ',' + options.margin.top + ')'); var minN = d3.min(data, function (d) { return d.date; }).getTime(), maxN = d3.max(data, function (d) { return d.date; }).getTime(); var minDate = new Date(minN - 8.64e7), maxDate = new Date(maxN + 8.64e7); var yMin = d3.min(data, function (d) { return Math.min(d.value, d.valueBchk, d.valueIdx); }), yMax = d3.max(data, function (d) { return Math.max(d.value, d.valueBchk, d.valueIdx); }); var xScale = d3.time.scale() .domain([minDate, maxDate]) .range([0, options.w]), yScale = d3.scale.linear() .domain([yMin, yMax]).nice() .range([options.h, 0]); var navXScale = d3.time.scale() .domain([minDate, maxDate]) .range([0, options.nav_w]), navYScale = d3.scale.linear() .domain([yMin, yMax]) .range([options.nav_h, 0]); var xAxis = d3.svg.axis() .scale(xScale) .orient("bottom") .ticks(5); var yAxis = d3.svg.axis() .scale(yScale) .orient("left"); plotChart.append('g') .attr('class', … -
How to get the IP address of a client using aiohttp
I am currently working on a django project where I use aiohttp to communicate between the backend and frontend. I wanted to get the IP address of a client when a request is made from the frontend. Looked in different docs but none seems to point to exactly how to get the IP address using aiohttp. Someone Help! from aiohttp import web async def handler(request): ws = web.WebSocketResponse() await ws.prepare(request) try: async for msg in ws: # handle incoming messages # use ws.send_str() to send data back ... finally: task.cancel() -
Display previously uploaded files or images
I have two data tables and am using Django at the back end and Vuejs at the front end. (1) Products, stores the product details and a single image. (2) Products_Images, stores the multiple images with relation to the product. The below code is called from < Product List > when Editing the product details including adding images or removing images. My problem is that in Edit mode I need the previously selected displayed instead of ( No Files Chosen ) <!-- Edit a Product (Start) --> <template id="product-edit"> <div> <h2>Product (Edit)</h2> <form method="post" enctype="multipart/form-data" ref="itemMaster"> <!-- Display Product Name --> <div class="form-group"> <input class="form-control" id="edit-name" v-model="product.itemfullhd" required/> </div> <!-- Upload Single Image --> <div class="form-group"> <!-- ### MY PROBLEM HERE ### --> <label for="edit-imagemain">Main Image </label> <input type="file" id="edit-imagemain" v-model="product.Image_file" @change="onFileChanged" required/> <img class="cart-thumbnail" v-bind:src="'/media/' + product.image_file" alt="image"/> </div> <!-- Upload Multiple Images --> <div class="form-group"> <!-- ### MY PROBLEM ALSO HERE ### --> <label for="files">Xtra Images</label> <input type="file" id="files" ref="files" multiple v-on:change="handleFilesUpload()"/> <div> <!-- Display the Multiple Images --> <table class="table table-striped "> <thead> <tr> <th>Xtra Image File/s</th> <th>Image</th> <th>Delete</th> </tr> </thead> <tbody> <tr v-for="imagerec in products_images" and v-if="( imagerec.itemfullhd == product.itemfullhd )" style="clear: both;"> <td>/media/{{imagerec.images_multiple}}</td> <td> <img … -
django heroku in deploy debug mode
STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'staticproject') ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(STATIC_ROOT, 'media') server 500 Error when i add to setting.py django_heroku.settings(locals()) urlr.py urlpatterns = [ url(r'^media/(?P.)$', serve,{'document_root': settings.MEDIA_ROOT}), url(r'^static/(?P.)$', serve,{'document_root': settings.STATIC_ROOT}), path('admin/', admin.site.urls), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
changing javascript function name or ID of element in HTML template makes it stop working
I am developing an app in Django. I have this weird issue. on my template I have: <div class="form-group"> <input name="Data_inserimento_entry" type="date" class="form-control" id="date_to_turn_into_toda" > </div> <script type="text/javascript" src={% static "js/get_today_date.js" %}></script> <script> get_today_date(date_to_turn_into_toda) </script> on the js file get_today_date.js stored at static > js > get_today_date.js I have function get_today_date(id_data) { var now = new Date(); var day = ("0" + now.getDate()).slice(-2); var month = ("0" + (now.getMonth() + 1)).slice(-2); var today = now.getFullYear()+"-"+(month)+"-"+(day); document.getElementById(id_data).value = today; } when I load the template, in the input slot, today's date appears. I am glad of that. But if I change the id , like this: <div class="form-group"> <input name="Data_inserimento_entry" type="date" class="form-control" id="date_to_turn_into_today" > </div> <script type="text/javascript" src={% static "js/get_today_date.js" %}></script> <script> get_today_date(date_to_turn_into_today) </script> It does not work anymore. Why? And even if I change the function name in both scripts, like: <script type="text/javascript" src={% static "js/get_today_date.js" %}></script> <script> get_today_date_ID(date_to_turn_into_today) </script> and function get_today_date_ID(id_data) { var now = new Date(); var day = ("0" + now.getDate()).slice(-2); var month = ("0" + (now.getMonth() + 1)).slice(-2); var today = now.getFullYear()+"-"+(month)+"-"+(day); document.getElementById(id_data).value = today; } It does not work anymore. Why? Is the syntax to call javascript correct? Am I forgetting to change the … -
Convert Raw SQL to Django ORM code , possibility
Is it possible to perform something like this with only Django ORM? with connection.cursor() as cursor: cursor.execute( """SELECT word FROM ts_stat( 'SELECT to_tsvector(''simple'', description) FROM api_product');""", #[source, ] ) words_in_product_model = frozenset( more_itertools.one(word) for word in cursor.fetchall() db-Postgres 11 Thanks -
How to retrieve metrics such as CPU loading, database connections, memory with django-prometheus
Is it possible to retrieve CPU info, total database connections and memory info with django-prometheus? After installing django-prometheus to my Django project prometheus/metrics I cannot understand is there any metrics to achieve my goals. Or it there another ways to do it? -
How to integrate mockaroo with django
I would like to integrate django with mockaroo since mockaroo provides rest api to download data ,I would like to use it with django project. Any help would be appreciated -
POST method not allowed in custom viewsets
if I am going to add products to cart I get error. POST method not allowed views.py class CartViewSet(viewsets.ModelViewSet): queryset = Cart.objects.all() serializer_class = CartSerializer @action(methods=['post', 'put'], detail=False) def add_to_cart(self, request, pk=None): cart = self.get_object() try: cart.user = self.request.user product = Product.objects.get(pk=request.data['product']) quantity = int(request.data['quantity']) except Exception as e: print(e) return Response({'status': 'fail'}) if product.inventory <= 0 or product.inventory - quantity < 0: print('There is no inventory in store') return Response({'status': 'fail'}) existing_cart_item = CartItem.objects.filter(cart=cart, product=product).first() if existing_cart_item: existing_cart_item.quantity += quantity existing_cart_item.save() else: new_cart_item = CartItem(cart=cart, product=product, quantity=quantity) new_cart_item.save() serializer = CartSerializer(cart) return Response(serializer.data, status=status.HTTP_201_CREATED) It works when i give the url like that carts/1/add_to_cart here I am giving my cart id but in my case it is wrong because when user is created cart is also created that's why user and cart ids are same. I do not nedd to give cart id in the url because I am putting token in Authorization section in Postman, from that it should detect which user is sending post request. It is shown above that I added cart.user=self.request.user with it still it is not working. How can I solve this issue? Any help would be appreciated) -
Django - force user password reset/expiration
I'm stuck at this issue now for a good few hours. I've implemented all the standard password change, reset, etc functionalities which are built in with django.contrib.auth.forms. The task I want to accomplish is to force users to regularly change their passwords. Which leads to the following issues: If I redirect them to the reset workflow it will change the password and I have not found a way to update my password_changed timestamp in my custom user model since the functionality is built into django. I could redirect them to the password change view (which also uses a builtin form), unfortunately if the user is not logged in (which would be counter productive in this case) the user attribute in the request is "None" Maybe I'm thinking too complicated, can someone give me a hint whats the easiest way to implement this?? -
django get data from api with ajax
I was trying to get some information from API using ajax. I was able to post data but I was unable to get all the data from the server. I am new in the Django environment, though i have tried some references. I was wanted to get the data from the server using the API that I provide and show those data by using ajax get call. References that I have followed: 1.Django Ajax Jquery Call 2.https://simpleisbetterthancomplex.com/tutorial/2016/11/15/how-to-implement-a-crud-using-ajax-and-json.html 3.https://www.sourcecodester.com/tutorials/python/11762/python-django-simple-crud-ajax.html My code for get call: $.ajax({ type: "GET", url: "/save_composition", dataType: "json", success: function(data) { alert(data) }, error: function(xhr, textStatus) { alert("error.."); }}); Url section : path('restore_composition/', views.restore_composition, name='restore_composition') Views.py: def restore_composition(request): data = SaveComposition.objects.all() return render(request, 'index.html', context={'data': data}) -
Meaning of some errors while hosting django application on Cloud Foundry
While trying to host my Django application on Cloud foundry using Gunicorn, my application will be hosted correctly on the URL, but when I see the logs by doing cf logs --recent I see some errors: 2019-10-18T17:06:36.85+0530 [APP/PROC/WEB/0] ERR [2019-10-18 11:36:36 +0000] [9] [INFO] Starting gunicorn 19.9.0 2019-10-18T17:06:36.86+0530 [APP/PROC/WEB/0] ERR [2019-10-18 11:36:36 +0000] [9] [INFO] Listening at: http://0.0.0.0:8080 (9) 2019-10-18T17:06:36.86+0530 [APP/PROC/WEB/0] ERR [2019-10-18 11:36:36 +0000] [9] [INFO] Using worker: sync 2019-10-18T17:06:36.86+0530 [APP/PROC/WEB/0] ERR [2019-10-18 11:36:36 +0000] [68] [INFO] Booting worker with pid: 68 I want to know what are these errors. And, after these errors also the application is hosted and is up. -
How to implement protected file download with requests and authentication in django
I have a django app where I can upload files. I show my files in an API. Like so: class FileCollection(models.Model): name = models.CharField(max_length=120, null=True, blank=True) store_file = models.FileField(upload_to=upload_file, null=True, blank=True) creation_date = models.DateTimeField(null=True, blank=True) class FileDownloadAPIListView(ListAPIView): """Lists all files. """ queryset = FileCollection.objects.all() serializer_class = FileCollectionSerializer Later I will implement different queries to get specific files. I'd like to download these files from a script using python without the need to open up a browser or anything like that. I want to make an authenticated API call with requests that gets my file and then saves it to the local computer. The problem is that my files need to be private and only authenticated users should be able to download it. For my other APIs I am using JWT token authentication. My question now is: How do I implement this? Do I a) Save my files in S3 and make an API call to that URL somehow authenticating me with my AWS credentials? b) Save my files somewhere in my PostgrSQL database and get everything from there with an authenticated API call using JWT. c) third option I didn't consider Also if I use a, b or c how … -
"ModuleNotFoundError: No module named 'django'" when trying to deploy Django server on Azure
After I tried to deploy my Django website on Azure, I got an error saying: ModuleNotFoundError: No module named 'django' I added a requirements.txt in the root directory of my Django project, am I missing anything else? I've tried to install Django from Kudu BASH but it gets stuck on "Cleaning Up". Here is the full error: https://pastebin.com/z5xxqM08 I built the site using Django-2.2 and Python 3.6.8. -
What are the skills and steps required to do an interactive info chart like this?
As a beginner in python and with an interest in data visualisation, I am intrigued by this https://opportunityatlas.org It inspires me to use it as a guide to break down what to learn and skills to acquire to learn to do something similar. I wonder is the map done using matplotlib? or is it HTML/CSS? Is it Django or Flask for the interactive web interface? My knowledge at the moment is too limited to know what's out there or any terms to search on. If anyone knows what are the steps and skills to acquire for developing an application like this, can you share a general guideline? Or is there any tutorial out there? Thanks. -
How to set on_delete=models.CASCADE default in python 3?
Currently I am working to convert my python2 Django web-project into python 3. My project contains lots of models.py files so I have to add manually on_delete=models.CASCADE in all files where I have set default it in python 2. Now there are around more than 2000 instances where I need to do same practice. Is there are any hacks or possible solution available so that I can set on_delete=models.CASCADE in my all models instantly. -
Debugging Javascript in a Python Django project
I have a Python/Django project and am currently trying to find a way to debug the Javascript components on the site using VSCode. I've done some research and the only method I can find is to use the paid version of PyCharm. Does anybody know how to configure VSCode to do this? -
alternative to wkhtmltopdf to render pdf with javascript charts and bootstrap classes
I have a web application and I use the tool wkhtmltopdf to perform pdf exports. I am using wkhtmltopdf version 0.12.4 with unpatched QT (minimal version). I want to add a footer to the pdf pages and I saw that the wkhtmltopdf version with patched QT support this operation with the flag --footer-html. Unfortunately I noticed that the css and js engine under this version create some problem in rendering my html pages: First of all there are problem with the grid system in Bootstrap v > 4.1 Then also the javascript chart in my page are no more rendered in the pdf with this version of wkhtmltopdf So, is there an alternative to wkhtmltopdf that allow me to export to pdf my web pages ? My project is written in django / javascript so I would prefer a python of javascript tool. I also tried pdfkit but I discart it because I saw it is based on wkhtmltopdf , and django-weasyprint but I discarted because it does not support javascript (so my charts are not rendered). Finally the tool should allow me to connect to the web page passing cookies or similar, because login is required to access the … -
How to integrate SaaS result which needs to create multiple URLs at the website end?
Assume there is a SaaS product where user can create multiple pages and content at the dashboard. Now we wish to make a plugin system where we can let the website owner just plug it and display all the content. Now we are facing problem where we don't have an effective way to automatically create the different URL as required by the backend content. What is the best way to do it? Is there any workable example of this? -
Django: int() argument must be a string, a bytes-like object or a number, not 'Post'
I am getting this error for a long time and I tried to solve with some forums but I don't find the gap. Here is my Models.py: class Post(models.Model): def show_article(request, id_post): article= Post.objects.get(id=id_post) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): nick = form.cleaned_data['nick'] message= form.cleaned_data['message'] email = form.cleaned_data['email'] rating = form.cleaned_data['rating'] to = article #comentario = Comment(nick=nick, email=email, message=message, rating=rating, to=to) comentario = Comment() comentario.nick=nick comentario.email=email comentario.message=message comentario.rating=rating comentario.to_id=to comentario.save() send_mail( "Thanks for your comment %s" % nick, "Here is a copy of your message: \n %s" % message, 'noreply.ibai@gmail.com', [email], fail_silently=False) return redirect('/news/%i' %id_post) else: form = CommentForm() context = {'articulo': article, 'form':form} return render(request, "cnn/articulo.html", context) And: class Comment(models.Model): nick= forms.CharField(max_length=10) email= forms.EmailField(max_length=30) message= forms.CharField(max_length=600) rating= forms.ChoiceField(choices=LIKE_CHOICES) to_id= models.ForeignKey(Post, on_delete=models.CASCADE) class CommentForm(forms.Form): nick= forms.CharField(max_length=10) email= forms.EmailField(max_length=30) message= forms.CharField(max_length=600) rating= forms.ChoiceField(choices=LIKE_CHOICES) The problem came when I do 'migrate', because with de makemigrations the error dont occured. This is the log from console: (env2) C:\Users\ibaig_vi6j6bo\AppData\Local\Programs\Python\Python37-32\.projects\pruebasDjango>python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, polls, sessions Running migrations: Applying polls.0013_comment_to...Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\ibaig_vi6j6bo\AppData\Local\Programs\Python\Python37-32\.virtualenvs\env2\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() …