Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using Django Rest Framework, is it possible to get results internally on server within Django?
I have a complex DRF ViewSet that supports paging, filtering, sorting, etc. that backends a grid view. To build an "export" capability, I need to be able to take the same querystring that my endpoint uses, such as: ?obj_id=129&ordering=latitude&city__icontains=nap And be able to, in Django, send that string into DRF somehow and get the fully-modified queryset after all the view's filters, sorts, etc are applied (the same way as the GET did). I could use the fully-rendered json response or some interim filter-applied queryset. Is it possible to use DRF in this way? -
Django creating new project - access is denied
I'm trying to create a Django project with the command: django-admin startproject mysite unfortunately, I get the error: CommandError: [WinError 5] Access is denied: 'C\\Windows\\mysite' How can I resolve this error? -
NoReverseMatch in Django; views and urls are properly defined
I am currently working on a website and I am receiving an error that is driving me up a wall. I have the following url defined in urls.py. urlpatterns = [ url(r'^', views.homeFeed, name='home'), url(r'^posts/(?P<uid>[\w+])$', views.discussPostView, name='post') ] I then have the following code defining views.discussPostView. def discussPostView(request, **kwargs): if request.method == 'GET': print(kwargs['uid']) post = get_object_or_404(DiscussPost, uid=kwargs['uid']) return render(request, 'discuss/post.html', {"post": post}) if request.method == 'POST': reply = DiscussReply.objects.create( by=request.user, content=request.POST['reply']) reply.save() reply_to = DiscussPost.objects.get(pk=request.POST['post_id']) reply_to.replies.add(reply) reply_to.save() return HttpResponseRedirect(request.get_full_path()) However, when I try to create a post on the site or access a post with a certain uid, I receive this error; Reverse for 'post' with arguments '()' and keyword arguments '{u'uid': u'CHacFvE_'}' not found. 1 pattern(s) tried: [u'discuss/posts/(?P<uid>[\\w+])$'] I literally have no idea what's wrong with my code. I am a bit rusty on python so I might be missing some obvious pointers, but any pointers in the right direction would be helpful. Thank you! -
How to translate this this instructions in a query expression in Django
Hello everyone I have a set of instructions to query my data base and I wonder myself if these are possible in a compact way as Query expression, so I have a model who has a fild called solapin as you can see here: class Question(models.Model): question_text = models.CharField(max_length=200) ......... solapin = models.CharField(max_length=250) def __str__(self): # __unicode__ on Python 2 return self.solapin and I want to change the solapin field for every Question object whose solapin has between 0 to 9 characters, adding as '0' characters as the difference between 10 and the current solapin length of the everyone as you can see here: from appname.models import Question resultset = Question.objects.filter(solapin__iregex=r'^.{0,9}$'); for item in resultset: diff = 10 - len(item .solapin); item .solapin = "0"*diff+item.solapin; item.save(); this woks perfectly for me but I want to see if is possible to improve it. -
No File was submitted while trying to make a POST. Django Rest Framework
I'm trying to make a "POST", but the problem is that I get a "no file was submitted error" and I don't know why. in my models.py I don't have "icon" in PersonalDetail PersonalDetailSample class PersonalDetailSample(models.Model): ... icon = models.FileField(_('icon'), db_index=True, null=True, blank=True, upload_to='files/') ... serializers.py class PersonalDetailSerializer(serializers.ModelSerializer): ... icon = serializers.FileField(source='details_sample.icon') ... class Meta: model = PersonalDetail fields = ( ..., 'icon', ... ) and in my views.py def perform_create(self, serializer): preview_text, preview_name = personal_details.find_text_name(serializer.validated_data) serializer.save(user_id=self.request.user, details_sample=serializer.validated_data['details_sample'], content=serializer.validated_data['content'], preview_name=preview_name) The post I would like to do: { "checked":true, "content": { "text_field_1": { "size":"small", "text":"My userdefined Title", "title":"Title" }, "text_field_2": { "size":"big", "text":"I don't have inspiration", "title":"Nachricht" } }, "details_sample":27, "preview_user_title": "This is my User Title" } And I get this error: { "icon": [ "No file was submitted." ] } And I don't know why... Maybe someone had the same trouble. -
Django models - Passing function object with arguments
I'm trying to make default values(and other kwargs) of models fields more dynamic, so i made a function for that: def get_latest_id(cls, text, *args): try: ret = globals()[cls].objects.latest('id').id + 1 return text.format(ret, args) except: return text.format(1, args) I wanted to use this function as default for some field, but i need arguments to tell function with what to work. So i did next: @deconstructible class callable: def __init__(self, foo, *args): self.foo = foo self.args = args def __call__(self): return self.foo(*self.args) @deconstructible class lazy_call: def __init__(self, foo): self.foo = foo def __call__(self, *args): return callable(self.foo, *args) @lazy_call #return this function as callable object that know its arguments def get_latest_id(cls, text, *args): try: ret = globals()[cls].objects.latest('id').id + 1 return text.format(ret, args) except: return text.format(1, args) And it works fine but now i have noticed that i've got infinite migrations(if there's no errors i can makemigratons any number of times and it will not say 'No changes detected'), and it surely linked with my function. Is it fixable? Or my code isn't valid for how django works? -
Validate field not in model by Django rest
I have a model: class EventTracker(models.Model): """ Track events of user's behaviors """ class Meta: verbose_name = "EventTracker" verbose_name_plural = "EventTrackers" unique_together = ("application", "label") application = models.ForeignKey(Application, related_name='events') label = models.CharField(max_length=50) count = models.PositiveIntegerField(default=0) value = models.IntegerField(null=True) def __str__(self): return "[{}] {}".format(self.application, self.label) This is my serializer for this model: class EventTrackerSerializer(serializers.ModelSerializer): subscriber_id = serializers.IntegerField(min_value=1) class Meta: model = EventTracker fields = ('id', 'application', 'label', 'count', 'value', 'subscriber_id') write_only_fields = ('subscriber_id', ) read_only_fields = ('count',) subscriber_id is a field that doesn't belong to this model. But request data must have subscriber_id to do a thing. So I want to validate it in serializer. I don't know how to validate it. I tried like above, it threw error: This may be because you have a writable field on the serializer class that is not a valid argument to..... So what can I do ? -
DRF-Extension cache ignoring query parameters
I am using drf-extension for caching my APIs. But it is not working as expected with cache_response decorator. It caches the response for say /api/get-cities/?country=india . But when I hit /api/get-cities/?country=usa, I get the same response. Here is the sample code: settings.py CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/0", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient" }, "KEY_PREFIX": "city" } } REST_FRAMEWORK_EXTENSIONS = { 'DEFAULT_USE_CACHE': 'default', 'DEFAULT_CACHE_RESPONSE_TIMEOUT': 86400, } views.py class GetCities(APIView): @cache_response() def get(self, request): country = request.GET.get("country", "") return get_cities_function(country) Please help with this. -
Override template in django admin
I'm using Django 1.11 I was able to extend/override one template called change_form.html I placed this file under /templates/admin/my_app/my_model/ For this one I extended and changed one block, like in the example in django docs I was not able to override one template called submit_line.html I tried placing it under /templates/admin/, /templates/admin/my_app/, and /templates/admin/my_app/my_model/. None worked. I edited the file under django/contrib and it worked, but I don't want to change that file. It was just to see if the content was showing. I just want to add one button to the template, so the user can download one XML file. -
Image is being displayed as white box in Django template
The images are showing up as blank boxes. I'm confused as to why this is the case. Models.py class Aircraft(AirlineModelBase): image = models.ImageField(upload_to="uploads/airline", blank=True, null=True) Settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ map_path('static'),] Template <div class="box"><img src="{{ aircraft.image }}" alt="{{ image.title }}"/> -
Passing data back to Django view
Inside of a table in my template I have the following which works great: <tbody> {% for item in items %} <tr> <td>{{ item.id }}</td> <td>{{ item.name }}</td> <td>{{ item.status }}</td> <td>{{ item.start_time }}</td> <td>{{ item.end_time }}</td> </tr> </tbody> I would like to add a form that posts the items to a view. I've tried this: <form align="center" action="{% url 'app:doit' %}" method="post" ><b></b> {% csrf_token %} <input type="hidden" name="items" value="{{ items}}" /> <input type="submit" name="export" value="Export" > </form> but that doesn't work. How do I pass {{items}} back to a view? The export method in my view contains this: if 'items' in request.POST: my_items = request.POST['items'] -
Is it possible to use Django-Admin editor/interface outside of the admin?
I have a model that I need to edit. I have it registered in Admin.py. It works fine in my admin. How do I use this particular editing interface in other parts of my project? What I mean is, I want to use the admin editor on another template to do exactly what the admin does inside of it. Is there a module or library that will let me do this in django? -
django authentication multi upload files
I have create I simple Django auth project and I need to add the user to can upload some images. multi upload images from this video views.py from django.shortcuts import render from django.http import HttpResponse def Form(request): return render(request, "index/form.html", {}) def Upload(request): for count, x in enumerate(request.FILES.getlist("files")): def process(f): with open('/Users/Michel/django_1.8/projects/upload/media/file_' + str(count), 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) process(x) return HttpResponse("File(s) uploaded!") but how to define that to multi upload images in specific unique folder for any user. first I use login_required and in destination I use user_directory_path. But how to define the code in the views.py to work with authentication per user. for example for user_1 upload images in your folder for user_1 in folder for user_2. medels.py def user_directory_path(instance, filename): return 'user_{0}/{1}'.format(instance.user.id, filename) class MyModel(models.Model): upload = models.ImageField(upload_to=user_directory_path) -
Django - no such column: blog_comment.body error
I am following a tutorial as I am fairly new to Django, and I am trying to add a comments system to my blog. However, whenever I try and use it I get an error message saying the following:no such column: blog_comment.body. I am not sure what is going on, as in my model I have body = models.TextField(), and I am just generally very confused. -
Rendering django form error next to field label in crispyforms
When a form has an error, the error message is displayed under the input html element. Is there a way to modify its location so that every error message is displayed next to the label html tag? -
No changes detected with makemigrations
I just installed crispy forms and added them to my applications and set the template_pack, but now it wont migrate also it wont makemigrations When I do makemigrations: python manage.py makemigrations. - No changes detected python manage.py migrate. - Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, website How can I fix this? -
Django push notifications options
I am new to Django push notifications. So I was looking for a Django push notification solution in which I could trigger notifications from one page of the website to another page of the same website. The idea is to have an admin which sends notification to customers(since several users will be visiting website so notification should reach a particular user only who is targeted but not all [Something related to channels may be needed]). I really don't have any clue on where to start. So could I get some help -
csrf token missing when signing up
I am in need to customize my signup form. I need additional fields i.e user_type so i created a new model called UserProfile where user is OneToOneField and user_type is the choice. I have used django-allauth so i have defined new singupform as in below ACCOUNT_SIGNUP_FORM_CLASS = 'account_page.custom_form.SignupForm' class UserProfile(models.Model): DESIGNER = 'designer' DEVELOPER = 'developer' BOTH = 'both' CHOICE = ((DESIGNER, 'designer'), (DEVELOPER, 'developer'), (BOTH, 'both')) user = models.OneToOneField(User, related_name="profile") user_type = models.CharField(choices=CHOICE, max_length=50, blank=False, null=False, default=DESIGNER) def __str__(self): return self.user.username from user_account.models import UserProfile from background.tasks import send_request_received_email class SignupForm(forms.ModelForm): class Meta: model = UserProfile fields = ['user_type'] def clean(self): email = self.cleaned_data.get('email') if email and settings.INVITE_MODE: try: obj = Invitation.objects.get(email=email) if not obj.request_approved: self.add_error('email', 'Sorry you are not accepted yet') except Invitation.DoesNotExist: invitation = Invitation.objects.create(email=email) self.add_error('email', 'Sorry we have added you to our invite list') elif email is None: raise forms.ValidationError('Email field should not be empty') else: return email def signup(self, request, user): print('user.profile', user.profile) print('##############') profile = UserProfile() print('profile', profile) profile.save(commit=False) # user.save() user.profile = profile profile.user = user profile.user_type = self.cleaned_data.get('user_type') profile.save() <form class="singup-form" action="{% url 'account_signup' %}" method="POST"> {% csrf_token %} {{form.as_p}} <button type="submit" class="button primary">Signup</button> </form> Where have i done wrong so i … -
Adapt translation method from django to my function
I am working on a django project. I have created a function that will display the current date in french or english. We have to install sudo locale-gen fr_FR.utf8 and then from datetime import datetime import locale def set_locale(locale_): locale.setlocale(category=locale.LC_ALL, locale=locale_) def date_customerprofile(language): now_ = datetime.today() if language == 'English': set_locale('en_US.utf8') date_ = now_.strftime("%A %B %d %Y") else: set_locale('fr_FR.utf8') date_ = now_.strftime("%A %B %d %Y") I know it works well, but I would like to use the django translation method. There are good informations here : https://docs.djangoproject.com/fr/1.10/topics/i18n/translation/ and in particular here : https://www.technomancy.org/python/django-i18n-manually-turn-on-a-language/. Could anyone be able to adapt the last website method to my function? -
Is it possible to mix 2 ORMS in same web app?
So is it possible to mix 2 ORM's in same web app,and if so how optimal would it be ? Why so? - I'm working on a web app in flask using flask-mysqldb and I came to a point where I need to implement an auth system, and on flask-mysqldb there's no secure way to do it. - With that said now I'm trying to implement flask-security but it only works on flask-sqlalchemy so I'm trying to mix sqlalchemy with mysqldb and before that I want to know it it's optimal and if it works.That would lead to using user auth along sqlalchemy and other data to mysqldb.Thanks! -
How do I direct requests in an angular 2 front end to a multi-tenant, django rest framework backend?
I created an API backend with django-rest-framework and django-tenant-schemas for multi-tenancy. Each tenant will access their own resources (each tenant has their own schema in the database) by prepending their organization's name to the base url like so: "tenant1.my-api-backend.com/api/*****" "tenant2.my-api-backend.com/api/*****" My Angular2 frontend is completely decoupled from the API and I'm struggling to understand how I can route the requests to the correct tenant. What do I have to do to setup my front end so that it looks something like this and properly directs the requests to the correct tenant: "tenant1.my-site-frontend.com" "tenant2.my-site-frontend.com" -
Django - how to work cursor for saving data during work another cursor in mysql
What I want to do is that 'views.py' lists db tables, creates them as dictionaries and renders them as 'index.html'. At the same time, we want to save the value received from mqtt to the DB in real time. I've written it in code, but I'm having trouble working at the same time. There is no problem in outputting the data obtained by accessing db to index.html, but at the same time, if I try to save the data value of mqtt in the database in real time, it will not be saved and the mqtt.py will be quite. There are no errors. However, when I shut down the web server in that state, the data is saved again in the db. I think the cause is at cursor(). I need your advice. I need your advice. views.py def index(request): cur_1 = db.cursor() cur_2 = db.cursor() cur_1.execute("SHOW TABLES") result = cur_1.fetchall() for row in result: if 'iot_' in row[0] table_list.append(row[0]) for i in range(0, len(table_list)): query = """ SELECT sensor_data From %s """ % table_list[i] cur_2.execute(query) sensor_data = cur_2.fetchall()[-1][0] context = { "even" : dict_even, "odd" : dict_odd } return render(request, 'index.html', context) mqtt.py class Sensor_Table: cur = db.cursor() def … -
How multiple Django projects can share a same template
i) Suppose I am running a Django project whose landing page is having a Login and Registration page and some other basic information (I am thinking of using the Django login). ii) After registration users will be redirected to a page where they can enter some information through a form, like database name , user name etc. iii) then I want to reflect this information which is entered by the user to a settings.py file of a separate Django project (which will run on different port of the same IP or any other option you can suggest) this project will be created automatically after user click a submit button. and then I want to reflect the output of this Django project to their logged in screen. iv) Users would also be able to download their project in a .zip format Any suggestion on how to implement this would be appreciated. -
Django Search bar feature not working?
In my base template I have this search bar. When I search for something it doesn't actually return anything. I'm not sure if the url is correct because I want it to work on every page. In the base navbar this is the code: <form class="navbar-form navbar-left" target="_self"> <div class="form-group"> <label class="control-label" for="search-field"> <i class="glyphicon glyphicon-search"></i></label> <input type="text/submit" value="{{request.GET.q}}" name="q" class="form-control search-field" action={% url 'search_posts' %} placeholder="Search Airline or Aircraft" id="search-field" /> </div> </form> Urls.py url(r'^$', search_posts, name='search_posts'), Views.py def search_posts(request): aircraft = Aircraft.objects.all() airline = Airline.objects.all() query = request.GET.get("q") if query: aircraft = aircraft.filter( Q(name__icontains=query) | Q(description__icontains=query) ).distinct() return render(request, 'search_post.html', {'aircraft': aircraft}) Is it possible to combine two models into a variable? I have Aircraft and Airline. Will this work? queryset_list = Aircraft.objects.all() + Aircraft.objects.all() -
Django backwards foreign key manager
I am trying to dynamically get a model's backwards foreign key manager. If I have: class modelA(models.Model) name = models.CharField(max_length=100) class modelB(models.Model) fk = models.ManyToManyField(modelA) From the docs I can see that I can get the backwards foreign key manager by doing: a = modelB.modela_set in the shell this gives me django.db.models.fields.related_descriptors.create_forward_many_to_many_manager.<locals>.ManyRelatedManager with which I can do a.all() and get a result. However If I have the string 'modela' and I do: a = getattr(modelB, 'modela_set') I will get django.db.models.fields.related_descriptors.ManyToManyDescriptor and if i do: a.all() I get an attribute error. I do not understand why getattr() is behaving this way. Is there a way to do this?