Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
People API or Contact API? Are there any costs?
I need to get some people's information (not my personal google contacts). I want to use this api in my django project and I dont know which api I should use. Contact API or People API? Are there any costs for these apis? -
How to add a datepicker to django forms
Django doesn't support a datepicker for its forms, i didn't find any solution that works for me. If anyone knows some simple solution for this, i'd be very thankful. Thanks. -
Unable to tweet more than 100 characters in tweepy?
I am using tweepy in my django project to tweet automatically. The following code do the same: access_token_secret = users.access_token['oauth_token_secret'] access_token = users.access_token['oauth_token'] # OAuth process, using the keys and tokens auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) # Creation of the actual interface, using authentication api = tweepy.API(auth) if request.method == 'POST': # create a form instance and populate it with data from the request: form = NameForm(request.POST) # check whether it's valid: if form.is_valid(): name = form.cleaned_data['your_name'] api.update_status(status=name); return HttpResponseRedirect('/home') This works fine if the length of status is less than 100, otherwise neither the tweet get posted, nor I get any error message. Any help? -
Django cannot be installed on virtual environment. (permission)
I like to install django on virtual-env I get the following error. I am just curios why it is trying to change things under /usr/local/lib/python2.7/dist-packages/django. Thank you in advance. Your help is much appreciated and voted. Cheers, (env) mike@mike-VirtualBox:~/Desktop/work/django/estore$ pip install django Collecting django Using cached Django-1.10.3-py2.py3-none-any.whl Installing collected packages: django Exception: Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/usr/local/lib/python2.7/dist-packages/pip/commands/install.py", line 342, in run prefix=options.prefix_path, File "/usr/local/lib/python2.7/dist-packages/pip/req/req_set.py", line 784, in install **kwargs File "/usr/local/lib/python2.7/dist-packages/pip/req/req_install.py", line 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "/usr/local/lib/python2.7/dist-packages/pip/req/req_install.py", line 1064, in move_wheel_files isolated=self.isolated, File "/usr/local/lib/python2.7/dist-packages/pip/wheel.py", line 345, in move_wheel_files clobber(source, lib_dir, True) File "/usr/local/lib/python2.7/dist-packages/pip/wheel.py", line 316, in clobber ensure_dir(destdir) File "/usr/local/lib/python2.7/dist-packages/pip/utils/__init__.py", line 83, in ensure_dir os.makedirs(path) File "/usr/lib/python2.7/os.py", line 157, in makedirs mkdir(name, mode) OSError: [Errno 13] Permission denied: '/usr/local/lib/python2.7/dist-packages/django' -
django rest auth verification email
I am trying to use default registration process with django rest auth.After I filled the following registration form it generates a key for me. There is no problem in here However, it does not send any verification email. I really stucked at this point. How can I send the verification email? -
How do I make HTML input values as variables in Python (Django)
Recently started learning python django and I wanted to learn how to make the values that has been input in html as variables in Django. I had look everywhere in the internet but can't seem to find anything so I came here. I am trying to make a voting system. -
Error: cannot import name RemovedInDjango110Warning in django 1.9.5
So this code has been running for like a week now, today it is throwing this error. And this is not happening at the URL level, which many places seem to say. I am using celery, djcelery and Django 1.9.5. In my celery task, in one part where I am trying to connect to my DB, it is throwing this error. The strange part is when I run the code line by line in shell, it works. All this code runs inside a virtualenv being used by two projects which have exactly same requirements. to confirm, I just checked the django version in pip. It is 1.9.5 Please let me know if any extra info is required. -
django admin css on apache server
I need to solve the missing admin page css problem. I have tested almost all the solutions on the web with no luck! (I'm using django 1.8 on apache2.4) Here's what I've done so far: in setting.py I have: INSTALLED_APPS = [ ... django.contrib.staticfiles', ... ] STATIC_URL = '/static/' PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_DIR, 'static') and in etc/apache2/sites-available/000-default.conf I have: Alias /static /var/www/mysite/mysit/static <Directory /var/www/mysite/mysite/static> Require all granted </Directory> I also reloaded the apache. It seems that I'm doing something wrong since the django admin doesn't show the css. Any help would be appreciated. -
Software as a service in Django - many companies should be able to have the same users
Workflow: User in registration form gives his email, password and company name. The company with the same name is automatically creates during registration process(model Company). This user is automatically admin of the company(in User model I have role field). Company admin can invite candidates. In form gives candidate email, first and last name. Application sends an email with activation link to candidate. The candidate by clicking the link is transfered to the page with form where sets his password and is redirected to login page Candidate can log in and add new items to database(model Item) The problem is that many companies should be able to have the same user(the same email address). Currently application returns that email is already in use(in other company but it can't be like that). So this is something like Software as a Service. Any ideas how to solve this problem? -
Django / SQLite : Is there a way to see if someone is *currently* logged-in by checking db.sqlite3?
I'm using Django 1.10 with SQLite as my database back-end. I have a site running with nginx/uwsgi and the above configuration, which I'm constantly updating with new code. Each time I want to update the site code, I'm shutting down uwsgi, nginx, git pull ing the new version from my repo, then restarting uwsgi and nginx. While this works, in the sense that the site is updated with the new version of my code, the side-effect is that in the event that a user is currently logged in the site and working on something (which generally will result in modifying the db), the user's work will be interrupted. Worse still would be the case that the new version of my code contains migrations, which will change the db structure, with (unpredictable?) consequences on the user's on-going work. So the question is: is there a way, like a command-line script, to check db.sqlite3 and see if a user is currently logged-in, before deciding to shutdown uwsgi and nginx ? -
how do i delete a users message without query error?
I am having trouble with my page redirect when deleting a users comment. below is my code. It deletes the message but gives me this error: Message matching query does not exist for Message.objects.get(id=message_id).delete(). def remove_message(request, message_id): Message.objects.get(id=message_id).delete() return redirect(reverse('dashboard:show')) -
Relative Import Error
I am originally a Django developer and now I'm trying to play some basic and pure python OOP. I'm all good until I tried importing an abstract base class to be inherited on my child classes My folder structure is: βββ OOP β βββ __init__.py β βββ abstract_base_class.py β βββ classes.py β βββ inheritance.py β βββ inheritance.pyc My abstract_base_class.py is: from abc import ABCMeta, abstractmethod class Vehicle(object): """ @brief An example of Abstract Base Class @attrs base_sale_price: wheels: """ __metaclass__ = ABCMeta """ - A metaclass is the class of a class. Like a class defines how an instance of the class behaves, a metaclass defines how a class behaves. A class is an instance of a metaclass. - This declares that the class is abstract -- This will not run as long as there is an abstractmethod decorator -- Try running this and it will result to: --- TypeError: Can't instantiate abstract class Vehicle with abstract methods vehicle_types - Try removing this and the class will work just fine """ base_sale_price = 0 wheels = 0 def __init__(self, miles, make, model, year, sold_on, *args, **kwargs): """ @brief Constructs the object. @attrs wheels: An integer representing the number of wheels β¦ -
How to redirect a page which don't want show it within modal
I defined a modal which has a form inside. When load the modal, it will send a get request to ModelForm, but if the user is not log in, I want to redirect to login page which don't show it within modal box. So how to redirect a new/single page when I solve the get request in Django part. -
Django - ForeignKey : Is it possible get multiple kind of objects referencing itself?
models.py class BaseModel(TimeStampedModel): is_active = models.BooleanField(default=True) def deactivate(self): # Make all child objects is_active=False class ModelA(BaseModel) pass class ModelB(BaseModel): model_a = models.ForeignKey(ModelA) class ModelC(BaseModel): model_a = models.ForeignKey(ModelA) As you can see above, I want to make deactivate method for setting all childeren's is_active field as False. Someone might think of this way: def deactivate(self): # Make all child objects is_active=False b = ModelB.objects.filter(parent=self) c = ModelC.objects.filter(parent=self) for obj in b: obj.is_active = False obj.save() for obj in c: obj.is_active = False obj.save() But it only works for ModelA which ModelB, ModelC are referencing, not available for all models. I want to make it general method so that I can use it in any models: all_model_objects = ModelsReferencingMe.objects.filter(parent=self) Is there any way to implement this? -
Queryset is evaluated when sliced?
In django queryset doc(https://docs.djangoproject.com/en/1.10/ref/models/querysets/), it says "Internally, a QuerySet can be constructed, filtered, sliced, and generally passed around without actually hitting the database. No database activity actually occurs until you do something to evaluate the queryset." And then, it says "You can evaluate a QuerySet in the following ways: Iteration / Slicing / . . ." . So, my question is "whether Queryset is evaluated when sliced" . -
How can I prevent 'staff' from deleting models in django admin?
I have a team members and make them able to manage admin sites. But I want to give them permission only for add, change(not delete) models in admin site. What I tried is below: Make them staff (Not Superuser) Give them only add, change pemissions. However, this user is able to delete models in admin site! What's wrong with my setting? -
upload image path in Richtextfield in Django
I am using RichTextField() from CKEDITOR in Django. How can I set path for the images I upload to RichTextField() and how can i retrieve them ? from ckeditor.fields import RichTextField from django.db import models class Post(models.Model): page_content = RichTextField() -
Properties Format on Geojson to MongoDB/Mongoengine
I would like to find a solution on what DataField I should give to a geojson with a properties column. Currently a geojson format below would not have any issues since it it would only need the StringField() and PointField(). A geojson format looks like this: { name : "Timmy's Taco Truck", loc : { type : "Point", coordinates : [ 37.7577 , -122.4376 ] } } However for a geojson with this format: { "type" : "Feature", "id" : "ID80001", "geometry":{"type": "LineString", "coordinates":[[122.332,14.241],[125.332,13.532]]}, "properties":{ "name":"Dummy Name", "color":"#000000" } } Using a model like the one below: from mongoengine import * from colorful.fields import RGBColorField class Geometry(Document): type = StringField() id = StringField() geometry = LineStringField() name = StringField() color= RGBColorField() ***OR*** properties = ??? If I use EmbeddedDocumentField and create a separate properties field it would result to "properties": [{"name": "Dummy Name","color": "#000000"}] not: "properties": {"name": "Dummy Name","color": "#000000"} How can I preserve the geojson format in the models? -
How to reuse setup code of Django tests?
Writing setUp function of test case is a challenging work. Since code lines increasing. I have to write some similar code in different test case. How to improve the reusability? -
Django : combine variable and HTML id in template
I'm looking for a way to "concatene" a django object list (get via the get_queryset in the views.py) with a Javascript variable. then concatene them to a field of a model object. My model is a blog post, and contains the post_title field (a charfield). In my index.html, I have a pager button with id="1" or id="2" corresponding to the index of the page and a onClick="displayPostContentOnPageButtonCliked(this.id)" attribute. My index.html retrieve all post objects in a context_object_name called all_post_by_date. In my index.html, I want to display on alert dialog the post title corresponding to the button clicked, something like: <script> function displayPostContentOnPageButtonCliked(page_button_clicked_id){ var all_posts_by_date = "{{all_posts_by_date.page_button_clicked_id.post_title}}"; alert(all_posts_by_date); } </script> But this doesn't work. I tried to add filter or create my own filter (called get_index, but only manage to get like: all_posts_by_date|get_index:page_button_clicked_id and not be able to combine the .post_title part. My question is: how to get {{all_posts_by_date.page_button_clicked_id.post_title}} to work, and alert "Title of post 3" when the button 3 is clicked ? Thank u ! -
How can I make two differents login forms in Django?
How can I log in and redirect to his "Dashboard" and a login form for the admin site and redirect to his "Admin Panel" I have been looking for and read that it can be done by creating a ModelBackend and found this as a reference but it does not make me clear how to do it. https://docs.djangoproject.com/en/1.8/topics/auth/customizing/ Thank you very much for your help.! -
How to inject csrf token into request before POSTing from a python function?
I am doing a POST request from a python function. Is there a helper to add csrf to the POST body? I tried the csrf_protect decorator but that does not seem to work in this case. I think it works for a GET operation only. -
Django TypeError from Ajax action
I'm using DjangoTables to display records. I want to use Ajax on a Delete link to delete the relevant Site record (and the Deal records linked to it) without having to refresh the table page. Clicking on 'Delete' deletes the relevant records and vanishes that row of the table as I wanted, but then I get this in my console: TypeError: int() argument must be a string, a bytes-like object or a number, not 'builtin_function_or_method' [19/Nov/2016 03:51:56] "GET /sites/tested/sites/delete/?recordid=1 HTTP/1.1" 500 18116 That doesn't look good. Why is it there, and how do I make it go away? static .js file: $(document).ready(function() { $(".row-delete").click(function(event) { event.preventDefault(); var recordid; recordid = $(this).attr("data-recordid"); $.get('sites/delete/', {recordid: recordid}, function(data){ }); $(this).parent().parent().fadeOut("fast"); }); }); View: class SiteDelete(View): model=Site def get (self, request): site_id = None if request.method == 'GET': site_id = request.GET['recordid'] DealsToDelete = Deal.objects.filter(Site=id) DealsToDelete.delete() DeleteSite = Site.objects.get(id=site_id) DeleteSite.delete() Table class TestedTable(tables.Table): Approve = tables.TemplateColumn('<a href="{% url \"sites:approve\" id=record.id %}"</a>Approve') Delete = tables.TemplateColumn('<a href="{% url \"sites:delete\" %}\" data-recordid = \"{{ record.id }}\" class=\"row-delete\">Delete</a>') Name = tables.TemplateColumn('<a href="{% url \"deals:bysite\" record.id %}"</a>{{ record.Name }}') urls.py from django.conf.urls import url from sites.views import SiteCreate, SiteUpdate, SiteDelete, IndexView, TestedView, DetailView, ApproveSite from django.core.urlresolvers import reverse_lazy app_name = β¦ -
Django Adaptor CSV import Date format issues
I am trying to upload a csv file into a database with a date column using the package Django Adaptor - https://django-adaptors.readthedocs.io/en/latest/ My csv file date format is %d/%m/%Y and it seem the system only accept a date format %Y-%m-%d. How do I change my csv format to fit the system? Or is there away to change the system to accept my csv file date format? I am using Django 10.1. Thanks in advance! class Transactions(models.Model): date = models.DateField() description = models.CharField(max_length=40) amount = models.DecimalField(max_digits=15, decimal_places=2) balance = models.DecimalField(max_digits=15, decimal_places=2) class UploadTransactionsModel(CsvDbModel): class Meta: delimiter = ";" dbModel = Transactions -
Returning items as they come in Python
I am not quite sure I am using the correct terminology but I would like to have access to items being returned by my function before the function finishes. For example, I am working on a Django project where I have a function that scrapes a cooking website, and returns what recipes you can cook based on the ingredients that you have. The function works as expected but it takes a very long time. I would like to present users with the recipes that they can cook as they are found, instead of them having to wait for the entire function to run and thus the webpage to load. I've pasted the relevant code below. Any help would be greatly appreciated. def give_recipe_from_ingredients(pantry_items): for link in get_recipe_links(): current_ingredient_list = [] can_cook = True grab_from = link grab_page = urllib.request.urlopen(grab_from) grab_soup = BeautifulSoup(grab_page, 'html.parser') rec_title = grab_soup.find('h2', attrs={'entry-title'}) title = rec_title.text.strip() for ingredient in grab_soup.find_all('span', itemprop="name"): ingredient_strip = ingredient.text.strip() current_ingredient_list.append(ingredient_strip) for item in pantry_items: for ingredient_in in current_ingredient_list: if str(item) in ingredient_in: if title not in recipes_you_can_cook: recipes_you_can_cook.append(title) return recipes_you_can_cook