Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deploy django app as collaborator of already created account
I have a django app deployed on heroku . I have to deploy this Django app on my customer heroku account . 1)I asked my customer to create heroku account , create an app and add me as collaborator . 2)Then I have created a new folder for my customer and cloned his empty project to this folder. 3) I have copied src of my app into the empty folder 4)I have copied customer database credentials into my settings file 5)added and pushed it to his app via git All the process want smoothly and was able to deploy no errors but when I log into actual app I am getting my first screen to login and after I input credentials I get Server Error (500) Any Idea what step/steps I could be missing ? And is it a good idea to deploy this way at all? -
What do you think about my Django model structure?
My project has 2 or more different kind of models as post And i want to bookmark for all kind of post models I need dashboard or timeline that shows bookmarked posts whatever the kind of that post So i thought 2 plans. First Plan : Making different bookmark model at every post Like : class UserProfile(models.Model): user = AutoOneToOneField(User, primary_key=True)#its_from_django-annoying class Post1(models.Model): text1 = models.TextField(max_length=110) class Post2(models.Model): text2 = models.TextField(max_length=120) class bookmarkForPost1(models.Model): who_user = models.ForeignKey(UserProfile) what_bookmarked = models.ForeignKey(Post1) class bookmarkForPost2(models.Model): who_user = models.ForeignKey(UserProfile) what_bookmarked = models.ForeignKey(Post2) And do something for dashboard in views.py Second Plan : Making PostProfile model and bookmark it Like : class UserProfile(models.Model): user = AutoOneToOneField(User, primary_key=True) class PostProfile(models.Model): description = models.TextField(max_length=100) #Do something to connect Post1 or Post2 class Post1(models.Model): text1 = models.TextField(max_length=110) #Do something to connect PostProfile class Post2(models.Model): text2 = models.TextField(max_length=120) #Do something to connect PostProfile class bookmarkForPosts(models.Model): who_user = models.ForeignKey(UserProfile) what_bookmarked = models.ForeignKey(PostProfile) Second Plan is seemed to be simple and good for my eyes. Second Plan, i can't sure where i put OneToOneField. In PostProfile or In Post1(+Post2)? Plus, I can't understand how to auto-create PostProfile just after creating of Post1 or Post2. But Second Plan is good at that there … -
syntax error at or near "COLLATE" wagtail1.9 postgresql9.5.2
have got this error when I run python manage.py migrate because of this line ALTER TABLE wagtailcore_page ALTER COLUMN path TYPE VARCHAR(255) COLLATE "C" https://github.com/wagtail/wagtail/blob/master/wagtail/wagtailcore/migrations/0001_squashed_0016_change_page_url_path_to_text_field.py#L130 How can I solve it? -
Users visiting other profile users
I'm creating a web application 'blog' and I have profil page, so I want users visit other users without editing their posts. here is my Profil view: def Profil(request, username): posts = Post.objects.filter(user=request.user) user = User.objects.get(username=username) if not request.user.is_authenticated(): return render(request, 'blog/visitor.html') editable = False if request.user.is_authenticated() and request.user == user: editable = True return render(request, 'blog/profil.html', {'user':user, 'posts':posts}) ( Is there any other solution apart this ? ) My urls.py url(r'^(?P<username>\w+)/$', views.Profil, name = 'profil'), and a link from index.html to profil.html looks like this: <a href="{% url 'blog:profil' user.username %}"> the problem with this is when i click on the link it passes with the current user I'm logging in with and not the user that I click on it LogIn with admin and want to see Ala's profil When I click it shows in the url this: http://127.0.0.1:8000/blog/imedadmin/ which is supposed to be 'Ala' instead of 'imedadmin' And thanks in advance. -
Add multiple hostnames to .env file for Django
I have created a Django project using Django Cookiecutter with Docker. So far so good, but I keep getting a 400 error (Bad request). When I look in the log on Sentry, I can see the message that I need to add the ip address 123.123.123.132 to allowed hosts. In .env there is a variable DJANGO_ALLOWED_HOSTS, which by default contains the domain name that was entered when using Cookiecutter. Some ways I have tried so far: DJANGO_ALLOWED_HOSTS=.foo.bar,123.123.123.132 DJANGO_ALLOWED_HOSTS=.foo.bar 123.123.123.132 DJANGO_ALLOWED_HOSTS=[.foo.bar,123.123.123.132] What syntax should I use here to make this work? Thanks -
Retreiving an encryption key from a table in Django - 'character mapping must return integer, None or unicode'
I'm generating an encryption key and then saving the key to a table. Here is the table: class Tweeter(models.Model): user = models.OneToOneField(User) key = models.TextField() And here is how I'm generating the key and saving it: from cryptography.fernet import Fernet def generate_key(request, id): key = Fernet.generate_key() user = User.objects.get(id=id) tweeter = Tweeter.objects.create(user=user, key=key) Now when I try to retrieve that key to use it in my encryption method, I get the error in the title. It fails on cipher_suite = Fernet(key). Printing the key gives me the proper key (something like this: "gy1y6iZ8zkec4LeqRjDjfYzjKlUjwVj4iv0yYnpbsHc=", and type(key) returns . import Tweepy from tweepy import OAuthHandler from cryptography.fernet import Fernet def create_tweet(request): auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET) api = tweepy.API(auth) tweet = str(request.POST['tweet']) key = Tweeter.objects.get_key(request.session['id']) print key ////The key is successfully retrieved cipher_suite = Fernet(key) ////Execution fails here encrypted_tweet = cipher_suite.encrypt(tweet) print encrypted_tweet Things I've tried: Encoding to base64 before saving to db and then decoding on retrieval (How to encode text to base64 in python). THis doesn't seem like the right course of action because the key is already base64 (I think?) saving the key to session, and calling cipher_suite with argument request.session['key'] (same error message) If i save the … -
showing which post a user liked/saved with python django.
I have trouble to display the ''saved''/''liked'' posts of my users in django/admin. I would like to have a field in the Adminpage to show which user likes which posts. I made an Userprofile model where all extra information (besides the one on the given django admin user Profile) are stored. so here is my model View: class UserProfile(models.Model): user = models.OneToOneField(User, null=True) #likes = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True,default=1, related_name='likes') likedPosts=models.ManyToManyField('self') Field1 = models.CharField(max_length=50,default='Sunny') Field2 = models.CharField(max_length=50,default='') class Meta: ordering =['-user'] #def __unicode__(self): # return self.user.username User.profile =property(lambda u: UserProfile.objects.get_or_create(user=u)[0]) right now in the liked post field I have only some usernames or "User object" I tried all kinds of combinations to get the information into the admin page but as you can see I did not make it. I tried to change the unicode and of course the liked post line. If you need more information please tell me so. I appreciate every kind of help. -
Tox: Permission Denied when running tests
I'm getting this error both locally and from TravisCI when running tox. I've tried updating all of the requirements and tweaking the tox.ini's install_command to no avail. Any ideas? Incidentally I've also tried swapping ./runtests.py to an arbitrary ./file.py to see if it would work– I still get a Errno 13 Permission Denied error. I've also tried sudo tox and get the same Permission Denied error. ERROR: invocation failed (errno 13), args: ['/Users/Aaron/Documents/Projects/organelle/runtests.py', '--lintonly'], cwd: /Users/Aaron/Documents/Projects/organelle Here's my tox.ini [tox] envlist = py35-flake8, {py33,py34,py35}-django{1.8,1.9,1.10}-drf{3.1,3.2,3.3,3.4,3.5,3.6} [testenv] commands = ./runtests.py --fast {posargs} --verbose setenv = PYTHONDONTWRITEBYTECODE=1 deps = django1.8: Django<1.9 django1.9: Django<1.10 django1.10: Django<1.11 drf3.1: djangorestframework<3.2 drf3.2: djangorestframework<3.3 drf3.3: djangorestframework<3.4 drf3.4: djangorestframework<3.5 drf3.5: djangorestframework<3.6 drf3.6: djangorestframework<3.7 -rrequirements/testing.txt [testenv:py35-flake8] commands = ./runtests.py --lintonly deps = -rrequirements/codestyle.txt -rrequirements/testing.txt -
How to use the saved image in model in html
Hello sorry if this question seems basic but im new to django. I've successfully saved an image in my filefield inside my model but when I try to access it in html, it returns me a 404. Can someone help me solve the problem? Do I need to make a handler for get requests in my view? Can't I just use the path in my media folder? HTML <img id="profilepicture" src = {{ profile_picture.url }}> models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) email = models.TextField(max_length=500, blank=True) contact_number = models.CharField(max_length=30, blank=True) profile_picture = models.FileField(null=True,blank=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() views.py @login_required(login_url='/home/') def profile(request: HttpRequest) -> HttpResponse: date = convert_string(request.user.date_joined.month) + " " + \ str(request.user.date_joined.day) + " " +\ str(request.user.date_joined.year) context = { 'user': request.user.first_name, 'profile_picture': request.user.profile.profile_picture, 'date_joined':date, 'email':request.user.profile.email, 'contact_number':request.user.profile.contact_number } return render(request, 'Bartr/HTML/Profile.html',context) -
How to use django-filters with LinkWidget on choice field?
I am allmost done with my django filters panel. Last thing I wiuld like to test before I wrap it up was LinkWidget. Plain and simple: status = django_filters.AllValuesFilter(widget=django_filters.widgets.LinkWidget) Problem is that status is a choice field that looks like that: STATUS_CHOICES{ ('A','Active') ('U','Unactive' } status = models.CharField(max_length=1, choices=settings.STATUS_CHOICES, verbose_name="Status", default="A") Wjen I use plain template it shows this filter as A and U. My question is: how do I make it to show as 'Active', 'Unactive' ?? -
Testing Django Rest Framework Serializers with pytest
I could use pytest for testing models and views in my django project. Is it possible to use pytest for DRF serializers as well, appreciate pointers to samples. -
Can Google reCaptcha Validation Fail?
I am asking a theoretical and perhaps stupid question here, however I really want to know the answer. Now I am using Django to write a website with Google reCaptcha to prevent spam in filling the form. I have set a js to avoid skipping Google reCaptcha so that every submission will show the message that "I am not a robot". My question is, if on the form the submission has already been proved not by spam (as not the robot), then why I have to write syntax at views.py to validate the Google reCaptcha with secret key matching the site key? Under what situation could the submission by spam pass the Google reCaptcha and not by the validation at the backend? I attach my code if you would like to take reference of what I am doing, though it's a purely theoretical question. Thanks a lot. template: <form id="contact_form" class="form-horizontal" method="post" action="{% url 'contact' %}"> {% csrf_token %} <div class="form-group"> <span id="name_err" style="color:red; bold: false; font-size:1vw; padding-left:1vw; display:none">Please enter your name</span> <label class="control-label col-sm-2" for="name">Name:</label> <div class="col-sm-10"> <input type="text" class="form-control" id="name" name="name" placeholder="Enter name here"> </div> </div> <script src='https://www.google.com/recaptcha/api.js'></script> <div style="padding-left: 11vw;" class="g-recaptcha" data-sitekey="xxx"></div><br> <div style="padding-left: 11vw;" id="submit-div"><input type="submit" … -
Possible to use Django as a web service for a mobile app?
I'm sorry if my question appears naive to all experienced coders at stack! We have a windows based POS software which stores all data in Microsoft SQL database. The software provider is willing to provide an API which can allow a web application to pull name of items, its price and stock for all inventory in store. Now, if we want to have a mobile app that our customers can use to place an order for products. What are the set of skills (eg: Django, django rest framework etc) I need to search for in a freelancer who will develop such app? I know this is a forum for coders and my question may seem irrelevant. But nowhere except stack overflow we can find people who can give a good advise on this. -
Customize related field in django model specifying foreign keys
In my Django project I have a model for products that look like this: class Manufacturer(models.Model): name = models.CharField(max_length=100) class Product(models.Model): manufacturer = models.ForeignKey('Manufacturer') # .favorite_set: ManyToOne relation coming from the # 'Favorite' class (shown a couple of lines below) My site's User(s) can mark some products as Favorite. To provide this functionality, I have a Django model that looks like this: class Favorite(models.Model): user = models.ForeignKey(User) product = models.ForeignKey('Product') class Meta: unique_together = ('user', 'product',) In that model, the .product ForeignKey creates a reverse relation in the Product model called favorite_set. That's all good and useful: When I get an HTTP request from a user to retrieve products, I can easily figure out whether it's been favorited by a particular user or not by doing this: product = Product.objects.get(id='whatever_id') is_favorited = bool(product.favorite_set.filter(user=self.user).count() == 1) # or probably: # is_favorited = product.favorite_set.filter(user=self.user).exists() # Now, I have another model that is heavily denormalized (SQL denormalized, that is) that I want to use for fast text searches. This model "pretends" to be a Product, but includes data found through the "regular" Product's FK relationships into the model itself. Something like this: class ProductSearch(models.Model): product = models.OneToOneField('Product', on_delete=models.CASCADE, related_name='searcher') product_name = models.CharField(max_length=100) manufacturer_name … -
How to create a new user with django rest framework and custom user model
I have a custom user model and I am using django-rest-framework to create API models.py: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField( unique=True, max_length=254, ) first_name = models.CharField(max_length=15) last_name = models.CharField(max_length=15) mobile = models.IntegerField(unique=True) date_joined = models.DateTimeField(default=timezone.now) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) serializers.py: class UserSerializer(serializers.ModelSerializer): password1 = serializers.CharField(write_only=True) password2 = serializers.CharField(write_only=True) class Meta: model = User fields = ('first_name', 'last_name', 'email', 'mobile', 'password1', 'password2') views.py: @api_view(['POST']) @permission_classes((AllowAny,)) def create_user(request): serialized = UserSerializer(data=request.data) if serialized.is_valid(): User.objects.create_user( serialized.save() ) return Response(serialized.data, status=status.HTTP_201_CREATED) else: return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST) However, when I try to create a new user I am getting this error: Got a TypeError when calling User.objects.create(). This may be because you have a writable field on the serializer class that is not a valid argument to User.objects.create(). You may need to make the field read-only, or override the UserSerializer.create() method to handle this correctly. This maybe because there's no password1 or password2 fields in the User model. But so, how can I create an API to create a new user using django-rest-framework? -
Migrating from MySQL to Postgres leads to performance drop
I'm working to migrate my application from MySQL to PgSQL, because I don't like the MySQL default utf-8 3 byte char limit. Of course I could change the charset from utf8 to utf8bm4, but there are some other things I liked about PgSQL (GEO-spatial support for example). All in all I though migrating to Postgres would be the way to go forward. However, one of the main queries is about 10x slower on Postgres then on MySQL. This is the query explained in Postgres: https://explain.depesz.com/s/FC5 This is the same query as with MySQL, but the MySQL variant seems to execute in +/-100ms, whereas the PgSQL variant takes about 1 second on the same tables (copied the mysql table to postgres with https://github.com/philipsoutham/py-mysql2pgsql) Please not I'm using the Django ORM, and Django created the query for me. -
Django middleware catches exception
I am using python-social-auth, and I am catching any exceptions using the following middleware: class ExtendedSocialAuthExceptionMiddleware(SocialAuthExceptionMiddleware): def process_exception(self, request, exception): if hasattr(social_exceptions, exception.__class__.__name__): return HttpResponse('error') else: raise exception What I would like to do in this exception handler is redirect the user to the page they came from, and display the exception in a label in that template. How would I do this? -
Token Auth - Django Rest Framework Postman
I am fairly new to Django so sorry if this is a silly question: When I try to send the request through postman I receive this 403 error: { "detail": "CSRF Failed: CSRF token missing or incorrect." } I have also tried adding it to the params section as well in postman, resulting in the same error. However, when using the curl command, I receive the correct response: curl -X POST -d "grant_type=convert_token&client_id=r29GLakM6OZ7c4Zg2cwuSXR7M1jiQHIEEMLvtbWA&client_secret=S2xKO81zzYBUTdxM14QiQWb63jnNvPLIcqDTrN9HIYj7t7ldfuCQFWoziWF6h88OgsMUCUNI6HbhIxZQ8ScPFWUWVcJNjaZspbGkDK1j9SsRYJi9uW6DhTr0A9QKvyOZ&backend=facebook&token=EAAY5l4TWgr4BAMjficP4mPKqlbVwVRXI0Xs5GLXSN97sMyKe3muElrkpXRcxJkiZCMzC7tfZBfT4Cci52Pk6Bb2GQm2BARm23tsJoaViOovmvZABlGlJPPZCJ9OecYvfEinUOBaDeBugiDv614yUzOAIfyE0lfZCAX8YAbYyxnlqYYtmS6ywH" http://localhost:8000/api/social/convert-token What am I doing wrong? -
TypeError: view must be a callable or a list/tuple in the case of include django
I am new in Django and want to run some projects from GitHub. I want to see from this projects codes and results where that project running but I have some errors any time I run projects. For urls.py I get the following error: error TypeError: view must be a callable or a list/tuple in the case of include() simple urls.py from django.conf.urls import patterns, include, url from django.contrib import admin from website import views admin.autodiscover() urlpatterns = [ # Examples: url(r'^$', views.home, name='home'), url(r'^home/', views.home, name='home'), url(r'^admin/', include(admin.site.urls)), url(r'^register/', views.register, name='register'), url(r'^login/$', views.user_login, name='login'), url(r'^logout/$', views.user_logout, name='logout'), ] or from other project : from django.conf.urls import patterns, include, url from django.contrib import admin from blog.views import * urlpatterns = [ # Examples: # url(r'^$', 'firstDjango.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^home/$','blog.views.home'), url(r'^login/$','blog.views.login'), url(r'^register/$','blog.views.register'), ] I have Django final version. Have I done something wrong? Or do I need replace all urls.py ? -
View other users profil without editing their posts
So I want that user view other user profil, and their posts without editing them. I know that I need a username or user id as argument and pass it in the index.html but I don't know how to do it and I have some trouble doing it. In the view I have something like this: def Profil(request): if not request.user.is_authenticated(): return render(request, 'blog/visitor.html') else: posts = Post.objects.filter(user=request.user) return render(request, 'blog/profil.html', {'posts': posts}) And here the index.html where a user click on another user to view his profil. <a href="{% url 'blog:profil' %}">{{post.user.username }}</a> And my url.py looks like this: url(r'^profil/$', views.Profil, name = 'profil'), Thanks ! -
Django - catching a function raised by python-social-auth URL in template
Authenticate With GitHub Is a link in a template. However, it is possible for this to raise an exception. I would like to catch this exception, but this does not seem possible in a template. How would I catch this exception? -
display foreign key in parent class
I could not show reverse relation in Django Rest Framework. Here in my case, a rent can have multiple images and i want to display all the images of that rent(living room image, kitchen image, bathroom image etc) in /api/v1/rent, i mean in rent resource. So, how do I fetch these Galleries to display in the Rental resource? class Rental(models.Model): user = models.ForeignKey(User) name = models.CharField(max_length=300, blank=False, null=False) phone_number = models.PositiveIntegerField(null=False, blank=False) renter = models.CharField(choices=RENTER_CHOICES, max_length=1, default=RENTER_CHOICES[0]) def __str__(self): return self.name def user_directory_path(instance, filename): return 'rent_{0}/{1}'.format(instance.rent.id, filename) class Gallery(models.Model): rent = models.ForeignKey(Rental, related_name="rent") image = models.FileField(upload_to=user_directory_path) tag = models.CharField(max_length=1, choices=TAGS, null=True, blank=True) class GallerySerializer(serializers.ModelSerializer): rent = serializers.ReadOnlyField() class Meta: model = Gallery fields = ('rent', 'image', 'tag',) class RentalSerializer(serializers.ModelSerializer): user = serializers.ReadOnlyField(source='user.username') # gallery = serializers.SerializerMethodField('get_children') # # def get_children(self, obj): # print ('obj', obj.gallery_set) # serializer = GallerySerializer(obj.gallery_set.all(), many=True) # return serializer.data gallery = GallerySerializer(source='gallery_set',many=True, read_only=True) class Meta: model = Rental fields = ('user', 'name', 'phone_number','gallery',) Right now i dont get the list of gallery, using both way, one commented way and another source='gallery_set' way. -
After deploying django in AWS EB its not working similarly as it runs in localhost
This is how Admin page works in local host This is how its showing after deploying in AWS EB can i get help on this like how to get it normal or how to modify it using my own templates please . -
{% extends .. %} doesn't run javascript in child template
I am trying to inject some javascript blocks into my parent template but they don't run. My templates are very straightforward, so I am simplifying: base.html {% load i18n static %} <html> <head> .. </head> <body> {% block content %}{% endblock %} ... {% block specificjs %} {% endblock %} child.html {% extends base.html %} {% load i18n static %} {% block content %}{% endblock %} {% block specificjs %} <script> console.log('blah'); </script> {% endblock %} So whenever I click on a button with href='link_to_child_view', it goes through the view and no blocks have been included/run When I refresh the child.html page, it load all the injected js, css, etc. I wonder, do I need Jinja2 to run extends, etc. ? I thought it belongs to Django by default.. If Jinja2 is not required, what am I doing wrong? I also tried the following three methods to render/return but no difference affected: # return TemplateResponse(request, 'child.html', locals()) # return render(request, 'child.html', locals()) # return render_to_response(, locals(), context_instance=RequestContext(request)) -
Issue when looping through form fields in Django's __init__ method
My goal is to loop through all form fields and to assign certain classes to them like this: class ContactForm(forms.Form): def __init__(self, *args, **kwargs): super(ContactForm, self).__init__(*args, **kwargs) # self.fields['name'].widget.attrs['placeholder'] = _('Name') for field_name, field in self.fields.items(): field.widget.attrs['class'] = 'form-control input-sm plain' if field.required == True: field.widget.attrs['required'] = '' class Meta: model = Contact fields = '__all__' The issue with this code is that self.fields.items() seems to be empty (and as a result I never get into the for-loop). My guess is that the issue arose because of my upgrade from Django 1.9 and python 2 to Django 1.10 and python 3. Could anyone share expertise on this?