Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
creating windows batch to run django server
I want to define django virtualenv, then operate the server. but I want it in one operation, not 2. so, I tried to write batch. my batch is: start workon moviesEngine timeout 2 start python manage.py runserver but it not success. it create a new cmd for the workon (i.e the virtualenv I want to work with), and operate the python command in different cmd (which hasn't the support of the virtualenv). how do I force the python command to run in the new cmd with the virtualenv? -
Using an embedded Iframe in Django?
How do I use an Iframe in Django. Currently its searching for the src url in my own files. How do I tell it to not look in my files but to look at the url? Currently I'm storing the embed code minus the tag in a database and then trying to dynamically generate it in my template. games.embed = 'allowtransparency="true" width="485" height="402" src="//scratch.mit.edu/projects/embed/82384372/?autostart=false" frameborder="0" allowfullscreen' {% extends 'code_games/base.html' %} {% block content %} <div class="game"> {{games.title|linebreaks}} <iframe '{{ games.embed }}'></iframe> </div> {% endblock %} The iframe itself shows up on my page but the contents of it don't. The request URL per the error: Request URL: http://chacemcguyer.pythonanywhere.com/games/1/%22/scratch.mit.edu/projects/embed/82384372/?autostart=false%22 You can see that its searching for the url in my site. How do I get around that? The error also says: Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: Then it shows all of my urls from settings.py -
I have a django model but i only want to put some of my models as forms.
For example, lets say this is my model: class Author(models.Model): author = models.CharField() friends = models.CharField() and I only want to have the friends as a form field -
Django Admin List Filter Without Sidebar
I want to be able to apply a list filter based on a known foreign-key value without showing the sidebar at all. I have 3 schools with IDs 1, 2 & 3. I have 39 programs, each having various fields, one of which being 'school' a foreign-key to schools table, and 39 records having either 1, 2, or 3 in 'school' field. In admin.py, I create a ProgramsAdmin with list_filter = (('school')). This works perfectly, with the 3 schools appearing in sidebar. Clicking on any of them properly filters the programs. Since user is going to log in and select the school they are working on, I want the list to be filtered without seeing the sidebar. Chosen school will be stored in database in settings table, but for now I just want to get it to work hard-coded to 1, 2 or 3 and not show sidebar. This works SO easy in models.py, filtering a many-to-many relationship, just using limit_choices_to clause. Not so easy filtering in admin. Is it even possible to filter the admin on a hard-coded value, or a function which returns a filter value like limit_choices_to does? Thanks... -
Django: Set E-Mail settings in view
I am trying to send a email using SMTP from Google. I already get to send a email putting the setting variables in the file "settings.py" but I need to configure these variables in a view and set them using my "Config" model. This is my model code: class Config(models.Model): email_sender = models.CharField(max_length = 100, default = '', blank = True) email_password = models.CharField(max_length = 30, default = '', blank = True) smtp_server = models.CharField(max_length = 100, default = '', blank = True) smtp_port = models.PositiveIntegerField(default = 587, blank = True) This is my view code: def send_custom_mail(request): config = Config.objects.get(pk = 1) EMAIL_HOST = config.smtp_server EMAIL_PORT = config.smtp_port EMAIL_HOST_USER = config.email_sender EMAIL_HOST_PASSWORD = config.email_password EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = EMAIL_HOST_USER subject = 'test' msg = '<p>Test: <strong>Mensaje</strong>></p>' mail_from = config.email_sender mail_to = ['{}'.format(email)] from django.core.mail import EmailMessage email2send = EmailMessage(subject, msg, mail_from, to=mail_to) email2send.content_subtype = "html" # Main content is now text/html email2send.send() My problem: The email is not sent when I set the variables in the view. I need to configure these variables dinamically so I can't write it in the setting.py file. -
gunicorn does not start after boot
I'm running a Debian web server with nginx and gunicorn running a django app. I've got everything up and running just fine but after rebooting the server I get a 502 bad gateway error. I've traced the issue back to gunicorn being inactive after the reboot. If I start the service the problem is fixed until I reboot the server again. Starting the service: systemctl start gunicorn.service After the reboot here is my gunicorn service status: {username}@instance-3:~$ sudo systemctl status gunicorn ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled) Active: inactive (dead) Contents of my /etc/systemd/system/gunicorn.service file: [Unit] Description=gunicorn daemon After=network.target [Service] User={username} Group={username} WorkingDirectory=/home/{username}/web/{projname} ExecStart=/usr/local/bin/gunicorn {projname}.wsgi:application Restart=on-failure [Install] WantedBy=multi.user.target Any ideas to figure out why the gunicorn service isn't starting after reboot? -
Migrating SQLite3 database (w/ very similar schema) to already created Django models
Please go easy on me, I literally just started using Django at 3am this morning... As part of a school project, I wrote a Python script to scrape data, generate SQLite3 tables and insert records from a Python dictionary into said tables. The schema of this SQLite3 db looks like this: CREATE TABLE state ( id INT PRIMARY KEY, name VARCHAR(100) NOT NULL ); CREATE TABLE city ( id INT PRIMARY KEY, name VARCHAR(100) NOT NULL ); CREATE TABLE restaurant ( id INT PRIMARY KEY, name VARCHAR(100) NOT NULL, rating FLOAT, url VARCHAR(300), price VARCHAR(4), review_count INT, street VARCHAR(100), city VARCHAR(100), state VARCHAR(2), country VARCHAR(100), zip_code INT, phone VARCHAR(20), image_url VARCHAR(300) ); CREATE TABLE category ( id INT PRIMARY KEY, title VARCHAR(100) ); CREATE TABLE restaurant_by_category ( restaurant_id INT, category_id INT, FOREIGN KEY (restaurant_id) REFERENCES restaurant, FOREIGN KEY (category_id) REFERENCES category ); CREATE TABLE review ( url VARCHAR(300) PRIMARY KEY, restaurant_id INT, rating FLOAT, name VARCHAR(100), time VARCHAR(100), text VARCHAR(300) ); Weeks after making this database, I then decided to start making the web app using Django. I have a (basically) fully operational Django app with a SQLite3 backend whose models.py looks like this: class City(models.Model): name = models.CharField(max_length=100) def … -
How to filter django python object with list
I have the following django models class Article(models.Model): article_tags = models.CharField(max_length=200, blank=True, null=True) class UserProfile(models.Model): user_interests = models.CharField(max_length=200, blank=True, null=True) I have a feed feature for my users and want to filter articles based on user_interests. For example I have a user with user_interests = ['horror', 'comedy', 'fiction']. And I have articles with article_tags which are also lists = ['funny', 'comedy', 'new york'] I want to filter my users' feeds by comparing their user_interests with the article_tags of all the articles. I had tried this: user_interested_articles = Article.objects.filter(case_tags__in = user_interests) But it doesn't work, I believe this is because I'm trying to compare a list with a list. Is there another way to do this? -
Django signal ongoing execution of model method
class ItemDetailView(DetailView): def get_context_data(self, **kwargs): context = super(MovieDetailView, self).get_context_data(**kwargs) if self.object.expire < time.time(): self.object.update_sth() return context I'm executing model object method on user request on certain condition. How do I signal execution of this method so that another user don't call it for the second time while executing? -
Displaying image file from django model in jade
I want to render an image file from a django model into a jade template the model is as follows class Brand photo = models.FileField(null=True, upload_to= 'brands') photo_updated_at = models.DateTimeField(default=None) What is the syntax i use to render it in a jade template? i do not want to use STATIC_DIRS. is there any way to use MEDIA_ROOT to display in jade -
Connect to a PostgreSQL database on a Docker container
I want to run an application with a PostgreSQL database and a REST API powered by Django on separate Docker containers. So far the API has been running on Docker connecting to a SQLite database, but I'm having trouble now that I want to connect to a PostgreSQL database instead. Docker's docker-compose.yml file: version: '2' services: postgres: image: postgres api: build: . command: bash -c "python manage.py migrate && python manage.py runserver 0.0.0.0:1337" volumes: - .:/usr/src/app ports: - "1337:1337" depends_on: - postgres Django's settings.py (using the default settings which the base postgres image works with according to the documentation): DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'wgomanager', 'USER': 'postgres', 'PASSWORD': 'mysecretpassword', 'HOST': 'localhost', 'PORT': '5432', } } When I launch the application with docker-compose up eventually this error is thrown: api_1 | connection = Database.connect(**conn_params) api_1 | File "/usr/local/lib/python3.6/site-packages/psycopg2/__init__.py", line 130, in connect api_1 | conn = _connect(dsn, connection_factory=connection_factory, **kwasync) api_1 | django.db.utils.OperationalError: could not connect to server: Connection refused api_1 | Is the server running on host "localhost" (::1) and accepting api_1 | TCP/IP connections on port 5432? api_1 | could not connect to server: Connection refused api_1 | Is the server running on host "localhost" (127.0.0.1) and … -
Django rest framework - pass additional arguments to validate_foo
As per DRF documentation DRF Validators My method should be like def validate_title(self, value): """ Check that the blog post is about Django. """ if 'django' not in value.lower(): raise serializers.ValidationError("Blog post is not about Django") return value I want to pass an additional argument to validate_title, so it should look like def validate_title(self, value, id): """ Check that the blog post is about Django. """ # Use <id> here if 'django' not in value.lower(): raise serializers.ValidationError("Blog post is not about Django") return value I am not able to understand how to achieve this, any help? -
Django. Print all admin actions.
Someone in my team deleted an important object. I need to know who did it, he obviously had access to the admin. Is there a way I can print to the terminal (or anywhere) all the admin actions of the last 3 hours? I'm sure django keeps a history, I just don't know where to find it. -
How to properly test django UpdateView?
I have the following unit test def test_category_update_view(self): """ Make sure that a category can be updated :return: """ self.log_user_1_in() self.assertEqual('Bacon', self.category.name) res = self.client.put( reverse( 'calendars:categories:edit_category', kwargs={'calendar_pk': self.calendar.id, 'pk': self.category.id} ), urlencode({'name': 'bacon is yummy'}) ) self.assertEqual('bacon is yummy', self.category.name) self.assertEqual(302, res.status_code) self.assertEqual( reverse('calendars:categories:category_list', kwargs={'calendar_pk': self.calendar.id}), res.url ) As you can see it's saying that the form is invalid, so my question is why is it invalid? Shouldn't the test client be using the data I gave it? My POST request done in the same fashion is working just fine and passing the proper data. I haven't posted in awhile so forgive me if this is kind of vague. If you need more information to help me please let me know. -
Splitting models.py and/or splitting into packages
While working on this open source Django package, I met the following situation and proposed solutions. The question is to make me aware about all possible problems with this situation like circular imports or maybe other problems. I have a models.py file with several models for storing in a DB in the package debits_base. I want to move the DB models into models/db.py and new unmanaged reminder models (see below) into models/reminder.py (possible with separate models/email_reminder.py) or into a separate package (not yet decided). But now I want to create models Reminder and its derivative EmailReminder with managed = False in class Meta. I want these classes to be models so that I could be able to specify a derivative of Reminder in settings (for example PAYMENTS_REMINDER = 'debits_base.EmailReminders' to send reminders by email) using apps.get_model(). Some questions: Are three strong reasons that I should or should not place reminders in debits_base package or create separate debits_reminders package? What are strong reasons pro and counter these decisions? Particularly will some of these two variants lead to problems like erroneous circular imports (possibly when I call get_model())? (It is not an opinion based question: If both variants work, say that both … -
Django ModelForm with Many to Many Field
I have a Django model for a List with a many to many field to Item, it uses a through table, that has a column for quantity. I want to use Django forms to display a form that the user can add items to the list. If I just try and create the ModelForm, it shows a selection box, where I can choose items, but there is no way to denote quantity for each item. I'd like to have it display a dropdown menu where you can select an item, and a input box where you can enter the quantity. Do I have to do something custom to get it to work this way? EDIT: I could probably just write the form in HTML myself, but I want to use the validation features of Django forms in the backend too. -
make Pyspark (Logistic Regression) Prediction from Django queryset
I recently built and saved a Pyspark Logistic Regression model to classify customers into 3 classes. The final part requires that I predict a customer's classfrom a django queryset with features. I created a Django Admin Action to make this prediction but I cannot proceed since I have to use Spark SQL and am using Spark Dataframes. My code for the prediction is as shown below; def allocate_service(ModelAdmin, request, queryset): silver_customers = [] gold_customers = [] platinum_customers = [] message = '' for customer in queryset: data = [(customer)] df = spark.createDataFrame(data, schema=None, samplingRatio=None, verifySchema=True) # Creating Spark SQL temporary views with the DataFrame df.createOrReplaceTempView("cust_temp") result = spark.sql("SELECT Gender, Account_Type, Age, Education, Employment, Salary, Employer_Stability, Customer_Loyalty, Balance, Residential_Status, Service_Level FROM cust_temp") result.show() cols = result.columns categoricalColumns = ["Gender", "Account_Type", "Age","Education", "Employment", "Employer_Stability", "Residential_Status"] stages = [] # stages in the pipeline for categoricalCol in categoricalColumns: # Category Indexing with StringIndexer stringIndexer = StringIndexer(inputCol=categoricalCol, outputCol=categoricalCol+"Index") # Using OneHotEncoder to convert categorical variables into binary SparseVectors encoder = OneHotEncoder(inputCol=stringIndexer.getOutputCol(), outputCol=categoricalCol+"classVec") # Adding the stages: will be run all at once later on stages += [stringIndexer, encoder] # convert label into label indices using the StringIndexer label_stringIdx = StringIndexer(inputCol = "Service_Level", outputCol = … -
Configuring and using structlog with Django
Does anyone use structlog with Django? I'm looking for a code sample how can I integrate Django logging (which is done via standard library), and structlog. I've tried the code from the "Rendering Using structlog-based Formatters Within logging" example, with only slightest modifications: # From my settings.py, basically the same code as in the linked example timestamper = structlog.processors.TimeStamper(fmt="%Y-%m-%d %H:%M:%S") pre_chain = [ structlog.stdlib.add_log_level, timestamper, ] LOGGING = { "version": 1, "disable_existing_loggers": False, "formatters": { ... }, # Exactly like in the linked example "handlers": { ... }, # Ditto, but only "default" handler (no files) "loggers": { "django": { "handlers": ["default"], "level": "INFO", }, # I also had "" logger here, with the same config as "django", # but it's irrelevant for the example purposes. } } # Same as in the example structlog.configure( processors=[ structlog.stdlib.add_log_level, structlog.stdlib.PositionalArgumentsFormatter(), timestamper, structlog.processors.StackInfoRenderer(), structlog.processors.format_exc_info, structlog.stdlib.ProcessorFormatter.wrap_for_formatter, ], context_class=dict, logger_factory=structlog.stdlib.LoggerFactory(), wrapper_class=structlog.stdlib.BoundLogger, cache_logger_on_first_use=True, ) However, I end up with logging errors. This is an excerpt of what happens on a simple GET request that ends up with 404 TypeError: not all arguments converted during string formatting ... File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 152, in get_response extra={'status_code': 404, 'request': request}, Message: '\x1b[2m2017-05-08 18:34:53\x1b[0m [\x1b[33m\x1b[1mwarning \x1b[0m] \x1b[1mNot Found: /favicon.ico\x1b[0m' Arguments: … -
Django bootstrap 3 not responsive with form
I write a simple form in Django with this fields: DateField, CharField, Textarea and Autocomplete-light (query the database to autocomplete). All fields works good but when I render in html they are not resizing when the browser window become small. I put jumbotron in a container, only the button actually is responsive... Which is the problem of the other fields? html: {% load staticfiles %} <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}" type="text/css"/> <link rel="stylesheet" href="{% static 'css/custom.css' %}" type="text/css"/> <body> <div class="container"> <div class="jumbotron"> <form method='POST' action'' enctype="multipart/form-data">{% csrf_token %} <div class="form-group"> <table class="rica"> {{ form.as_table }} </table> </div> <input type="submit" class="btn btn-light-blue btn-md btn-block" value="INVIA RICHIESTA"> </form> </div> </div> </body> -
Accessing child from parent
I have the models defined below: class PrimaryAsset(models.Model): title = models.Charfield(max_length=200) class Service(PrimaryAsset): description = models.Charfield(max_length=200) class Website(PrimaryAsset): url = models.Charfield(max_length=200) class AssetLinks(models.model): high = models.ForeignKey(PrimaryAsset) low = models.ForeignKey(PrimaryAsset) AssetLinks.objects.filter(high=212)[0].low When I do the filter above, how can I know which instance the objects is (website or service)? Also, is there a way to avoid an N+1 query using prefetch_related in a way that it gets all the child information as well? -
User created in migration does not exist
I have a system user that I've created in a data migration: from __future__ import unicode_literals from django.db import migrations from django.contrib.auth.models import User def create_system_user(apps, schema_editor): system_user = User.objects.get_or_create(username="system")[0] system_user.set_password("system") system_user.save() class Migration(migrations.Migration): dependencies = [ ('app', '0021_prev_migration'), ] operations = [ migrations.RunPython(create_system_user) ] I ran python manage.py migrate and the migration seemed to run normally. If I drop into the shell, the user exists as expected. However, when I run my test suite, I get an error of: Traceback (most recent call last): File "/home/user/.virtualenvs/admin/local/lib/python2.7/site-packages/nose/loader.py", line 418, in loadTestsFromName addr.filename, addr.module) File "/home/user/.virtualenvs/admin/local/lib/python2.7/site-packages/nose/importer.py", line 47, in importFromPath return self.importFromDir(dir_path, fqname) File "/home/user/.virtualenvs/admin/local/lib/python2.7/site-packages/nose/importer.py", line 94, in importFromDir mod = load_module(part_fqname, fh, filename, desc) File "/home/user/admin_api/scheduler/tests/test_tasks.py", line 18, in <module> from scheduler.tasks import (floor_datetime_to_minutes, save_task_details, File "/home/user/admin_api/scheduler/tasks.py", line 48, in <module> SYSTEM_USER = User.objects.get(username='system') File "/home/user/.virtualenvs/admin/local/lib/python2.7/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/user/.virtualenvs/admin/local/lib/python2.7/site-packages/django/db/models/query.py", line 385, in get self.model._meta.object_name DoesNotExist: User matching query does not exist. Django 1.10, Python 2.7 -
Cannot send data read from csv file (comma separated) to javascript using django
Hello I haven't been able to use data from file comma separated in javascript. So far i've been trying to read it in python and send it through django to javascript in json format but nothing seems to work. In the File views.py I have: from django.shortcuts import render import json def home2view(request): f= open('filess.csv','r' ) reader = csv.DictReader( f, fieldnames = ( "name","lat","lng") ) out = json.dumps( [ row for row in reader ] ) return render(request,'index3test.html') If I print out, I get this: [{"country": "EU", "lng": "149.0321159", "lat": "-23.2869226"}, {"country": "ES", "lng": "120.2920532", "lat": "-20.621217"}] Why cant I send it to javascript? this is not even executing (I use pythonanywhere) -
Django forms sends back html
When I make a Django form it sends back the actual html. Please help my Html: <form action="" method="post" class="register-form"> {% csrf_token %} {{ form.as_p }} <p class="agree"> <input type="checkbox" required> I agree to <a href="#" </p><br/> <input class="signup" type="submit" value="Sign up for free" name="signup2"><br/> </form> my View: def homepage_view(request): if request.method == "POST": form = forms.SignUpForm(request.POST) if form.is_valid(): first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] username = form.cleaned_data['username'] email = form.cleaned_data['email'] password = form.cleaned_data['password'] new_user = User.objects.create_user( first_name=first_name, last_name=last_name, username=username, email=email, password=password, ) login(request, new_user) print(form) return redirect("/account/") else: print(form) else: form = forms.SignUpForm() return render(request, 'homepage/homepage.html', {"form": form}) all help would be appreciated thanks. sorry it just said i needed more details so im writing random letters. -
Accessing a static file in django from a filename in a for loop
I'm writing an application that obtains a filename from a database and outputs the associated image. However, django templates seems to be having trouble parsing my requests Here is the django view: def nii2(request): conn_str_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'connection_string.txt') connection_string = open(conn_str_file).read() cursor = db.connect(connection_string).cursor() sql = ''' SELECT img.[djangoFileLoc] FROM [image_locations$] img, [Metadata$] meta WHERE img.[originalFileName] = meta.[originalFileName] ''' if 'Machine' in request.GET: sql += 'AND Machine = %r' % request.GET['Machine'] if 'Dir' in request.GET: if request.GET['Dir'] != 'Both': sql += ' AND Dir = %r' % request.GET['Dir'] sql += ' ORDER BY img.[originalFileName]' djangoImages = [] sql += ';' data = cursor.execute(sql) for row in data: djangoImages.append(row[0]) context = {"imageLoc": djangoImages[0:21]} return render(request, 'template.html', context) Here is template.html: {% extends "images.html" %} {% load staticfiles %} {% block images %} {% for img in imageLoc %} <a><img onmouseover="previewFunction('{% static '{{img}}' %}', 'Image One', 'Detailed info on Image one')" src='{% static '{{img}}' %}' title ="Image 1"/></a> {% endfor %} {% endblock %} This is what the output source comes out as: <a><img onmouseover="previewFunction('/static/%7B%7Bimg%7D%7D', 'Image One', 'Detailed info on Image one')" src='/static/%7B%7Bimg%7D%7D' title ="Image 1"/></a> <a><img onmouseover="previewFunction('/static/%7B%7Bimg%7D%7D', 'Image One', 'Detailed info on Image one')" src='/static/%7B%7Bimg%7D%7D' title ="Image 1"/></a> <a><img onmouseover="previewFunction('/static/%7B%7Bimg%7D%7D', 'Image … -
How do I 'cleanly' create this Django/DRF serialization relationship between models?
I've read that circular imports is a 'code smell' and is fundamentally a bad design choice. I have an app that has models, User, Deck, Hand. I want the User to be able to create a Hand without needing to create a Deck, but also give the User the choice to put the Hand in the Deck if wanted. So I end up with something like this: models.py: class User(AbstractUser): pass class Deck(models.Model): created = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=100, unique=True, blank=False, null=False) user = models.ForeignKey('users.User', related_name='decks', on_delete=models.CASCADE, null=False) class Hand(models.Model): created = models.DateTimeField(auto_now_add=True) deck = models.ForeignKey('goals.Deck', related_name='hands', on_delete=models.CASCADE, null=True) name = models.CharField(max_length=100, blank=False, null=False) user = models.ForeignKey('users.User', related_name='hands', on_delete=models.CASCADE, null=False) serializers.py: class HandSerializer(serializers.HyperlinkedModelSerializer): user = serializers.ReadOnlyField(source='user.username') deck = serializers.CharField(required=False, source='deck.name') class Meta: model = Hand fields = ('url', 'id', 'created', 'deck', 'name', 'user') extra_kwargs = { 'url': { 'view_name': 'goals:hand-detail', } } class DeckSerializer(serializers.HyperlinkedModelSerializer): user = serializers.ReadOnlyField(source='user.username') hands = HandSerializer(many=True, read_only=True) class Meta: model = Deck fields = ('url', 'id', 'created', 'name', 'user') extra_kwargs = { 'url': { 'view_name': 'goals:deck-detail', } } class UserSerializer(serializers.HyperlinkedModelSerializer): decks = DeckSerializer(many=True) hands = HandSerializer(many=True) ... Is this the correct approach API-design-wise in order to achieve what I want app-design-wise? If not, how should I …