Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Understanding Django Q - Dynamic
I'm reading this article on dynamically generating Q objects. I understand (for the most part) Q objects but I'm not understanding how the author specifically is doing this example: # string representation of our queries >>> predicates = [('question__contains', 'dinner'), ('question__contains', 'meal')] # create the list of Q objects and run the queries as above.. >>> q_list = [Q(x) for x in predicates] >>> Poll.objects.filter(reduce(operator.or_, q_list)) [<Poll: what shall I make for dinner>, <Poll: what is your favourite meal?>] What I specifically don't get is the list comprehension. A Q object is formatted with arbitrary keywords arguments as such Q(question__contains='dinner'). If doing it like the author suggests with the list comprehension, won't that effectively just place a tuple inside a Q object on each iteration? Like such: Q(('question__contains', 'dinner')). I'm not sure how this code produces a correctly formatted Q object. -
Django redirect to form page and submit the form?
Right now. I have a search function in my page to search for item id. When I click search, I will render the same page with the result items and show item. And in other pages where I also display the item id, I want to add a link to the id to go to the same page where I search for that id. Example: id: 123, I want the same page when: 1. search '123' in my search page(my search only accept exact match) 2. In other pages, click '123', go to the search page with results How should I achieve this, I have tried many ways which don't wok. -
Django: Request timeout for long-running script
I have a webpage made in Django that feeds data from a form to a script that takes quite a long time to run (1-5 minutes) and then returns a detailview with the results of that scripts. I have problem with getting a request timeout. Is there a way to increase time length before a timeout so that the script can finish? -
Django CreateView - How to show a related field (FK) like integer instead of select?
Hi (sorry for my bad english), i'm trying to show a form using a number input instead a select in a FK Relation on django model, but i cant make it. The thing is that i need to fill the ID of the product manually writing the id in a input box, but django automatically makes the select form with all the products! this is what i have in forms.py class PurchaseForm(forms.ModelForm): class Meta: model = Purchase fields = [ 'date', 'supplier', 'warehouse', ] widgets = { 'date': forms.DateInput(attrs={ 'type': 'date', }), } class PurchaseItemForm(forms.ModelForm): class Meta: model = PurchaseItem fields = [ 'product', 'quantity', 'net_purchase_price', 'sell_price', ] widgets = { 'product': forms.NumberInput(), } PurchaseFormSet = inlineformset_factory( Purchase, PurchaseItem, fields='__all__', extra = 10, ) this is my view class PruchaseCreateView(CreateView): template_name = 'purchases/create_purchase.html' form_class = PurchaseForm def get_context_data(self, **kwargs): context = super(PruchaseCreateView, self).get_context_data(**kwargs) if self.request.POST: context['formset'] = PurchaseFormSet(self.request.POST) else: context['formset'] = PurchaseFormSet() return context def form_valid(self, form): context = self.get_context_data() formset = context['formset'] if formset.is_valid(): self.object = form.save() formset.instance = self.object formset.save() return redirect(self.object.get_absolute_url()) else: return self.render_to_response(self.get_context_data(form=form)) i try with the widget NumberInput but nothing!!! any idea? -
Managing django urls
I am making a personal site. I have a blog page(site.com/blog), where I have a list of my blog posts. If I want to check a blog post simple enough I can click it and the code: <a href="/blog/{{ obj.id }}"><h1>{{ obj.topic_title }}</h1></a> will get me there. Also if I want to go to my contacts page (site.com/contacts). Easy enough I click nav contacs button and I go there <a href="/contacts">Contacts</a> but if I enter a blog post (site.com/blog/1), I am using the same template and if I want to go to my contacts page I have to yet again click the <a href="/contacts">Contacts</a> link, but that will port me to a 404 page site.com/blog/contacts . How do I deal with this problem without harcoding every single page -
Why does `get_or_create` execute expression from defaults when object is found?
lang_group = 'en' for place_category in place['categories']: translation, created = \ PlaceTypesTranslations.objects.get_or_create( name=place_category, lang_group=lang_group, defaults={'place_type_group': PlaceTypesGroups.objects.create()}) In this case if the loop has 1000 iterations and, for example, 500 times created=True and other 500 times created=False, anyway will be created 1000 PlaceTypesGroups, so for some reason even if get_or_create returns get, defaults anyway is executed. The same algorithm, but different approach: lang_group = 'en' for place_category in place['categories']: if PlaceTypesTranslations.objects.filter(name=place_category, lang_group=lang_group).exists(): place_cat_trans = PlaceTypesTranslations.objects.get(name=place_category, lang_group=lang_group) place_group = place_cat_trans.place_type_group else: place_group = PlaceTypesGroups.objects.create() place_cat_trans = PlaceTypesTranslations.objects.create(name=place_category, lang_group=lang_group, place_type_group=place_group) In this case just 500 times will be created PlaceTypesGroups. Why is that? What I do not see? -
Django Rest Framework: How to include linked resources in serializer response?
If write my own implementation of a ViewSet, and I want to return some objects, it's pretty simple: class MyViewSet(ViewSet): def my_method(self, request): objects = MyModel.objects.all() return Response( MyModelSerializer(objects, many=True).data ) But let's say that I want to include the actual instance of another linked resource by a ForeignKey, instead of just an ID. For example: class MyModel(Model): author = ForeignKey(MyOtherModel) ... Is there a way to do something like this? ... return Response( MyModelSerializer(objects, many=True, include='author').data ) -
Using django-ratelimit with form to show captcha
I want to use django ratelimit to show if POST method was used too many times earlier even if use GET for next time. I want to show CAPTCHA in my form if someone send it more than 5 times in hour and then load a form again. Example view @ratelimit(key='ip', rate='5/h', method=ratelimit.UNSAFE) def get_name(request): if request.method == 'POST': was_limited = getattr(request, 'limited', False) else: form = NameForm() was_limited = getattr(request, 'limited', False) When user send POST data at next time was_limited will be True, but when he just load form again (using get) after this was_limited will be False so i dont know when i should show CAPTCHA to user. -
Automatically running app .py in in Heroku
I have created a bot for my website and I currently host in on heroku.com. I run it by executing the command heroku run --app cghelper python bot.py This executes the command perfectly through CMD and runs that specific .py file in my github repo. The issue is when I close the cmd window this stops the bot.py. How can I get the to run automatically. Thanks -
Access parent id in Django Rest Framework when serializing
I have this models: "Static models" class vehicleModel(models.Model): name = models.CharField(max_length=50) class acControlModule(models.Model): controlName= models.CharField(max_length=50) class airConditioning(models.Model): acModel = models.CharField(max_length=50) vehicleModel = models.OneToOneField(vehicleModel) acControlModule = models.ForeignKey(acControlModule) "Dynamic models" class actualVehicle(models.Model): licensePlate = models.CharField(max_length=50) model = models.ForeignKey(vehicleModel) class acStatus(models.Model): currentTemp= models.CharField(max_length=50) vehicle = models.ForeignKey(actualVehicle) ac = models.ForeignKey(airConditioning) It is not the best example, but imagine a car can have 0 to N air conditioning modules. No I want to serialize the actual temperature into the global representation of a vehicle as follows: { "licensePlate": "0000AAAA", "model": { "name": "Ford focus", "ac": [ { "acModel": "12AB37", "controlName" : "bizone touch display", "acStatus": { "currentTemp": "78" } } ] } } The problem is, that I can't filter by the "actualVehicle id" when generating the serialization of the acStatus model, so instead of the above I get: { "licensePlate": "0000AAAA", "model": { "name": "Ford focus", "ac": [ { "acModel": "12AB37", "controlName" : "bizone touch display", "acStatus": [ { "currentTemp": "78" }, { "currentTemp": "89" }, { "currentTemp": "110" } ] } ] } } That is, all the acStatus with the foreignKey matching the one in the "extra" field, independently of the "vehicle" field. -
how to populate static database tables in django
I am trying to learn Django and so far I have been able to create models and be able to inject data into the database using views and have a small web app working nicely. I have a small confusion regarding how Django works with tables that will need to be populated outside the application. For example, I should have a table called Products. Now the products change extremely infrequently and moreover there are some products that the database should already be populated with. For example, my product model could be simple as: class ProductModel(models.Model): name = models.CharField(max_length=200) What is the Django-nic way to pre-populate this table with a set of products already? -
unable to runserver in django 1.10.1 due to database connection
I am using PostGRE sql in my localhost in Django 1.10.1 and have installed all dependencies, psycopg2, postgresql, pgadmin3 and have set the password of postgresql via command line. I've used exactly the same password in settings.py of the django project. Still I am being shown the authentication error. I am using pyvenv virtual environment with python 3.5.2 Please check the error code below: Traceback (most recent call last): File "/home/jayesh/django/myproject/lib/python3.5/site-packages/django/db/backends/base/base.py", line 199, in ensure_connection self.connect() File "/home/jayesh/django/myproject/lib/python3.5/site-packages/django/db/backends/base/base.py", line 171, in connect self.connection = self.get_new_connection(conn_params) File "/home/jayesh/django/myproject/lib/python3.5/site-packages/django/db/backends/postgresql/base.py", line 176, in get_new_connection connection = Database.connect(**conn_params) File "/home/jayesh/django/myproject/lib/python3.5/site-packages/psycopg2/init.py", line 164, in connect conn = _connect(dsn, connection_factory=connection_factory, async=async) psycopg2.OperationalError: FATAL: password authentication failed for user "postgresql" FATAL: password authentication failed for user "postgresql" The settings.py contains the following reg DB: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'myproject', 'USER': 'postgresql', 'PASSWORD': 'mypassword', 'HOST': '127.0.0.1', 'PORT': '5432', } } Please guide regarding the above issue. I've already followed the following links: Django setting : psycopg2.OperationalError: FATAL: Peer authentication failed for user "indivo" ImportError: No module named psycopg2 How connect Postgres to localhost server using pgAdmin on Ubuntu? -
nginx: [warn] conflicting server name "example.com" on 0.0.0.0:80, ignored
When I'm trying to restart nginx, I'm getting the following error nginx: [warn] conflicting server name "example.io" on 0.0.0.0:80, ignored I used my deploy scripts, to do deploying for 2 domains. For first it works fine, but for second, it gives error. Can anybody help me to solve this? Thanks! -
How to store images, music, video and etc with aiohttp?
how to store files like images and video with aiohttp. In django i can make it like these: image = ImageField(upload_to='/images') Save them as binary files in the base - is not an option, I need to work with files on the server side after saving -
How to get spcific child page in django cms with {% show_menu_below_id %}?
My DjangoCMS has the structure: --Page a ----Page a.1 ----Page a.2 ----Page a.3 ----Page a.4 Using {% show_menu_below_id "Page a"%} shows this: <ul> <li> Page a.1</li> <li> Page a.2</li> <li> Page a.3</li> <li> Page a.4</li> </ul> I need to show then in the navegation menu in two separeted columns, like: <ul> <li> Page a.1</li> <li> Page a.2</li> </ul> <ul> <li> Page a.3</li> <li> Page a.4</li> </ul> How do I get just some of the childs page? -
Graphene/Django (GraphQL): Create a query argument that excludes edges matching a specific filter
I have some video items in a Django/Graphene backend seteup. Each video item is linked to one owner. In a React app, I would like to query via GraphQL all the videos owned by the current user on the one hand and all the videos NOT owned by the current user on the other hand. I could run the following GraphQl query and filter on the client side: query AllScenes { allScenes { edges { node { id, name, owner { name } } } } } I would rather have two queries with filters parameters directly asking relevant data to my backend. Something like: query AllScenes($ownerName : String!, $exclude: Boolean!) { allScenes(owner__name: $ownerName, exclude: $exclude) { edges { node { id, name, owner { name } } } } } I would query with ownerName = currentUserName and exclude = True/False yet I just cannot retrieve my exclude argument on my backend side. Here is the code I have tried in my schema.py file: from project.scene_manager.models import Scene from graphene import ObjectType, relay, Int, String, Field, Boolean, Float from graphene.contrib.django.filter import DjangoFilterConnectionField from graphene.contrib.django.types import DjangoNode from django_filters import FilterSet, CharFilter class SceneNode(DjangoNode): class Meta: model = Scene class … -
error to execute djangocms -f -p . mysite
I have a problem when I execute djangocms -f -p . mysite the process started but fail when it have to create an admin user. Creating admin user /Users/ccsguest/Site/djangoProject/django1101/bin/python2.7: can't open file 'create_user.py': [Errno 2] No such file or directory The installation has failed. Traceback (most recent call last): File "/Users/ccsguest/Site/djangoProject/django1101/bin/djangocms", line 11, in <module> sys.exit(execute()) File "/Users/ccsguest/Site/djangoProject/django1101/lib/python2.7/site-packages/djangocms_installer/main.py", line 41, in execute django.setup_database(config_data) File "/Users/ccsguest/Site/djangoProject/django1101/lib/python2.7/site-packages/djangocms_installer/django/__init__.py", line 394, in setup_database create_user(config_data) File "/Users/ccsguest/Site/djangoProject/django1101/lib/python2.7/site-packages/djangocms_installer/django/__init__.py", line 411, in create_user subprocess.check_call([sys.executable, 'create_user.py'], env=env) File "/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 541, in check_call raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command '['/Users/ccsguest/Site/djangoProject/django1101/bin/python2.7', u'create_user.py']' returned non-zero exit status 2 The process created the folder with the project and inside I have all the normally files and folder but there is a file call create_user.py, and when I run the server I see the page for login but I never define user and password My environment has this configuration cmsplugin-filer==1.1.3 dj-database-url==0.4.1 Django==1.8.15 django-appconf==1.0.2 django-classy-tags==0.8.0 django-cms==3.4.0 django-filer==1.2.5 django-formtools==1.0 django-mptt==0.8.6 django-polymorphic==0.8.1 django-sekizai==0.10.0 Django-Select2==4.3.2 django-treebeard==4.0.1 djangocms-admin-style==1.2.4 djangocms-attributes-field==0.1.1 djangocms-column==1.7.0 djangocms-googlemap==0.5.2 djangocms-installer==0.9 djangocms-link==2.0.1 djangocms-snippet==1.9.1 djangocms-style==1.7.0 djangocms-text-ckeditor==3.2.1 djangocms-video==2.0.2 easy-thumbnails==2.3 html5lib==0.9999999 Pillow==3.3.1 pytz==2016.6.1 six==1.10.0 South==1.0.2 tzlocal==1.2.2 Unidecode==0.4.19 any idea how to fix the problem! Thank in advance -
i want to save a nested model django rest framework
I'm a beginner to the Django Rest Frame work. I want to create a custom user but I have a problem from a long period i try to find a solution through many forums but unfortunately i didn't succeed. hope you help me models.py class Produit (models.Model): titre=models.CharField(max_length=100) description=models.TextField() photo_principal=models.ImageField(upload_to='produits/',default='image.jpg') photo_1 = models.ImageField(upload_to='produits/', default='image.jpg') photo_2 = models.ImageField(upload_to='produits/', default='image.jpg') photo_3 = models.ImageField(upload_to='produits/', default='image.jpg') prix=models.FloatField() new_prix=models.FloatField() categorie=models.ForeignKey(Categorie,related_name= 'produit', on_delete=models.CASCADE) serializers.py class ProduitCreateSerializer(serializers.ModelSerializer): categorie = CategorieListSerializer(many=True) class Meta: model=Produit fields=['titre','description','photo_principal','photo_1','photo_2','photo_3','prix','new_prix','categorie',] there is two problem the first one is the browser did not show me the list of the categories to choose when i want to create a new product please can you give me an example of create and update serializers for a models which contains a foreign key -
How to handle response data from success ajax function (DJANGO)
So i am having this view.py file : def home(request): return render_to_response('proj1/index.html', RequestContext(request, {'variable': 'world'})) And i desire to display "hello world" with the following ajax function in my index.html $.ajax({ url: '127.0.0.1:8000', type: "GET", dataType:'html', success: function(data){ <h1>Hello {{ data.variable }} , welcome to my AJAX WebSite</h1> }); Any help ? -
Django signal received not being called
I've used Django signals in the past. I'm working on a 1.10 app now, and for some reason I cannot get my receiver to be called. app1/signals.py from django.dispatch import Signal list_member_updated = Signal(providing_args=['list_member_id',]) app1/models.py print('Dispatching signal...') list_member_updated.send(self.__class__, list_member_id=list_member.id) app1/apps.py class DjangoApp1Config(AppConfig): name = 'app1' def ready(self): import app1.signals app2/util.py from django.dispatch import receiver from app1.signals import list_member_updated @receiver(list_member_updated) def handle_member_updated(sender, **kwargs): print('Received signal') So I get the "Signal dispatched..." in the console, but not the "Received signal". I have a feeling I'm missing something simple, but I just cannot see it. -
How to make my azure django project https?
I have my website in Azure named djangoproj.azurewebsites.net When I request homepage it goes to http://djangoproj.azurewebsites.net. I know all projects in azure are SSL protected and when i type https://djangoproj.azurewebsites.net, it works fine ! I can access the site via https. But how do i make it to default https in azure? because when i call the homepage, it gives http response by default until i forcibly specify https. How do i make default https in azurewebsite ? -
how to send notification to android app using FCM from a django server?
I am a beginner trying to handle the server side from django for my android application. I need to send notification to the user on android and I want to use FireBase. But I am unable to find how to do it. If someone can point me the right direction it will be very helpful. I also encountered, a kind of, predefined library PyFCM. (https://github.com/olucurious/PyFCM). But I cannot understand how to trigger it. Will writing these codes in views and then calling it through a request do the work for me? -
Local Django server cannot connect when run through Bash on Windows
I recently realized that I could use Bash for Windows as the terminal for use in Pycharm so that the IDE had a proper terminal in it even through it was in Windows. I want to work on a Django project but I realized something strange. When I run the server through the IDE's run button, everything runs as expected. However, when I try to run the server through the command line via python3 manage.py runserver, the terminal output is the same, but my browsers cannot connect. Instead they say that the connection was reset. I have full installations of Django and Python for both Windows and the Bash environment and both seem to be fully functional. I can make migrations and create new apps through the command line just fine, but I was wondering if anybody else knew why the Django Server does not connect when run through Bash on Windows -
Django userena check if mugshot is set
Ok so this is the models.py of userena. Can i check using template tags in html if mugshot is set? The first if statement checks if the mugshot is uploaded. def get_mugshot_url(self): """ Returns the image containing the mugshot for the user. The mugshot can be a uploaded image or a Gravatar. Gravatar functionality will only be used when ``USERENA_MUGSHOT_GRAVATAR`` is set to ``True``. :return: ``None`` when Gravatar is not used and no default image is supplied by ``USERENA_MUGSHOT_DEFAULT``. """ # First check for a mugshot and if any return that. if self.mugshot: return self.mugshot.url # Use Gravatar if the user wants to. if userena_settings.USERENA_MUGSHOT_GRAVATAR: return get_gravatar(self.user.email, userena_settings.USERENA_MUGSHOT_SIZE, userena_settings.USERENA_MUGSHOT_DEFAULT) # Gravatar not used, check for a default image. else: if userena_settings.USERENA_MUGSHOT_DEFAULT not in ['404', 'mm', 'identicon', 'monsterid', 'wavatar']: return userena_settings.USERENA_MUGSHOT_DEFAULT else: return None -
Aws not detect urls.py file in django?
I made changes in a urls.py in my application but AWS EC2 showing page not found error , I restarted server several time but still I get same result . I am using Nginx + gunicorn + MySQL + Django on AWS . urls.py from django.conf.urls import url from django.contrib import admin from django.conf.urls.static import static import settings from collapp.views import get_branch, get_college, get_course, get_university, get_department, signup, login, \ email_exist, forget_password, change_password, username_exist, get_newsfeed urlpatterns = [ # admin site url(r'^admin/', admin.site.urls), # get all university url(r'^universities/', get_university), # get all colleges with university slug url(r'^(?P<university_slug>[\w-]+)/college/$', get_college), # get all courses url(r'^courses/$', get_course), # get all branch url(r'^(?P<course_slug>[\w-]+)/branches/$', get_branch), # get all departments url(r'^departments/$', get_department), # student-teacher-society signup data url(r'^signup/$', signup), # check email id exist or not url(r'^exist/email/(?P<email_id>[\w.%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})/$', email_exist), # check username exist or not url(r'^exist/username/(?P<username>[\w\W]+)/$', username_exist), # check user email exist url(r'^login/email/(?P<email_id>[\w.%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})/password/(?P<password>[\w\W]+)/$', login), # forgot password url(r'^forgot/email/(?P<email_id>[\w.%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})/$', forget_password), # change password url(r'^change/password/(?P<email_id>[\w.%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})/$', change_password), # get all news feed url(r'^newsfeed/$', get_newsfeed) ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Helpful suggestion will be appreciated .