Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: saving date into database
I'm trying to save a date into the database for an attendance system. The print statement works just fine however the date does not get saved into the database. Please help. models.py class Attendance(models.Model): last_here = models.DateTimeField() views.py while(num!=amount): #there are multiple students. stu = Student.objects.filter(squad='LearnToSwim1')[num] if request.POST.get(stu.student_name, '') == 'on': stu.attendance.last_here = datetime.today() #this does not work. print("Student attendance taken") print(stu.attendance.last_here) stu.save() num += 1 -
Django - Looping over unique model field in template
I have a model which a choice field, category, which the user must enter when submitting an entry. I would like to create a view in which each category has its own heading (only once), therefore each unique category would have its own heading, and then display the title associated to each category. models.py class Position(models.Model): club_functions = Choices('Corporate Relations', 'Events & Conference', 'Marketing & Operations', 'Software Development', 'Product') title = models.CharField(max_length=50) category = models.CharField(choices=club_functions, max_length=30, blank=False) description = models.TextField(blank=True) spec_q1 = models.CharField(max_length=500) spec_q2 = models.CharField(max_length=500) views.py def position_list_view(request): all_objects = Position.objects.all() context = { 'object_list' : all_objects } return render(request, "exec_list.html", context) exec_list.html {% for object.category in object_list %} <h3>{{ object.category }}</h3> <p>{{ object.title }}</p> {% endfor %} Any ideas on how to do this? -
tags of content written by django_summernote is exposed, not applied
I start using Django for personal blog building, and just install django_summernote as an editor. However when I get the text in html templets, the html tags of main articles are exposed, not applied properly. It looks like below. Here is the main text. Hellow World! First Post <h1><span style="font-family: Arial;">Hello, World!</span></h1><p><span style="font-family: Arial;">This is my first post.</span></p><p><br></p> Where the templet is like below. <div id="middle_canvas"> Here is the main text. <br> {% for post in recent_posts %} {{ post.title }} {{ post.text }} <br><br> {% endfor %} </div> Also, the Post model is like below. class Post(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title I have no idea where to check. -
How to recieve context to base template django?
I have base template base.html and page.html and page2.html, who extend base.html page.html {% extends 'base.html' %} page2.html {% extends 'base.html' %} I want to recieve some context to base.html when i send request to page.html and page2.html How can i do it? Real example, if it possible. Now i write data to every view, but it is wrong way, i think. -
How can I access a URL's named group in a Django Generic View?
Given a url like: url(r'^foos/(?P<foo_id>[0-9]+)/bars/new/$' How can I access foo_id from within a CreateView instance in order to populate a foreign key form field? I've tried a number of approaches (most recently overriding get_context_data and trying to pull the value out of the request object or from kwargs) without success. There may be a better way to do this (e.g. formsets), but I'd like to make as few changes to my existing flow. -
How to Print Entries from Database in Django
I have some separate entries saved in a database (they are called "Pastes"). For each of these entries, I have a randomly generated string that is saved into a field called generated_url which I can then enter into the address bar to access details tied to that specific entry. Going to projectname.com/jF7Fwr will print all details tied to the entry that has jF7Fwr as the generated_url. My issue is that while it correctly redirects to the page, I am not getting any of the details printed and I'm not sure why. Here is the relevant portion of my views.py def home_view(request, *args, **kwargs): print(args, kwargs) print(request.user) if request.method == 'POST': form2 = PostForm(request.POST) if form2.is_valid(): post = form2.save(commit=False) post.poster = request.user post.content = form2.cleaned_data.get('content') post.title = form2.cleaned_data.get('title') post.syntax = form2.cleaned_data.get('syntax') post.public = form2.cleaned_data.get('public') rand = str(uuid.uuid4())[:6] while Paste.objects.filter(generated_url=rand): rand = str(uuid.uuid4())[:6] post.generated_url = rand form2.save() context = { "poster_name": post.poster, "paste_contents": post.content, "paste_title": post.title, "paste_syntax": post.syntax, "paste_visible": post.public } return HttpResponseRedirect(reverse('details', args=(post.generated_url,))) else: form2 = PostForm() return render(request, "home.html", {'form2': form2}) And here is my details.html page: {% extends "base.html" %} {% block content %} <p>Content of post:</p> I AM REDIRECTED <h1>Name of post: {{ post.title }}</h1> <p>Content of post:</p> … -
Django View funciton is not working for first object
I am trying to implement a feature in which when I click on Publish button, the value in my Django database for this field changes to 'True’ and is displayed on the HTML page as Publish. The problem i am encountering is only for the first object displayed in browser the button is not calling the view function. for the rest of the object the button is working. model.py class Post(models.Model): submitted = models.ForeignKey(User, on_delete=models.CASCADE) ad_name = models.CharField(max_length=500) is_published = models.BooleanField(default=False) views.py def change_post_true(request, post_id): if request.method == 'POST': try: obj = Post.objects.get(pk=post_id) obj.is_published = True obj.save() return redirect(approved_post) except Post.DoesNotExist: return HttpResponse('Post not found', status=404) except Exception: return HttpResponse('Internal Error', status=500) return HttpResponse('Method not allowed', status=405) post.html {% if listing.is_published %} <form method="POST" action="{% url 'post-status-false' post_id=listing.id %}"> {% csrf_token %} <input type="submit" name="Unpublish" value="Unpublish"> </form> {% endif %} -
django user created drop down list items
I want the users to be able to create items from the drop down menu is this possible. I very new to django so any help is appreciated. Currently I'm just saving the title of the item they want to add and have some dummy data as the items. LIST_CHOICES = ( ('green','GREEN'), ) class Listing(models.Model): title = models.CharField(max_length=250) def get_absolute_url(self): return reverse('project-create') Is there a way I can get the inputed title from the Listing Model and display it as a dropdown item with Post? class Post(models.Model): department = models.CharField(max_length=100, choices=LIST_CHOICES, default='green') date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def get_absolute_url(self): return reverse('project-detail', kwargs={'pk': self.pk}) -
How can I search inside large number of Log Files for specific keywords in Python?
So, I am in the situation where I have to search for a specific keyword inside a directory containing large number of log files to return the whole line containing that keyword. I basically want to make a local search engine for searching inside the log files. I can proceed by reading each and every file by and searching inside of it for each files line by line, but that would be highly inefficient (obviously). How can I proceed with this situation considering I have more than 30 thousand files each having approx 600 lines and of size approx 150kB? -
Fetch JSON from Google Maps Autocomplete and Submit it into Django Form Data
For my website, I want to place a Google Maps autocomplete form into a page, and when the user submits the coordinates, and will send the JSON to Django forms, so it can submit it into the database. My only issue is that I do not know how to get the latitude and longitude from the Google Maps application, and submit it into Django. Here's the code for the Google Maps Autocomplete: <html> <head> <title>Place Autocomplete</title> <meta name="viewport" content="initial-scale=1.0, user-scalable=no"> <meta charset="utf-8"> <style> /* Always set the map height explicitly to define the size of the div * element that contains the map. */ #map { height: 100%; } /* Optional: Makes the sample page fill the window. */ html, body { height: 100%; margin: 0; padding: 0; } #description { font-family: Roboto; font-size: 15px; font-weight: 300; } #infowindow-content .title { font-weight: bold; } #infowindow-content { display: none; } #map #infowindow-content { display: inline; } .pac-card { margin: 10px 10px 0 0; border-radius: 2px 0 0 2px; box-sizing: border-box; -moz-box-sizing: border-box; outline: none; box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3); background-color: #fff; font-family: Roboto; } #pac-container { padding-bottom: 12px; margin-right: 12px; } .pac-controls { display: inline-block; padding: 5px 11px; … -
Is django.http.request.method not a thing?
Ok so I get this weird error under the following conditions and am really confused by it: In my views.py file i import request like this: from django.http import HttpResponse, HttpRequest, request Then in generic CreateView I try to do this: class createAnswer(CreateView): model = Answer fields = ['content'] if request.method == "GET": do some stuff The full errormessage looks like this: AttributeError at / module 'django.http.request' has no attribute 'method' Request Method: GET Django Version: 2.1.7 Exception Type: AttributeError Exception Value: module 'django.http.request' has no attribute 'method' I am really confused by this because i have seen other people do this. Is this just not a thing or is there just some obvious mistake i made? -
PostgreSQL database on EC2: Connection refused
I have my Django app and PostgreSQL database set up on two EC2 instances in the same VPC. App is on the instance with subnet connected to internet gateway; database is on instance with subnet that has no internet gateway. The app instance's private IP is 10.0.0.164; the database instance's private IP is 10.0.1.136. When I try to connect my Django app to the database, I get the error could not connect to server: Connection refused Is the server running on host "10.0.1.136" and accepting TCP/IP connections on port 5432? However, I have allowed inbound TCP traffic on port 5432 on the database instance. My security group rules for the instance that hosts the database: Inbound: allow all TCP and ICMP IPV4&IPV6 traffic in all ports from the internal IP address of the instance hosting the Django app (10.0.0.164/32) (screenshot of my inbound rules https://imgur.com/a/HNbrIDm) Outbound: allow all traffic in all ports to anywhere My pg_hba.conf file on the database EC2 instance: # Database administrative login by Unix domain socket local all postgres md5 # TYPE DATABASE USER ADDRESS METHOD # "local" is for Unix domain socket connections only local all all md5 # IPv4 local connections: host all all … -
How to make fields unique with other models referencing the same ForeignKey
Is there a way to make model fields unique with other models referencing the same ForeignKey? In my case I am trying to make it so that the names of Attribute models with the same Obj are unique. Ex: if there exists a CharAttribute with name='Types' and obj=1 there can't be another CharAttribute with name='Types' and obj=1 nor an IntAttribute with name='Types' and obj=1 class Obj (models.Model): name = models.CharField(max_length=40) class CharAttribute (models.Model): name = models.CharField(max_length=40) obj = models.ForeignKey(Obj, on_delete=models.CASCADE) class IntAttribute (models.Model): name = models.CharField(max_length=40) obj = models.ForeignKey(Obj, on_delete=models.CASCADE) My current idea for a solution would be something like this: def clean_fields(self, exclude=None): super().clean_fields(exclude=exclude) for other_name in IntAttribute.objects.filter(obj=self.obj): if self.name == other_name: raise ValidationError( ('Attributes of the same object may not have the same name, %(name) s already exists for ' '%(object) s' % {'name': self.name, 'object': self.obj.name}) ) for other_name in CharAttribute.objects.filter(obj=self.obj): if self.name == other_name: raise ValidationError( ('Attributes of the same object may not have the same name, %(name) s already exists for ' '%(object) s' % {'name': self.name, "object": self.obj.name}) ) But creating another for loop for each possible future created Attribute feels repetitive and there must be a better way of accomplishing this task. Thank … -
Error setting up debugger for Django VS Code
So i'm starting to explore Django in VS Code using a tutorial and got this error when running the debugger on manage.py: Exception has occurred: ModuleNotFoundError No module named 'hello' File "C:\Users...\Desktop\django_test\manage.py", line 15, in execute_from_command_line(sys.argv) For context the name of my project is web_project which is essentially a skeleton, and "hello" refers to an app made with mostly just a skeleton. I have tried three main things that were unsuccessful: modifying launch.json, modifying manage.py, and modifying the file structure. None of which have worked. Any advice you have would be appreciated. My manage.py file: import os import sys if __name__ == '__main__': os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'web_project.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) My launch.json: { "version": "0.2.0", "configurations": [ { "name": "Django", "type": "python", "request": "launch", "program": "${workspaceFolder}/manage.py", "args": [ "runserver", "--noreload", ], "django": true }, } The file structure: https://i.stack.imgur.com/33vgX.png -
How to allow specified user to view premium content of specified book in django
I hope someone can help me. I am a student and a beginner in django. I am trying to allow a certain premium user to view the premium content of a specific book. I already have models for the books, users, and membership type. However, I would like to know how I can connect those 3 so that a certain user can only see just the ALLOWED PREMIUM CONTENT of ONE specific book coming from a list of books. Here's the code sample: class Book(models.Model): code = models.SlugField(unique=True, help_text="Enter BIC Code", null=True) title = models.CharField(max_length=200) author = models.ForeignKey('Author', on_delete=models.CASCADE, null=True) artist = models.ForeignKey('Artist', on_delete=models.CASCADE, null=True) summary = models.TextField(max_length=1000, help_text="Enter a brief description of the book") book_type = models.ForeignKey('Type', on_delete=models.SET_NULL, null=True) isbn = models.CharField('ISBN', max_length=15, help_text='Enter ISBN number') status = models.CharField(choices=STATUS_CHOICES, default='Ongoing', null=True, max_length=30) genre = models.ManyToManyField(Genre, help_text="Select a genre for this book") language = models.CharField(max_length=50, null=True, help_text="Enter the book's natural language (e.g. English, Tagalog, Japanese etc.)") released_date = models.CharField(max_length=50, null=True, help_text="Enter the Released Date (e.g. March 2014)") cover = models.ImageField(upload_to='book_cover', null=True, validators=[img_file_extension], help_text="Image File Only") teaser = models.FileField(upload_to='book_preview', validators=[pdf_file_extension], help_text="PDF File Only") featured = models.BooleanField(null=True, default=False) timestamp = models.DateTimeField(default=timezone.now) def display_genre(self): return ', '.join([genre.name for genre in self.genre.all()[:3]]) display_genre.short_description = … -
Django HTML max length of imported text
I am working on a project in django and am trying to minimize the amount of text displayed on a page showing entries for various topics. The idea is to just give the first 200 characters and then they can open it in another page to read the whole entry. Below is the code for the html page... {% extends "AARs/base.html" %} {% block header %} <h2>{{ topic }}</h2> {% endblock header %} {% block content %} <p> <a href="{% url 'AARs:new_action' topic.id %}">Add new action</a> </p> {% for action in actions %} <div class="panel panel-default"> <div class="panel-heading"> <small> {{ action.date_added|date:'M d, Y H:i' }} </small> <small> <a href="{% url 'AARs:edit_action' action.id %}">Read or Edit Action</a></small> </div> <div class="panel-body"> <small> <input type="text" name="action" maxlength="10"> {{ action.text|linebreaks }} </small> </div> </div> {% empty %} No actions have been added yet. {% endfor %} {% endblock content %} I have tried inserting maxlength="200" in various places that I thought might work, but to no avail. Obviously, I am a newbie. Am excited to be doing stuff beyond my level. Any help is appreciated. -
Is Writing Non-Model Code in a Model Class Acceptable?
I am building a very small API using Python and was wondering whether it is generally acceptable to place API code in a model class when using frameworks like Django or Flask (with an ORM like Peewee or Pony). Let me explain what I mean... To illustrate what I mean, imagine I have a package with all my models and then another package with my API code which executes when a client pings a particular route that I have defined. As you know, the models are basically only for mapping objects to the database. Although, under certain circumstances, it personally makes more sense for some reason to place some of the API code in one of the model classes I have defined. For example, I have a User model that maps a user to the database. Additionally, in the API code, I have a function to login the user. This function basically sets the cookies to login the user so it might make sense to place it in the API package. However, I feel like if I make this function a method and place it in the user model, it makes more sense semantically and might be easier to understand. … -
Django: How to establish persistent connection to rabbitmq?
I am looking for a way to produce messages to a rabbitmq server from my django application. This is not for task offloading, so I don't want to use Celery. The purpose is to publish to the queue using the django application and have a sister application in the docker container consume from that queue, using rabbitmq to manage the queue. This all seems very straightforward, however, I can't seem to produce to the queue without establishing and closing a connection each time, even without explicitly calling for that to happen. In order to accomplish this, I have defined a class with a nested singleton class that maintains a connection to the rabbitmq server using Pika. The idea was that the nested singleton would be instantiated only once, declaring the connection at that time. Any time something is to be published to the queue, the singleton handles it. import logging import pika import os logger = logging.getLogger('django') class PikaChannelSingleton: class __Singleton: channel = pika.adapters.blocking_connection.BlockingChannel def __init__(self): self.initialize_connection() def initialize_connection(self): logger.info('Attempting to establish RabbitMQ connection') credentials = pika.PlainCredentials(rmq_username, rmq_password) parameters = pika.ConnectionParameters(rmq_host, rmq_port, rmq_vhost, credentials, heartbeat=0) connection = pika.BlockingConnection(parameters) con_chan = connection.channel() con_chan.exchange_declare(exchange='xchng', exchange_type='topic', durable=True) self.channel = con_chan def send(self, routing_key, … -
django admin list sum fields
I'd like to combine the same table data from the inventory admin page list. My admin.py is as follows admin.py class CounselAdmin(admin.ModelAdmin): list_display = ('counsel_idx', 'show_firm_url', 'answer_count', 'counsel_status', 'deleted', 'register_date',) search_fields = ('counsel_status',) list_filter = ('counsel_status',) def show_firm_url(self, obj): return format_html("<a href='/admin/counsel/view/{0}'>{1}</a>", obj.counsel_idx, obj.counsel_title) show_firm_url.short_description = 'title' For example, I would like to put it together in this way show_firm_url The data in show_firm_url is = TITLE TEST answer_count is = 7 in case of TITLE TEST (answercount 7) I want it to come out together like a stomach. Please help me. -
Bootstrap invalid-tooltip not working correctly on IE
Funny IE-compatibility issue I have just experienced. I have a code like that: <div class="row d-flex justify-content-around"> <div class="col-sm-12 col-md-4 px-3"> <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text" id="basic-addon1">{% trans 'Some string' %}</span> </div> {{ base_form_key.ss }} <div class="invalid-tooltip"> {% trans 'Enter a correct value or leave this field empty. x and y cannot be the same!' %} </div> </div> </div> </div> That code in Chrome generates for me a nice output I expect: However, on IE it ends up vertically stretching that tooltip box like so: What it tells me is that IE interprets some CSS styling differently to Chrome here, but dunno what exactly. Has anyone encountered the same problem? -
Webpage which can update file in a server
Don't know where to begin. I have a requirement to create a web page 1) Dropdown file names which exist on the Linux server 2) and can accept server names (max 10) in a block 3) Validate if each server exists by running nslookup 4) if the check is passed then update the file which is on Linux server Question - 1) Which script and web framework is suitable for this job 2) I am learning python so prefer python and Django. Not sure if this combination is suitable Thanks -
I can not sort by city distance in GeoDjango (PostGis)
The distance method does not work in GeoDjango (QuerySet) My model : class City(models.Model): name_english = models.CharField(max_length=500, null=True, blank=True) site = models.ForeignKey(Site, on_delete=models.CASCADE, null=True, blank=True, verbose_name="city", db_index=True, related_name="city_relate") name_city_avito = models.CharField(max_length=500, null=True, blank=True) country = models.ForeignKey(Country, on_delete=models.CASCADE, null=True, blank=True, verbose_name="Country", db_index=True, related_name="Country_relate") region = models.ForeignKey(Region, on_delete=models.CASCADE, null=True, blank=True, verbose_name="Region", db_index=True, related_name="Region_relate") point = models.PointField(blank=True, null=True) view.py class Landing_head(View): def get(self, request): b = Site.objects.get_current() current_location = City.objects.get(site__id=b.id).point cities = City.objects.filter(point__distance_lte=(current_location, D(km=200))).distance(current_location).order_by('point_distance')[:1][0] for z in cities: print(z) output error 'QuerySet' object has no attribute 'distance' Although it works in this version, but without sorting by distance class Landing_head(View): def get(self, request): b = Site.objects.get_current() current_location = City.objects.get(site__id=b.id).point cities = City.objects.filter(point__distance_lte=(current_location, D(km=200))) for z in cities: print(z) Friends can anyone tell me? -
How to access django model function from class in different app
I have an app (app1) where I define a function to return a specific value in my models.py, like so: class Product(models.Model): name = models.TextField(null='true',blank='true') description = models.TextField(null='true',blank='true') multiplier = models.DecimalField(max_digits=2, decimal_places=1, default='2.2') price = models.DecimalField(max_digits=6, decimal_places=2, null='true') def final_price(self): return self.price * self.multiplier This works perfectly within app1. I can return it in my views and it renders in templates as it should. I am trying to use this in another app, app2, which uses a custom class called 'cart', defined as such: from app1.models import * class Cart(object): def __init__(self, request): self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def add(self, product, quantity=1, update_quantity=False): product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {'quantity': 0, 'price': product.final_price} if update_quantity: self.cart[product_id]['quantity'] = quantity else: self.cart[product_id]['quantity'] += quantity self.save() def save(self): self.session[settings.CART_SESSION_ID] = self.cart self.session.modified = True def remove(self, product): product_id = str(product.id) if product_id in self.cart: del self.cart[product_id] self.save() def __iter__(self): product_ids = self.cart.keys() products = Product.objects.filter(id__in=product_ids) for product in products: self.cart[str(product.id)]['product'] = product for item in self.cart.values(): item['price'] = Decimal(item['price']) item['total_price'] = item['price'] * item['quantity'] yield item def __len__(self): return sum(item['quantity'] for item in self.cart.values()) def get_total_price(self): return … -
Django Set Auto-Generate Many-To-Many Data
Being that Django Admin and Model have different save processes, I keep running into an issue trying to auto-populate data for a Many-to-Many field. If I put the code in the model save() method, the Many-to-Many relationship gets cleared when I save through the Admin interface, and if I put it in the Admin save_related() method it doesn't generate the fields when data is added directly through the model. If I do it in both, then I end up with 2 copies of the data in the table. I have also tried adding the code to a post_save and m2m_changed signal, rather than the model save(), but that creates the same issues from above. Is there any clean solution outside of monkey patching the Manager so the admin doesn't clear the Many-to-Many data? Here is a simplified version of what I'm trying to accomplish: class Clothing(models.Model) labels = models.ManyToManyField(Label, blank=True) def create_default_labels(user_id): labels = LabelType.objects.all() label_list = [] for label in labels: label_list.append( Label.objects.create(user_id=user_id, label_type=label, is_active=False) ) return label_list def save(self, *args, **kwargs): super().save(*args, **kwargs) # if no label data was sent to model and row doesn't exist yet if not self.labels.all() and not self.id: labels = self.create_default_labels(self.user_id) self.labels.add(*labels) -
Disabled option in Django Select Widget using ModelChoiceField
I am trying to show inactive users as "disabled" in my form's Select widget. I have a worker who is a django user model. models.py class Task(models.Model): worker = models.ForeignKey(settings.AUTH_USER_MODEL, models.DO_NOTHING, blank=True, null=True,related_name='worker') It is represented by a ModelForm, using a subclass to display the full name of the user. forms.py class UserModelChoiceField(forms.ModelChoiceField): def label_from_instance(self, obj): return obj.get_full_name() class TaskForm(forms.ModelForm): worker = UserModelChoiceField(queryset=User.objects.filter(is_active=1).order_by('first_name'),widget=forms.Select(attrs={'class':'form-control'}),required=False) class Meta: model = Task fields = ['worker'] Currently, the filter is_active=1 means that inactive users simply don't show in the list and where they've already been selected it appears as "---". My ideal would be they appear but are greyed out so they are presented but can't be selected. From reviewing https://djangosnippets.org/snippets/2453/ Which I found in "Disabled" option for choiceField - Django I was able to conclude that the subclass of the select should work. However I can't tell how to get between the queryset and the widget in order to achieve the expected result. Reading suggests the render method on the widget might be the way but I couldn't find examples of how to pass the information or exactly where create_option is invoked.