Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Database connection during Django-cms installation doesn't work
I'm trying to set up a django-cms on a new Ubuntu 16.04 droplet on digital ocean. I followed this tutorial for setting up Django: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-14-04. I got up until the gunicorn test which didn't work, but that's a different question, I think. Then I tried to follow the django-cms tutorial: https://django-cms.readthedocs.io/en/latest/introduction/install.html#. I have an empty django project in my home folder and made an empty folder in it for the django-cms project. When trying to run the installer in this empty folder, I get the following error: Database setup commands: /opt/cp-env/bin/python2 -W ignore manage.py migrate The installation has failed. ***************************************************************** Check documentation at https://djangocms-installer.readthedocs.io ***************************************************************** Traceback (most recent call last): File "/opt/cp-env/bin/djangocms", line 11, in <module> sys.exit(execute()) File "/opt/cp-env/local/lib/python2.7/site-packages/djangocms_installer/main.py", line 41, in execute django.setup_database(config_data) File "/opt/cp-env/local/lib/python2.7/site-packages/djangocms_installer/django/__init__.py", line 396, in setup_database output = subprocess.check_output(command, env=env) File "/usr/lib/python2.7/subprocess.py", line 574, in check_output raise CalledProcessError(retcode, cmd, output=output) subprocess.CalledProcessError: Command '['/opt/cp-env/bin/python2', u'-W', u'ignore', u'manage.py', u'migrate']' returned non-zero exit status -9 I assume the database connection somehow failed. When running python manage.py migrate from the parent folder of the django-cms folder, I get System check identified some issues: WARNINGS: ?: (1_7.W001) MIDDLEWARE_CLASSES is not set. HINT: Django 1.7 changed the global defaults for the MIDDLEWARE_CLASSES. … -
Django social-auth-app-django 504 on production
I have a django site on my local pc. Using social-auth-app-django for Facebook register/login. All is working as it should. No problems. At the facebook app settings in the input "App Domains" and "Site URL" I set localhost and http://localhost:8000 everything is ok but on my local computer. When I upload the project online and change the facebook app settings (inputs I mentioned before) to my real domain name (example.com and http://example.com) I get a 504 timeout from nginx. What am I missing? Also I have set at nginx.conf http{ proxy_connect_timeout 60s; proxy_send_timeout 60s; proxy_read_timeout 60s;} Any idea would be useful. Thank you a lot. -
djagno, rest_framework..TypeError: object() takes no parameters
I am a beginner in django. I do not know why this is an error. Please help me. ㅠ^ㅠ TypeError: object() takes no parameters Following is my code: class JSONResponse(HttpResponse): def __init__(self, data, **kwargs): content = JSONRenderer().render(data) kwargs['content_type'] = 'application/json' super(JSONResponse, self).__init__(content, **kwargs) @csrf_exempt def mood_list(request): if request.method == 'GET': mood = Mood.objects.all() serializer = MoodSerializer(mood, many=True) return JSONRenderer(serializer.data) elif request.method == 'POST': data = JSONParser().parse(request) serializer = MoodSerializer(data=data) if serializer.is_valid(): serializer.save() return JSONResponse(serializer.data, status=201) return JSONResponse(serializer.errors, status=400) -
Wagtail: Passing Django form to WagtailAdmin (Sidebar: Forms)
I have a very interesting task. Wagtail Form with a FileField - For image upload (I guess this is not possible yet) From the point that this is not possible yet in Wagtail I've tried another thing. A Django Form (from this example django form in wagtail) that has actually a FileField. Generate the link to uploaded image (let's say '/media/pics/image_example.jpg') Somehow pass this link (a text field) to Wagtail Form and auto-submit it. So at the end, we have the Form Submissions in WagtailAdmin that has a field with the direct url to the uploaded image. But.. I don't really understand how this must work. Any ideas? Maybe there are better solutions for my problem. -
How can I create customizer with postman
enter image description here When I tried createsuperuser at terminal, I could make it. Also I could see created custom user password is hashed. But when I tried to create custom user. I could make it. But password is not hashed, and I could not log in. -
Displaying content using back-end languages
I want to display some content on my website but I don't want to show it in source code. I think it can be done by back-end languages like PHP, Django, ruby etc. Can someone please give me detail information to achieve my target -
Pagination not working in DRF APIView
I am using APIView for get and post items. I wanted to implement a pagination system in my API but the pagination is not working. I want to show 10 items per page but when i do api/v1/items?page=1, i get all the items and if i just do api/v1/items i get empty list. How can i use pagination feature when using APIView in Django Rest Framework? Here is what i have done from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger class ItemsAPIView(APIView): permission_classes = (permissions.IsAuthenticated,) def get(self, request, format=None): """ Return a list of all items of this user. """ reply = {} page = request.GET.get('page') print ('page is', page) try: products = BaseItem.objects.owned_items().filter(owner=request.user) reply['data'] = OwnedItemSerializer(products, many=True).data items = BaseItem.objects.filter(owner=request.user) paginator = Paginator(items, 1) items_with_pagination = paginator.page(page) if page is not None: reply['data'].extend(ItemSerializer(items_with_pagination, many=True).data) reply['data'].extend(ItemSerializer(items, many=True).data) -
django add images to models.py from views.py
I create a simple Django authentication app and work fine. now I want to add a python script where to can do some simple image processing. my python script for processing work fine and I put in the views.py. my question is the new image created from the script how to can add back to image from mymodel ?first must be save temporarily ? can I do this ? sorry I am new. class MyModel(models.Model): user = models.ForeignKey(to=settings.AUTH_USER_MODEL) image = models.ImageField(upload_to=generate_path(self.user)) forms.py @login_required class CronForm(forms.Form): days = forms.ModelChoiceField(queryset=MyModel.objects.all) views.py @login_required def show_something(request,user_id): user = UserProfile.objects.get(user__id=user_id) form = CronForm() if request.method == "POST": form = CronForm(request.POST) if form.is_valid: # do image processing # do image processing # and finaly ta ke new image from the image processing like newim='newim.tif' return HttpResponseRedirect(...) errors = form.errors or None return render(request, 'path/to/template.html',{ 'form': form, 'errors': errors, }) -
What should I do with non-project migrations?
I have, as usual the <project>/<app>/migrations folder that I added to the version control for deployment. Since recently I am also using django-auditlog, which creates its own migrations in <project>/env/Lib/site-packages/auditlog/migrations. These migrations are applied just like my own ones. So I wonder: should I also add them to VCS and deploy them? -
Django selectable don´t drops down autocomplete
i'm using django-selectable and i'm getting nervous :| models.py @python_2_unicode_compatible class Filing(models.Model): company = models.CharField(max_length=60, null=True) ticker = models.CharField(max_length=5, null=True) number = models.CharField(max_length=15, null=True) description = models.CharField(max_length=100, null=True) url = models.CharField(max_length=110, null=True) created_date = models.DateTimeField(null=True) def __str__(self): return self.ticker lookups.py from __future__ import unicode_literals from selectable.base import LookupBase from selectable.registry import registry from .models import Filing class CompanyLookup(LookupBase): model = Filing search_fields = ('company__icontains', ) registry.register(CompanyLookup) So don't work :( but other lookups.py from __future__ import unicode_literals from selectable.base import LookupBase from selectable.registry import registry from .models import Filing class CompanyLookup(LookupBase): def get_query(self, request, ticker): data= Filing.objects.values_list('company',flat=True) return [x for x in data if x.startswith(ticker)] registry.register(CompanyLookup) works, drops down, but only with the attributes of "startswith" and i need "icontains". Also don't work "istarswith", neither "contains": In my consoles: Request URL:http://127.0.0.1:8000/assets/flash/ZeroClipboard.swf? noCache=1491057317592 Request Method:GET Status Code:404 Not Found Remote Address:127.0.0.1:8000 and: Uncaught ReferenceError: jQuery is not defined at jquery.dj.selectable.js?v=0.9.0:390 (anonymous) @ jquery.dj.selectable.js?v=0.9.0:390 $(document).ready(function () { // Patch the django admin JS if (typeof(djselectableAdminPatch) === "undefined" || djselectableAdminPatch) { djangoAdminPatches(); } // Bind existing widgets on document ready if (typeof(djselectableAutoLoad) === "undefined" || djselectableAutoLoad) { window.bindSelectables('body'); } }); })(jQuery || grp.jQuery); <------ this is the line 390 also i don't understand … -
DataBase is locked in Django project
I'm developing a chatbot chatting page that uses a DB.sqlit3 as a knowledge base for reply to users questions .Also, a have a admin chatting page for the admin to add new question and reply to DB.sqlit3 by chatting.So, for that i have 2 python script (one for the chatbot chatting and one for the admin chatting) each with its own html and JS. The chatbot chatting page works fine but sometime when i run the admin chatting page after and try to insert new data ( questions and replay) to DB.sqlit3 i get : The database is locked Thank you, PS: i'm using Django 10 , python3 , sqlite3, web faction server -
Directed Acyclic Graph - Uncle/aunt relationships and generalizations
I am building a directed acyclic graph (using python/django). I want to avoid relationship where node is its uncle/aunt or generalizations as shown in the image - As shown a node can't be at two different levels if it's root node is same. A node can be it's sibling or cousin(i.e. can be at same level in two branches). I am using this code as of now to for building DAG. What would be the efficient way to check uncle relationship ? -
How to fetch a directed graph with Django
Having this models.py: class Place(models.Model): name = models.CharField(max_length=50) parent = models.ForeignKey("self", null=True, blank=True) I'm looking for the Django way to get all Place objects which are children of one. One approach I came around was to build up a recursion like this: def get_children(self, children=False): childs = list(self.place_set.all()) if children: result = [] if childs: for child in childs: result.append(child) result.extend(child.get_children()) return result else: return childs No I'm wondering whether there is some kind of a build in helping me on this as this solution works, but looks somehow wrong. -
Django: text-input instead selection on foreignkey
I want to create a messaging function in ma django app. User should be able to write other users a textmessage. models.py from django.contrib.auth.models import User class Message(models.Model): recipient = models.ForeignKey(User, null=True) contentDescription = models.CharField(max_length=1000, null=True) By default, with no forms.py entry I get a selection, which will be unuseful with many users. I want the message sender to type in the user name, or in the first step the user id (which I could resolve with ajax from the name) . Integer But with forms.py recipient = forms.IntegerField( widget=forms.NumberInput , required=False,) I get: Cannot assign "11": "Transport.recipient" must be a "User" instance. ChoiceField and NumberInput with: recipient = forms.ChoiceField( widget=forms.NumberInput, required=False,) I get the error message "not valid" Is it possible to write the foreignkey 'manually' at all? -
DRF 'Manager' object has no attribute 'get_by_natural_key' Help me plz
Here are my code I can successfully make customeuser But when I try to make shop, I got 'Manager' object has no attribute 'get_by_natural_key' this error message. Anyone help me? Thanks This is code for making customizer ```python class CustomUser(AbstractBaseUser): name = models.CharField(max_length=20, null=True, blank=True) phone = models.CharField(max_length=11, null=True, blank=True) gender = models.CharField(choices=GENDER_CHOICE, null=True, blank=True, max_length=10) email = models.EmailField(max_length=50, unique=True) birth = models.DateField(null=True, blank=True) CustomID = models.CharField(max_length=15, null=True, blank=True, unique=True) password = models.CharField(max_length=20, null=True, blank=True) is_staff = models.BooleanField(default=False, blank=True) USERNAME_FIELD = 'CustomID' REQUIRED_FIELDS = ['name', 'phone', 'gender', 'birth', 'email'] ``` ```python class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) token, created = Token.objects.get_or_create(user=serializer.instance) return Response({'token': token.key}, status=status.HTTP_201_CREATED, headers=headers) ``` From here, code for making shop ```pyton class UserSerializer(serializers.HyperlinkedModelSerializer): #Shop = serializers.HyperlinkedRelatedField(many=True, view_name='user-detail', read_only=True) class Meta: model = CustomUser fields = ('name', 'phone', 'gender', 'email', 'birth', 'CustomID', 'password') ``` ```python class ShopViewSet(viewsets.ModelViewSet): queryset = Shop.objects.all() serializer_class = ShopSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly) ``` ```python class ShopSerializer(serializers.HyperlinkedModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') class Meta: model = Shop fields = ('owner', 'shopname') ``` ```python class Shop(models.Model): owner = models.ForeignKey(CustomUser, blank=True) shopname = models.CharField(max_length=30, blank=False) ``` -
Django Rest_framework "Got AttributeError when attempting to get a value for field Process"
I have encountered the error which I cannot solve when browsing towards my rest_framework api page. The full error (Django Error) is : Got AttributeError when attempting to get a value for field `process` on serializer `ResultSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Shop` instance. Original exception text was: 'Shop' object has no attribute 'process'. It seems that the serializer trying to get a value in the field given in another serializer called ResultSerializer but could not found it. I have checked all the fields are all of them are correct. Here is my models.py from django.db import models class ResultSet(models.Model): process = models.CharField(max_length=10) subprocess = models.CharField(max_length=10) class Shop(models.Model): Establishment = models.CharField(max_length=100) Address = models.CharField(max_length=100) Suburb = models.CharField(max_length=50) Postcode = models.CharField(max_length=10) State = models.CharField(max_length=5) Establishment_Type = models.CharField(max_length=20) latitude = models.DecimalField(decimal_places=6, max_digits=12) longtitude = models.DecimalField(decimal_places=6, max_digits=12) class Meta: ordering = ('Establishment',) class EntirelyResult(models.Model): Result = models.ManyToManyField(Shop, related_name='fullresult') Status = models.ManyToManyField(ResultSet, related_name='status') Here is my serializers.py from rest_framework.serializers import ModelSerializer from .models import Shop, ResultSet, EntirelyResult class ResultSerializer(ModelSerializer): class Meta: model = ResultSet fields = ('process', 'subprocess') class ShopSerializer(ModelSerializer): class Meta: model = Shop fields = ('__all__') class ShopDetailSerializer(ModelSerializer): Result = ResultSerializer(many=True, … -
Django Rest Framework - Limiting fields of nesting serializer
I have User and Item models, and am having an issue with nested Items in a Item.objects.all() view. Specifically, I'm getting the following in the ItemListView resource: [ { "id": 3, "description": "Some test item description", "user": { "id": 10, "username": "jason", "email": "test@test.com", "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0aW1lIjoiRnJpIE1hciAyNCAyMDo1NDo1OSAyMDE3IiwidXNlcm5hbWUiOiJqYXNvbiJ9.x4qdTF5eVKGLnrkcunm63n4d_X8xEzEYM0z48E5HKh4", "items": [ { "id": 3, "description": "Some item description", "timestamp": "2017-03-25T15:50:08.265780Z", "user": 10 }, { "id": 2, "description": "test item description", "timestamp": "2017-03-24T22:28:49.904198Z", "user": 10 } ] }, "timestamp": "2017-03-25T15:50:08.265780Z" }, What I want is the User.items excluded from the output. How can I do that with the serializers and models below: class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only = True, required = False) confirm_password = serializers.CharField(required = False) class Meta: model = User fields = ('id', 'username', 'email', 'password', 'confirm_password', 'token', 'posts') read_only_fields = ('confirm_password', ) depth = 1 def create(self, validated_data): return User.objects.create_user(**validated_data) def validate(self, data): if data['password'] != data['confirm_password']: raise ValidationError('Passwords do not match') return data class ItemSerializer(serializers.ModelSerializer): user = UserSerializer(read_only = True) def create(self, validated_data): return Item.objects.create(**validated_data) class Meta: fields = ('id', 'content', 'user', 'timestamp') read_only_fields = ('timestamp', ) model = Item depth = 1 Models: class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length = 50, unique = True) email = models.EmailField(unique = True, … -
Django Initialize database in management can't run with duration field:error- 'int' object has no attribute 'total_seconds'
I have problem with duration field in diango when I try to load_data to database in management in Django. in models.py: class Sport(models.Model): name = models.CharField(max_length=32) description = models.TextField(null = True, blank = True) duration = models.DurationField(default=3600.0) capacity = models.SmallIntegerField(null=True) def __str__(self): return self.name load_data.py in management: def populate(): Sport.objects.update_or_create(name="KICKBOXING", description="Dyscyplina sportowa w której walczy się stosując zarówno bokserskie ciosy pięścią, jak i kopnięcia. Sport rozwijający w sposób holistyczny umiejętności fizyczne takie jak: siła, szybkość, wytrzymałość, gibkość, poczucie rytmu. Dodatkowo rozwijający cechy psychiczne m.in.: panowanie nad stresem, poczucie własnej wartości, czy pewność siebie." ,duration= 3000000000, capacity = 10) Sport.objects.update_or_create(name="BODYPUMP", description="To oryginalny program ćwiczeń z wykorzystaniem sztangi, który wzmocni i ukształtuje Twoje mięśnie." ,duration= 3600000000, capacity = 15) Sport.objects.update_or_create(name="CROSS CAGE", description="Zajęcia o bardzo wysokiej intensywności oparte na treningu funkcjonalnym. Mają na celu ukształtowanie sylwetki jak również wypracowanie szeroko pojętej sprawności fizycznej." ,duration= 3600000000, capacity = 20) Sport.objects.update_or_create(name="BODYCOMBAT", description="To intensywny trening cardio, podczas którego uwolnisz swoje emocje! Cały program zainspirowany jest sztukami walki tj. karate, taekwondo, boks, tai chi czy muay thai." ,duration= 3600000000, capacity = 20) Sport.objects.update_or_create(name="STRETCHING", description="Zestaw ćwiczeń rozluźniająco-rozciągających wszystkie grupy mięśniowe. Zajęcia odbywają się przy relaksującej, nastrojowej muzyce. Ćwiczenia zwiększają elastyczność mięśni i gibkość ciała. Zajęcia gwarantują relaks i … -
changing default to function django
so im trying to change the default language according to a setting a user made before. My problem is that the value of the function im calling is 'English' or 'Spanish' but I need a short term like 'en' or 'esp' to make it actually work. I also have this error message when I try to try to run it: userlang() takes exactly 1 argument (0 given) so here is what I tried: def userlang(self): return (self.user.userprofile.language) class 123(models.Model language = models.CharField(verbose_name=_(u"Language"), max_length=4, choices=settings.LANGUAGES,default=userlang) I hope somebody can help me out. -
Wagtail Images Not Loading Once Deployed
I'm not quite sure what's going on, but my images loaded fine on my local development server. However, once I deployed, the images will not load. I checked the URL and it seems to be correct. I'm not sure what's going on here. base.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' HTML {% load wagtailcore_tags wagtailimages_tags %} ... {% with post.main_image as main_image %} {% if main_image %}{% image main_image fill-400x200 %}{% endif %} {% endwith %} Page Source for Element <img alt="photo" src="/media/images/Lily.2e16d0ba.fill-400x200.jpg" width="400" height="201"> I'm pretty confused and I can't really find much about the topic. Am I the only one who's run in to this issue? Any help would be greatly appreciated. -
PostrgeSQL + Django on Debian 8
Good day, I've got a Debian 8 server where I'm running a few of django test apps and I want to connect them to PostgreSQL instead of SQLite. Can you please help me with this problem ? this is settings.py of my project (DATABASES block) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'testProject', 'USER': 'admin', 'PASSWORD': 'adminPassword', 'HOST': 'localhost', 'PORT': '', } } I think I've installed it successfully by sudo apt-get install python-pip python-dev libpq-dev postgresql postgresql-contrib and CREATE DATABASE testProject; CREATE USER admin WITH PASSWORD 'adminPassword'; GRANT ALL PRIVILEGES ON DATABASE testProject TO admin; And when I try to access page, It shows "server refused connection" or something like that. Thank you guys and have a nice day ! -
Chaining methods with lazy execution in Python
I was studying Django when i found they are chaining their query methods like Post.objects.filter(pk=1).filter(title='first').filter(author='me') to construct a query without actually executing it, and only execute the query when we try to access and work with its result. From there i got interested to know how they are doing this so i can apply the same approach in building DB manager for non Django apps where i can chain my query methods and execute the query automatically only when i try to access its result (or at least when chaining ends). So i can end with something like #doesn't hit the DB myPost = Post.objects.select(...).where(...).where(...).limit(...) #only hit the DB on usage print(myPost.title) So my QUESTION is, how can i do so? Approaches that i thought of but i don't like I can implement an .execute() method to perform the actual execution, calling it at the tail of the chain or whenever desired Post.objects.select(x).where(y).offset(z).execute() I can insert a delay within each of the query builder methods to make sure it is the last in chain class Post: def where(self,...): me = now() self.lastCall = me #process the inputs here self.query += "WHERE ..." self.lazyExecute(me) return self def lazyExecute(self,identifier): delay(5000) if self.lastCall … -
is it possible to send a media file in JsonResponse in django ajax?
I wanted to know if is it possible to get media file such as (.mp3) as Json Response, if it's not then how music sites play songs even without refreshing surely they don't load all the songs at first get request. -
Efficiency of itertools groupby with nested list comprehension function
i've written a simple function that does this job: #Splits the dishes by category and returns an ordered dict with key the category name and values the color of category and the dishes name def split_order_details_by_categories(dishes): order_details_dishes_by_category = OrderedDict() for category, group_dishes in itertools.groupby(dishes, key=lambda k: k.dish.category): order_details_dishes_by_category[category.name] = {'color': category.color, 'dishes' : [order_detail.dish.name for order_detail in group_dishes]} return order_details_dishes_by_category Now, i was wondering if this approach it's better than doing some nested for loops, and if there are more efficient way to do that. Thanks -
Attributeerror: 'int' object has no attribute 'resolve_expression'
I am trying to annotate a value to queryset calculated based on model field (user id in this case). Code - users = User.objects.all() def calculate_value(user_id): qs1 = Model1.objects.filter(user_id=user_id) qs2 = Model2.objects.filter(user_id=user_id, some_field=some_value) # do some calculations using qs1 and qs2 return result users.annotate(x=calucated_value(F('id)) I am aware about Conditional Expressions, but in this case I want to first evaluate qs1 and qs2 and then do some calculations based on that. How should this be done ? I don't know the exact issue but it may be because I am passing a F expression not an integer id.