Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django forms render static text
I am using django form wizard to render a series of forms and in my last screen, I want to show the user a simple screen that says press the save button to continue. So, this last screen has no input elements. I, of course, need it to be part of the wizard workflow. I was wondering if there is a Form element that can be used for something like this or if there is some hack to basically just show this text. So basically I have something like: class FinalForm(Forms.Form): text = Forms.CharField(label="Press Save to update the record") def __init__(self, *args, **kwargs): super(FinalForm, self).__init__(*args, **kwargs) self.helper = FormHelper() # crispy-forms bit Here, of course, the CharField renders the text as a label and is an input field. Can it be done that we can have this form only contain some static text? The urls.py is declared as: url(r'^reviewrecord/(?P<pk>\d+)/$', views.ContactWizard.as_view([FirstForm, SecondForm, FinalForm]), name='reviewrecord'), -
How to modify wagtail CMS so that any user can post blog posts under their own blog
I have an existing website that is a Django App. I have installed Wagtail, and the Wagtail CMS is now accessible at www.example.com/cms. Wagtail is working correctly with my database, and all the existing users are visible when I go to settings and then users, in the wagtail CMS admin page. I want to use Wagtail to add blog functionality to my website. Requirements I want any user to be able to create a new blog and add posts to their blog. I want the blog created by a user to be visible at www.example.com/blogs/username/ How can I set Wagtail up to accomplish this? I have checked the documentation at http://docs.wagtail.io/en/v1.9/ but could not figure out where to start with my modifications. I have also installed the example blog project (https://github.com/wagtail/wagtaildemo) but I was also unable to figure out how to accomplish 1 and 2 above from this. Any complete answers, or general pointers, very welcome. -
Heroku seems to not use Django database?
I've got an app that works locally for me and has about ~50000 entires in an sqlite DB. The heroku app however, seems to have the same reaction searching for any day that I would have locally searching for data not in the database. So, I believe everything static is being served (pictures are static and are being served), and debugging in the JS console shows that the Django view is not returning data (because the JS function gets nothing). It also gives chrome something about loading unsecure scripts, and I have to turn of HTTPS to view the html/css/js properly. I think this is somewhat a seperate issue. These leads me to believe that Heroku does not have the database. How can I fix this or is there something else I can look into? Here is some code, I've added all Heroku recommendations: Views: def getTweets(request, tag): data = tweets.objects.filter(tag = tag).values('xcoord', 'ycoord', 'tag') return JsonResponse(list(data), safe=False) Model: class tweets(models.Model): id = models.AutoField(primary_key=True) tag = models.CharField(max_length=255, default=None) xcoord = models.CharField(max_length=40, default=None) ycoord = models.CharField(max_length=40, default=None) Settings: import os import dj_database_url # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECURITY WARNING: keep the secret … -
Django: How can I provide different users a different subset of options for the same ManyToManyField
The Question: How can I provide different users a different subset of options for the same ManyToManyField in the admin, and have each user's selections only affect their options? The Scenario: I am building an interactive map web app. There can be many Maps. There can be many MapItems. MapItems can be on many Maps and Maps can have many Map Items. Thus a ManyToMany relationship. Each Map has an owner, and I want only the owner of a Map to be able to add or remove MapItems from his/her Map. Here are the relevant parts of my models: class Map(models.Model): # Omit owner = models.ForeignKey(User, default=1) class MapItem(models.Model): # Omit map = models.ManyToManyField(Map, default=None, blank=True) MapItem.map is represented by a <select> on the MapItem admin interface: <select multiple="multiple" id="id_map" name="map"> <option value="1">Bob's Map</option> <option value="2">Sally's Map</option> </select> I want Bob to only have the option to select/deselect Bob's Map and not even see Sally's Map as an option. I have been able to filter the options that are displayed in the admin <select> widget by overriding get_form() on the ModelAdmin. def get_form(self, request, obj=None, **kwargs): kwargs['form'] = MapItemAdminForm form = super(MapItemAdmin, self).get_form(request, obj, **kwargs) form.base_fields['map'].queryset = form.base_fields['map'].queryset.filter(Q(owner=request.user) | Q(groups__in=request.user.groups.all())) … -
Q Lookups TypeError Django
In my Car model I have the following fields: name, manufacturer, body, car_type and description. I've implemented a search bar but when I search it's complaining: Related Field got invalid lookup: icontains on Q(car_type__icontains=query) Whats the issue here exactly? query = request.GET.get("q") if query: car = car.filter( Q(name__icontains=query) | Q(manufacturer__icontains=query) | Q(body__icontains=query) | Q(car_type__icontains=query) ).distinct() -
How to connect MySQL Database in django 1.10.6
raise ImportError, "This is MySQL Version %s, But _mysql is version %r" SyntaxError: invalid syntax -
How to integrate two Django projects with different databases?
I have my original Django project which runs on sqlite3 database. I want to integrate another Django project from GitHub which runs on postgre database. I added github link in requirements.txt file & installed it and added the new Django project app in original INSTALLED_APPS section of settings.py file and also updated urls.py file of original project. Now I got stuck with how to combine settings.py of these two projects? When I run command python manage.py migrate then it gives me this error:- AttributeError: 'DatabaseOperations' object has no attribute 'geo_db_type' Correct settings are already in github downloaded django project but not in original project. I have read almost all answers on Stack Overflow as well as on official docs. But enable to understand. my apologies if this is a duplicate or stupid question. -
ignoring unnecessary urls from making a server call
If you feel that the title is not appropriate ,pleae change it .I have a django url shown below : url(r'^update_status/field1/(?P<field1_id>.*)/field2/(?P<field2_id>.*)/$', 'update_status', name='update_status') This is working fine . But this catches both the urls like : update_status/field1/0445df4d8e1c43ae9/field2/f12b6b5c98/mraid.js/ and update_status/field1/0445df4d8e1c43ae9/field2/f12b6b5c98 But i want to capture only the second url . What should i change in the django url . Any suggestion is appreciated . -
performing scp command from django error returned non-zero exit status 1
I'm uploading a file from Django web-site to my WordPress. try: check_call(['scp', filename, upload_filename]) .... except (CalledProcessError, OSError): report['error_messages'].append("4 %s" % exc_info()[1]) return report This gives error: Command '['scp', '/uploads/test-01.txt', 'mysite.com:/home/wp-content/uploads/test-01.txt']' returned non-zero exit status 1 Now, If I do it manualy from the console: scp /uploads/test-01.txt mysite.com:/home/wp-content/uploads/test-01.txt it's working: test-01.txt 100% 0 0.0KB/s 00:00 (It's an empty file so 0 KB) I don't understand why the scp fails from the Django. The error is not clear. What can I do? -
Saving and using context data per request
How do I save context data per request and will be used further for logging/tracking without use of request object again and again? -
instantiate django modelform with POST data and instance and prefix
I am instantiating an instance of a modelform. The modelform holds data for an object that will be updated, not created new. I want to populate the form with POST data and include an instance of prior data. So: myform = MyForm(request.POST, instance=instance, prefix=myPrefix)The catch is that the POST data for this modelform has a prefix. When I call .is_valid() on the modelform the fields from the instance are not recognized because they don't have the prefix. Can somebody help? Thanks! -
Compare data from two different models with Django
I'm trying to compare two Django models with some common fields (lastname, firstname, ....) in order to apply a process if the answer is "yes" or "no". I have two models : Person (which gives the person's identity with lot of fields like lastname, firstname, birthday, ...) BirthCertificate (it's an act which is filled when a new child is borned with some fields : firstname, lastname, ...) With this both models, I have common fields and I would to compare these fields in order to apply two different processes. My models look like : class Person(models.Model): social_number = models.CharField(max_length=30, null=True, verbose_name='numero social') title = models.CharField(max_length=12,choices=TITLE_CHOICES, verbose_name='Civilité') young_girl_lastname = models.CharField(max_length=30, verbose_name='Nom de jeune fille', blank=True) lastname = models.CharField(max_length=30, verbose_name='Nom de famille') firstname = models.CharField(max_length=30, verbose_name='Prénom(s)') sex = models.CharField(max_length=8, choices=SEX_CHOICES, verbose_name='Sexe') status = models.CharField(max_length=15, choices=STATUS_CHOICES, verbose_name="Statut civil") birthday = models.DateField(verbose_name='Date de naissance') birthcity = models.CharField(max_length=30, verbose_name='Ville de naissance') birthcountry = CountryField(blank_label='Sélectionner un pays', verbose_name='Pays de naissance') birthmairie = models.CharField(max_length=30, verbose_name='Mairie de naissance') nationality = models.CharField(max_length=30, verbose_name='Nationalité') job = models.CharField(max_length=30, verbose_name='Profession') adress = models.CharField(max_length=30, verbose_name='Adresse') city = models.CharField(max_length=30, verbose_name='Ville') zip = models.IntegerField(verbose_name='Code Postal') country = CountryField(blank_label='Sélectionner un pays', verbose_name='Pays') mail = models.CharField(max_length=30, verbose_name='Email', blank=True) phone = models.CharField(max_length=20, verbose_name='Téléphone', blank=True) created = models.DateTimeField(auto_now_add=True) mairie … -
Django migrations not detecting all changes
I have the following models. BaseClass1 and BaseClass2 are abstract models used by models. In this case, the model AdBreak is used by a viewset and a serializer. When I run python manage.py makemigrations, the changes on AdBreak model is detected. The model AdBreakStatus is not getting created. Since, AdBreakStatus is linked to AdBreak, I am expecting a migration for AdBreakStatus also. Is my understanding wrong? Thanks in advance for the help. class BaseClass1(models.Model): class Meta: abstract=True timestamp = models.DateTimeField(auto_now_add=True) class BaseClass2(models.Model): class Meta: abstract=True other_field = models.IntegerField() class AdBreak(BaseClass1): class Meta: db_table = "ad_break" ad_break_id = models.AutoField(primary_key=True) ... # Other fields class AdBreakStatus(BaseClass2): class Meta: db_table = "ad_break_status" ad_break = models.ForeignKey(AdBreak) ... # Other Fields -
Django user registration where username becomes "firstname.lastname"
I want to make a registration page for my django application in order to 'request' access. In other words they submit the form and it creates the user and user.is_active = False. Then as admin I can approve their access. I do this at the moment using a signup view: def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() first_name = form.cleaned_data.get('first_name') last_name = form.cleaned_data.get('last_name') raw_password = form.cleaned_data.get('password1') username = form.cleaned_data.get('username') user = authenticate(username=username, password=raw_password) user.is_active = False user.save() return render(request, 'registration/signedup.html', {'user': user}) else: return render(request, 'registration/signup.html', {'form': form, 'invalid': 'Please try again.'}) else: form = SignUpForm() return render(request, 'registration/signup.html', {'form': form}) and a signup form: class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False, help_text='Optional.') last_name = forms.CharField(max_length=30, required=False, help_text='Optional.') email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', ) and this as the html for my signup page: <form method="post" autocomplete="off"> {% csrf_token %} <table class='login' width='400'> {% for field in form %} <tr> <td width='200' class='loginrow'>{{ field.label_tag }}</td> <td width='180' class='loginrow'>{{ field }}</td> {% for error in field.errors %} <p style="color: red">{{ error }}</p> {% endfor %} </tr> {% endfor %} </table> <button … -
Get Search Link when Using Haystack Django Pagination
I am working on making my project a bit faster so I decided to include pagination on my haystack+elasticsearch interface. Unfortunately, I am not able to parse the query details to the link for the next pages. I have 4 queries on my search, you can search by s name, ID, age or gender. -
Django get the Model name using ORM's related field name
I have a string like this order__product__category__description which is a related expression of my Django's model structure Now I have a model called Shipment field = 'order__product__category__description' Here description is a column name of table/model Category. Here comes the question, just by having this model Shipment and this field string order__product__category__description how do I find these models Order, Product, Category. My use-case is I need to store all the field_names of Category in a list. Any idea on how to connect the dots? having left with just two details Shipment & that field string. First thing comes to mind is to split by __ and to come up with a list like this ['order','product','category'] and to iterate the model _meta based on the field name. Any other elegant ways would be appreciated. -
Django: How to return user to correct pagination page after editing or updating?
I am editing a content from table which has pagination in it.But,if i update a user which is at the page no 9 so when i update and save that user it return me to page no 1. I want it to return to a same page where user was previously there that is at page no 9. -
Data toggle tab is not working properly . Extending data downward rather then toggle.
Hello I am using Bootstrap And using this example https://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_tabs_dynamic&stacked=h But As in example on click data is changed with whole div. But In my case data is not changed but expanding downward. Last two divs would carry same data but I didnt post here due to so much code. can someone guide ? <div class="container" > <ul class="nav nav-tabs"> <li class="active"><a data-toggle="tab" href="#pv-maps" >PV Maps</a></li> <li><a data-toggle="tab" href="#wv-maps">WV Maps</a></li> <li><a data-toggle="tab" href="#custom-maps">Custom Maps</a></li> <li><a data-toggle="tab" href="#gn-maps">GN Maps</a></li> </ul> <div class="tab-content"> {# specify for pv-maps #} <div id="pv-maps" class="tab-pane fade in active" > <table class="table" > <thead> <tr> <th></th> <th>Name</th> <th></th> <th></th> </tr> </thead> <tbody> <tr class="dummy"> </tr> {% for map in maps %} <tr> <td> {% if site_acl >= acl.DEMIGOD %} <input type="checkbox" name="ids" value="{{ map.id }}" /> {% endif %} </td> <td>{{ map.name }}</td> <td><a href="{% url 'mapport.map' map.slug %}">Main Interface</a></td> <td> {% if map.acl >= acl.ADMIN %} <a href="{% url 'mapport.maps.one' map.id %}">Dashboard</a> {% endif %} </td> </tr> {% empty %} <td colspan="42">You do not have any maps.<br/>Talk to your map administrator to get this fixed.</td> {% endfor %} </tbody> </table> <div class="action-buttons"> {% buttons %} {% if site_acl == acl.ADMIN or user_type == 'pro' %} <a … -
Django model inheritance: override restrictions in child classes
I will try to abstract my problem: I need to create two model classes for IPv4 and IPv6. I want to do it via inheritance; namely, to create a model class, and then to inherit from this class, but with the additional (different) limit for each of the child classes: class IP(models.Model): ip = models.GenericIPAddressField() class Meta: abstract = True class IPv4(IP): ip = models.GenericIPAddressField(protocol='ipv4') class IPv6(IP): ip = models.GenericIPAddressField(protocol='ipv6') I'm not sure whether or not this is the correct way to do that, and I would like to know which problems might be caused due to such a model. -
Django - user restriction from getting access to same value
I have a calendar which is suppose to be connected to the current admins-association. Admin picks a date in the calendar and register the form so that event is set. But when i log in with another admins-association, i still can see the event from the last admin: I want to keep them separately from each other. These data seems correct to me as no other admins who does not have the same association_id will see the event. Still a newbie so guide me in the right way and appreciate all your help, folks! models.py class Administrator(AbstractUser): # inherits the standard User-model ... association = models.ForeignKey(Association) class Event(models.Model): name = models.CharField(max_length=50) location = models.CharField(max_length=100) start = models.DateTimeField(blank=False) end = models.DateTimeField(blank=False) allday = models.BooleanField() description = models.TextField(max_length=200) synced = models.BooleanField(default=False) gid = models.CharField(default='', max_length=100) association = models.ForeignKey(Association) class Association(models.Model): asoc_name = models.CharField(max_length=50, null=True, blank=True) views.py class calendar(ListView): template_name = 'calapp/calendar.html' def get_queryset(self): queryset = Event.objects.filter(association=self.request.user.association) return queryset def event_add_edit(request): if request.method == 'POST': res = {'success': False} action = request.POST['action'] name = request.POST['name'] location = request.POST['location'] start = request.POST['start'] end = request.POST['end'] allday = request.POST['allday'] == 'true' description = request.POST['description'] synced = request.POST['synced'] == 'true' association = Association.objects.filter(asoc_name=request.user.association) asoc = Association.objects.get(id=association) … -
Django-restframework with pandas
I am using django-restframework,pandas,django-pandas to make an api and i am getting the following output This is the data of a single user and each label represents a column name but I want the output in the following format can anyone help to get the data in the desired format My code is views.py @api_view(['GET']) def my_view(request,id): qs = Health.objects.filter(id = id) df = read_frame(qs) df['x-Mean'] = abs(df['Age'] - df['Age'].mean()) df['1.96*std'] = 1.96*df['Age'].std() df['Outlier'] = abs(df['Age'] - df['Age'].mean()) > 1.96*df['Age'].std() df['bmi'] = df['Weight']/(df['Height']/100)**2 a = df.fillna(0) return Response(a) -
django rest framework Serialization of foreign key
The following are my files of Post app ======models.py===== class Post(models.Model): title = models.CharField(max_length=100,verbose_name="Post Title") description = models.CharField(max_length=500, verbose_name="Post Description") user = models.ForeignKey(to=User,related_name="user_posts") =====serializers.py===== class PostSerializer(ModelSerializer): class Meta: model = Post fields = "__all__" =====views.py===== class PostViewSet(ModelViewSet): queryset = Post.objects.all() serializer_class = PostSerializer I'am able to create a "Post" Model data using httpie as follows http POST http://127.0.0.1:8989/api/v1/posts/ description="Learn Python" title="Python" user=1 Also for the GET request of the Post Model Detail, The serializer works as expected for the foreign key and returns the id for "User" model http GET http://127.0.0.1:8989/api/v1/posts/1/ HTTP/1.0 200 OK { "description": "Learn Python", "id": 1, "title": "Python", "user": 1 // user id } NOW my need is that the post detail should have the "user" key expanded for the User - (While maintaining the same "user" key to PASS user id to create a post) ie., making a GET request to the detail should return the following http GET http://127.0.0.1:8989/api/v1/posts/1/ ===== HTTP/1.0 200 OK { "description": "Learn Python", "id": 1, "title": "Python", "user": { name:"blah blah" ... ... } } *What changes do i need to do in serializers *, so that i will be able to get the details expanded in "user" key? as … -
Launching Django project terminates immediately (sometimes)
I am using PyDev on a Win 8.1 machine with Python 3.6.1. When I launch my debug (or run) configuration, I see in the console: pydev debugger: starting (pid: 8864) Then, a second or so later, the process is inexplicably terminated. No further information is given. Every once in a while, I do manage to launch the server. The behavior is completely random. -
Using Django Restframework to create Single User Sign On
I am currently using the Django Rest Framework. However an external cloud service provider would require a SSO. I was browsing through some answers but didn't get anything helpful. I can authenticate the user for the api curl -X POST -d "email=useremail&password=password" 127.0.0.1:8000 I get the token back. Now i can make api requests. I read something about using SAML, however all the packages are outdated. I was thinking about rewriting the authentication() function, to take in the username and the token to verify the user and redirect him to the App Dashboard. To clarify an external Cloud Service is trying to log in a user into our APP with a direct link. I can't find a nice, clean approach to use here. I don't think i should use something like request.GET.get('username') request.GET.get('password') because i don't think that will be very secure. On the other hand the curl call is pretty much doing the same thing to get the token. Any Advice, Ideas? -
Django - static/CACHE files not found
I'm using Django 1.10 + uWsgi + nginx. In Prod mode the static files do not show up, this is what my nginx error-log tells me: 404 ... static/CACHE/js/e3a6fa7588d1.js" failed (2: No such file or directory), The folder static/CACHE remains empty (so the 404's make sense), but why? I already set the permissions to 775 for static/CACHE . nginx conf: # /etc/nginx/sites/available/mysite_nginx.conf # the upstream component nginx needs to connect to upstream bdjango { server unix:///tmp/mysite.sock; # for a file socket } # configuration of the server server { # the port your site will be served on listen 80; # the domain name it will serve for server_name dev.mysite.com; # substitute your machine's IP address or FQDN charset utf-8; # max upload size client_max_body_size 8M; # adjust to taste # Django media location /media { alias /var/www/mysite/src/media; # your Django project's media files - amend as required } location /static { alias /var/www/mysite/src/static; # your Django project's static files - amend as required } # Finally, send all non-media requests to the Django server. location / { uwsgi_pass adjango; include /var/www/mysite/src/uwsgi_params; # the uwsgi_params file you installed } } Django settings contains PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__) + "../../../") STATIC_ROOT = …