Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django cms - plugin manyToMany variable always empty
I wrote a simple plugin which display contact people, but I need to exclude some contact on certain pages. So I added a related model to my plugin which use an "structure_to_exclude" ManyToMany relationship. My issue, when I get this variable it's allways empty. The cms_plugins.py class VMContactContactPlugin(CMSPluginBase): module = 'VM Contact Plugin' render_template = 'vm_contact/calendars/contacts_list.html' model = VMContactCalendarPluginModel name = _('VM Contact plugin') def render(self, context, instance, placeholder): print 'Instance : {0}'.format(instance) inst = instance.structure_to_exclude.all() print 'Instance.all() result : {0}'.format(inst) structures = Structure.objects.exclude(contact=None).exclude(pk__in=instance.structure_to_exclude.all().values_list('id',flat=True)) context.update({ 'structures': structures, }) return context plugin_pool.register_plugin(VMContactContactPlugin) The related model class VMContactCalendarPluginModel(CMSPlugin): structure_to_exclude = models.ManyToManyField( Structure, verbose_name=_(u'Structures Γ exclure'), ) The Structure Models (Polymorphic !!) class Structure(PolymorphicModel): contact = models.ForeignKey(Contact, blank=True, null=True) members = models.ManyToManyField(Contact, blank=True, null=True, related_name='%(class)s_members') title = models.CharField(max_length=50, default='Castor') description = models.CharField(max_length=254, blank=True) categories = CategoryManyToManyField('aldryn_categories.Category', verbose_name=_('categories'), blank=True) calendars = models.ManyToManyField(Calendar, blank=True) has_pages = models.BooleanField(default=True) avatar = FilerFileField(null=True, blank=True, on_delete=models.SET_NULL) classcss = models.CharField(max_length=1, choices=CSS_CLASS, default='5') order = models.PositiveSmallIntegerField(default=0) class Meta: ordering = ['order'] Print results : Instance : 93 Instance.all() result : [] Any idea ? I tried to retrieve the plugin instance with the ID (93) to be sure that was not an issue with instance var but it doesn't change anything... β¦ -
How to dynamically pass instance into django form
I have a list of similar entries and for each entry I want to add editable comment. I've done it with multiple forms so far, but rendering lots of text fields is not a option. I want to make one jQuery Modal Dialog Form and load required data to it, set proper instance for this form. So user presses a comment and filled dialog form appears. Clicking on different comment should show same form with different data in it. How to do this in Django? -
Django AJAX parse json objects
I have a table, with items(name, price, status).I have a live search with ajax and i'm filtering query, it returns Json objects, how can i parse it and update my html table, which is loaded with objects already. $(function() { $('#search-item').keyup(function() { $.ajax({ type: "GET", url: "/constructprices/", data: { 'query' : $('#search-item').val(), 'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val() }, success: searchSuccess, dataType: 'json' }); }); }); function searchSuccess(data) { console.log(data); } -
Django REST Framework - Serialize nested relations on create
I have those two seralizers based on following models: class LanguageSerializer(serializers.ModelSerializer): class Meta: model = Language fields = '__all__' class GameSerializer(serializers.ModelSerializer): language = LanguageSerializer() class Meta: model = Game fields = '__all__' class Game(models.Model): language = models.ForeignKey(Language) class Language(models.Model): name = models.CharField(max_length=50, unique=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) When I try to create a new Game entity, I pass as parameter the Language id of this Game. For some reasons, DRF is expecting the language to be passed as a dictionary and not as an integer. Here is the error: { "language": { "non_field_errors": [ "Invalid data. Expected a dictionary, but got int." ] } } What is the proper way to indicate to DRF, to create a Game which has the Language property based on the provided Language id ? -
SECRET_KEY error when pushing django project to heroku
I am trying to push a django project that works well locally (with heroku local) to heroku. I my settings.py, I have a SECRET_KEY set, randomly created by django with startproject. In both manage.py and wsgi.py, I have : os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") This is my project's arborescence: mysite/ βββ db.sqlite3 βββ lecture β βββ admin.py β βββ apps.py β βββ forms.py β βββ __init__.py β βββ media β βββ migrations β β βββ 0001_initial.py β β βββ 0002_auto_20161021_0952.py β β βββ __init__.py β β βββ __pycache__ β β βββ 0001_initial.cpython-34.pyc β β βββ 0002_auto_20161021_0952.cpython-34.pyc β β βββ __init__.cpython-34.pyc β βββ models.py β βββ __pycache__ β β βββ admin.cpython-34.pyc β β βββ apps.cpython-34.pyc β β βββ __init__.cpython-34.pyc β β βββ models.cpython-34.pyc β β βββ urls.cpython-34.pyc β β βββ views.cpython-34.pyc β βββ static β β βββ lecture β β βββ images β β β βββ background.gif β β βββ style.css β βββ templates β β βββ lecture β β βββ ajouter.html β β βββ base_site.html β β βββ debug.html β β βββ detail.html β β βββ detail_oeuvre.html β β βββ index.html β β βββ index_lectures.html β β βββ results.html β βββ tests.py β βββ urls.py β βββ views.py βββ log β βββ admin.py β¦ -
Django Ajax returns whole html page
I'm trying to create live search filter,with ajax $(function() { $('#search-item').keyup(function() { $.ajax({ type: "GET", url: "/toysprices/", data: { 'query' : $('#search-toy').val(), 'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val() }, success: searchSuccess, dataType: 'html' }); }); }); function searchSuccess(data, textStatus, jqXHR) { console.log(data); } and my views.py f request.method == "GET": search_text = request.GET['query'] if search_text: search_text = request.GET['query'] statuss = Status.objects.filter(status__contains = search_text) else: statuss = Status.objects.all() return render(request, 'ajax_search.html', {'statuss':statuss}) it works correctly, but it returns whole html page, how can i make to get only part which I want to render in my template. -
Django: inlineformset validation fail by foreign key
models.py class Item(TimeStampedModel): name = models.Charfield(max_length=40) user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True) class ItemImage(TimeStampedModel): item = models.ForeignKey(Item, on_delete=models.CASCADE) image = models.ImageField() I created custom-inline-formset for not allowing empty data. formset.py class ItemInlineFormSet(BaseInlineFormSet): def __init__(self, *args, **kwargs): super(ItemInlineFormSet, self).__init__(*args, **kwargs) for form in self.forms: form.empty_permitted = False And now, suppose user have three Item, which means user.item_set.count() == 3. In this situation, user accessed the view. What I want to do in my view is attach image files for each item. views.py def myview(self, request, *args, **kwargs): items = request.user.item_set.all() # three items ItemImageFormSet = inlineformset_factory( Item, ItemImage, fields=('image',), formset=ItemInlineFormSet, extra=1 ) formset_list = [] # POST request if request.method == 'POST': all_formset_valid = True for item in items: formset = ItemImageFormSet(request.POST, request.FILES, instance=item) if not formset.is_valid(): all_formset_valid = False formset_list.append(formset) if all_formset_valid: for formset in formset_list: formset.save() return redirect(reverse('success')) # GET request else: for item in items: formset_list.append(ItemImageFormSet(instance=item)) return render( request, 'a.html', context={"formset_list": formset_list,} ) GET request worked well, but problem is POST request. After I attached image for all item in my view and sent POST request, formset invalid happend! print(formset.errors) show, `primary key of parent object doesn't match with inline foreign key' I have no idea why this happend. Need β¦ -
Accessing User 'extended models' in Template
I have extended my user model with a Profile model (housing pictures, information etc). I have done this as follows: user = models.OneToOneField(User, related_name='profile') Is it possible to pull this directly in my template without passing it from the view (via context) each time? Something like the following: {{ request.user.profile.picture }} (The above does not work for me) As I want to use this in the base template, I don't want to pass it in every view. -
Create multiple type object in restframework
i use restframewotk in django for project! i want to when post to this url (example) : /profiles/ created five object! one in profiles model and fourth in Stories model ! so, i write ProfileViewSet : class ProfileViewSet(viewsets.ViewSet): """ API endpoint that allows groups to be viewed or edited. """ serializer_class = ProfileSerializer def create(self, request): serializer = ProfileSerializer(data=request.data) if serializer.is_valid(): serializer.save() # StoriesViewSet.create(StoriesViewSet , defualt_stories ) return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) and my question is : how add fourth Stories in my db when one profile posted? -
Django auto deploy github to digital ocean
I'm newbie in auto deployment. Previously I was using auto deploy to heroku using the flow github->codeship(testing)->heroku. But at present I'm working on a digitalocean vps. Is there any good resource(tutorial, books) deploying django app using the flow github->codeship(testing)->vps -
Make Ajax Get Request when a key is typed into a search box
I am trying to create a real time search box in my Django Application. The general idea is that when a key is pressed in the search field, it should send the get request to my server, and on success, the data should append to my search-result p tag. However, for some reason, I am appending my entire HTML content. I want to only append the information sent inside the search box. This is what I have so far. Html <form method="get" action="{% url 'sell' %}" class="search_form center-block"> <!--{% csrf_token %}--> <div class="input-group search_option"> <input type="text" id="searchBox" class="search_field form-control" name="q" placeholder="Search for..."> <span class="input-group-btn"> <input id="search" class="search_submit btn btn-default" onclick="myFunction()" type="submit" value="Search"> </span> </div><!-- /input-group --> </form> Script $(document).ready(function(){ $('.search_field').keyup(function(){ $.ajax({ url: "{% url 'sell' %}", type: "GET", cache: false, data: { 'search_text' : $('.search_field').val() }, success: function(data){ $('#search-results').append(data); } }); }); }); I believe data is where I am trying to get the value off of the search_field input, but for some reason. This isn't working. Thanks for the help in advance -
Django Model form: restricting selection to group
I have an existing Model form in Django. The field I am interested in is the language_pairs model multiple choice field. Here are some of the entries: { "model": "projects.LanguagePair", "pk": 1, "fields": { "name": "English (en) - German (de)", "code": "en_de" } }, { "model": "projects.LanguagePair", "pk": 2, "fields": { "name": "German (de) - English (en)", "code": "de_en" } }, { "model": "projects.LanguagePair", "pk": 3, "fields": { "name": "French (fr) - English (en)", "code": "fr_en" } The form code: class ProjectForm(forms.ModelForm): class Meta: model = Project fields = ('title', 'notes', 'url', 'content') language_pairs = forms.ModelMultipleChoiceField(queryset=LanguagePair.objects.order_by('code')) def __init__(self, *args, **kwargs): if kwargs.get('instance'): initial = kwargs.setdefault('initial', {}) initial['language_pairs'] = [t.pk for t in kwargs['instance'].language_pairs.all()] super(ProjectForm, self).__init__(*args, **kwargs) def save(self, commit=True, user=None): instance = super().save(commit=False) source_languages = set() if commit: if user: instance.user = user instance.save() instance.language_pairs.clear() for lang in self.cleaned_data['language_pairs']: source_languages.add(lang['code'].split("_")[0]) if len(source_languages) !=1: raise ValidationError("You can only have one source language") for lang in self.cleaned_data['language_pairs']: instance.language_pairs.add(lang) return instance My question is this the right place to raise a validation error if any of the source languages are different (set has more than one entry)? -
Dictionary sent using POST C# is empty
I am trying to send dictionary using POST in C# to a django server. The server receives the request and acknowledges with 200 message, however it receives an empty Multi Value Dictionary. Here is the client sending POST request. public class Hello1 { public static void Main() { Console.WriteLine("Request Initiating"); using (var wb = new WebClient()) { var data = new NameValueCollection(); data["key1"] = "test"; data["key2"] = "TEST2"; data["key3"] = "NA"; string url = "http://10.34.150.153:8000/key_detect/detect/"; var response = wb.UploadValues(url, "POST", data); string result = System.Text.Encoding.UTF8.GetString(response); Console.WriteLine(result); Console.ReadLine(); } } } -
Communication frontend - backend, and security issue
I have a problem with security. I have backend in Django (little mechanics and webpage). On webpage I have some tiles with some content. After click on this tiles logged user (request.user) earn some points. But this adding is by url. I mean. <a href='{url "path_to_view" tiles_id}'> And in webpage source I can see this url and id. And someone can send this request without click. How to prevent this situation, and secure this? -
Where can I access request parameters in Django Rest Framework?
I'm using Django Rest Framework and python-requests and passing several variables through the URL as shown below. "GET /api/boxobjects/?format=json&make=Prusa&model=i3&plastic=PLA HTTP/1.1" So I'm passing the variables make, model, and plastic. The recommended method to access these parameters is shown below. makedata = request.GET.get('make', '') However, I have no idea where to place that line of code. I've completed the tutorial for Django Rest Framework and have my views set up to roughly match the tutorial. views.py @api_view(['GET']) @login_required def api_root(request, format=None): return Response({ 'Users': reverse('api:user-list', request=request, format=format), 'Objects': reverse('api:object-list', request=request, format=format), 'Files': reverse('api:file-list', request=request, format=format), 'Config Files': reverse('api:config-list', request=request, format=format), 'Box-objects': reverse('api:box-object-list', request=request, format=format), }) class BoxViewSet(viewsets.ModelViewSet): queryset = Uploadobject.objects.all().exclude(verified=False) serializer_class = BoxSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsBox) def perform_create(self, serializer): serializer.save(owner=self.request.user) #Maybe get function here? Not displaying ''' def get(self, request): print ("request set here?") ''' Where would I place the one line of code to access these request parameters? -
django modelforset_factory() doesn't include actual forms
I've been trying to follow tutorials and other SO questions and have a modelformset_factory that's displaying a list of what looks like forms in the html, but it turns out they're not actual forms. html that gets displayed: <div ='container'> <div class='row'><tr><th><label for="id_form-0-config_key">Config key:</label></th><td><input id="id_form-0-config_key" maxlength="63" name="form-0-config_key" type="text" value="ClientMustVerify" /></td></tr> <tr><th><label for="id_form-0-config_value">Config value:</label></th><td><input id="id_form-0-config_value" maxlength="63" name="form-0-config_value" type="text" value="TRUE" /><input id="id_form-0-id" name="form-0-id" type="hidden" value="3" /></td></tr> <input type="submit" value="Update" /></div> <div class='row'><tr><th><label for="id_form-1-config_key">Config key:</label></th><td><input id="id_form-1-config_key" maxlength="63" name="form-1-config_key" type="text" value="Auditing" /></td></tr> <tr><th><label for="id_form-1-config_value">Config value:</label></th><td><input id="id_form-1-config_value" maxlength="63" name="form-1-config_value" type="text" value="FALSE" /><input id="id_form-1-id" name="form-1-id" type="hidden" value="4" /></td></tr> <input type="submit" value="Update" /></div> <div> notice there is no form tag anywhere. working backwards, here's the excerpt from the template: <div ='container'> {% for form in formset %} <div class='row'>{{form}} <input type="submit" value="Update" /></div> {% endfor %} <div> yes, I added the submit button manually hoping to get these to work, but of course if there isn't a form tag, then the submit button won't do anything. views.py: from limbo.models import serverConfig from django.forms import modelformset_factory from django.forms import formset_factory def editServer(request): result = serverConfig.objects.values() myConfigs = [entry for entry in result] finalFormSet = modelformset_factory(serverConfig, exclude=('id',), extra=0) #other lines return render(request, 'limboHtml/ServerConfiguration.html', {'formset': finalFormSet, 'SubmitMessage': '', 'CurrentConfigs': myConfigs}) β¦ -
Django ImportError using python3 and compiled mod_wsgi in Centos7
I have recently setup a new project in Django. I'm now getting an error in /etc/httpd/logs/error.log: [Thu Oct 27 22:43:40.314525 2016] [wsgi:error] [pid 47381] [remote 127.0.0.1:52662] ImportError: No module named 'myproject.settings' I originally completed the polls tutorial, and got it working with: Centos7 Django 1.10 virtualenv Apache 2.4 MariaDB 10.1.17 (works the same as mysql) Python 3.4.3 mod_wsgi (using yum. This used python2.7) This all worked, but I noticed that when I ran this project using the internal webserver ./manage.py runserver It used python3. When I ran this project using apache with mod_wsgi it used python 2.7. It was fully functional, and all of the webpages worked but they used python2.7. So I found my error (or one of them) was installing mod_wsgi using yum instead of compiling it from source. So I uninstalled mod_wsgi using yum remove mod_wsgi I then compiled mod_wsgi from source using wget "https://github.com/GrahamDumpleton/mod_wsgi/archive/4.5.7.tar.gz" tar -xzf '4.5.7.tar.gz' cd ./mod_wsgi-4.5.7 ./configure --with-python=/bin/python3.4 make make install I then had to add a line to /etc/httpd/conf/httpd.conf: LoadModule wsgi_module modules/mod_wsgi.so When I now try to run this, I get the ImportError message above. My wsgi.py file is: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings") application = get_wsgi_application() For debugging, β¦ -
Django: ManyToManyField sortable and searchable in admin list view
I have these two models class Nations(models.Model): label = models.CharField(max_length=200) iso2 = models.CharField(max_length=2, unique=True) class Trip(models.Model): title = models.CharField(max_length=200, blank=False, verbose_name='Title') nations = models.ManyToManyField(Nations, blank=False) And this is the admin file form my Trip model: class TripAdmin(admin.ModelAdmin): def get_nation_names(self, obj): if obj.nations: return " / ".join([s.label for s in obj.nations.all()]) get_nation_names.short_description = 'Nation names' list_display = ('id', 'get_nation_names', 'title') ordering = ('title', ) search_fields = ['titolo',] By now get_nation_names function correcly prints me out a concatenation of all nations' labels contained into a Trip item row, but what if I need that field to be sortable or searchable as well? Of course I cannot put that function directly on ordering and search_fields lists like this ordering = ('title', 'get_nation_names') search_fields = ['titolo', 'get_nation_names'] so what's the proper way archieve that? Thanx in advance -
HTML and Python play nicely with date format
I have the following code: {% for x in fixtures %} <TR style="display:block" onclick="team_visibility('match{{ forloop.counter }}');"> <TD> {{ x.fixturedate }}</TD> There is obviously more to it but I do not think that is relevant for now. It currently works but it displays a horribly long looking date and time. Below is an example of the output: 29 Oct 2016, 5:30 p.m. Whereas I would like to just return "17:30". Is this possible within the code or do I have to go back to the drawing board and amend it at the view stage? -
Django: Python access to onetone field
I have the following code: fixtures = StraightredFixture.objects.select_related().filter(soccerseason=soccerseason,fixturematchday=fixturematchday).order_by('fixturedate') temp2 = fixtures[0].hometeamscore It works but it is using the "hometeamscore" from the model "StraightredFixture" but I need it from "StraightredFixtureLive". Could someone help me amend my code accordingly, many thanks, Alan. The two models are as below: class StraightredFixture(models.Model): fixtureid = models.IntegerField(primary_key=True) home_team = models.ForeignKey('straightred.StraightredTeam', db_column='hometeamid', related_name='home_fixtures') away_team = models.ForeignKey('straightred.StraightredTeam', db_column='awayteamid', related_name='away_fixtures') fixturedate = models.DateTimeField(null=True) fixturestatus = models.CharField(max_length=24,null=True) fixturematchday = models.ForeignKey('straightred.StraightredFixtureMatchday', db_column='fixturematchday') spectators = models.IntegerField(null=True) hometeamscore = models.IntegerField(null=True) awayteamscore = models.IntegerField(null=True) def __unicode__(self): return self.fixtureid class Meta: managed = True db_table = 'straightred_fixture' class StraightredFixtureLive(models.Model): fixtureid = models.OneToOneField(StraightredFixture, on_delete=models.CASCADE, primary_key=True,) hometeamscore = models.IntegerField(null=True) awayteamscore = models.IntegerField(null=True) def __unicode__(self): return self.fixtureid class Meta: managed = True db_table = 'straightred_fixturelive' -
django admin login error: A server error occurred. Please contact the administrator
trying to set up my admin environment but keep getting this stupid server error: A server error occurred. Please contact the administrator. Anyone know a fix for that ? thanks in advance! -
DecimalField Validation in Django
I'm trying to validate a DecimalField in Django Trying in shell: >> from django.forms import DecimalField >> from django.core.validators import MaxValueValidator >> f = DecimalField(max_digits=2, decimal_places=1, validators=[MaxValueValidator(10)]) >> f.validate(11) # after this I should get an error >> But it does not show validation errors. It should throw an error because 11 is greater that 10, right? What I'm doing wrong? -
TemplateSyntaxError in Django
I am following the django app tutorial and I get this error... Invalid block tag on line 5: 'endfor', expected 'elif', 'else' or 'endif'. Did you forget to register or load this tag? Request Method: GET Request URL: http://127.0.0.1:8000/polls/ Django Version: 1.10.1 Exception Type: TemplateSyntaxError Exception Value: Invalid block tag on line 5: 'endfor', expected 'elif', 'else' or 'endif'. Did you forget to register or load this tag? Exception Location: C:\Python34\Orange\lib\site-packages\django\template\base.py in invalid_block_tag, line 568 Python Executable: C:\Python34\Orange\python.exe Python Version: 3.4.4 Python Path: ['C:\xampp\htdocs\django\mysite', 'C:\WINDOWS\SYSTEM32\python34.zip', 'C:\Python34\Orange\DLLs', 'C:\Python34\Orange\lib', 'C:\Python34\Orange', 'C:\Python34\Orange\lib\site-packages'] Server time: Sat, 29 Oct 2016 21:30:59 +0300 My index.html looks like this... {% if latest_question_list %} <ul> {% for question in latest_question_list % } <li><a href="/polls/{{ question.id }}/">{{question.question_text}}</a></li> {% endfor %} </ul> {% else %} <p>No polls available</p>{% endif %} What am I doing wrong? Appreciated. -
How do I use python requests to download a processed files?
I'm using Django 1.8.1 with Python 3.4 and i'm trying to use requests to download a processed file. The following code works perfect for a normal request.get command to download the exact file at the server location, or unprocessed file. The file needs to get processed based on the passed data (shown below as "data"). This data will need to get passed into the Django backend, and based off the text pass variables to run an internal program from the server and output .gcode instead .stl filetype. python file. import requests, os, json SERVER='http://localhost:8000' authuser = 'admin@google.com' authpass = 'passwords' #data not implimented ############################################## data = {FirstName:Steve,Lastname:Escovar} ############################################ category = requests.get(SERVER + '/media/uploads/9128342/141303729.stl', auth=(authuser, authpass)) #download to path file path = "/home/bradman/Downloads/requestdata/newfile.stl" if category.status_code == 200: with open(path, 'wb') as f: for chunk in category: f.write(chunk) I'm very confused about this, but I think the best course of action is to pass the data along with request.get, and somehow make some function to grab them inside my views.py for Django. Anyone have any ideas? -
Django MySQL primary key also a foreign key
I have the following two django models: class StraightredFixture(models.Model): fixtureid = models.IntegerField(primary_key=True) home_team = models.ForeignKey('straightred.StraightredTeam', db_column='hometeamid', related_name='home_fixtures') away_team = models.ForeignKey('straightred.StraightredTeam', db_column='awayteamid', related_name='away_fixtures') fixturedate = models.DateTimeField(null=True) fixturestatus = models.CharField(max_length=24,null=True) fixturematchday = models.ForeignKey('straightred.StraightredFixtureMatchday', db_column='fixturematchday') spectators = models.IntegerField(null=True) hometeamscore = models.IntegerField(null=True) awayteamscore = models.IntegerField(null=True) soccerseason = models.ForeignKey('straightred.StraightredSeason', db_column='soccerseasonid', related_name='fixture_season') def __unicode__(self): return self.fixtureid class Meta: managed = True db_table = 'straightred_fixture' class StraightredFixtureLive(models.Model): fixtureid = models.IntegerField(primary_key=True) hometeamscore = models.IntegerField(null=True) awayteamscore = models.IntegerField(null=True) def __unicode__(self): return self.fixtureid class Meta: managed = True db_table = 'straightred_fixturelive' What I would like to do is have it so the fixtureid in StraightredFixtureLive is a foreign key to fixtureid in StraightredFixture. Any assistance with this would be appreciated, many thanks, Alan.