Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Compiled Sass files not found by Django-pipeline
I'm having trouble with running django-pipeline because I keep receiving errors similar to: ValueError: The file 'css/main.b7ade0b8392c.css' could not be found with <pipeline.storage.PipelineCachedStorage object at 0x7f66c22ef550>. When I perform an ls operation in my css folder, the css file that is present is called main.c2b6ea9fa0e1.css, which is different from the file that django-pipline is looking for. My django-pipeline configuration looks like this: PIPELINE = { 'PIPELINE_ENABLED': True, 'STYLESHEETS': { 'main': { 'source_filenames': ( 'css/main.scss', ), 'output_filename': 'css/main.css' }, 'COMPILERS': ( 'pipeline.compilers.sass.SASSCompiler', ), 'CSS_COMPRESSOR': 'pipeline.compressors.NoopCompressor', 'JS_COMPRESSOR': 'pipeline.compressors.NoopCompressor' } This problem only seems to be happening when I have DEBUG=False. I try to perform python manage.py collectserver before restarting the Apache server, but to no avail. I'm using Apache, Django 1.9.9, Python 2.7. -
How can I send form data to test.html by using asynchronous communication?
I wanna send form data to test.html by using asynchronous communication. I wrote in index.html <body> <form method="post" action=""> <select id="mainDD" data-placeholder="Choose" class="chzn-select" style="width:600px;"> {% for i in json_data.items.values %} <option value="{{forloop.counter}}">{{ i }}</option> {% endfor %} </select> {% for key, values in preprocessed %} <select name="type" id=type{{forloop.counter}}> {% for counter, value in values %} <option value="{{forloop.counter}}">{{ value }}</option> {% endfor %} </select> {% endfor %} </form> <script type="text/javascript"> $(document).ready(function () { $('#mainDD').on('change', function() { var thisType = "type" + $(this).val(); for(i=1; i<6; i++) { var thisId = "type" + i; if(thisType !== thisId) { $("#"+thisId).hide(); } else { $("#"+thisId).show(); } } }).trigger('change'); }); </script> <form id="postform" action="http://localhost:8000/app/test_view" method="POST"> {% csrf_token %} <input type="submit" value="SEND"> </form> <script type="text/javascript"> $('[name=type]').change(function() { var array1 = []; var array2 =[]; $('[name=main] option:selected').each(function() { array1 = $(this).text(); console.log(array1); }); $('[name=type] option:selected').each(function() { array2 = $(this).text(); console.log(array2); }); }); $.ajax({ url: 'test.html', dataType: 'html', timeout:3000, async: true, success: function(html) { $('.newsarea').html(html).fadeIn(5000); }, error: function() { alert('Error'); } }); </script> </body> I wanna send selected i & value's variables to test.html.Now when I put send button,nothing is shown in test.html. I wrote test.html like <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>RESULT</title> </head> <body> <h2>TOPIC</h2> <div … -
Django: Storing Images Database
Earlier I was using default database sqlite3, but today i've changed it to postgresql. I wants to save the image files in database not in project directory itself. How can I do that? Thank You :) -
Django admin search for multi-word phrase with ^ and = operators
Assume a model admin has: search_fields = ("^name", "=kind") If name is "Leonardo Da Vinci", it can be found using the query Leon or Leonardo, but not Leonardo Da or Leonardo Da Vinci. If kind is e.g. "polymath genius", such a value cannot be found with any query. Ideally, one would be able to post "multiple words" "Leonardo Da" and get this record; but given how Django splits the query, it doesn't do what one might expect. This problem was apparently raised 9 years ago in this ticket, and solved. Then Django got rewritten and apparently this got dropped somewhere. Does anyone have an idea if this is possible? I'm probably thinking I'd need to override ModelAdmin.get_search_results... Anything more elegant? -
Need help in understand Django-Facebook API and the Post extraction form a profile suing Python2
I am working on my machine learning project where I am in a great need to access the textual posts of the people from Facebook, of course with permission, and then process it to find the best personality traits. I am struggling to find a way to merge my application with something that can give me the post of the people from their profiles. Hence, I found something in the documentation of the Django-Facebook API. Here is the link for the documentation: http://django-facebook.readthedocs.io/en/latest/installation.html Here what I am not able to understand is how I can use this for extracting the post of the people? Can anyone give a small example that can be helpful in understanding what I can do to extract the text from the people profile and use it in my application. -
GAE: ImportError while using google-auth
I am using google-auth to allow firebase authentication in my GAE project. Everything works fine when I run the code locally using dev_appserver.py or when I deploy it to google app engine. But I get this ImportError exceptions when I try to use Django's manage.py script to create/run migrations. ```ImportError: Could not import 'firebase.authentication.FirebaseAuthentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'. ImportError: No module named auth.transport.requests. The google-auth module is installed under lib directory and has this structure: - lib - google - auth - oauth2 These import cause the ImportErrors: import google.auth.transport.requests from google.oauth2 import id_token My guess is that there might be naming conflicts as other imports work fine. Please help! -
Reverse for 'about' with no arguments not found
So I'm attempting to Django, and I've gotten a few urls working but one set just wont work. It keeps asking for a argument but it shouldn't require one. Error below. NoReverseMatch at / Reverse for 'about' with no arguments not found. 1 pattern(s) tried: ['$about/'] Error during template rendering In template hub\templates\partials\footer.html, error at line 33 hub\templates\partials\footer.html line 33 <a href="{% url 'hub:about' %}" class="nav__link">About</a> hub/urls.py urlpatterns = [ url(r'^$', views.HomePageView.as_view(), name='index') ] storyarchive/urls.py urlpatterns = [ url(r'^$', include('hub.urls', namespace='hub')) ] It worked before I started to use the {% url %} builtin. Django Version: 1.11.5 Python Version: 3.4.4 -
how to send data from HTML to python and get the result back to HTML?
I know nothing about the interface between HTML and python so I come here to ask for help hope you guys can help me. HTML are now post on apache server,and I visit this web by the address "http://127.0.0.1/name.html". Here is what I want to achieve: There is a form on HTML getting the data,and by clicking the button "submit",the data should be send to python.exe,and the python.exe runs itself and send the result back to HTML(by poping a new dialog). I searched on the Internet and was wondering will Django help?? Is this even possible?Can anybody help me ? -
Adding two fields while filtering and converting a field to an appropriate type
From this link I have Entry.objects.filter(mod_date__gt=F('pub_date') + timedelta(days=3)) While I want to achieve something like Entry.objects.filter(mod_date__gt=F('pub_date') + timedelta(seconds = F('delay'))) Here I have to combine two fields in the table while converting one to timedelta. I couldn't have F object as a timedelta seconds argument where it needs an integer. I want to have a filter where I can convert F type to integer while adding and filtering. Any help is appreciated. -
Django template tags filter by slug
I have a many-to-one relationship between organizations and events. One organization can have many events. I have a template for showing all events that everybody can see filtered by city. But I want the organization detail view to show events belonging only to a specific organization. models.py class Organization(models.Model): name = models.Charfield(max_length=27) slug = models.SlugField(max_length=25, null=True, blank=True) [...] def __unicode__(self): return self.name class Events(models.Model): org = models.ForeignKey(Organization, on_delete=models.CASCADE, default=1) time = models.DateTimeField(null=True, blank=True) city = models.CharField( max_length=25, choices = CITY_CHOICES, default = 'NY' ) [...] def __unicode__(self): return '%s %s' % (self.org, self.time) I use this template tag to filter events by city (NY for this one): @register.inclusion_tag('mysite/event_list.html') def event_ny_tag(event): return {'events': Events.objects.filter(linn='NY')} url.py urlpatterns = [ url(r'^$', HomePageView.as_view(), name='home'), url(r'^organizations/$', OrganizationList.as_view(), name='organizations'), url(r'^events/$', EventList.as_view(), name='events'), url(r'^(?P<slug>[-\w]+)/$', OrgDetailView.as_view(), name='org_detail'), ] But how can I filter events only by one specific organization? There are only two cities but 20 organizations. How to do it without hardcoding it? With a slug? This is not a copy paste. Just a sample code similar to mine. -
Django add aggregate operation to a query result
I'm trying to do an aggregate operation between two tables using Django, my models are: class Cusinetype(models.Model): hometype_en = models.TextField() active = models.BooleanField() hometype_es = models.TextField(blank=True, null=True) class Meta: managed = False db_table = 'cusinetype' class Foodpreferences(models.Model): id_client = models.ForeignKey(Client, models.DO_NOTHING, db_column='id_client') id_cusinetype = models.ForeignKey(Cusinetype, models.DO_NOTHING, db_column='id_cusinetype') created_at = models.DateTimeField() class Meta: managed = False db_table = 'foodpreferences' The query that I'm trying to build is: SELECT ct.id, ct.hometype_en, ct.hometype_es , ((SELECT COUNT(*) FROM foodpreferences fp WHERE fp.id_cusinetype = ct.id AND fp.id_client = 3 ) > 0 ) selected FROM Cusinetype ct I'm trying to generate a model, to store the information of those tables in a single one query, but anything works. Someone has an idea about how to do it? -
I cannot get an array when I put send button
I cannot get an array when I put send button. I wrote index.html <body> <form method="post" action=""> <select id="mainDD" data-placeholder="Choose" class="chzn-select" style="width:600px;"> {% for i in json_data.items.values %} <option value="{{forloop.counter}}">{{ i }}</option> {% endfor %} </select> {% for key, values in preprocessed %} <select name="type" id=type{{forloop.counter}}> {% for counter, value in values %} <option value="{{forloop.counter}}">{{ value }}</option> {% endfor %} </select> {% endfor %} </form> <script type="text/javascript"> $(document).ready(function () { $('#mainDD').on('change', function() { var thisType = "type" + $(this).val(); for(i=1; i<6; i++) { var thisId = "type" + i; if(thisType !== thisId) { $("#"+thisId).hide(); } else { $("#"+thisId).show(); } } }).trigger('change'); }); </script> <form id="postform" action="http://localhost:8000/app/test_view" method="POST"> {% csrf_token %} <input type="submit" value="SEND"> </form> <script type="text/javascript"> $('[name=type]').change(function() { var array = []; $('[name=alphabet] option:selected').each(function() { array.push($(this).text()); }); console.log(array); }); </script> </body> I wanna make a program when I put SEND button, array has variable of i&value are selected.But now array is empty although I selected these buttons, so how can I fix this?What should I write it? -
Multiple versions of web API. Separate models for each version?
I am implementing a web API with each API version defined in a separate Django app: foo.api.v1, foo.api.v2, etc. How should I structure the Django models modules? Separate foo.api.v1.models, foo.api.v2.models, etc.? A single foo.api.models module for all the versions? If it matters, I am using Django REST Framework to define the API. -
Django Security issue
So I have just completed my site, it is a basic social network. Each user has a profile and can edit their profile. However if a logged in user switches the user id in the edit url they can edit another users profile. So if I am logged in as user 1 I can edit my profile here: /user/1/edit However, if logged in as user 1 and I go to user 2's edit profile url here: /user/2/edit I can also edit their profile... How do I stop that?? -
How to inform a user that he is not active in Django login view
I'm creating a custom authentication app to Django, everything is fine, the user needs to verify email to set is_active True, this works like a charm, but once the user send the e-mail and the token expires, the user try to login and receive a message of user or pass incorrect, and I want to show the user has to activate the account and give a link to resend the activation token to his email. I'm using the default Login View: url(r'^login/$', auth_views.LoginView.as_view(template_name='accounts/login.html'), name='account_login') How can i modify this view or other thing to show the user is not active. -
Adding content between form in Formset_Factory = Django
I am working on a django application and more specifically, a formset (group of forms). I have the form set amount set the number of objects retrieved by a query set. What I want to do is make a change to the form set so that in between each of the forms in the formset, include a name for a user related to the form set. What is happening right now is that it is print the entire formset then the names that I want to move to be placed in between each of the forms in the formset. Here is what the form looks like: Add expense - restructured group Please complete the form below Amount: 0 Description: expense Amount: 0 Description: expense Amount: 0 Description: expense josh lifter omar submit I want to move the names to appear before the amount/description inputs Here is the code that I have: this is the views.py: def updateExpenseIndividual(request, groupId, groupName): currentUser = loggedInUser(request) currentProfile = Profile.objects.get(user = currentUser) currentGroup = Group.objects.get(id = groupId) host = Member.objects.filter(group = groupId).filter(status = 2).first() expenses = Expense.objects.filter(group = currentGroup).filter(name = groupName).all() expenses_count = Expense.objects.filter(group = currentGroup).filter(name = groupName).count() SplitFormSet = formset_factory(UpdateExpenseForm, extra=expenses_count) if request.method == … -
How to setup a DJANGO REST that requires information from a POST request?
I am trying to construct a class based Django REST API that takes in data from the POST request and outputs the relevent data. I have a list of buildings in the DB State Building California Golden Gate Bridge New York Empire State California TransAmerica New York Brooklyn Bridge The POST request will specify the state, and the API should output the appropriate building. I guess I'm just having a hard time understand how the class is taking in the request.data ['state_id']. Should I use APIView? So many questions! So far I have this in my view.py class BuildingViewSet(viewsets.ModelViewSet): queryset = BuildingRule.objects.values('building_name').distinct() serializer_class = BuildingSerializer def post(self, request, *args, **kwargs): queryset = BuildingRule.objects.filter(state_name=request.data['state_id']) return Response(queryset.values_list('building_name', flat=True)) This is in my serializer.py class BuildingSerializer(serializers.ModelSerializer): class Meta: model = BuildingRule fields = ('building_name',) This is my url.py: router.register(r'buildings', views.BuildingsViewSet, base_name='Building') -
Accessing user object when creating a user in Django
I'm using Django 1.10.6 and I'm working on a user registration form. During the validation process in my forms.py I'm trying to call the UserAttributeSimilarityValidator from within the clean method, but I'm having some trouble figuring out what the user object argument is that it requires. The request data is a QueryDict, not an object, so I'm confused as to what object I'm supposed to be using. Here is the UserAttributeSimilarityValidator class found in the link I provided class UserAttributeSimilarityValidator(object): DEFAULT_USER_ATTRIBUTES = ('username', 'first_name', 'last_name', 'email') def __init__(self, user_attributes=DEFAULT_USER_ATTRIBUTES, max_similarity=0.7): self.user_attributes = user_attributes self.max_similarity = max_similarity def validate(self, password, user=None): if not user: return for attribute_name in self.user_attributes: value = getattr(user, attribute_name, None) if not value or not isinstance(value, string_types): continue value_parts = re.split('\W+', value) + [value] for value_part in value_parts: if SequenceMatcher(a=password.lower(), b=value_part.lower()).quick_ratio() > self.max_similarity: verbose_name = force_text(user._meta.get_field(attribute_name).verbose_name) raise ValidationError( _("The password is too similar to the %(verbose_name)s."), code='password_too_similar', params={'verbose_name': verbose_name}, ) def get_help_text(self): return _("Your password can't be too similar to your other personal information.") Here's my clean method in forms.py def clean(self): cleaned_data = super(RegisterForm, self).clean() password = cleaned_data.get('password') password_validation.UserAttributeSimilarityValidator().validate(password, USER_OBJET_HERE) I tried to create a user object by using namedtuple like so user = namedtuple('user', 'username … -
How to keep form data when post fails and redirect with an error messages in Django?
I have been trying to look around but most answers are outdated. I have simple form and I am using python/django in my backend. index.html <form action="/add_blog" method="post"> <label for="title">Title</label> <input type="text" name="title" value=""> <label for="blog">Blog</label> <input type="text" name="blog" value=""> </form> There are more field there that when the form gets submitted and fails my backend validation, it will redirect back to 'index.html' and display some error messages. The question is, how can I preserve inputs so that when the post fails validation, the user won't lose their inputs and gives them time to edit their mistake. I have tried doing this: <form action="/add_blog" method="post"> <label for="title">Title</label> <input type="text" name="title" value="{{title}}"> <label for="blog">Blog</label> <input type="text" name="blog" value="{{blog}}"> </form> but it I need to pass a context on a redirect somehow. Is there a better and clean way to do this? Thanks a lot! -
How to ignore or handle django-hijack from the command line?
I'm writing some unit tests for an existing django project that has had no unit tests to date. When I run the tests from the command line using ./manage.py test I get Traceback (most recent call last): File "./manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 341, in execute django.setup() File "/usr/local/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python2.7/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named hijack Now hijack is actually installed as I can use it from the browser when I run the server using ./manage.py runserver So ... how I can disable the reference for hijack when running tests or how can I enable hijack to be available under the command line when running tests? (can someone create and add the tag django-hijack) -
Does searching by id depends on number of columns in postgres?
I have the following query: MyModel.objects.filter(id__in=ids). I noticed that increasing number of columns in table decreases speed of the above query. Why is that? -
How I access a table before select id of another table in Django
I'm new to Django and I was following the steps in the Django Projects Tutorial and adapting to my goal: creating a questionnaire but I am having a problem accessing the data from another table after selecting the test id. Here are the files (sorry for my English). models.p from django.db import models from django.utils.encoding import python_2_unicode_compatible class Prova(models.Model): idProva = models.CharField(max_length=5,primary_key=True,null=False) tipoProva = models.CharField(max_length=5,null=False) anoProva = models.CharField(max_length=4,null=False) def __str__(self): return self.idProva class Usuario(models.Model): matriculaUsuario = models.CharField(max_length=12,primary_key=True,null=False) nomeUsuario = models.CharField(max_length=200,null=False) tipoUsuario = models.CharField(max_length=1,null=False) emailUsuario = models.EmailField(null=False) senhaUsuario = models.CharField(max_length=20,null=False) def __str__(self): return self.matriculaUsuario class Questao(models.Model): idQuestao = models.CharField(max_length=7,primary_key=True,null=False) idProva = models.ForeignKey(Prova) areaQuestao = models.CharField(max_length=50,null=False) tipoQuestao = models.CharField(max_length=1,null=False) textoQuestao = models.CharField(max_length=500,blank=True,null=True) imagemQuestao = models.ImageField(null=True,blank=True) perguntaQuestao = models.CharField(max_length=200,blank=True,null=True) statusQuestao = models.CharField(max_length=1,null=False) def __str__(self): return self.idQuestao class Opcao(models.Model): idOpcao = models.CharField(max_length=8,primary_key=True,null=False) idQuestao = models.ForeignKey(Questao) aOpcao = models.CharField(max_length=200,null=False) bOpcao = models.CharField(max_length=200,null=False) cOpcao = models.CharField(max_length=200,null=False) dOpcao = models.CharField(max_length=200,null=False) eOpcao = models.CharField(max_length=200,null=False) escolhidaOpcao = models.CharField(max_length=200,null=True,blank=True) def __str__(self): return self.idOpcao class Historico(models.Model): idHistorico = models.CharField(max_length=10,primary_key=True,null=False) idProva = models.ForeignKey(Prova,null=False) matriculaUsuario = models.ForeignKey(Usuario,null=False) def __str__(self): return self.idHistorico class Resposta(models.Model): idResposta = models.CharField(max_length=9,primary_key=True,null=False) idQuestao = models.ForeignKey(Questao) matriculaUsuario = models.ForeignKey(Usuario) tipoResposta = models.CharField(max_length=1,null=False) certaResposta = models.CharField(max_length=1) textoResposta = models.CharField(max_length=1000) def __str__(self): return self.idResposta index.html <link rel="stylesheet" href="{% static 'polls/js/script.js' %}"> <link … -
How to receive RabbitMQ messages in a Django app? (Celery?)
We receive a RabbitMQ (or maybe Redis) message generated by an event external to our server. How to make our Django app to be notified on such event (and execute some our code)? Can it be done with Celery? -
d3 Bar chart with a tool tip is not working
I've been working with a D3 svg chart with built in tool tips (using the d3-tip library). The original code can be seen here: http://bl.ocks.org/Caged/6476579 I am using Django as back end and I am trying to populate log count as per year from datetime. I was successfully able to populate the axis and labels of the graph except the bars. Here is my html template called graph.html: <!DOCTYPE html> <meta charset="utf-8"> <style> body { font: 10px sans-serif; } .axis path, .axis line { fill: none; stroke: #000; shape-rendering: crispEdges; } .bar { fill: orange; } .bar:hover { fill: orangered ; } .x.axis path { display: none; } .d3-tip { line-height: 1; font-weight: bold; padding: 12px; background: rgba(0, 0, 0, 0.8); color: #fff; border-radius: 2px; } /* Creates a small triangle extender for the tooltip */ .d3-tip:after { box-sizing: border-box; display: inline; font-size: 10px; width: 100%; line-height: 1; color: rgba(0, 0, 0, 0.8); content: "\25BC"; position: absolute; text-align: center; } /* Style northward tooltips differently */ .d3-tip.n:after { margin: -1px 0 0 0; top: 100%; left: 0; } </style> <body> <script src="http://d3js.org/d3.v3.js"></script> <script src="http://labratrevenge.com/d3-tip/javascripts/d3.tip.v0.6.3.js"></script> <script> var margin = {top: 40, right: 20, bottom: 30, left: 40}, width = 960 - … -
Static site generator which updates in realtime
I’m trying to find a static site generator which is capable of updating static pages as changes are made to a django database. Would anyone known of an open source site generator which does this?