Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to remove and add completly new db.sqlite3 to django project written in pycharm?
How to remove and add completly new db.sqlite3 database to django project written in pycharm? I did something wrong and I need completelty new database. The 'flush' command just removes data from databse but it't dosent remove tables schema. So the question is how to get get back my databse to begin point(no data, no sql table) -
Django generic relations modelling
I'm trying to model something in Django and it doesn't seem quite right. A Book and a Movie can have one or more Persons involved in it, each of whom has a Role (like "Author" or "Director") on that Book or Movie. I'm doing this with Generic relations something like this: from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models class Person(models.Model): name = models.CharField(max_length=255) class Role(models.Model): role_name = models.CharField(max_length=255) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') class Book(models.Model): title = models.CharField(max_length=255) roles = GenericRelation('Role', related_query_name='books') class Movie(models.Model): title = models.CharField(max_length=255) roles = GenericRelation('Role', related_query_name='movies') Which seems to work, but it seems odd when getting all the Books a Person has worked on: person = Person.objects.get(pk=1) for role in person.role_set.all(): print(role.role_name) for book in role.books.all(): print(book.title) The for book in role.books.all() feels wrong - like a role can have multiple books. I think I want a more direct relationship between a person working on a particular book/movie. Is there a better way to model this? -
How to access variables in an API view from my permission class in Django Rest Framework?
so I have this system set up so that whenever a POST, PUT or DELETE request is made to my API, I check for my shop's key in the header, and match it. I am trying to set this up using a permission class. I am doing the following: permissions.py SAFE_METHODS = ('GET', 'HEAD', 'OPTIONS') class BasePermission(object): def has_permission(self, request, view): return True def has_object_permission(self, request, view, obj): return True class IsShopkeeperClient(BasePermission): def has_permission(self, request, view): if request.method in SAFE_METHODS: return True else: if request.method == 'POST' or request.method == 'PUT' or request.method == 'DELETE': if not request.META.get('HTTP_SHOPKEY') == view.shop.key: return False return True Notice how I try to call view.shop.key in my permission. In my views, I am doing the following: @api_view(['GET', 'POST']) @permission_classes((IsShopkeeperClient,)) def categories_list(request, username): try: shop = Shop.objects.get(username=username) categories = shop.categories.all() except: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = CategorySerializer(categories, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = CategorySerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) So, basically, the shop is a variable in my view. As a result of this, I get the following error: categories_list does not have the attribute shop Something along those lines. So, how can I pass … -
Can't log in to Django-Admin but can log in with custom form
In a recent code change I am no longer able to log in through /admin/ or my default login page, but I can log in using a page that redirects to the login page. The redirect in question: def show_calendar(request): user = None if request.method == "POST": email = request.POST.get('email') password = request.POST.get('password') user = authenticate(email=email, password=password) if user is not None: login(request, user) else: return render(request, 'registration/login.html', {'error': 'Email and password not recognised. Please try again.'}) if request.user.is_authenticated or user: return render(request, 'calendar/full_calendar.html', {}) return render(request, 'registration/login.html', {}) The above view works when authenticating like that. However, when logging in via my login page or /admin/ I get some logs from within django.contrib.auth.authenticate and it seems to always be hitting This backend doesn't accept these credentials as arguments. Try the next one.: def authenticate(**credentials): import logging logging.basicConfig(filename='example.log', level=logging.DEBUG) """ If the given credentials are valid, return a User object. """ for backend, backend_path in _get_backends(return_tuples=True): logging.debug(credentials) try: inspect.getcallargs(backend.authenticate, **credentials) except TypeError: logging.debug("This backend doesn't accept these credentials as arguments. Try the next one.") # This backend doesn't accept these credentials as arguments. Try the next one. continue credentials logs as: DEBUG:root:{'password': 'pass', 'username': 'admin@admin.com'} Relevant settings.py: INSTALLED_APPS = [ … -
Install site-packages inside virtual environment python
I am working on deploying my django application on a RHEL with pre installed python packages using uwsgi and nginx. Server is installed uwsgi and nginx globally(as root). My server is not connected to internet. I have secure copied my django project inside this server. For best practices I am told to use virtual environment and when I do the command, virtualenv -p /usr/local/lib/python3.5/bin/python3.5 venv All is cool. It creates a virtual environment with python 3.5. But the problem is, I need these site packages which is pre installed on the server into this virtual environment. Example django, redis etc. When I do the above command with --system-site-packages it throws me this error PermissionError: [Errno 13] Permission denied: '/usr/local/lib/python3.6/site-packages/wheel-0.29.0.dist-info' Is there a cleaner way to do this or where is it going wrong `? -
Django and Ajax: CSRF token missing despite being passed
I'm trying to hit an API endpoint that I made using django-rest-framework when a button is pressed. I'm using jQuery's ajax method, and passing the csrf token, but am receiving an error that states {"detail":"CSRF Failed: CSRF token missing or incorrect."}. Here's my ajax request: $('#deactivateBtn').click(function(){ $.ajax({ url: '/api/v1/companies/{{ object.pk }}/', type: 'PATCH', contentType: 'application/json', data: { 'is_active': false, 'csrfmiddlewaretoken': '{{ csrf_token }}' }, dataType: 'json', success: function(data){ $('#deactivateBtn').hide(); console.log('hiding'); $('#deactivateSuccess').show(); } }) }); and my authentication settings for django-rest-framework: REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ] } Why am I getting a CSRF error, despite passing the token in my ajax request? I've tried decorating my view with ensure_csrf_cookie from django.views.decorators.csrf, but that doesn't seem to fix it. -
Why can't I authenticate from other computers on my Django site?
I've published my site with pythonanywhere, inside there is a simple login for users, I created an user and when I authenticate with my own computer it works, but when I authenticate with another machine I get this error : Forbiddem (403) - CSRF verification failed. Request aborted. My site is published on a domain name and everything else works just fine. What can be the problem ? -
django-dynamic-formset and django-autocomplete-light integration bug
Im using the latest packages of django-dynamic-formset and django-autocomplete-light to build a custom form (like the classic Order/Products example). Everything work, but when I create a new line this is created the double and I can’t fix it. I think the problem is what the cloning method does. Someone can help me or has an example that works? Thanks. -
javascript post django form gives csrf error
I have a html form like: <form id="comment" action="{% url "url_name" ur.id %}" method="post">{% csrf_token %} <textarea required="required" maxlength="255" rows="4" class="form-control" name="comment"> </textarea> <button class="btn btn-default" onclick="add_comment(event)">Comment</button> </form> It is a html form and not django's form. Here I have included csrf token in the form. I have post this form form javascript and now it gives me csrf verification failed error. What am I missing here ? Is it mandatory to create form from django' form class to use csrf token ? Need help -
Django channels for asynchronous periodic tasks with intervals
I found that most of the docs regarding Django Channels are about WebSockets. But I want to use them in a different way, and I believe it is possible. How to run the async periodic task using Django channels? For example, I want to check the temperature on some website (through the API) every 15 seconds and I need a notification when its hit > 20. It also means that this task will live for a long time (maybe even for 3 month), is Django is capable of keeping the consumers live for a long time? Thank you. -
timedelta instead of datetime
I have a class : class timetravel(object): """ Fast forward in time with simulated CRON jobs (used for unit testing) """ def __init__(self, delta): self.delta = delta self.initial_now = datetime.now() self.now = self.initial_now self.freezer = freeze_time(self.now) self.freezer.start() def __enter__(self): hours = self.delta.total_seconds() / 60 / 60 weekday = self.now.weekday() month = self.now.month year = self.now.year for i in range(1, int(hours)+1): call_command('cron', hourly=True, verbosity=0) if weekday != self.now.weekday(): weekday = self.now.weekday() call_command('cron', daily=True) if self.now.weekday() == 6 and weekday != self.now.weekday(): call_command('cron', weekly=True) if self.now.month != month: month = self.now.month call_command('cron', monthly=True) if self.now.year != year: year = self.now.year call_command('cron', yearly=True) self.freezer.stop() self.now = self.now + timedelta(hours=1) self.freezer = freeze_time(self.now) self.freezer.start() return self.now def __exit__(self, *args): self.freezer.stop() In a test.py file, I did from project.utils.test import timetravel def function1(self): with timetravel(datetime(2017,03.01)) as now: ... When I start python manage.py test, I got Traceback (most recent call last): File "...", line 100, in function1 with timetravel(datetime(2017,03,01)) as now: File ".../project/utils/testing.py", line 27, in __enter__ hours = self.delta.total_seconds() / 60 / 60 AttributeError: 'datetime.datetime' object has no attribute 'total_seconds'. I just don't know how to fix this issue. I think we have to pass timedelta as argument in timetravel instead of a datetime, … -
device_list is not shown
I am creating an api where the list of groups are shown along with the devices id that falls under that groups. For example if there is a device named Speedometer, Humidifier and they fall under Home group then my api should include { "id": 1, "name": "Home" "device_list": [ { "id": "b45c56ioxa1" }, { "id": "h4oc2d5ofa9" } ] }, but my code does not produce device_list in the api. It only shows name and id device_list is the list of all the devices id that are in a certain group. Here is my code class DeviceIdSerializer(serializers.ModelSerializer): id = serializers.UUIDField(source='token', format='hex', read_only=True) class Meta: model = Device fields = ('id') class DeviceGroupSerializer(serializers.ModelSerializer): name = serializers.StringRelatedField() device_list = DeviceIdSerializer(read_only=False, many=True, required=False) class Meta: model = DeviceGroup fields = ('id', 'name', 'device_list') class DevicesGroupsAPIView(APIView): permission_classes = (permissions.IsAuthenticated,) def get(self, request, format=None): """ Returns a list of groups """ reply = {} try: groups = DeviceGroup.objects.all() print ('reply', groups) reply['data'] = DeviceGroupSerializer(groups, many=True).data except: reply['data'] = [] return Response(reply, status.HTTP_200_OK) class BaseDevice(PolymorphicModel): # User's own identifier of the product name = models.CharField(max_length=250, blank=False, null=False) # Any device should have a owner, right from the creation owner = models.ForeignKey(User, blank=False, null=False) token = models.UUIDField(default=uuid.uuid4, … -
How to update extended User Model using Django Forms?
I am new to Django and need a help. I want to allow users to update their account data using form, but struggle with associating Django User model with my UserProfile model, which extends default model with some additional fields. I found, that solution is to create my own model form, but unfortunately I'm not exactly sure how to implement this. models.py: class UserProfile(models.Model): user = models.OneToOneField(User) description = models.CharField(max_length=100, default='') city = models.CharField(max_length=100, default='') website = models.URLField(default='') phone = models.IntegerField(default=0) image = models.ImageField(upload_to='profile_image', blank=True) def __str__(self): return self.user.username def create_profile(sender, **kwargs): if kwargs['created']: user_profile = UserProfile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) forms.py: class EditProfileForm(UserChangeForm): image = forms.ImageField(required=False) city = forms.CharField(required=False) class Meta: model = User fields = ( 'email', 'first_name', 'last_name', 'password', 'image', 'city' ) views.py: def edit_profile(request): if request.method == 'POST': form = EditProfileForm(request.POST, instance=request.user) if form.is_valid(): form.save() return redirect(reverse('accounts:view_profile')) else: form = EditProfileForm(instance=request.user) args = {'form': form} return render(request, 'accounts/edit_profile.html', args) edit_profile.html: <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> -
Django REST with remote jwt authentication
I'm going to create a Django REST project that have to be remote users: an external server exposes authentication api and uses JWT. It exposes to me also a bearer token to permit me to use apis. My Django will have to expose api for authentication for the clients (mobile apps). I don't have much clear in my mind how to handle the authentication flux: do I have to build a custom authentication? Thank you! -
how do I further simplify this method?
I wrote a to query the model with known lookup types. The flags which denotes what the input type is passed as kwargs. The kwarg lookup is explained as below along with passed kwargs. A database hash (a random no unique to instances, with db_hash=True) Name of the objects ("John" or "Sam" as name=True) ID of the object. (obj.ids 124, or 134 as id=True) The instances (objs without any flag) for example just for the name the method call would look like, self.check_all_routes("Sam", "452", name=True) I want refactor the below method to reduce the mess it is producing while violating DRY. def check_all_routes(self, driver, route, **kwargs): _hash = kwargs.get('db_hash') _name = kwargs.get('name') _id = kwargs.get('id') if _hash: return self.model.objects.filter( driver__db_hash=driver, route__db_hash=route ).prefetch_related().select_related().values_list('route_number') if _name: return self.model.objects.filter( driver__name=driver, route__name=route ).prefetch_related().select_related().values_list('route_number') if _id: return self.model.objects.filter( driver_id=driver, route_id=route ).prefetch_related().select_related().values_list('route_number') return self.model.objects.filter( driver=driver, route=route ).prefetch_related().select_related().values_list('route_number') What can be done to make it doesn't violate DRY. -
How to deactivate the default language fallback when translating (Python Django i18n)
I have an i18nized Python Django application. It currently uses two languages; German (DE) and French (FR). I have all my keys (.po-/.mo-files) translated and ready in German, however for French, some are missing. In the Django settings I specified 'de' as the LANGUAGE_CODE. I can switch from one language to the other just fine without issues. The routing works fine and every other feature I need is handled by the Django Middleware. However, in the current scenario when I switch from German to French, all the keys which are missing in French, just fallback to the German values. But I would like them to just default to their keys. E.g. Current Scenario Sortiment (available in French) -> Assortiment Gratis Lieferung (not available in French) -> Gratis Lieferung Expected Scenario Sortiment (available in French) -> Assortiment Gratis Lieferung (not available in French) -> free.shipping.info What would be a clean solution to solve this? I couldn't find anything in the Django documentation. I'd like to solve this without using additional plugins. And one solution I could come up with, would be to just add all the missing keys in the french translations and have their values also be their keys but … -
Unable to use json.loads on boto3.client.get_batch_predictions()
I'm getting the following error when trying to parse a json response expected string or buffer Within my Django model I have the following: def get_batch_prediction(self): client = boto3.client('machinelearning', region_name=settings.region, aws_access_key_id=settings.aws_access_key_id, aws_secret_access_key=settings.aws_secret_access_key) return client.get_batch_prediction( BatchPredictionId=str(self.id) ) I then call it like so batch = BatchPrediction.objects.get(id=batch_id) response = batch.get_batch_prediction() response = json.loads(response) I know the response is json so I expected this to change it to a dictionary but, instead, I get the error above. What's going on? -
ImportError: No module named rest_framework_jwt.views
I am using ubuntu anb Django(python 2.7.12) I am trying to run python manage.py migrate but an error shows up from rest_framework_jwt.views import obtain_jwt_token ImportError: No module named rest_framework_jwt.views I have alread install rest like this: pip install djangorestframework Any idea about the error? -
Django authentication against django-oauth-toolkit
I am working on a Django rest api, which should register and manage various user-owned products. There are a number of php websites, which currently authenticate against an inhouse django oauth2 provider (django-oauth-toolkit+rest). The above mentioned websites, as well as a python desktop application should be able to fetch/manage the data in my app for the currently logged in user. The general idea is that once users log into the website, or the desktop app, they should be able to see/manage their products in my api, along with their data in the other locations. Unfortunately, I have minimal experience with authentication development, so advice and examples on how to implement this will be appreciated. I've been thinking of using something like python social authentication, but so far I have not been able to create a working authentication backend for django-oauth-toolkit, although I have managed to make it work for other providers using the existing backends (eg. github). My app will be residing on a separate server from the auth provider, so I cannot merge the two apps into one service. Using Django v.1.10.5 and Python 3.5.2 -
how to get Database deatils from settings.py
I am newbie in python and I started two projects at same time and I need to get the database details into a page. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'dynamic', 'USER': 'root', 'PASSWORD': 'root', 'HOST': '192.168.10.130', } } This is my database details in setting.py page.And the setting .py in a project folder and I need to access the values into another file in another folder.In one of my project I can access all the details .but the other project I can't get it?now what can I do? This is the methos that I access the details from django.conf import settings dbHost = settings.DATABASES['default']['HOST'] dbUsername = settings.DATABASES['default']['USER'] dbPassword = settings.DATABASES['default']['PASSWORD'] dbName = settings.DATABASES['default']['NAME'] please help me. Thanks in advance -
How to build Django application that renders to both web client and mobile app
I am building a web application in django, and so far I have been using django templating for rendering to a web browser. However, I intend to extend the application for mobile app as well. I read that the best way of doing is to build a RESTful application. I know how to do it in django as it's very easy using django-restframework, however, I don't really see how to build an app that will render to both a web browser using templating and a web app with a simple JSON response. Do I need to check in my views the client type and use a different response depending whether it is a web or mobile app ? or is there another way to do so. Thank you in advance. -
Exception : coercing to Unicode: need string or buffer, ValuesListQuerySet found
my model.py from django.db import models class RateSheetDetails(models.Model): file_location = models.FileField(upload_to='LCR_files') my view.py from forms import * from models import Lerg_uploading,RateSheetDetails from ratesheet import Lerg class RateSheet( View ): def post( self, request, *args, **kwargs ): file_instance = RateSheetDetails.objects.values_list('file_location') lerd_class_instance=Lerg() lergupload = lerd_class_instance.readfile(file_instance) print lergupload the additional file ratesheet.py import os class Lerg: def readfile(self,path): filename = "" filepath = path if os.path.exists(filepath): #check filepath existing or not filename = os.path.basename(filepath) return self.filename when I click the submit button in form.py in django.It returns an error.I can't continue with my project.the error is, ERROR: coercing to Unicode: need string or buffer, ValuesListQuerySet found I realize that the error is occuring from the ratesheet.py page. please help me. Thanks in advance -
AttributeError: 'QuerySet' object has no attribute 'add'
I try to define a function that adds elements to a new, empty queryset and returns it. The current version of my function looks like this: def get_colors(*args, **kwargs): colors = Color.objects.none() for paint in Paint.objects.all(): if paint.color and paint.color not in colors: colors.add(paint.color) return colors I get the error message that says: AttributeError: 'QuerySet' object has no attribute 'add' Why can't I add elements to the empty queryset? What am I doing wrong? -
Django Mysql querying in loop but getting same output
This below code in Django is printing same results all the time. Even if there are more rows in the mysql DB. Please Help. while True: print Event.objects.last().id time.sleep(5) -
How built a dynamic webpage in Django without PHP [on hold]
How could I built a dynamic web site with Python Django framework, I just started learn Python and I have no idea about PHP or other server site languages..