Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to copy all the data from main server database to the local sqlite database to use locally?
Local database setting- `DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } }` main database setting- `DATABASES = { 'default': { 'ENGINE':'django.db.backends.mysql', 'NAME': '******', 'USER': '******', 'PASSWORD': '********', 'HOST': '******', 'PORT': '****', } }` I did it from the git project python manage.py dumpdata > all.json . But then i don't know what to do next like how to use this json file to update local database by which commands. i am very beginner to this. kindly help me solve this problem. -
Why is this form being returned as invalid (uploading a text file)
I am trying to develop a minimal text file uploading example. This is what I currently have. Whenever I submit my form with a selected file its validation fails. This is the Form class UploadFileForm(forms.Form): file = forms.FileField() This is the View def add_view(self, request, form_url='', extra_context=None): if request.method == 'POST': form = UploadFileForm(request.POST) if form.is_valid(): file = form.cleaned_data["file"] ..... ..... else: form = UploadFileForm() return render(request, 'upload.html', {'form': form}) This is the template : upload.html <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form|crispy }} <input type="submit" value="Submit" /> </form> I am aware there are a couple of examples out there however I would like to know what might be wrong with my code. Whenever I submit my file my form validation fails. -
Django Models Option Save
i just want to ask how it works that method "save", in this model? I just trying to add this to my code, but i really dont know how it works.. Those lines help me to save the slugify if theres is not an id in the model? Thank you so much. class Category(models.Model): name = models.CharField(max_length=50) slug = models.SlugField(editable=False) def save(self, *args, **kwargs): if not self.id: self.slug = slugify(self.name) super(Category, self).save(*args, **kwargs) def __unicode__(self): return self.name -
Django Error-13 to some html files in a folder
I am facing a permission error while using django via apache in my local system (using apache). First, my config: Django: 1.9.5 Python:3.4.3 Apache: 2.4.7 Now, the complete site is getting rendered via apache except the forgot password (used to send mail). The issue is not with mail as the mail can be sent from other locations. This is the error being shown: [Errno 13] Permission denied: '/home/sayantan/Desktop/djangowork/project/school/templates/registration/password_reset_form.html' Now, this same root (inside registration) has my login and logout files. However, the password reset files are the ones causing the problem (all the four html: password-reset, password-reset/done, password-reset/confirm/...,password-reset/complete, are not working). I have set up a usergroup (varusergroup), added www-data to it, and have given 770 permission to this. Any help would be greatly appreciated. -
Employing caching for the first page of a paginated view in Django
I have a paginated Django forum where posts by users accumulate according to most recent time of posting. I show 20 posts per page. During peak time, a new post is saved every ~2 seconds, whereas pages are requested for viewing up to 11 times per second. I want to reduce DB hits by introducing caching here. I've noticed most of the traffic hits the first of the paginated pages - so this is the one I want to cache. Essentially, I plan to set the first page in the cache at every write, and get it whenever viewers want to consume it. I have the options of redis and memcache as a cache backend (I'm using both in varying capacities). My question is about how to cache and serve just the first page. I can't seem to wrap my head around that. My uncached code is as follows. An illustrative example of how to proceed from here would be great: #object_list has up to 1000 object ids at a time paginator = Paginator(object_list, 20) #pass list of obj ids & no. of objs/page page = request.GET.get('page', '1') try: page = paginator.page(page) except PageNotAnInteger: # If page is not an … -
Coding with pygame for android platform?
Hello guys i have this questions: It is possible to write games with python and port to android?if it has someway which one is the proper way to use?and need advice from expert in python ,is there anyway you make simple game with pygame and use it in your django project? -
Django: append a count of manytomany object instances and then retrieve it in template
Okay, so I'm sure i'm making a simple error here but I'm at a loss as to what it might be at this point or where to even begin to find the cause of this failing... I have 5 models, set up like so: class Keyword(models.Model): key = models.CharField(max_length=2000, unique=True) def __str__(self): return self.key class Entries(models.Model): name = models.CharField("Name", max_length=200) updated = models.DateTimeField("Last Updated", auto_now=True) key_list = models.ManyToManyField(Keyword, blank=True, verbose_name="Keywords") description = models.TextField("Description", blank=True) class Meta: abstract = True class Employee(Entries): uid= models.SlugField("UserID", max_length=6, unique=True, blank=True) manager = models.SlugField("Manager's UserID", max_length=6) def __str__(self): return self.name class Vendor(Entries): company = models.CharField("Vendor Company", max_length=200) email = models.EmailField("Vendor's Company Email Address", max_length=254, unique=True) vend_man_name = models.CharField("Manager's Name", max_length=200) vend_man_email = models.EmailField("Manager's Email Address", max_length=254) def __str__(self): return self.name class Application(Entries): app_url = models.URLField("Application URL", max_length=800, unique=True) def __str__(self): return self.name class Machine(Entries): address = models.CharField("Machine Address", max_length=800, unique=True) phys_loc = models.TextField("Physical Location", blank=True) def __str__(self): return self.name and my templatetag to display the data is thus: @register.inclusion_tag('Labswho/key_cloud.html') def key_cloud(keys_selected=''): key_list = Keyword.objects.all() for entry in key_list: counter = Keyword.objects.filter(employee__key_list__key__contains=entry).distinct().count() counter += Keyword.objects.filter(vendor__key_list__key__contains=entry).distinct().count() counter += Keyword.objects.filter(application__key_list__key__contains=entry).distinct().count() counter += Keyword.objects.filter(machine__key_list__key__contains=entry).distinct().count() entry.append({'counter': counter}) context = {'key_list': key_list} return context but it keeps throwing me errors. What … -
define custom search terms with django rest framework search backend
A Django rest framework serializer for one of my models (Child) includes a value from another instance of another model (Parent) that holds a many to many relationship to Child. class Child(models.Model) ... class Parent(models.Model) example = models.CharField(max_length=128) children = models.ManyToMany(Child, null=True) where the serializer for Child uses a rest framework SerializerMethodField to return the example value from the parent that holds a relationship to it. I am using the django rest framework filter backend to do both filtering and searching in my API ViewSet filter_backends = (filters.DjangoFilterBackend,filters.SearchFilter) My question is how can I add a search term like 'child__parent__example' to the search fields? I appear to be able to do 'child__peer__example' if peer holds a foreign key to the child; however, I can't do this with many to many. How can I customize what this search query should return in the search backend? Furthermore, how can I also add this customization for filter as I don't see enough flexibility in subclassing django_filters.rest_framework.FilterSet. -
to 'get_success_url()' or not (Django)
Need to clear a basic concept. In Django, what's the harm in redirecting to a view from form_valid() itself, instead of declaring a get_success_url()? I.e. why is the following inferior, compared to what's below it: class PostCreateView(CreateView): model = Post def form_valid(self, form): # do something return redirect("home") class PostCreateView(CreateView): model = Post def form_valid(self, form): # do something return super(CreateView, self).form_valid(form) def get_success_url(self): return reverse_lazy("home") -
Django 1.10, Apache 2.4 Serving Basic App on CentOS7 Getting 403 Forbidden to /
Screwing around at this point just to try and get it working. I am getting a 403 Forbidden: You don't have permission to access / on this server. error. I have been following this guide on how to setup Apache to work with CentOS and Django: https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-apache-and-mod_wsgi-on-centos-7 Also, read several questions on SO regarding the error, but none have resolved the problem. Fresh Django project install so should just be showing the static "it's working page" at localhost:8000, I would think. /etc/httpd/conf.d/django_test.conf Alias /static /home/dev/testserver/static <Directory /home/dev/testserver/static> Require all granted </Directory> <Directory /home/dev/testserver/testserver> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess testserver python-path=/home/dev/testserver:/home/venvs/django/lib/python3.6/site-packages WSGIProcessGroup testserver WSGIScriptAlias / /home/dev/testserver/testserver/wsgi.py I am pretty naive when it comes to this, but do I or don't I have to run python manage.py runserver in addition to having HTTPD setup? Or does that only apply to if you are developing locally using the built in Django server? Speaking of which, I can visit the page on the remote server using the built in Django server, but understand this highly undesirable. I do have port 80 open and can see that it is listening for traffic. Per the tutorial I gave the /home/dev directory chmod 710 … -
AttributeError: 'ManyToManyDescriptor' object has no attribute 'all' - django
I have a staff model which can be assigned to many other groups model I tried calling to get a response of what groups does this staff belong to but I keep on getting errors. Can someone please give me a hand? User model class Staff(Model): groups = ManyToManyField(Group, related_name="%(class)ss", related_query_name="%(class)s", blank=True) class Group(Model): creator = ForeignKey(Employer, on_delete=CASCADE, related_name="%(class)ss", related_query_name="%(class)s") group_name = CharField(max_length=256, unique=True) created_at = DateTimeField(auto_now_add=True) I have tried a few ways such as staff = Staff.objects.filter(pk=1) groups = staff.group.all() or groups = staff.group_set.all() or groups = staff.group.filter() and some other ways that I can't remember but I keep on getting errors. Thanks in advance -
Is it possible to query state of a celery tasks using djang-celery-results during the execution of a task?
I am using Celery + RabbitMQ for queuing tasks in my Django App, I want to track the state of a task using the task_id and the task_state. For that i created a TaskModel(Model) to store the task_id, task_state and some additional data in the database. On task execution, a new TaskModel object is save and updated as the task progresses. Everything is working fine. However, i still need to add a lot of functionality and features and error protections etc. That's when i remembered the celery documentation mentions the django-celery-results. So i followed the django-celery-results documentation instructions. Tasks results get stored in the default django database in a dedicated table, However only after the task concludes... and not during the PENDING, STARTED states. Is it possible to use django-celery-results to store and query tasks during the PENDING and STARTED states? or not? Thanks -
Registering Django app for OAuth and Consuming API
I've been creating a Django app, and my current goal for it is to pull data from an API to my app, the Open Street Map API test service to be exact. All of the API calls must be made by an authenticated and authorized user (via OAuth). So far I've made an OAuth account and they've given me values for my app (Consumer Key, Consumer Secret, Request Token URL, Access Token URL, Authorise URL). This is where my knowledge of OAuth and APIs comes to an end, as I have no idea how to continue to reach my goal. I have tried searching for a solution, but it seems every example I can find uses a version of Django that's too old and their steps are incompatible with my current version (Python 3.6 and Django 1.10). Any help will be appreciated. -
Django Ajax 403 only when Posting from custom localhost url
I followed all the instructions to get Ajax working properly with Django (ajaxSetup to add the X-CSRFToken header on every request, etc) and that part now works fine. I'm using django-rest-framework, django-allauth and rest-auth I'm now trying to test Facebook login with DRF, since Facebook doesn't allow for localhost to be a registered app I edited ~/etc/host and added local.test.com as an alias for 127.0.0.1. Now whenever I try to post to Django I get 403 forbidden again. I think it may have something to do with the Request URL and the Remote Address being different, but I don't really know what to do with it. Since I'm not sure where the problem is I think it makes more sense to just share the link to the project on github: https://github.com/Sebastiansc/Sauti What can I do to allow POST Ajax requests coming from local.test.com to work? -
How do you create a sitemap index in Django?
The Django documentation is very minimal and I can't seem to get this to work. Currently I have 3 individual sitemaps, and I would like to create a sitemap index for them: (r'^sitemap1\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps':sitemap1}), (r'^sitemap2\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps':sitemap2}), (r'^sitemap3\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps':sitemap3}), The Django documentation mentions adding something along the lines of: url(r'^sitemap-(?P<section>.+)\.xml$', views.sitemap, {'sitemaps': sitemaps},name='django.contrib.sitemaps.views.sitemap'), What is in this case? And how do I access this index file? Is it downloadable or is it accessible via a url? Any help is greatly appreciated! -
How to build a Slack-like left panel in Django to minimize database access
I am working on a Django app that has a left panel similar to Slack's. It shows the channels that the current user has subscribed to. Since this panel is shown for every page, I put it in the base template. My question is that because the panel content is dynamic, it will create a database access (getting the list of channels for the user) each time a page is loaded. What would be the best way to optimize it? Should I cache the content of the left panel and invalidate it if it changes (if the user subscribed to a new channel or left a channel)? Are there any other options? -
Query django model for data from an external source
Given a django model and some data from an external source. # models.py class UserRelationship: user_id - IntegerField staff_id - IntegerField valid_from - DateTime # api.py class Approval: user_id - Int created_at - DateTime Given a list of "approvals" (derived from an external source) e.g approvals = [{'user_id': <user_id>, 'created_at': <created_at>}, ...] I need find an efficient way to find "staff_id" at the time of approval for a list of ~20k+ "approval" objects. i.e for each dict find a matching row where approval.user_id = user_relationship.user_id and approval.created_at <= user_relationship.valid_from Im not sure where to start, I can't think of a way to do this using django ORM. Any help or tips will be greatly appreciated. Many Thanks. -
Django: Multiple parameters in URLs reverse resolution without querystrings or captured parameters
Without using query strings (like ?case=/2/), nor captured parameters in the url conf (like ?P) (so they dont show up in the url), is there a way to pass parameters to a view function when using URLs reverse resolution? Hopefully an example will clarify my question: With captured parameters I could do: views.py ... return HttpResponseRedirect(reverse('videos:show_details', args=[video.id])) urls.py ... url(r'^club/(?P\d+)/$',views.details, name='show_details'), ... But what if the view details needs / accepts more parameters, for example: def details (request, video_id, director='', show_all=True): And we dont want them to show up in the url? Any way of using args or kwargs without them being in the url? Im sure Im missing something trivial here :S Hopefully someone can point me in the right direction. Thanks! -
Which is best for Dashboard web development Python or Javascript
Folks Basically i have a large csv file with large amount of aws analysis data i want to develop a dashboard based on csv file Ex: No of instances their state ['Running', 'Stopped'], Running since n days, Size, health i want to develop a visualization board. Assuming In future i can include aws api calls On basis of above desc which language suits best to develop -
OperationalError: (1054, "Unknown column 'example.example_field' in 'field list'")
My Example model used to have a decimal field example_field defined as: sample_field = models.DecimalField(decimal_places=1, max_digits=3, blank=True, null=True) I decided to remove this field from Example model and everywhere in the code that I used example_object.example_field. After makemigrations and migrate, everything worked well and I made a pull request to a remote branch. Then I switched to another local branch and got this error: OperationalError: (1054, "Unknown column 'example.example_field' in 'field list'") It makes sense becuase this branch still uses example_object.example_field. However, after the remote branch accepted the pull request. I still got the same error after pulling from the remote branch. Remote branch was deployed on AWS after accepting the PR. One of the two instances was working fine, but the other one had the same OperationalError. -
"No module named context_processors" After Upgrade
I've upgraded Django from version 1.8 to version 1.10 and I am now getting the below error: No module named context_processors This is in relation to this code in settings.py. If I comment out the lines that start with 'django.core it runs fine but I obviously will be losing functionality: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ TEMPLATE_PATH, ], 'APP_DIRS': True, 'OPTIONS': { 'debug': DEBUG, 'context_processors': [ ... 'django.core.context_processors.debug', 'django.core.context_processors.i18n', 'django.core.context_processors.media', 'django.core.context_processors.static', 'django.core.context_processors.tz', 'django.contrib.messages.context_processors.messages', ... ], }, }, ] How can I fix this? Note: This, this and this are all similar but nothing Google returns addresses this issue. -
call http (non SSL/HTTPS) rest from FireBase hosted site, using XMLHttpResponce
I am trying to build a firebase hosted page that will connect to a (Django) HTTP web service using XMLHttpResuest in the below script. <script> function UserAction() { var req = createRequest(); // defined below // Create the callback functions: var handleResponse = function (status, response) { alert("status " + status + " response: " + response) } var handleStateChange = function () { switch (req.readyState) { case 0 : // UNINITIALIZED case 1 : // LOADING case 2 : // LOADED case 3 : // INTERACTIVE break; case 4 : // COMPLETED alert("case 4" + req.responseType); handleResponse(req.status, req.responseJson); break; default: alert("error"); } } req.onreadystatechange = handleStateChange; req.open("GET", "https://foo.org:/bar/getid/?Id=" + document.getElementById('ID').value, true); req.send(); function createRequest() { var result = null; if (window.XMLHttpRequest) { // FireFox, Safari, etc. result = new XMLHttpRequest(); } else if (window.ActiveXObject) { // MSIE window.alert("windows"); result = new ActiveXObject("Microsoft.XMLHTTP"); } else { // No known mechanism -- consider aborting the application window.alert("no known mechanism"); } return result; } }</script> Using Chrome FireBase throws 404 error. Django server does not register any connection. Using FireFox FireBase throws 404 error. But Django server throws 'code 400, message Bad HTTP/0.9 request type ('\x16\x03\x01\x00\xcc\x01\x00\x00\xc8\x03\x03\xdf\x04{\x9f\xe4\xb2\xc2ij\x8d\x14\xd5\xaa\xdcu\x14+&\xa4\xa1\xdf\xdc\xd8\x9b?\xea\xbdh\xb8')` I did find this in the … -
Django - filter objects (multiple categories of the same model)
I have Site.model with has category, category1 values: Site A: - category1 - category2 Site B: - category1 - category3 I would like to filter objects in particular category to show only related sites (for example in category1 there should be Site A and Site B, in category3 - only Site B). Now my code looks like: class SiteList(): def __init__(self, category_slug, subcategory_slug=None): self.cat_slug = category_slug self.subcat_slug = subcategory_slug def get_context(self): context = {} if self.subcat_slug is None: category = Category.objects.get(slug=self.cat_slug) sites = Site.objects.filter(category=category, is_active=True) subcategory = SubCategory.objects.values().filter(category=category) else: category = Category.objects.get(slug=self.cat_slug) subcategory = SubCategory.objects.filter(category=category ).get(slug=self.subcat_slug) sites = Site.objects.filter(subcategory=subcategory, is_active=True) context['subcategory'] = subcategory print(subcategory) context['category'] = category context['sites'] = sites return context Is it possible to write something like??: sites = Site.objects.filter(category=category or category1=category, is_active=True) I don't have any idea how can I filter sites to display proper objects. This is my Site model: class Site(models.Model): category = models.ForeignKey('Category') subcategory = ChainedForeignKey( 'SubCategory', chained_field='category', chained_model_field='category', show_all=False, auto_choose=True) name = models.CharField(max_length=70) description = models.TextField() keywords = MyTextField() date = models.DateTimeField(default=datetime.now, editable=False) url = models.URLField() is_active = models.BooleanField(default=False) category1 = models.ForeignKey('Category', related_name='category', blank=True, null=True) subcategory1 = ChainedForeignKey( 'SubCategory', chained_field='category1', chained_model_field='category', related_name='subcategory', show_all=False, auto_choose=True, blank=True, null=True) group = models.CharField(max_length=10, choices=(('podstawowy', 'podstawowy'), ('premium', 'premium')), … -
Django ModelForm not saving user that create posts on db
A Django beginner here having a lot of trouble getting forms working. I' ve trie different ways but I can't save the user on the database. I get this error : "IntegrityError at /n_post/ NOT NULL constraint failed: learning_logs_post.owner_id" views.py: def nuovo_post(request): if request.method != 'POST': # No data submitted; create a blank form. form = PostForm() else: # POST data submitted; process data. form = PostForm(request.POST) if form.is_valid(): n_post = form.save(commit=False) n_post.owner = request.user n_post.save() return HttpResponseRedirect(reverse('learning_logs:posts')) context = {'form': form} return render(request, 'learning_logs/nuovo_post.html', context) models.py: class Post(models.Model): title = models.CharField(max_length=200) description = models.TextField() image = models.ImageField(blank=True) date_added = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User) forms.py: class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'description', 'image'] labels = {'title': "Title", 'description': "Description"} widgets = {'description': forms.Textarea(attrs={'cols': 80})} -
Django YearArchiveView Year offest?
I am making a simple calendar application that will track events across a School Year (Aug-May). What I would like to do is have an archive view that will allow the user to select a school year and see that school year’s worth of events. For this I thought I would use the Django Class YearArchiveView. The issue is, I am not sure how to filter the results so that instead of getting a Jan to Dec result to get Aug to May. View: class EventArchiveView(YearArchiveView): template_name = "cal/cal_archive.html" queryset = CalEvent.objects.all() date_field = 'start_date' make_object_list = True allow_future = True Model: class CalEvent(Audit): CAL_CHOICES = ( ('HOLIDAY','Holiday'), ('SECONDARY','Secondary'), ('ELEMENTARY','Elementary'), ('TEACHER','Teacher'), ('TERM','Term'), ('TESTING','Testing'), ('GRAD','Graduation'), ) title = models.CharField(max_length=255) category = models.CharField(max_length=20,choices=CAL_CHOICES,default='HOLIDAY') start_date = models.DateField(help_text="Format: M/D/Y") end_date = models.DateField(blank=True,null=True,help_text="Format: M/D/Y. Not Required. Fill if event will spans multiple days.") week = models.IntegerField() active = models.BooleanField(default=False) def __str__(self): return self.title def cat_verbose(self): return dict(CalEvent.CAL_CHOICES)[self.category] class Meta: verbose_name_plural = "Cal Events"