Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
set slug field form manually in views Django
I'm new in Django and I'm trying to pre fill one of the fields of my form with a slug. I'm getting the slug from another model. I'm not using ForeignKey because that shows me a list with my objects and I want to save in the form the same slug that I'm using in the url. Maybe I'm not thinking this right. What should I do? Thank you! This are my models: from django.db import models class Thing(models.Model): name = models.CharField(max_length=255,) rut = models.CharField(max_length=12, blank= True) cel = models.CharField(max_length=12, blank= True) slug = models.SlugField(unique=True) class Control(models.Model): id_p = models.SlugField() pa = models.CharField(max_length=3,) My forms from django.forms import ModelForm from collection.models import Thing, Control, Medicamento class ThingForm(ModelForm): class Meta: model = Thing fields = ('name', 'rut','cel','pet',) class ControlForm(ModelForm): class Meta: model = Control fields = ('id_p', 'pa',) This is what I'm doing in the views def add_control(request, slug): thing = Thing.objects.get(slug=slug) form_class = ControlForm form_class(initial={'id_p':thing}) if request.method == 'POST': form = form_class(request.POST) if form.is_valid(): form.save() return redirect('thing_detail', slug=thing.slug) else: form = form_class() return render(request, 'things/control.html', { 'thing': thing, 'form': form, }) -
How to put disabled attribute inside input?
In my form I use MultipleChoiceField. It shows data from tuple CHOICES. forms.py: CHOICES = ( ('A', 'Name A'), ('B', 'Name B'), ('C', 'Name C'), ) class SomeForm(forms.ModelForm): symbol = forms.MultipleChoiceField(required=False, widget=forms.CheckboxSelectMultiple, choices=CHOICES,) class Meta: model = SomeModal fields = ('symbol',) MultipleChoiceField generate in template this html: <ul id="id_symbol"> <li> <label for="id_symbol_0" disabled=""> <input id="id_symbol_0" name="symbol" value="A" type="checkbox">Name A </label> </li> <li> <label for="id_symbol_1" disabled=""> <input id="id_symbol_1" name="symbol" value="B" type="checkbox">Name B </label> </li> <li> <label for="id_symbol_2" disabled=""> <input id="id_symbol_2" name="symbol" value="C" type="checkbox">Name C </label> </li> </ul> QUESTION: Is it possible to add disabled attribute to one of input element?! For example: <input id="id_symbol_2" name="symbol" value="C" type="checkbox" disabled> -
How to pass parameter to view method using {% 'url' %} syntax in django
In my url.py: url(r'hardware/common_report/(?P<line_id>[a-zA-Z]+)', 'Report.views.hardware_common_report', name='hardware_common_report'), In my view.py: def hardware_common_report(request): return render_to_response('Report/hardware/common_report.html') HTML: {% for report in reports %} <div class="col s12 m4 l4 waves-effect waves-green"> <div class="card cardMarPad light-green darken-4"> <a href="{% url 'hardware_common_report' report.report_display_name %}"> <div class="card-content white-text"> <span class="card-title">{{ report.report_display_name }}</span> <p class="descri">&nbsp;</p> </div> </a> </div> </div> {% endfor %} I'm getting this error: NoReverseMatch at /report/hardware/ Reverse for 'hardware_common_report' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['report/hardware/common_report/(?P[a-zA-Z]+)'] -
sending json from django to d3.js
i am trying to pass a queryset in django's views.py to d3.js. views.py : def index(request): qs = DCPOWERSTATS.objects.all().values('TS','PuE').order_by('TS') return render(request, 'dashboard/dash.html', context=qs}) dash.html : <!DOCTYPE html> <meta charset="utf-8"> <style> .chart div { font: 10px sans-serif; background-color: steelblue; text-align: right; padding: 3px; margin: 1px; color: white; } </style> <div class="chart"></div> <script src="//d3js.org/d3.v3.min.js"></script> <script> var data = {{ data_json }}; var x = d3.scale.linear() .domain([0, d3.max(data)]) .range([0, 420]); d3.select(".chart") .selectAll("div") .data(data) .enter().append("div") .style("width", function(d) { return x(d) + "px"; }) .text(function(d) { return d; }); </script> I need to make changes in views.py and dash.html to create something like : https://bl.ocks.org/mbostock/3885304 All previous answers are confusing.I need a solution for views.py as well as dash.html. I also need to know the perfect way of sending queryset results to javascript. Thanks! -
Django multiple pluralization
Im quite new to django so can`t really figure out how to define multiple pluralization forms for some object. Here is my models.py from django.core.validators import MinValueValidator, MaxValueValidator from django.db import models class Bancnote(models.Model): HRYVNA = 'Гривня' KARBOVANETS = 'Карбованець' TYPE_CHOICES = ( (HRYVNA, 'Гривня'), (KARBOVANETS, 'Карбованець') ) type = models.CharField(max_length=11, choices=TYPE_CHOICES, default=HRYVNA) par = models.PositiveIntegerField() year_from = models.PositiveIntegerField() year_to = models.PositiveIntegerField() size = models.CharField(max_length=7) sign = models.CharField(max_length=20) desc = models.TextField(max_length=200) image = models.ImageField(upload_to='bons_images') def __str__(self): return str(self.par) + ' ' + self.type + ' ' + str(self.year_from) + '-' + str(self.year_to) As you can see there will be 2 options of type: HRYVNA, KARBOVANETS. And the form of this words depends on bancnote par. So the rule for possible forms in ukrainian language could be next: if Bancnote.par == 1: name = 'Гривня' elif Bancnote.par == 2 or 3 or 4: name = 'Гривні' elif Bancnote.par > 4: name = 'Гривень' The same for KARBOVANETS. I was reading django docs here: https://docs.djangoproject.com/en/1.11/topics/i18n/translation/#pluralization But didn`t find step by step solution for this. Please help! Thaks a lot in advance for any help. Here is my template 'index.html' if needed {% extends 'catalogue/base.html' %} {% load i18n %} {% block title … -
How can I select records n-at-a-time for multiple users to edit?
I am using a Django backend with postgresql. Let's say I have a database with a table called Employees with about 20,000 records. I need to allow multiple users to edit and verify the Area Code field for every record in Employees. I'd prefer to allow a user to view the records, say, 30 at a time (to reduce burnout). How can I select 30 records at a time from Employees to send to the front end UI for editing, without letting multiple users edit the same records, or re-selecting a record that has already been verified? I don't need comments on the content of the database (these are example table and field names). -
Django and docker, ImportError: Could not import settings '"config"' Is it on sys.path?
I'm step by step switching my django project to work on local from vagrant to docker. With docker, you don't need a virtualenv. Even if I find it very convenient I'm facing some new troublesome issues. The main one is this error on ./manage.py cmd: ImportError: Could not import settings '"config"' (Is it on sys.path? Is there an import error in the settings file?): No module named '"config"' So when I start the python console code and type: >> import sys >> sys.path >> ['', '/usr/lib/python3.4', '/usr/lib/python3.4/plat-x86_64-linux-gnu', '/usr/lib/python3.4/lib-dynload', '/usr/local/lib/python3.4/dist-packages', '/usr/lib/python3/dist-packages'] But my path project is: /var/www/webapps/wrapper_website/app I've a setup environment loaded on docker-compose up which contain: DJANGO_CONFIGURATION="LocalContent" And that's what I'm trying to reach. The config folder is in: /var/www/webapps/wrapper_website/app/config I've tried this in the wsgi.py: import os import sys os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config") os.environ.setdefault("DJANGO_CONFIGURATION", "Production") sys.path.insert(0, os.path.abspath(os.path.dirname(os.path.dirname(__file__)))) <- this line from configurations.wsgi import get_wsgi_application application = get_wsgi_application() Without success. -
django ajax post to unexpect url
my ajax as follow: <script> $(document).ready(function () { $.ajaxSetup({ data: {csrfmiddlewaretoken: '{{ csrf_token }}'} }); $("#submit").submit(function () { var title = $("#title").val(); var body = $("#body").val(); var images = $("#browsefile")[0].files[0]; $.ajax({ type: "POST", data: {title: title, body: body, images: images}, url: "{% url 'xxxxx' %}", success: function (result, statues, xml) { alert(result); }, error: function () { alert("false"); } }) }) }) </script> and my urls pattern as follow: url(regex=r'^add/$', view=views.add, name='bbb'), url(regex=r'^newBlog/$', view=views.addblog, name='xxxxx'), I except ajax post data to the method addblog, but I get POST /add/ HTTP/1.1 instead. anyone can told me where i made a mistake, thanks! -
Do dynamically drop down filtering from queryset of a models.ModelChoiceField on a forms.Form
Hi I'm trying to build a drop down template where we can filtering. The order is the following one: University --> degree --> markDegree When we will choose a University in the following select or dropdown menu we only can choose the dregree of this University and in the markDegree we will see the mark of this degree recently select. My model is te following one: class Universitys(models.Model): university = models.CharField(max_length=50) degree = models.CharField(max_length=50) degreeMark = models.DecimalField(decimal_places=3,max_digits=5) the form: class Universities(forms.Form): #class Meta: Universidades = forms.ModelChoiceField(label='Escoge Universidad',queryset=Universitys.objects.values_list('university',flat=True)) Carreras = forms.ModelChoiceField(label='Escoge Carrera',queryset=Universitys.objects.values_list('degree',flat=True)) #class Carreras(forms.Form): def __init__(self, *args, **kwargs): qs = kwargs.pop('Universitys') super(Universities, self).__init__(*args, **kwargs) self.fields['Carreras'].queryset = qs#Universitys.objects.values_list('degree',flat=True) and the views: def prueba(request): universitys = Universities(request.POST or None) context = {"form":universitys, } return render(request,"prueba.html", context) I've tried to do different foms, but without solution, is the first time that I try to built this if you can help me I'm grateful with you. -
Page not found with Django (404)
in my django project,when i access localhost:8000 it say: Page not found (404) Request Method: GET Request URL: http://localhost:8000/ the urls.py is: from django.conf.urls import include, url from django.contrib import admin from polls import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^polls/', include('polls.urls', namespace="polls")), ] polls urls.py is: from django.conf.urls import url, include from django.contrib import admin from polls import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(?P<question_id>\d+)/$', views.detail, name='detail'), url(r'^(?P<question_id>\d+)/vote/$', views.vote, name='vote'), url(r'^(?P<question_id>\d+)/results/$', views.results, name='results'), url(r'^admin/', admin.site.urls), ] the django version is 1.10 what's problems ,thanks in advance -
Django static files do not resolve constant 404 errors
I am new to Django current version I'm running is 1.11 with python 3. I have configured the static file stuff as the docs suggest. Inside installed apps I have 'django.contrib.staticfiles' nonprofit/nonprofit/settings.py # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' STATICFILES_DIR = ( os.path.join(BASE_DIR, "static/"), ) And django seems to be working as far as putting the right path in the template. Though even if I hardcode the path into the template the browser still gives a 404 not found. I have a base.html template, with some css. {% load staticfiles %} <!--Bootstrap--> <link rel="stylesheet" href="{% static 'css/bootstrap.css' %}"> <link rel="stylesheet" href="/static/css/bootstrap-theme.css"> My directory structure is -- nonprofit - goals - nonprofit - static - css bootstrap.css bootstrap-theme.css - templates base.html db.sqlite3 manage.py From the browser it shows both 404 not found errors as well as not being able to go straight to the files- GET http://127.0.0.1:8000/static/css/bootstrap.css 127.0.0.1/:19 GET http://127.0.0.1:8000/static/css/bootstrap-theme.css 127.0.0.1/:20 I don't think the problem is with django because it shows the right path, but even the hardcoded one cannot be accessed through the browser. I'm running the development server. Whats going on with this stuff? Do I have something wrongly … -
Djano group by month name
I want to get an output of {'month': 'jan', 'count': 1600} but I get the following with the current code {'month': 1, 'count': 1600}. How do I do this so I get the name of the month and not the integer. class Month(Func): function = 'EXTRACT' template = '%(function)s(MONTH from %(expressions)s)' output_field = IntegerField() Note.objects.filter( email_status__in=status_list, email_template__isnull=False, creation_time__gt=one_year ).annotate( month=Month('creation_time') ).values('month').annotate( total_count=Count( 'email_id', distinct=True) ).values('total_count', 'month') -
Django for loop in html template not displaying
So I am trying to get the latest post and I ran into a problem where it will not display the post views.py def latest_post(request): latest = Post.objects.all().order_by('-id')[:1] context = {'latestPost': latest} return render(request, 'latest_post.html', context) Note: I also tried it with this, latest = Post.objects.all() There are entries in the database, I tested with the shell from blog.models import Post >>> Post.objects.all() <QuerySet [<Post: test>, <Post: okay so>, <Post: okay-okay>]> latest_post.html {% for newest in latestPost %} <section class="hero is-primary is-medium"> <div class="hero-body header"> <div class="container"> <div class="font"> <h1 class="title is-1"> <span id="blog_title">{{ newest.title }}</span> </h1> <h2 class="subtitle is-3 subup"> <span id="blog-subtitle">{{ newest.content|truncatechars:20|safe }}</span> </h2> <h2 class="subtitle is-5 dateup"> <span id="blogdate">{{ newest.timestamp }}</span><br><br> <a href="{{ newest.blog_url }}" class="button is-danger is-large is-inverted">Read More >></a> </h2> </div> </div> </div> </section> {% endfor %} in my blog_index.html I have the following {% extends "blog_base.html" %} {% block blog_main %} {% load staticfiles %} {% include 'latest_post.html' %} <p> other html here </p> {% endblock %} Latest_post.html displays when i use {% include 'latest_post.html' %} only if I don't use {% for newest in latestPost %} {% endfor %} So i am sure there aren't any typos somewhere that prevents the latest_post.html from … -
How can I make search form to filter items by location with Django?
I want to make search location form like Gumtree. In this website, if we put some words like "sy" to search location box, it shows "Inner Sydney, NSW", "Mount Sylvia 4343, QLD" like this. How can I make this with Django? And How can I prepare name of states, regions, cities? Is this made by using geo something and jQuery? -
Django template not displaying looped keys, values
I'm very new to Django and am trying to figure out why I can call the keys in a dict in my template as expected, but looping through the dict does not produce any text, nor any error messages. I don't want to hard code the key names (i.e. below msgid in my template, because the dict is dynamic and so I only want to loop through it. views.py class Pymat_program(View): def get(self, request, *args, **kwargs): selected_xml = 'a_directory_to_my_file' smsreport_dict = self.parse_xml_file(selected_xml) html = self.populate_html_text(smsreport_dict) return HttpResponse(html) def populate_html_text(self, smsreport_dict): t = get_template('template2.html') html = t.render(smsreport_dict) return html template2.html <p>MSGID: {{ msgid }}</p> <p> Begin {% for key, value in smsreport_dict %} <tr> <td> Key: {{ key }} </td> </tr> {% endfor %} </p>End In the template2.html you can see the msgid value (one of several values in smsreport_dict) being called, which is displayed on my page. But for some reason the smsreport_dict looping produces no text. Where am I going wrong? -
Django latex template with images
I'm trying to generate pdf from django latex template. To do so I'm using the code from here: So I have this code in views.py context = {....} template = get_template('my_latex_template.tex') rendered_tpl = template.render(context).encode('utf-8') with tempfile.TemporaryDirectory() as tempdir: for ppp in range(2): process = Popen( ['pdflatex', '-output-directory', tempdir], stdin=PIPE, stdout=PIPE, stderr=PIPE, ) process.communicate(rendered_tpl) with open(os.path.join(tempdir, 'texput.pdf'), 'rb') as f: pdf = f.read() r = HttpResponse(content_type='application/pdf') r.write(pdf) Here is my_latex_template.tex {% autoescape on %} \documentclass[a4paper,12pt]{article} \usepackage[T1,T2A]{fontenc} \usepackage[utf8]{inputenc} \usepackage[english,russian]{babel} \usepackage{graphicx} \begin{document} blabla \includegraphics{img.png} \end{document} {% endautoescape %} The structure of my directories: myapp |..templates |..|..my_latex_template.tex |..|..img.png |..views.py ... When compiling this latex template without \includegraphics{img.png}, everything works perfect. When compiling it with the image, I'm getting error that [Errno 2] No such file or directory: '/var/folders/73/r8hl47ld11l68v_1kjh_m61m0000gn/T/tmprfp7wf_x/texput.pdf' That basically means that this temporary file is not generating correctly by running pdflatex on rendered template... When I'm just running locally in terminal "pdflatex my_latex_template.tex" everything works fine and I'm getting pdf with the image. Do you have any ideas on what can I do? I would be super grateful if someone could help me. Thank you -
create site as alltop.com with django
way or package for create a site example site: www.alltop.com with framework django. for Implementation of these sites with Django framework, what measures should be taken? this site alltop use rss for give post tnx -
What is the "Best Practice" for invoice calculations in Django 1.10+?
If one has two models: class Invoice(models.Model): class Meta: ordering = ('-date_added', ) number = models.CharField(max_length=10,) comments = models.TextField(blank=True, help_text="Notes about this invoice." ) total = models.DecimalField(max_digits=9, decimal_places=2, default="0" ) date_added = models.DateTimeField(_('date added'), auto_now_add=True) date_modified = models.DateTimeField(_('date modified'), auto_now=True) def __unicode__(self): return "%s: total %s" % (self.number, self.total) class Part(models.Model): for_invoice = models.ForeignKey(Invoice) description = models.CharField(max_length=200, blank=True, help_text=_("Briefly describe the part.") ) supplier = models.CharField(max_length=100, blank=True, help_text=_("Supplier Name.") ) supplier_number = models.CharField(max_length=100, blank=False, help_text=_("Supplier's order number.") ) qty = models.DecimalField(max_digits=3, decimal_places=0, blank=False, null=False, help_text=_("How many are needed?") ) cost = models.DecimalField(max_digits=7, decimal_places=2, blank=True, null=True, help_text=_("Price paid per unit") ) line_total = models.DecimalField(max_digits=9, decimal_places=2, default="0") date_added = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) def __unicode__(self): return "%s: total %s" % (self.for_invoice, self.line_total) First choice I see is one could implement "line_total" or "total" as a calculated model field. But if you do that, then you cannot ever sort the change list by "line_total" or "total", and the users want to be able to do that. So I made them a saved field on the model. Reading the Django 1.10 docs I see 3 places where code can be defined to calculate and update the "total" and "line_total" fields: ModelAdmin.save_model(request, obj, form, change) … -
Django celery scheduled task django.core.exceptions.ImproperlyConfigured
I am trying to run this scheduled task and when i run this command the following error occurs. celery -A Htweetprod2 beat According to celery4.0 documentation to start the schedule this command should run, yet i am getting this error: C:\Users\hisg316\Desktop\Htweetprod2>celery -A Htweetprod2 beat Traceback (most recent call last): File "c:\python27\lib\runpy.py", line 174, in _run_module_as_main "__main__", fname, loader, pkg_name) File "c:\python27\lib\runpy.py", line 72, in _run_code exec code in run_globals File "C:\Python27\Scripts\celery.exe\__main__.py", line 9, in <module> File "c:\python27\lib\site-packages\celery\__main__.py", line 14, in main _main() File "c:\python27\lib\site-packages\celery\bin\celery.py", line 326, in main cmd.execute_from_commandline(argv) File "c:\python27\lib\site-packages\celery\bin\celery.py", line 488, in execute_from_commandline super(CeleryCommand, self).execute_from_commandline(argv))) File "c:\python27\lib\site-packages\celery\bin\base.py", line 281, in execute_from_commandline return self.handle_argv(self.prog_name, argv[1:]) File "c:\python27\lib\site-packages\celery\bin\celery.py", line 480, in handle_argv return self.execute(command, argv) File "c:\python27\lib\site-packages\celery\bin\celery.py", line 412, in execute ).run_from_argv(self.prog_name, argv[1:], command=argv[0]) File "c:\python27\lib\site-packages\celery\bin\base.py", line 285, in run_from_argv sys.argv if argv is None else argv, command) File "c:\python27\lib\site-packages\celery\bin\base.py", line 367, in handle_argv *self.parse_options(prog_name, argv, command)) File "c:\python27\lib\site-packages\celery\bin\base.py", line 403, in parse_options self.parser = self.create_parser(prog_name, command) File "c:\python27\lib\site-packages\celery\bin\base.py", line 419, in create_parser self.add_arguments(parser) File "c:\python27\lib\site-packages\celery\bin\beat.py", line 114, in add_arguments '-s', '--schedule', default=c.beat_schedule_filename) File "c:\python27\lib\site-packages\celery\utils\collections.py", line 130, in __getattr__ return self[k] File "c:\python27\lib\site-packages\celery\utils\collections.py", line 431, in __getitem__ return getitem(k) File "c:\python27\lib\site-packages\celery\utils\collections.py", line 280, in __getitem__ return mapping[_key] File "c:\python27\lib\UserDict.py", line … -
Microservices with shared database? using multiple ORM's?
I'm learning about microservices and im gonna build a proyect with a microservices arquitecture. The thing is, one of my team mates want to use one database for all services, sharing all tables so "data doesnt get repeated", each service would be built with differente frameworks and lenguages like django and rails, wich use very different ORM standards. What would be the correct aproach? since i think working with one database would involve a lot of "hacking" the orms in order to make them work correctly. -
Local field 'created_at' in class 'Attachment' clashes with field of similar name from base class 'Timestampable'
I have the following two models: class Timestampable(models.Model): created_at = models.DateTimeField(null=True, default=None) updated_at = models.DateTimeField(null=True, default=None) class Meta: abstract = True def save(self, *args, **kwargs): now = timezone.now() if not self.created_at: self.created_at = now self.updated_at = now super(Timestampable, self).save(*args, **kwargs) class Attachment(Timestampable, models.Model): uuid = models.CharField(max_length=64, unique=True) customer = models.CharField(max_length=64) user = models.CharField(max_length=64) file = models.FileField(upload_to=upload_to) filename = models.CharField(max_length=255) mime = models.CharField(max_length=255) publicly_accessible = models.BooleanField(default=False) When I try to migrate these models, I get the following error: django.core.exceptions.FieldError: Local field 'created_at' in class 'Attachment' clashes with field of similar name from base class 'Timestampable' I read here, here, and here that this should work when the base class is abstract. However, I marked it as abstract it still it doesn't seem to work. What else could be wrong? I am using Django 1.8.14. -
Django: Bokeh.safely is not a function
I was trying to embed a bokeh plot into my django app. I followed the instructions given here and here. I am getting the following error on my browser console and not getting any plot output: Uncaught TypeError: Bokeh.safely is not a function at HTMLDocument.fn (localhost/:15) I am not a JS guy but Bokeh.safely is present in the script generated by Bokeh. I have attached the script generated at the end: My views.py file: from django.shortcuts import render from bokeh.plotting import figure from bokeh.resources import CDN from bokeh.embed import components def showGraph(request): arr = [1,4,9,16,25,36] y = [1,2,3,4,5,6] plot = figure() plot.line(arr, y) script, div = components(plot, CDN) return render(request, "data_collection/simple_chart.html", {"script": script, "div": div}) simplechart.html file: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Bokeh example</title> <link rel="stylesheet" href="http://cdn.pydata.org/bokeh/release/bokeh-0.12.0.min.css"> <link rel="stylesheet" href="http://cdn.pydata.org/bokeh/release/bokeh-widgets-0.12.0.min.css"> <script src="http://cdn.pydata.org/bokeh/release/bokeh-0.12.0.min.js"></script> <script src="http://cdn.pydata.org/bokeh/release/bokeh-widgets-0.12.0.min.js"></script> {{ script | safe }} </head> <body> {{ div | safe }} </body> </html> Script generated by bokeh: (function(){ var fn = function(){ Bokeh.safely(function(){ var docs_json = {....json.....}; var render_items = [ {"docid": "27fe9292-3142-4617-b273-f9d932e47df3", "elementid": "7b2ef36e-a7d2-4a6b-88e6-186edecde6ca", "modelid": "741db3b0-26ce-45c1-86b4-d95394c7331f"}]; Bokeh.embed.embed_items(docs_json, render_items); }); }; if (document.readyState != "loading") fn(); else document.addEventListener("DOMContentLoaded", fn); })(); -
Serving Django CMS Admin Styles in Production with Apache
I made a simple site using Django CMS. Everything seems to work, except for the styles on the admin toolbar. They are not loading. What should I do to configure the app or server to serve them properly? Here is the settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'some secret here' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'djangocms_admin_style', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'cms', 'menus', 'treebeard', 'sekizai', 'filer', 'easy_thumbnails', 'mptt', 'djangocms_text_ckeditor', 'djangocms_link', 'djangocms_file', 'djangocms_picture', 'djangocms_video', 'djangocms_googlemap', 'djangocms_snippet', 'djangocms_style', 'djangocms_column', 'aldryn_bootstrap3', 'parler', 'aldryn_apphooks_config', 'aldryn_categories', 'aldryn_common', 'aldryn_newsblog', 'aldryn_people', 'aldryn_reversion', 'aldryn_translation_tools', 'sortedm2m', 'taggit', 'reversion', 'aldryn_boilerplates', 'absolute', 'aldryn_forms', 'aldryn_forms.contrib.email_notifications', 'captcha', 'emailit', ) MIDDLEWARE_CLASSES = ( 'cms.middleware.utils.ApphookReloadMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.middleware.locale.LocaleMiddleware', 'cms.middleware.user.CurrentUserMiddleware', 'cms.middleware.page.CurrentPageMiddleware', 'cms.middleware.toolbar.ToolbarMiddleware', 'cms.middleware.language.LanguageCookieMiddleware', ) ROOT_URLCONF = 'iboyko.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'sekizai.context_processors.sekizai', 'cms.context_processors.cms_settings', ], }, }, ] WSGI_APPLICATION = 'app_name.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': … -
Install mysqlclient for Django Python on Mac OS X Sierra
I have already installed Python 2.7.13 Django 1.11 MySQL 5.7.17 I want use MySQL with Django, but after install mysql connector I was try to install mysqlclient for Python on $ pip install mysqlclient, but I have this issue: Collecting mysqlclient Using cached mysqlclient-1.3.10.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/var/folders/y_/c31n_1v12v169zfv829p_v_80000gn/T/pip-build-f51KhW/mysqlclient/setup.py", line 17, in <module> metadata, options = get_config() File "setup_posix.py", line 54, in get_config libraries = [dequote(i[2:]) for i in libs if i.startswith('-l')] File "setup_posix.py", line 12, in dequote if s[0] in "\"'" and s[0] == s[-1]: IndexError: string index out of range ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/y_/c31n_1v12v169zfv829p_v_80000gn/T/pip-build-f51KhW/mysqlclient/ -
duplicate key value violates unique constraint "wagtailcore_page_path_key" DETAIL: Key (path)=(0001) already exists
I am working on a system that has been developed by someone else based on Django and wagtail. I managed to import data to postgresql but I believe not everything was imported since I get an error when I try to migrate data. Here is the error I get: # python manage.py migrate /root/Desktop/Projects/sautimtaani/sautivenv/local/lib/python2.7/site-packages/treebeard/mp_tree.py:102: RemovedInDjango18Warning: `MP_NodeManager.get_query_set` method should be renamed `get_queryset`. class MP_NodeManager(models.Manager): /root/Desktop/Projects/sautimtaani/sautivenv/local/lib/python2.7/site-packages/django/forms/widgets.py:143: RemovedInDjango18Warning: `TaskMonitor.queryset` method should be renamed `get_queryset`. .__new__(mcs, name, bases, attrs)) /root/Desktop/Projects/sautimtaani/sautivenv/local/lib/python2.7/site-packages/djcelery/loaders.py:192: UserWarning: Autodiscover: Error importing sauti_mtaani.apps.core.app.CoreConfig.tasks: ImportError('No module named CoreConfig',) app, related_name, exc, /root/Desktop/Projects/sautimtaani/sautivenv/local/lib/python2.7/site-packages/djcelery/loaders.py:192: UserWarning: Autodiscover: Error importing sauti_mtaani.apps.sauti_mtaani_main.app.SautiMtaaniMainConfig.tasks: ImportError('No module named SautiMtaaniMainConfig',) app, related_name, exc, /root/Desktop/Projects/sautimtaani/sautivenv/local/lib/python2.7/site-packages/djcelery/admin.py:256: RemovedInDjango18Warning: Creating a ModelForm without either the 'fields' attribute or the 'exclude' attribute is deprecated - form PeriodicTaskForm needs updating class PeriodicTaskForm(forms.ModelForm): /root/Desktop/Projects/sautimtaani/sautivenv/local/lib/python2.7/site-packages/django/forms/widgets.py:143: RemovedInDjango18Warning: `PeriodicTaskAdmin.queryset` method should be renamed `get_queryset`. .__new__(mcs, name, bases, attrs)) Operations to perform: Synchronize unmigrated apps: wagtailsnippets, compressor, modelcluster, djcelery, django_extensions Apply all migrations: core, wagtailusers, wagtailembeds, wagtailadmin, sauti_mtaani_main, sessions, admin, polls, auth, wagtailcore, contenttypes, wagtaildocs, taggit, wagtailsearch, wagtailforms, wagtailredirects, wagtailimages Synchronizing apps without migrations: Creating tables... Installing custom SQL... Installing indexes... Running migrations: Applying wagtailcore.0002_initial_data...Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/root/Desktop/Projects/sautimtaani/sautivenv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line utility.execute() …