Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How does two client javascript files interact with each other, when the server is running seperately?
I have created a django application. There are two different html pages, which run different scripts in each other. I want to share data between the two script files, so while I update the variables in one script, I can send the updated data to the other script file, and make the corresponding changes to the variable present in the other script file. As I researched, one way I found to do that is to use websockets, where a regular connection is built with the django server and the client. But, it is limited to single client. So, through websockets, I can not share data between two different client pages. What other methods, can I use to share data between the two script files in the client? -
jinja is not wroking properly in django
In django created template directory, with three html files. index.html {% extends "web/header.html" %} {% block content %} { % include 'web/includenippet.html' %} <p> hello this is my page.</p> {% endblock %} header.html <h2>hey iam there in header of login page</h2> {% block content %} {% endblock %} <h2>hey iam there in footer of login page</h2> incl.html {% block content %} <p>iam in include file</p> {% endblock %} expected output is hey iam there in header of login page iam in include file hello this is my page. hey iam there in footer of login page But the actual output is hey iam there in header of login page { % include 'web/includenippet.html' %} hello this is my page. hey iam there in footer of login page I added jinja2 and django-jinja in django project using setting->project_interpreter -
Python 2 timezone.utc in Django project
What is the alternative for python 2 : user_last_seen = datetime.now(timezone.utc) Thank you -
Stuck on Django project tutorial I'm doing on Udemy - OperationalError at /admin/jobs/job/add/ no such table: main.auth_user__old
I am doing a Django tutorial I bought off Udemy. It's titled "Django 2.2 & Python | The Ultimate Web Development Bootcamp", in case some of you know this tutorial by instructor Nick (something, forgot last name). I'm using Django 2.0.2, exactly what was asked in the tutorial. SQLite3 database version 3.27.2, using up-to-date version of Spyder with Anaconda prompt, I'm on Windows 10 Pro, latest versions of "virtualenv" and "pip" as well. So on the tutorial, I had to sign into the admin page and create an app called "jobs", with a jobs.models.py class called "Job". It adds this to the admin UI and then click on it and add (using "+" icon at top right) a "Job", which is adding an ImageField and a CharField that gets added. I get an error on the django admin page when I click "Save". The name of my project is "portfolio-project", sub-folders include "portfolio","blog", and "jobs". I went back and re-did all the steps up to that point in the tutorial, and did it "to the letter". I've researched many questions for that error and can't find anything that works. I tried makemigrations, then migrate. It's possible it's a bug with … -
python logging: also show few lines of code above and below at that location
I am working on a django project. I have the following logging config in settings.py file LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(levelname)s %(funcName)s() %(pathname)s[:%(lineno)s] %(name)s \n%(message)s' } }, 'handlers': { 'console': { 'level': 'DEBUG', 'formatter': 'verbose', 'class': 'logging.StreamHandler', }, 'loggers': { 'custom_string': { 'level': 'DEBUG' if DEBUG else 'INFO', 'handlers': ['console'] } } } We can see that verbose shows the '%(levelname)s %(funcName)s() %(pathname)s[:%(lineno)s] %(name)s \n%(message)s. It shows the filename, line number and function. I have to open that file and see that line number to get have a look at the code around the logger. Now suppose i have the following code in views.py from django.http import HttpResponse import logging logger_custom_string = logging.getLogger("custom_string") def test_log(request): from django import db user_set = User.objects.all() logger_custom_string("*********testing logging*********") for user in user_set: pass html = "<html><body>testing</body></html>" return HttpResponse(html) The logging will show in the console: DEBUG test_log() ./django_log_project/views.py[:13] custom_string *********testing logging********* What i want to see is DEBUG test_log() ./django_log_project/views.py[:13] custom_string Code: 11 from django import db 12 user_set = User.objects.all() 13 logger_custom_string("*********testing logging*********") 14 for user in user_set: 15 pass output: *********testing logging********* This will show me the code line +2/3 and -2/3 lines from … -
Auto increment of number input in Django Formset
I am using django formset for adding multiple periodic inputs of price range WarehousePriceSpacetSet = formset_factory(WarehouseSpacePricePerdayForm, extra=1) this is my formset. I need to append from input data with respect previous to data. Here is the example Here the first row saving the prices of 1 to 10 So next Period from field should auto fill 11 I have tried with Jquery by appending value when to field change function. for(i=0;i<=pallet_num;i++){ $(".pallet_to").change(function() { $("#id_palletss-"+i+"-period_from_pallet").val($(this).val()); // $(".pallet_to").closest(".pallet_from").val($(this).val()); }); } But the change function working only for first periods row. Because others are adding dynamically by clicking "Add more" in form-set. Please help me to find a solution. Thanks in advance -
Python/MySQL: Escaping strings used as parameters in raw database queries
I am using a connection/cursor to migrate data from an old database/schema into a new one built with Django models. I encounter a problem with names that have an apostrophe to simplify business = "Tom's Diner" cursor.execute("select * from businesses where name = '" + business + "'") This would obviously fail as I'm forcing a single quote which causes an SQL syntax problem. It would work if I did this: business = "Tom''s Diner" But as this is an automated process that deals with migrating millions of rows. I am looking for a way to escape my string before applying it to the direct MySQL query. My question: is that something I have to do manually, or is there some function in Django/Python that escapes strings, and may handle cases I haven't even thought of yet, like double quotes in the string, etc. -
Is there a Django Live Simulator? (like simulator for Xcode - Swift)
Is there a live simulator editor for Django where you can watch live front end editions just like in Xcode's simulator or Android Studio? -
How to assign a logged in user automatically to a post?
I have created a model to post an ad. Since the CreateApiView is protected so that only logged in user can create or post ad, but if the logged in user posts an ad how to automatically take the logged user name or assign that user to his ad? This is what I have tried in my viewsets def perform_create(self, serializer): return serializer.save(owner=self.request.user) this is my models.py user = models.ForeignKey(User, on_delete = models.CASCADE) title = models.CharField(("Title"), max_length=50) category = models.IntegerField(("Choose Category"), choices=CATEGORY_CHOICES) Short_discription = models.CharField(("Short Discription"), max_length=200) this is my serializers.py class KhashiSerializer(serializers.ModelSerializer): class Meta: model = Add fields = '__all__' read_only_fields = ['user'] this is my viewset class KhashiCreateApiView(generics.CreateAPIView): queryset = Add.objects.all() serializer_class = KhashiSerializer def perform_create(self, serializer): serializer.save(user=self.request.user) Is there any way to assign user to the post so that if POST reqest in Postman without user provided will automatically assign logged in user or user with Token that is provided in Authorization header?? -
Mapping list of keys to delete the keys from a dictonary
How can I shorten del request.session['love'] del request.session['good'] del request.session['paid'] del request.session['need'] Can this be using a list that includes the keys. Can map/lambda function used here? If yes, How? Don't mark negative. New to Python -
How to merge 2 models with similar fields using django?
I want to merge 2 different models with different but overlapping fields. First, I'm trying to merge the model A into model B, keeping all the fields from model A. Second, I also want to add additional fields into model B. To do so, I tried to create arrays for both models; array A from model A and array B from model B. Then I want to compare the positions of the former model fields between both arrays. I also tried: def merge(self): old = DetailItem.objects.all() for item in old: and i don't know how to iterate over the model fields and compare for identity. So that I have a model that contains the data from the old model and some new fields. Here is my code for the two models: class DetailItem(Base): title = models.CharField(max_length=500) description = models.CharField(max_length=20000) link = models.URLField() cpvcode = models.ManyToManyField('CPVCode',related_name='cpv') postalcode = models.ForeignKey('PostalCode',on_delete=models.SET_NULL,null=True,blank=True,related_name='postal') def __str__(self): return self.title class CrawlItem(Base): guid = models.CharField( primary_key=True, max_length=500) title = models.CharField(max_length=500) link = models.URLField() description = models.CharField(max_length=2000) pubdate = models.DateTimeField() detail = models.ForeignKey('DetailItem',on_delete=models.SET_NULL,null=True,blank=True,related_name='crawldetail') def __str__(self): return str(self.title) This is what I want to get: class CrawlItem(Base): guid = ... title = ... link = ... cpvcodes = ... postalcode … -
Using cursor data directly without iteratingin for loop
I have a query, when I am using find() in my django framework it is returning a cursor "" when I am iterating this cursor in for loop which is returning the list of data. My problem is data which I am fetching in for loop has too much data which is affecting performace of function. So I donot want to iterate it and want to use it directly So is there any way I can call without iterating in for loop. I checked stackoverflow mask_descriptor_result = db.collection.find(query) fetch data without iterating through for loop -
Creating unique model for each business
Guys i am new in django this is my first project i am creating accounting app. I need this .For example if some one create busines it must have new budget expense date fields. class Business(models.Model): busines = models.CharField(max_len=60) class Add(models.Model): budget = models.IntegerField(blank=True, null=True) expense = models.IntegerField(default=0) date = models.DateField() -
Django: group items by foreign key
I have comment and post models as below class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) parent = models.ForeignKey('self', unique=False, blank=True, null=True, on_delete=models.CASCADE) class Post(models.Model): title = models.CharField(max_length=120, null=False, blank=False) I use this raw sql query to get all the comments which has post_id 11 and group the results. all_comments = Comment.objects.raw('SELECT * FROM comments_comment where post_id=11 order by coalesce(parent_id, id), (case when parent_id is null then 1 else 2 end ), created_at') This query works perfectly okay for me. However, I would like to do the query in Django way instead of using raw query. What would be the Django equivalent of this? -
Group by query in Django
I am still in the same problem. I hope you cooperate in the solution. I want to get the result of this query in Django. SELECT city_name, MAX(total_places) total_places FROM(SELECT city city_name, COUNT(city) total_places FROM Places GROUP BY 1) t1 GROUP BY 1; -
How to make multiple string queries on DJANGO 2.2
I want to make a query to search my table peoples on field name all rows that contains some word in a snames var: snames='john bush george robert' I do it on SQL with bellow code: SELECT * FROM names.peoples WHERE name LIKE'%john%bush%george%robert%'; snames='john bush george robert' p = peoples.objects.all().filter(name__icontains=snames) Is it possible in a single query? -
C# vs Django: Which one for Information System that will replace current Excel based records?
I've been thinking about developing a system that would replace the current Excel-based records we've got in our office: It's got a lot of data entry and reports based on the saved data. Being Excel-based, both data entry and reports generation are not standardized. I've made some macro enabled workbooks that automate some of these, but it's not complete and isn't really something I could easily share to the rest of the office. Backing it all up is a huge challenge, and having the same (relevant) updated/live data accessible by multiple people is currently impossible. I need help deciding between C# and Django(RF) with the following considerations: I haven't coded for a long time, unless the VBA used for the Excel macros count. I have no real experience with either C# or Django, but C# looks a lot more familiar to me. I think developing the GUI would be easier with C#, but deploying (and hopefully maintaining) could be easier with a web based DRF approach. This project being a voluntary (not yet even asked for) one, I'd prefer keeping the code to myself, instead of having it easily accessible by other people in the organization. I guess you could … -
How to pass dictionary value as path to image in django?
I am a beginner in django and currently struggling to pass dict value as path to image. I have dictionary in following format:- { 'features': [ { 'icon': 1, 'heading': 'Lorem Ipsum', 'description': 'Neque porro quisquam est qui ipsum quia dolor sit amet, adipiscing velit quia dolor sit amet, adipisci velit' }, { 'icon': 2, 'heading': 'Lorem Ipsum', 'description': 'Neque porro quisquam est qui ipsum quia dolor sit amet, adipiscing velit quia dolor sit amet, adipisci velit' } ] } Inside template, I am accessing images in following way:- {% for feature in content.features %} <div class="col-lg-4 col-md-6 col-sm-12 mx-auto my-1 mt-5 text-center d-flex flex-column align-items-center"> <div class="h-40 w-100 d-flex"> <img class="img-fluid mx-auto" src="{% static "base/images/{{feature.icon}}" %}" alt="{{ feature.heading }}" width="100" height="100"> </div> <div class="h-60 w-100 d-flex flex-column"> <h4 class="feature-caption">{{ feature.heading }}</h4> <p class="feature-description p-2 pt-3 pb-3">{{ feature.description }}</p> </div> </div> {% endfor %} However, the images are not loading. Can someone suggest how to solve this? -
Django: Adding M2M Relationships in post_save signal
I'm trying to process an uploaded archive after it's been saved. Within the archive are photos that get saved as separate entities and are then associated with the archive upload / gallery, but I can't figure out how to properly commit the photos and create the m2m references needed during the post_save signal. Photo(models.Models): image = models.ImageField() MediaGallery(models.Model): archive = models.FileField() photos = models.ManyToManyField(Photo) post_process(self): # Pseudo Code for image in self.archive: photo = Photo(image = image) photo.save() # This line has no affect because the photo hasn't been committed yet self.photos.add(photo) @receiver(post_save, sender=MediaGallery) def gallery_post_save(sender, instance, **kwargs): instance.post_process() End result is the photos are uploaded and saved, but no relationsip is created between the MediaGallery and the individual Photos -
How to construct a condition to choose appropriate function in template
I have two apps and want them to run one function in view.py and render in template. The only difference is that each app uses different models. For example, my first app uses function called like_post_fin: post = get_object_or_404(Post_Fin, id=request.POST.get('id')) and my second app uses function called like_post: post = get_object_or_404(Post, id=request.POST.get('id')) other part of code is same for each function. In my first app template I will use to call function: <form action="{% url 'like_post_fin' %}" method="post"> In my second app template I will use: <form action="{% url 'like_post' %}" method="post"> other part of html code is same for both template. When I run codes separately everything works perfect. But I want to have just one function and template for both apps which should use condition in view function or template. I tried to use condition in app's template by using following code {% if title == 'my app title' %} <form action="{% url 'like_post_fin' %}" method="post"> {% else %} <form action="{% url 'like_post' %}" method="post"> {% endif %} But it did not work. Template titles are given using following code: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['title'] = 'my app title' In my base html {% if title … -
Save results of a Django Form in a list to use it in future for the next form. [Answers from one form servers as input for next]
I am working on a project that requires to take input from user using form but the results are not supposed to be saved inside the DB. I am using a Form to show Display multiple choices to users using a list and users have to select from them but rather than saving them inside the DB, I want these to be saved in a list (or Dict ) and use them for the next step of processing. Here is my Form class DemoForm(forms.Form): input_list = ['a', 'b', 'c', 'd', 'e'] # example list that I show to users answers = forms.MultipleChoiceField( choices=[(c, c) for c in input_list], widget=forms.CheckboxSelectMultiple ) To process the form, this is the demo view.... def show_result(request): if request.method == 'POST': form = DemoForm(request.POST) if form.is_valid(): future_list = form.cleaned_data['answers'] # I want this list to be available for the next form as the Input_list2 for DemoForm2 else: form = DemoForm() return render(request, 'paid_for.html', {'form': form}) How can this be achieved? -
login to Django with URL?
Is it possible to login to Django by passing the username/password in the URL? I am using https to communicate to my server and I need a remote machine to access some raw text via a django view. So I am hoping I can just make a user for this remote machine, and login via the url. Or is there a better way of automatically logging in? Most of the other posts I have read talk about using the DjangoREST framework, and using a API token to get the data via JSON, but this would mean I need to store all the text on the database and create new models etc etc. I would rather just serve this text with a regular django view and HTML template. -
Getting the ID of the Max record in an aggregate
Take these models: class Rocket(Model): ... class Flight(Model): rocket = ForeignKey(Rocket) start_time = DateTimeField(...) If I want to get start times of the latest flight for every rocket, that is simple: >>> Flight.objects.values('rocket').annotate(max_start_time=Max('start_time')) <QuerySet [ {'rocket': 3, 'max_start_time': datetime.datetime(2019, 6, 13, 6, 58, 46, 299013, tzinfo=<UTC>)}, {'rocket': 4, 'max_start_time': datetime.datetime(2019, 6, 13, 6, 59, 12, 759964, tzinfo=<UTC>)}, ...]> But what if instead of max_start_time I wanted to select IDs of those same Flights? In other words, I want to get the ID of the latest Flight for every rocket. -
Is it possible to access the module or view class from inside a request
I have a Django project with a context processor to have the same object on every page. It is working so far. # /core/context_processor.py # (is correctly linked in settings.py) def default(request): context = {'email': Email()} return context Now i want to implement a "TAG" constant in every Django module. I want to have it accessible in every view context without passing it from every View class It should be similar to accessing the "{{request.path}}" inside the template but explicite. # /home/views.py TAG = "TagOfHome" class HomeView(TemplateView): template_name = 'home/list.html' # /addresses/views.py TAG = "TagOfAddresses" class AddressView(TemplateView): template_name = 'address/list.html' Now i want to access the TAG constant from the inside of every Template. If it is a view of the addresses module it should be "TagOfAddresses", at home views it should be "TagOfHome" etc. How can i achieve this? Can i access the TAG somehow from within the context processor (request)? -
How overwrite Django Admin readonly FileFields HREF url
I have a Django project in production on Apache and I've made a model with file that is uploaded to custom path. Now I need to change it's representation in Django admin details. My Filefield in admin is readonly and I want that it only shows a correct link to open the file in a new tab. The problem is that I have alias in Apache and the current link showed in the admin is for example: /var/www/html/moeaforhdl/moeaforhdlweb/uploads/uploaded_c_files/194/extracted_dfg.json but when I click to open the file it try to open this URL: http://201.174.122.25/moeaforhdlweb/uploads/var/www/html/moeaforhdl/moeaforhdlweb/uploads/uploaded_c_files/194/extracted_dfg.json when the correct URL to open the file is: http://201.174.122.25/moeaforhdlweb/uploads/uploaded_c_files/194/extracted_dfg.json I need to remove part when user click on the link in admin forms and details: /var/www/html/moeaforhdl/moeaforhdlweb/uploads How can I overwrite this URL in admin panel, por example in admin.py? Thank you so much.