Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Suddenly it does not deploy to heroku in C9 ,Django
Only 30 minutes before it was running normally. I am developing on c9. There are three commands I use to deploy. git add . git commit -m'a' git push heroku master I've been deploying with these three commands, and an error occurred at some point. 2017-11-22T14:13:32.376772+00:00 app[web.1]: bash: gunicorn: command not found 2017-11-22T14:13:32.462690+00:00 heroku[web.1]: State changed from starting to crashed 2017-11-22T14:13:33.756325+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=quiet-tundra-61346.herokuapp.com request_id=964a2694-e6c3-41c6-8357-4d5aa1ae70e6 fwd="175.193.51.62" dyno= connect= service= status=503 bytes= protocol=https I was so embarrassed because I had no problems for 10 days. When I looked at the difference, it was different from the previous one when pushing heroku. remote: -----> Compressing... remote: Done: 59.2M Previously, the figure was clearly above 70 meters. On c9, it runs without any problems. The modified code is also veiw.py logic. I commented out that part, but the same result came out. I do not even know where to get the code because I do not know which part is the problem. Can not you find out with this information? I've written git commit -m'q in the middle, and is this a problem? -
Django-allauth EmailAddress does not exist error
So i am using django-allauth==0.34.0 with django==1.11.7 and every time a new user signs up with a facebook or google account, i get a EmailAddress does not exist: xx@example.com error on the url: /accounts/facebook/login/callback/ or /accounts/google/login/callback/. I get this error, but the strange thing is that the user stays registered and works fine. I have applied all migrations as well. Some traceback from my sentry error: SELECT "socialaccount_socialaccount"."id", "socialaccount_socialaccount"."user_id", "socialaccount_socialaccount"."provider", "socialaccount_socialaccount"."uid", "socialaccount_socialaccount"."last_login", "socialaccount_socialaccount"."date_joined", "socialaccount_socialaccount"."extra_data" FROM "socialaccount_socialaccount" WHERE ("socialaccount_socialaccount"."provider" = 'google' AND "socialaccount_socialaccount"."uid" = '100000') and SELECT "account_emailaddress"."id", "account_emailaddress"."user_id", "account_emailaddress"."email", "account_emailaddress"."verified", "account_emailaddress"."primary" FROM "account_emailaddress" WHERE UPPER("account_emailaddress"."email"::text) = UPPER('xx@example.com') Any ideas how i can fix this? -
django filtering with q objects with dynamic fields
I need to prepare filter with dynamic fields.. I don't know the field name so i need to give it dynamically. here what i tried so far, gen_query = reduce(operator.or_, (Q(eval('%s=i' % (field, i))) for i in request.query_params.get(field).split(','))) but it raising syntax error! i am using, eval(field_name as string) still i am getting an error.. how to achieve this? i want to do django filtering with q objects with dynamic fields -
Django count relations where conditions in foreign field is met
I am getting started on a Django project, I have four models, client, staff, booking_request, meeting_event A client can book a lot of meetings, each meeting can involve many staffs. Each booking request is assigned to one meeting_event. I would like to query a list of Staff objects, order by the number of client they are booked with within an meeting_event. Currently i can figure Staff.objects.annotate(num_bookings=Count('bookings_with_clients')).order_by('-num_bookings') but i cannot filter the results to a specific meeting_event Models are as below: Client Request_booking client = ForeignKey(Client) event = ForeignKey(MeetingEvent) staff = ManytoManyField(Staff) Staff Meeting Event Any help would be appreciated :) -
Django oauth2 implementation using auhorization_code as grant type
I want to register my Django oauth2 app using postman or other REST client and also use authorization_code as grant type. First When I register the app I should get client_id and secrete and then I should get the authorization code and next I should get the access token.and what should be exact redirect URI? please help. -
Reference to another field in model.py // Django
I would like to return in str method of the Chapter, title of the Chapter and title of the Book (from book model). I need it for better display at the admin pages. How to do that? Should I create some new method in Book or use Model instance reference https://docs.djangoproject.com/en/1.11/ref/models/instances/#model-instance-methods ? Or maybe I should use Retrieving specific objects with filters? https://docs.djangoproject.com/en/1.11/topics/db/queries/#retrieving-objects I am new to the django, thank you in advance for the solutions. class Book(models.Model): author = models.CharField(max_length=200) title = models.TextField() created_date = models.DateTimeField( default=timezone.now) def __str__(self): return self.title+" ("+self.author+")" def book_author(self): return self.author class Chapter(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE) title = models.TextField() created_date = models.DateTimeField( default=timezone.now) body = models.TextField() hierarchy = models.IntegerField() sort = models.IntegerField(unique=True) def __str__(self): print(repr(Book)) print(repr(Book.author)) # print(repr(Book.objects.all().filter(id==1))) # print(repr(Book.objects.get(id=1))) print(repr(Book.book_author(self))) return self.title+"(book: "+")" -
What is the optimal way to create user and admin sides of program?
I am just learning Django, but I already have a previous application that I am rebuilding on Django and Python. The original app did not use MVC. Original app is a control-panel kind of a thing, where you have basic CRUD-methods to manipulate information in database, and displaying it on a website. I had built that with PHP and HTML, so I did not use a framework. User has access to basic CRUD methods, and to view the data. Admin has all these, + more advanced database and table operations. In this app, there is a login system that supports normal users, and admins. Now that I am using Django, I would like to design the app correctly before building it. So here's the question: Inside Django, should I create one app for users, and one for admins? This would let me separate the views, and have two urls-files. If so, as an admin, could I use the models created on the user side, to display data correctly on the admin side? Or would I need to create the models again on the admin side aswell? They both query the same data and get same results from the DB. If … -
ImportError: cannot import name '_imaging'
Apache or Python doesn't import image on the media folder. When I tried to upload something It returns 500 error. Django is working behind Apache with mod_wsgi on CentOS 7. Django also works in a virtual environment. I disabled all firewalls (selinux, firewalld and iptables) I gave every permission to the Apache for the project folder. (chown apache:apache and chmod 777 I applied public write permission only for the media folder) Here is my apache conf file for the project: <VirtualHost *:80> ServerAdmin webmaster@domain.com ServerName example.com ServerAlias www.example.com DocumentRoot /var/www/example.com/html Alias /static/ /var/www/example.com/html/static/ Alias /media /var/www/example.com/html/media <Location "/static/"> Options -Indexes </Location> <Directory /var/www/example.com/html/logging> <Files debug.log> Require all granted </Files> </Directory> <Directory /var/www/example.com/html> <Files db.sqlite3> Require all granted </Files> </Directory> <Directory /var/www/example.com/html/media> Require all granted </Directory> <Directory /var/www/example.com/html/media/uploads> Require all granted </Directory> <Directory /var/www/example.com/html/static> Require all granted </Directory> <Directory /var/www/example.com/html/example> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess example.com python-path=/var/www/example.com/html:/var/www/example.com/html/env/lib/python3.4/site-packages WSGIProcessGroup example.com WSGIScriptAlias / /var/www/example.com/html/example/wsgi.py #Log Settings ErrorLog "/etc/httpd/logs/example_error" CustomLog "/etc/httpd/logs/example_acess" combined </VirtualHost> model.py from django.db import models from services.file_extentions import validate_image_extention # Create your models here. class FotografModel(models.Model): """Model definition for GaleriModel.""" # TODO: Define fields here foto = models.ImageField(verbose_name="Fotoğraf", upload_to='uploads/fotograflar/', max_length=100, height_field=None, width_field=None, validators=[validate_image_extention]) foto_baslik = models.CharField(verbose_name="Fotoğraf Açıklaması (Görme … -
How about create multi model instance through serializer?
How about create multi model instance through serializer? I have a views.py: class CloudServerCreateAPIView(CreateAPIView): """ Create CloudServer """ serializer_class = CloudServerCreateSerializer permission_classes = [] queryset = CloudServer.objects.all() Its serializer is this: class CloudServerCreateSerializer(ModelSerializer): count = serializers.IntegerField() class Meta: model = CloudServer exclude = [ 'expiration_time', 'buytime', 'availablearea', 'profile', ] def create(self, validated_data): count = validated_data.pop("count") for _ in range(0, count): # create the CloudServer instance, then save to database. And other logic stuff # But there must return a CloudServer instance. You see, my serializer, I override the create method, and I use for-loop to save the CloudServer instances to database. But the create method must return a instance, what to do with that? Because I access the view one time, to create the count times CloudServer instances, in my create method I have saved to database, what should I do then(in this line # But there must return a CloudServer instance.)? -
Efficiently loop over CSV file and validate against very large database tables in Django/Python
I'm working on a project where I upload a CSV file then I loop through each row, and enumerate over each value in the row. If the field has an entry I need to validate it against a large table of values. How I handle this at the moment is I do a single query from each table I need, the primary keys. So, I will pull in 300k primary keys and validate against that list. This is much quicker than hitting the database with a single .get request each and every time. My question is - can this be done more efficiently? Example of my code: large1_list = list(large1.objects.values_list('pk', flat=True)) large2_list = list(large2.objects.values_list('pk', flat=True)) csv_file = request.FILES['csv_file'] csv_parsed = csv.reader(codecs.iterdecode(csv_file, 'utf-8'), delimiter=',') for fields in csv: for i, x in enumerate(fields): if i == 0: if x not in large1_list: return blah blah blah And so on. I'm thinking there has to be a more efficient way to do this... But I figure this is better than actually hitting a DB each and every time. -
Django Copy multiple items from DB Query to dict
i have a Problem with Django and dicts. I want to get only items that match a sting as below. but i can´t get it to work. Thanks for your help. django_db_query = [{'time': '13:00 Uhr', 'titel': 'test1'}, {'time': '14:00 blah', 'titel': 'test2'}, {'time': '13:00 Uhr', 'titel': 'test3'},] all_db_items = Django_db.objects.all() only_13 = dict() for item in all_db_items: if item.time is "13": only_13 += item wanted: for item in only_13: print item.titel console test1 test2 -
AttributeError when serializing model object on deletion
I work an a django project and want to keep objects deleted by users for databases synchronization, so I decided to store them in a json file. For this I override the delete() method of the model. I first retreive previously deleted objects from the file, and then add the one being deleted. When serializing this new list, I get an AttributeError: AttributeError: 'DeserializedObject' object has no attribute '_meta' What am I doing wrong ? Here is the delete() code : def delete(self, *args, **kwargs): force = kwargs.pop("force", None) if force is None: objects_to_delete = list() user_dir_path = os.path.join(STATIC_ROOT, self.user.username) if not os.path.exists(user_dir_path): os.makedirs(user_dir_path) path = os.path.join(user_dir_path, "obj_to_delete.json") if os.path.exists(path): with open(path, "r") as fp: json_str = fp.read() if len(json_str) > 0: objects_to_delete = list(serializers.deserialize( "json", json_str, indent=4, use_natural_foreign_keys=True, fields=('pk', 'user', 'slug') )) objects_to_delete.append(self) if objects_to_delete: with open(path, "w") as fp: jsonData = serializers.serialize("json", objects_to_delete, indent=4, use_natural_foreign_keys=True, fields=('pk', 'user', 'slug') ) fp.write(jsonData) super(UserOwnedModel,self).delete(*args, **kwargs) -
Django + Factory Boy: How to use a named parameter to control behavior of factory.Maybe + factory.RelatedFactory
Is there a way to define a named parameter (that is not a model attribute) to control the behavior of factory.Maybe? For example: I want to create a named parameter that controls the creation of a RelatedFactory through a Maybe condition, I tried to do this: # factories.py class Purchase(factory.DjangoModelFactory): user = factory.SubFactory('project.factories.UserFactory') total = uniform(10, 100) class Meta: model = Purchase class UserFactory(factory.DjangoModelFactory): first_name = factory.Faker('first_name') last_name = factory.Faker('last_name') has_purchase = False purchases = factory.Maybe( 'has_purchase', yes_declaration=factory.RelatedFactory(Purchase, 'purchase'), no_declaration=None ) class Meta: exclude = ['has_purchase', 'purchases'] model = User # tests.py user_without_purchase = UserFactory.create() user_with_purchase = UserFactory.create(has_purchase=True) It seems that I can't change the value of has_purchase through the named parameter, it's always set as False. I don't know if it's because both fields are declared in exclude Meta attribute. And I have to put them in exclude or else DjangoModelFactory tries to use these fields when saving it to the database, which causes an Integrity error. Is there a way to do that? -
Accessing attributtes of an object in the browser with parent key
def detail(request,x_id): try: album = X.objects.get(pk=x_id) except X.DoesNotExist: raise Http404("X Does NOt Exist") return render(request, 'abc/abc.html', {'x':x}) When I try to access it on the browser it just shows x object. Not the attributes it has. abc.html has just this: {{x}} -
Django REST: How to filter related set?
I'm trying to create a Serializer which contains cities and for every city list of trips which belongs to the current user. The problem is that I'm getting all trips, not just users ones. My expectation for example if user was two times in London and once in Prague: [{<serialized London>,'trips':[<serialized the two London trips>]}, {<serialized Prague>, 'trips':[<serialized one trip to Prague]}] Now I'm getting all trips connected with the city. Models: class City(models.Model): place_id = models.CharField(max_length=1000, unique=True, null=True, blank=True) lat = models.DecimalField(max_digits=6, decimal_places=3, db_index=True, null=True, blank=True) lng = models.DecimalField(max_digits=6, decimal_places=3, db_index=True, null=True, blank=True) class Trip(models.Model): user = models.ForeignKey('auth.User', related_name='trips') city = models.ForeignKey('locations.City', related_name='trips') date_from = models.DateField(default=now) date_to = models.DateField(default=now) detail = models.TextField(null=True, blank=True) View: def ajax_get_my_trips(request): trips = Trip.objects.filter(user=request.user) cities = City.objects.filter(trips__in=trips) response = MyCityTripsSerializer(cities,many=True).data return JsonResponse(response, safe=False) Serializers: class MyTripsSerializer(serializers.ModelSerializer): class Meta: model = Trip fields = ('date_from', 'date_to', 'detail') def get_queryset(self): user = self.request.user return Trip.objects.filter(user=user) class MyCityTripsSerializer(serializers.ModelSerializer): trips = MyTripsSerializer(many=True) class Meta: model = City fields = ('place_id', 'lat', 'lng', 'number_of_users_here_now', 'formatted_address', 'trips') Do you know how to make it work? -
Django REST: 'QuerySet' object has no attribute 'trips'
I'm having problems to make my Serializer work. I have models: class City(models.Model): place_id = models.CharField(max_length=1000, unique=True, null=True, blank=True) lat = models.DecimalField(max_digits=6, decimal_places=3, db_index=True, null=True, blank=True) lng = models.DecimalField(max_digits=6, decimal_places=3, db_index=True, null=True, blank=True) class Trip(models.Model): user = models.ForeignKey('auth.User', related_name='trips') city = models.ForeignKey('locations.City', related_name='trips') date_from = models.DateField(default=now) date_to = models.DateField(default=now) detail = models.TextField(null=True, blank=True) I'm trying to create a serializer and a view, which returns all cities in which user has at least one trip, and for every city, list of the trips (only for this user). def ajax_get_my_trips(request): trips = Trip.objects.all() cities = City.objects.filter(trips__in=trips) response = MyCityTripsSerializer(cities).data return JsonResponse(response, safe=False) class MyTripsSerializer(serializers.ModelSerializer): class Meta: model = Trip fields = ('date_from', 'date_to', 'detail') def get_queryset(self): user = self.request.user return Trip.objects.filter(user=user) class MyCityTripsSerializer(serializers.ModelSerializer): trips = MyTripsSerializer(many=True) class Meta: model = City fields = ('place_id', 'lat', 'lng', 'number_of_users_here_now', 'formatted_address', 'trips') If user was two times in London and once in Prague: [{<serialized London>,'trips':[<serialized the two London trips>]}, {<serialized Prague>, 'trips':[<serialized one trip to Prague]}] But when I perform get request, it returns: Got AttributeError when attempting to get a value for field trips on serializer MyCityTripsSerializer. The serializer field might be named incorrectly and not match any attribute or key on the QuerySet … -
Django's template cannot get a list
When a list render from "view.py", template cannot get this. This is my views.py: class MyFavCourseView(LoginRequiredMixin, View): def get(self, request): course_list = [] fav_courses = UserFavorite.objects.filter(user=request.user, fav_type=1) for fav_course in fav_courses: course_id = fav_course.fav_id course = Course.objects.filter(id=course_id) course_list.append(course) return render(request, 'usercenter-fav-course.html', { "course_list": course_list }) /urls.py: url(r'^course/', include('courses.urls', namespace="course")), /courses/urls.py: url(r'^detail/(?P<course_id>\d+)/$', CourseDetailView.as_view(), name="course_detail"), a link in "usercenter-fav-course.html": {% for course in course_list %} <div class="module1_5 box"> <a href="{% url 'course:course_detail' course.id %}"> <img width="214" height="190" src="{{ MEDIA_URL }}{{ course.image }}"/> </a> {% endfor %} When enter this page, an error occured: https://i.stack.imgur.com/PU8Vy.png -
Django-Taggit | Getting ALL tags, but only related to blog
I am using django-taggit to tag three different types of models: a blog a list of events a list of products. This all works fine. I am now trying to grab a list of all the available tags related to the blog so I can display them on the BlogIndex page. The furthest I've gotten is, thanks to a similar SO question: from taggit.models import Tag def blog_tags(self): tags = Tag.objects.all() return tags However this gives me a list of every single tag, including the product and event tags. How do I filter that list of tags down to just the blog? -
Restore a dump in MongoDB instead of skipping existing records , modify it
I am using mongod to store the data of a particular website. I have an existing database, I want to merge my new dump file with the existing database without loosing the data my requirement is like 1) The existing database won't overwritten 2) If new entries are there append with the current database 3) If Existing collection is identified (ie, with same _id) modify it with the new collections I tried with this solution , but it is skipping the existing records https://stackoverflow.com/questions/4021762/mongodb-mongorestore-and-existing-collection-with-records When I used the command mongorestore --drop it over write the existing data, so i lost my existing records When I remove the --drop and execute the command mongorestore it just adding the new records not modify the existing record I am using python django framework for the server side coding -
python flask oauth client replacement in django
from flask_oauthlib.client import OAuth twitter = oauth.remote_app('twitter', base_url='https://api.twitter.com/1/', request_token_url='https://api.twitter.com/oauth/request_token', access_token_url='https://api.twitter.com/oauth/access_token', authorize_url='https://api.twitter.com/oauth/authenticate', consumer_key='<your key here>', consumer_secret='<your secret here>' ) @app.route('/login') def login(): return twitter.authorize(callback=url_for('oauth_authorized', next=request.args.get('next') or request.referrer or None)) Can anyone suggest how to implement the above code in django. I need to authenticate my app to a third party server and redirect back after getting the bearer token. I have the client id and client secret for the third party site. I am able to do the same using above code in flask but i need the same in django. -
Django Rest Framework change root item and list item element name
I am new to Django-Rest framework. I want to change root and list-item element name depending upon model names: From: <root> <list-item>worrier1</list-item> <list-item>worrier2</list-item> <root> To: <tests> <test>worrier1</test> <test>worrier2</test> <tests> I've overridden the XMLRenderer based on answer from here, but I'm not sure how to route this to my view. My View: class SampleViewSet(viewsets.ModelViewSet): myrenderer = ModifiedXMLRenderer(item_tag="tests", root_tag="test") queryset = Sample.objects.all() serializer_class = SampleSerializer permission_classes = [IsAuthenticatedOrReadOnly] ModifiedXMLRenderer: class ModifiedXMLRenderer(XMLRenderer): def __init__(self, item_tag=None,root_tag=None): self.item_tag_name = item_tag or "item" self.root_tag_name = root_tag or "channel" def render(self, data, accepted_media_type=None, renderer_context=None): """ Renders `data` into serialized XML. """ if data is None: return '' stream = StringIO() xml = SimplerXMLGenerator(stream, self.charset) xml.startDocument() xml.startElement(self.root_tag_name, {}) self._to_xml(xml, data) xml.endElement(self.root_tag_name) xml.endDocument() return stream.getvalue() def _to_xml(self, xml, data): if isinstance(data, (list, tuple)): for item in data: xml.startElement(self.item_tag_name, {}) self._to_xml(xml, item) xml.endElement(self.item_tag_name) elif isinstance(data, dict): for key, value in six.iteritems(data): xml.startElement(key, {}) self._to_xml(xml, value) xml.endElement(key) elif data is None: # Don't output any value pass else: xml.characters(force_text(data)) -
Django admin upload files inline without Model
I have model with JSONField that holds uploaded file (there is no FileField in the model). class Task(models.Model): .... attachments = fields.JSONField(null=True) .... Example of JSON [ {"id": "file_id", "url": "file_url_at_S3", "type": "MIME type" } ] I want to build an admin interface so a user can fill Task details AND upload files that will be uploaded to S3 and resulted json will be saved in the database. So I decided to use custom Form class to handle it. My AdminModel is @admin.register(Task) class TaskAdmin(MarkdownxModelAdmin): form = TaskForm exclude = ('created_at', 'updated_at', 'attachments') list_display = ('message', 'publish_at') def save_model(self, request, obj, form, change): upload_result = upload_files_to_s3(form.cleaned_data.get('attachments', []), task_id=obj.id) obj.attachments = upload_result super(TaskAdmin, self).save_model(request, obj, form, change) Where MarkdownxModelAdmin is just a subclass of ModelAdmin for markdown. My custom form is class TaskForm(forms.ModelForm): attachments = MultiFileField() # redefine field from the model .... def clean(self): # validations... class Meta: model = Task fields = '__all__' All admin interface is I'd like inline style of attachments like from the docs. So a user can add files one-by-one with a small preview or with the uploaded file path. So the interface looks like this What's the best solution here? -
How can I able to handle both GET and POST requests in views.py in python vue js?
My views.py is def searchnew(request): name = request.POST.get('name') loc = request.POST.get('location') d = { 'name': name, 'loc' : loc, } return render(request,"searchnew.html",d) I have GET request and other POST request. How can I able to handle GET request in this case? This is my GET request <a v-bind:href="'searchnew/?name='+post.name">{{post.name}}</a> My POST request is working fine? How can I able to pass this name? -
Django: Edit Profile gives me algorithm, iterations and hash
When I go to my "edit profile" page this is what it looks like: So it shows me the algorithm, iterations and hash. And if I want to remove it form my forms.py (remove password): class EditProfileForm(UserChangeForm): template_name='/something/else' class Meta: model = User fields = ( 'email', 'first_name', 'last_name', **'password'** ) It shows me this: Feel free to share your ideas. -
openpyxl read out excel and save into database
I am trying to read out an excel sheet and save it into my database. This is my excel table: My code where I am trying to get the data and save it into an data array looks like this (workbook was loaded before with load_workbook): def getExampleData(workbook): sheet = workbook.get_sheet_by_name('ExampleData') titleCell = sheet.cell('D1') assert titleCell.value = u'Overview' startRow = (2, 1) endRow = (6, 1) #this is the first empty row and I have it hardcodened to this time but it needs to be dynamically found in the future data['ExData'] = {} for i in range(startRow, endRow): exData = {} exData['Name'] = sheet.cell(row=I, column=1).value exData['Param1'] = sheet.cell(row=I, column=2).value exData['Param2'] = sheet.cell(row=I, column=3).value exData['Param3'] = sheet.cell(row=I, column=4).value data['ExData'| = exData return data['ExData'] and then I want it to load it into my database table named ExampleDB (the whole project is made with Django so I am loading the ExampleDB just with an import) like this: def saveExampleData(): xData = data['ExData'] ex = ExampleDB.objects.filter(name = xData['Name'], param1 = xData['Param1'], param2 = xData['Param2'], param3 = xData['Param3]) ex.save() I just want to say that I KNOW that this functions don't work but I think they show what I want to do. Maybe someone …