Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django 1.10 url dispatcher not working
I'm trying to simply give an app url an option of /headless/ to make it show a different template my project/urls.py is like so: urlpatterns = [ url(r'^datastore/', include('datastore.urls')), ] my app/urls.py is like so: app_name = 'datastore' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^datastore/(?P<headless>"headless"{1})/$', views.index,name='index'), ] I get a 404 error with the above I've also tried: url(r'^datastore/(?P<headless>"headless"?)/$', url(r'^datastore/(?P<headless>\w{1})/$', views.index, name='index'), url(r'^datastore/(?P<headless>\w+)/$', views.index, name='index'), -
Django Database and User Authentication
Novice Programmer Here. I want to create a login system with hundreds of users. Initially, I am given a some database information about these users in the format: student#| first_name | last_name | student_ID | --------|------------|-----------|------------| 10001 | Bob | Jones | Bob100 | 10002 | Andy | Guo | And101 | 10003 | Andy | Sir | And102 | 10004 | Bob | Jones | Bob101 | The first and last names can be the same but student# and student_ID# will always be unique. Therefore, I want the student_ID to be the username and student# to be the password. After reading some tutorials I have implemented a very basic login system where I have to manually create the user: python manage.py createsuperuser Then I use the following code to authenticate the user: def auth_view(request): username = request.POST.get('username', '') password = request.POST.get('password', '') user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) return HttpResponseRedirect('/accounts/loggedin') else: return HttpResponseRedirect('/accounts/invalid') So I was thinking of a couple of options and I wanted to ask your opinions: Create a script that parses through the database for student# and student_ID and create the users. Whenever the students login, check the username(student_ID) and password(password) … -
How to use Sass in Django and versioning CSS and JS assets for cache busting
So I started a project in Laravel/MySQL and it became apparent after to some more experienced developers that Django/PostgreSQL might have been a better choice for the app. Despite being a Django newb, I have been converting it over Django and there is one feature in Laravel that I am not seeing in Django that I was wondering how to implement. In Laravel it is a combination of Gulp and Elixir that manages Sass to CSS compiling and also versioning CSS and JS files. In gulpfile.js for Laravel the code is this: elixir((mix) => { mix.sass('styles.scss') .version(['css/app.css', 'js/app.js', 'css/styles.css', 'js/custom.js']); }); It is then read into the Blade template with: <!-- Styles --> <link rel="stylesheet" href="{{ elixir('css/app.css') }}"> <link rel="stylesheet" href="{{ elixir('css/styles.css') }}"> <!-- Scripts --> <script src="{{ elixir('js/app.js') }}"></script> <script src="{{ elixir('js/custom.js') }}"></script> I am not seeing a similar functionality in Django so was wondering how to implement it because it is very handy turning watch on then having assets Sass->CSS and JS compiled, and versioned. I do see various npm packages out there: gulp, gulp-django, django-sass, etc. And then I see other packages like gulp-buster or gulp-cache-bust. It isn't clear to me if gulp comes with these packages, … -
Django show only the values in the selected field
So in my models.py I have this: class Profesie(models.Model): titlu = models.CharField(max_length=100) def __str__(self): return self.titlu class Domeniu(models.Model): profesie = models.ForeignKey(Profesie) titlu = models.CharField(max_length=100) def __str__(self): return self.titlu class Anunt(models.Model): titlu = models.CharField(max_length=150) user = models.ForeignKey('auth.User', related_name='anunturi') profesie = models.ForeignKey(Profesie) domeniu = models.ForeignKey(Domeniu) In the form when the user selects the field profesie, and then domeniu, for the domeniu field it should only display the values that are in the Profesie table. How can I accomplish that? -
How to Populate jQuery Datepicker widget from Django template variable?
I'm having trouble populating a jQuery Datepicker widget with the value of a Django template variable. I have the following model and form fields: # models.py class Meeting(models.Model): date = models.DateField() # forms.py class AddMeetingForm(forms.Form): date = forms.DateField( widget=forms.widgets.DateInput(attrs={'type': 'date'})) In my template, the datepicker widget acts on the 'date' input tag. I want the default date format to be "mm-dd-yyyy", e.g. "12-30-2016". I'm telling the datepicker what date format to expect and then I pass the meeting object to the template and print out its date field using a date filter to convert it to the desired format: # edit_meeting.html <div> <label for="id_date">Date</label> {{ form.date.errors }} <input type="text" name="date" id="id_date"/> </div> <script> $(function() { $( '#id_date' ).datepicker({ dateFormat: 'mm-dd-yy', }); $( '#id_date' ).datepicker( 'setDate', {{ meeting.date|date:"mm-dd-Y" }}) }); </script> The jQuery formatDate utility defines how dates are formatted for this widget while Django's date filter specifies how Django dates are formatted. When I print the value in my PostgreSQL database, I see the field has the value "2016-12-30" and when I print the meeting.date field to my console from inside the view that renders the template, I also see that its value is "2016-12-30". However, the datepicker widget is … -
Django Rest Framework override default viewset methods
I am facing the problem with overriding default methods in ModelViewSet (retrieve(), get_queryset(), ...) I have a simple foreign key relation in my models.py: class Material(models.Model): subject = models.ForeignKey(Subject, on_delete=models.CASCADE) url = models.URLField() def __str__(self): return 'Material #{} for {}'.format(self.id, subject) And a class MaterialsViewSet(viewsets.ModelViewSet) For example, the default structure of the retrieve() method in my MaterialsViewSet is the following def retrieve(self, request, pk=None). This represents the following URL pattern materials/<pk>/$, but I want to have materials/<subject_pk>/<pk>/$. I've tried some approaches with drf-nested-routers and decorators (detail_route(), list_route()), but I still can't reach the result that I want. Generally, I want to achieve the following URLs in a single viewset: /materials/ -> list all materials /materials/{subject_id}/ -> list all materials linked with this subject /materials/{subject_id}/{id}/ -> get the concrete material -
Get grandchildren of an object with django
I'm building a webapp with django with the following models: class Business(models.Model): ... class Branch(models.Model): business = models.ForeignKey(Business) ... class Event(models.Model): branch = models.ForeignKey(Branch) My questions is how can I get all events by their business (not their branch), and if it possible to do so in a DB query. Thanks! -
Django Sitemap Framework. Accepting query parameters
I'm using the Django Sitemap Framework I've no problem retrieving a list of articles from my DB. class ArticleSitemap(Sitemap): def items(self): return articles.objects.filter(tagid=1399).order_by('-publisheddate') I now want to accept a query parameter to filter by an inputted tag id ie: sitemap.xml?tagid=1000 I have yet to find an example in the docs or on stack. -
In Django how to get this kind of selection box for my app?
In django admin panel we see a control like shown in image below for user permissions and also selecting groups. I want to add similar control for my application outside of admin. What is this selection control called and where can I learn more about it? Please help me out as I am clueless about it and in django documentation I couldn't find anything meaningful. Thanks. -
how to add additional field and use it in User model? django
I have all set up user login / register / logout already and app is already running. Now I want to add something like a reset field into my User model in order for users to reset password if they forgot the password. I checked and I believe after migrations already ran, it would be the best to extend by adding OneToOneField But somehow I cannot get this to work and not sure how I can test it too. Can someone please give me a hand? I have this in my authUser models.py from django.db import models from django.contrib.auth.models import User class Reset(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) reset = models.CharField(max_length=100) in my authUser forms.py # Reset Password Form class ResetPasswordForm(forms.Form): email = forms.CharField(required=True) in my authUser views.py # reset password class ResetPasswordView(View): form_class = ResetPasswordForm template_name = 'authUser/resetForm.html' def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) # def post(self, request): I am not sure how I can continue with this and actually test it in the python console first before I continue more -
django 1.10 list of installed apps
So I'm trying this: import my_project.settings DEVOPS_APPS = [ app for app in my_project.settings.INSTALLED_APPS if not "django" in app ] Sometimes when I refresh, the data doesn't show. Other times when I refresh, the data shows. Still some other times when I refresh, I get the full list of INSTALLED_APPS My index function looks like so: template = loader.get_template('dashboard/index.html') context = { 'title': "Telematics DevOps Automation Team", 'server': 'atllvasbap001i.hughestelematics.net', 'charts': data['charts'] } return HttpResponse(template.render(context)) What am I doing wrong? -
Django form not submitting using Javascript
I have a Django form on one of the pages which I am trying to submit using Jquery-Ajax. Following is my code: I have used Jinja templating to render the form on page. <form action='' method='post' name='ContactForm' id='ContactForm'> {% csrf_token %} {% for field in form %} <div class="input-group"> <span class="input-group-addon">@</span> {{ field }} </div> {% endfor %} <div class="input-group form-buttons"> <span class="input-group-btn"> <button class="btn btn-default" type='submit' value='Submit' name='submitf' id="submitf">SAY HELLO</button> </span> </div> <div id='message_post'></div> </form> <script type="text/javascript" src="{% static 'personal/js/contact/contact-form.js' %}"></script> contact-form.js $(function(){ $("#ContactForm").submit(function(){ $("#submitf").value='Please wait...'; alert("Control reached the script."); $.post("/contact/add/", $("#ContactForm").serialize(), function(data){ alert("Alert entered function."); if(data.status == 'error'){ $("#message_post").html("<div class='errorMessage'>ERROR: " + data.msg + "!</div>"); document.ContactForm.submitf.value='Resend >>'; document.ContactForm.submitf.disabled=false; } else { $("#message_post").html("<div class='successMessage'>Hi! Glad to meet you. I'll definitely contact you shortly.</div>"); $("#submitf").value='Send >>'; } }, "json"); return false; }); }); urls.py from django.conf.urls import url, include from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^contact/add/$', views.add, name='add') ] But everytime I hit the submit button it gives the following error: POST /contact/add/ HTTP/1.1" 404 2043 Currently in learning phase of Python and Django. Highly appreciate any help. -
permission issue for collectstatic in docker-compose
I am using docker-compose to run django application and server it using ngnix.When i run docker exec DOCKERNAME /bin/sh -c "python manage.py collectstatic --noinput" following error occured OSError: [Errno 13] Permission denied: '/src/static/admin/js/popup_response.js' How to run collectstatic command with sudo permission in docker-compose -
Django migrations. Complex update
i have model like this: class Model(models.Model): number = models.CharField() category = models.ForeignKey(Category) created_at = models.DateTime() Suppose, we have following categories: [A, B1, B2, B3, B4, B5, C]. What i need, is to update records, where category==B2(~2.3 million records) with either category B2, B3, B4 or B5. Rule is, if, for number n it's first(ordered by created_at field) consecutive record with category==B2 then leave category as is, if it's second consecutive record with category==B2 -- update category to B3, if third, then update category to B4, etc. If previous record has category B2, but current has category A then reset this counter. -
What are security implications of mirroring the website with GET request?
So I'm trying to build a "viewer" that'll let users of my app to see the content of URLs. I could use Iframes but some websites DENY that - so I've got an idea to get around this with the "mirror" feature. Basically I would use GET request on URL and return the exact html, media, css and maybe js of that URL to user, but on my domain. It'd be some kind of "proxy". But my concern is security - I need for sure to watch out for XSS. But is there any other thing that I should watch out for while doing it? The stack is Ubuntu, Python 3 & Django 10. -
Get a random object from a list of objects with template
I'm listing every fonts I have in my models database under each icon from another model. I would like to get one random font for each icon. Here is how I show my template file : {% for Fo in FormOne %} {% for Ft in FormTwo %} {% for f in Ft.icon.all %} <p>{{ f.icon_name }}</p> #for each icon name {% for f in Fo.checkbox.all %} <p>{{ f.font_name }}</p> #show one random font name. {% endfor %} {% endfor %} {% endfor %} {% endfor %} I got the context of my view like this : context = {'FormOne':FormOne.objects.all(), 'FormTwo':FormTwo.objects.all()} here is my model structure : class Font(models.Model): font_name = models.CharField(max_length=100) ... class FormOne(models.Model): name = models.CharField(max_length=40) checkbox = models.ManyToManyField(Font, blank=True) ... class Icons(models.Model): icon_name = models.CharField(max_length=100) ... class FormTwo(models.Model): owner = models.ForeignKey(FormOne) icon = models.ManyToManyField(Icons, blank=True) ... How can I achieve it ? -
How to store user actions?
In our project, user can perform many types of actions like add product, change product, perform scan, set our price etc. I want to add a table of recent actions to the users dashboard so they can see for example last 20 actions performed. Something like Admin Recent actions: The problem is that I can't figure out some univerzal and effective way to do that. This is what I have done so far but I'm not sure if this is the good way: class Action(models.Model): user = models.ForeignKey('User') description = models.TextField() ACTION_CHOICES = (('product_added','Product added'), ('product_deleted', 'Product deleted'), ('product_changed','Product changed')) action = models.CharField(max_length=100,choices=ACTION_CHOICES) And in views I would do something like: def change_price(request): ... # if valid Action.objects.create(user=request.user,description='Changed price',....) Is there some common way or best practise to store such actions? -
Django filter for multidimensional arrays
In my ModelX I have such field: foo = ArrayField( ArrayField( models.BooleanField() ) ) So it can be represented as array with 2 dimensions (e.g. [[false,false,false],[true, false, true], [false, true, true]]) I want to filter ModelX by this field this way. Imagine I have pattern matrix, and matrixes, that should be filtered, I need to count how many true items have equal (row, column) and if this number is greater, than some n, than it should be in result. Example: pattern = [[true, true, false],[false, false, false],[false, false, false]] matrix = [[true, false, false],[true, false, true],[false, false, true]] matrix has one overlap with pattern (in (row, column) = (0,0)). So if number of overlaps is set to 1, then it should be in result, if more than 1, then it should not be in result. How can I implement this? Possibly with .filter() method. I use PostgreSQL. -
Use Image.copy in recursive deepcopy
I've basemodel that copy the model in contructor: class BaseModel(models.Model): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.original = copy.deepcopy(self My problem is that some models have ImageField, and when I try copy, I get AttributeError. I found the solution for this error here, that says "use image.copy() instead of copy.deepcopy(). Can I implement image.copy() in a recursive deepcopy when the field is a image? Thanks a lot! -
Getting error while integrating angularJS in Django project
I am trying to use angularJS in my django project. I have set the static folder and path for js files as required in my html file. But, When I run the code, it is raising following error as in the image. -
Update the fields of a single row in django
I have created a table with django model. class Likes(models.Model): likes = models.IntegerField(max_length=255,unique=False) def __unicode__(self): return self.likes Initially I have no records in the row.But I want to count the likes on the page.So I am having a single row which will contain the likes of the page.How should I increment the value likes as soon as user clicks the like button in my view. Like(view.py): def like(request): var=0 count=Likes.objects.count() if(count==0): l=Likes(likes=1) l.save() else: l1=Likes() l1.likes=int(l1.likes)+1 l1.save() var=l1.likes return HttpResponse("Likes"+str(var)) But this is not working.I just want to increment the likes as soon as user clicks on the button. -
Difference between APIView class and viewsets class?
What are the difference between APIView class and viewsets class ? I am following Django REST-framework official documentation. I think it lack examples. Can you explain the above difference with a suitable example. -
Django views: reuse function view variable in class-based view partial loaded with AJAX
I have a "main" view server through a function view in views.py that sets a lot of variables. The template returned used a lot of these variables, but also the templates included in it and additional data loaded with AJAX. def season_view(request, id): # we do a bunch of stuff return render_to_response('season.html', {groups: groups, date: date, ...} Now, in this template a list of matches is displayed. There are a lot of matches, so they are loaded in groups separately using AJAX, so the following class-based view is called repeatedly to load the matches: class GroupedMatches(TemplateView): template_name = 'partials/grouped_matches.html' def get_context_data(self, **kwargs): # stuff... context['matches'] = grouped_matches return context And then grouped_matches.html loops through the matches and includes a match partial: {% for match in matches }% {% include 'partials/match.html }% {% endfor %} Here is the thing: the match partial doesn't only use the data the match itself holds, but also needs (for whatever purpose) some of the variables from way before, the groups we set in season_view. The problem is that either dividing the logic in different views or using AJAX seem to lose the variables coming from season_view even though the match partials are included in that … -
Migrating from tagging to taggit
I have an old Django app that runs on 1.8 and uses django-tagging. As it has been abandoned a long time ago and is incompatible with Django>1.8, I'm trying to migrate my app to django-taggit. I've found http://blog.birdhouse.org/2011/04/17/migrate-django-tagging-taggit/, which does exactly that, but requires modifications on the SQL level, which I try to avoid so that I can stay fully in Django migration land. My current plan was to have tagging ('tags') and taggit ('new_tags') side-by-side in the first migration and run the first migration to be able to copy the tags over class Flow(models.Model): tags = TagField() new_tags = TaggableManager() Drop 'tags' and rename 'new_tags' to tags Unfortunately, I'm unable to store anything in new_tags when running the migrations: ` def transfer_tags(apps, schema_editor): Flow = apps.get_model("flow", "Flow") for f in Flow.objects.all(): if f.tags: f.new_tags.add(*f.tags.split(" ")) f.save() class Migration(migrations.Migration): dependencies = [ ('flow', '0003_flow_new_tags'), ] operations = [ migrations.RunPython(transfer_tags), ] ` File "/home/wr/twotoreal/env/local/lib/python2.7/site-packages/taggit/managers.py", line 153, in add tag_objs = self._to_tag_model_instances(tags) File "/home/wr/twotoreal/env/local/lib/python2.7/site-packages/taggit/managers.py", line 191, in _to_tag_model_instances if isinstance(t, self.through.tag_model()): AttributeError: type object 'TaggedItem' has no attribute 'tag_model' Outside the migrations (after I have run the first migrate that simply added the new_tags), I can add tags to new_tags just fine. -
How to add the function 'log out on other computers'?
For example, I often forget to log out on your site on other people's computers, but do not always have the opportunity to go back and log out. How to make a function that will automatically close all sessions except my current one, from my computer?