Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
How to connect to the Django database via a widget encoded in pure Javascript?
I'm creating an external widget to an existing application that is coded in Django/Angular. The widget that i'm coding is in HTML, CSS and pure Javascript. There is a REST Django API. I want to retrieve the data via a fetch. const url = 'http://localhost:8000/api/services'; const csrftoken = getCookie('csrftoken'); const headers = new Headers(); headers.append('X-CSRFToken', csrftoken); const myInit = { method: 'GET', headers: headers, mode:'no-cors', cache: 'default', credentials: 'include' }; fetch(url, myInit) .then(res => { res.json(); }) .then(data => { console.log(JSON.stringify(data)); }); function getCookie(name) { var value = "; " + document.cookie; var parts = value.split("; " + name + "="); if (parts.length == 2) return parts.pop().split(";").shift(); } My problem: I can't connect to the API, I get a 403 error. I tried to recover the data via Insomnia but it's the same thing, error 403 I also tested in the terminal via http but still the same thing. http http://localhost:8000/api/services/ 'Authorization: Token MyToken' HTTP/1.1 403 Forbidden Content-Length: 22 Content-Type: text/html Vary: Origin, Cookie X-Frame-Options: SAMEORIGIN <h1>403 Forbidden</h1> -
Rendering HTML to PDF with images included Django
I have a django app where users would print some pages which include images as a part of Data processing. I tried jsPDF but it didn't render my images and I ended up with just text $(document).ready(function() { $("#pdfDownloader").click(function() { var doc = new jsPDF('p', 'pt', 'a4', true); doc.fromHTML($('#renderMe').get(0), 15, 15, { 'width': 500 }, function (dispose) { doc.save('thisMotion.pdf'); }); }); }) This was my code and it didn't render the images so do I need to change anything? is using a Django view would solve this and is there any alternatives to xhtml2pdf as with this I need to include my CSS in the HTML file ? -
Catching some values in django signals
I'm using django signals to catching some values. My example: @receiver(post_save, sender=Profile) def my_example(sender, instance, created, **kwargs): if created: user_id = instance.user.id level = instance.is_admin company = instance.company I need to catch user_id, level and company. But only user_id contains value. company value is always None and level is always False. This is my basic model for profile: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) is_supervisor = models.BooleanField("Supervisor", default=False) is_admin = models.BooleanField("Admin", default=False) company = models.ForeignKey( "core.company", related_name="users", on_delete=models.CASCADE, blank=True, null=True, ) def __str__(self): """Unicode representation of MyUser.""" return self.user @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() -
Incorrect password can access database in django
I create posgresql db user named 'user'. Password: django1234. And I type the database info in settings.py. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'test', 'USER': 'user', 'PASSWORD': '1q2w3e', 'HOST': 'localhost', 'PORT': '5432', } } The password does not match definitely. However, it can access the 'test DB' when I run the server, which means, I guess, that anyone can access my DB. What is the problem? Thank you in advance. -
NameError: name 'api' is not defined for Django Rest Framework
I am trying to learn the Django Rest Framework. I create a project called djangorest. Then I created an app called api In djangorest/urls.py I have: from django.contrib import admin from django.urls import path, include from django.conf.urls import url urlpatterns = [ path('admin/', admin.site.urls), path('api/', include(api.urls)), ] In djangorest/settings.py I included the new app api: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'api.apps.ApiConfig', ] However, when I run the server I get the error: NameError: name 'api' is not defined -
Wrote a command that creates a Django-CMS plugin from an existing one
I have a plugin (PodcastPlugin) that contains two ManyToManyField (podcasts and custom_podcasts). I want to create a Django command that creates a new plugin on the same page and placeholder with the old instances. I can create a new plugin but it does not copy the old instances of podcasts and custom_podcasts into the newly created PodcastPlugin. Here is my code: from cms.models.pagemodel import Page from cms.api import add_plugin for page in Page.objects.all(): for placeholder in page.placeholders.filter(page=263): for plugin in placeholder.get_plugins_list(): if plugin.plugin_type == 'PodcastPlugin': for custom_ids in plugin.get_plugin_instance()[0].custom_podcasts.values_list('id'): for podcasts_ids in plugin.get_plugin_instance()[0].podcasts.values_list('id'): add_plugin( placeholder=placeholder, plugin_type='PodcastPlugin', podcasts=[podcasts_ids[0]], cmsplugin_ptr_id=plugin.id, custom_podcasts=[custom_ids[0]], title='New Podcast', language='de' )