Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Copying permissions for groups django
I want to copy group permissions from one place to another. This is my code: from django.db.models import Q from django.contrib.auth.models import Permission, User, Group user_ids = Permission.objects.filter(codename='bags').values_list('user', flat=True) groups = Permission.objects.filter(codename='bags').values_list('group', flat=True) new = Permission.objects.get(codename='bags_new') for user in User.objects.filter(~Q(user_permissions__in=[new]), id__in=user_ids): user.user_permissions.add(new) Till here it is working fine. My problem is when i try to copy for groups its not working. I have tried the following: for group1 in Group.objects.filter(~Q(groups_permissions__in=[new]), id__in=groups): group1.group.permissions.add(new) Any suggestions? -
django-rest-framework there is no autogenerated form in the BrowsableAPi while using viewsets and routes?
Kindly assist on this. I cant seem to get the HTML form in the browsable API for django rest. I figured its coz its no the default behaviour while using genericViews. But while using Viewsets the HTML form on the BrowsableApi is not available.What would be problem? How do i include the HTML form into the Browsable Api? -
Set a cookie (django) and get its value
I need to set a cookie on multiple domains (cross-domaine cookie). In order to do that, I've done a django server which creates the cookie. I then need to "read" the cookie from other domains where I call this django cookies server. If I call it through an img, the cookie is well set. But with the image, I can't access the cookie. I've tried with a javascript script, for example : function httpGet(theUrl) { var xmlHttp = new XMLHttpRequest(); xmlHttp.open( "GET", theUrl, false );request xmlHttp.send( null ); return xmlHttp.responseText; } But each time I call this fonction, a new value is given for the cookie (it does not put the cookie on my browser). Is there a way to achieve what I want ? To get this cookie value with a javascript request ? Thanks, -
Does creating atomic transaction in django create a lock automatically
I have a code block within transaction.atomic() within a view. My question is does django create some inbuilt table locking behind the scenes. with transaction.atomic(): #code block that does database operations update_user() #this updates user table create_customer_products() #this updates user id to customer products table The reason is I get a "Lock wait timeout exceeded; try restarting transaction" error when I run the code block. The setup is django mysql on centos -
DRF serializer filtering
I have a serializer that gives me everything fine. ModelClassASerializer((serializers.ModelSerializer)): ..... status = serializers.SerializerMethodField() def get_status(self, obj): .... status = ModelB.objects.get(id=obj.id).status .... return status class Meta: model = ModelClassA fields = (...) But if I want to make a filtering based on that status, I can't. I am using django_filters.rest_framework.FilterSet for the filtering. What is the best way to do that? -
Django JQuery Autocomplete
I am trying to add an autocomplete field to my form. But I can't get t to work. I have tried almost every tutorial. The request is sent out fine,I'm gettin a 200 response. In the developer tools pane when I click the request ,on the Response tab I see the whole HTML file. Shouldn't there be a json formated something..?? Here's the code: models.py class Signers(models.Model): uid = models.IntegerField(primary_key=True) firstName = models.CharField(max_length=255) lastName = models.CharField(max_length=255) views.py def get_signers(request): if request.is_ajax(): q = request.GET.get('term', '') signers = Signers.objects.filter(uid__icontains=q)[:20] results = [] for s in signers: signer_json = {} signer_json['id'] = s.uid signer_json['label'] = s.uid signer_json['value'] = s.uid results.append(signer_json) data = json.dumps(results) print data else: data = 'fail' mimetype = 'application/json' return HttpResponse(data,mimetype) urls.py url(r'^get_signers/', views.get_signers, name='get_signers'), praxis.html (my template) <script> $(function() { $("#id_signerIds").autocomplete({ source: "get_signers/", minLength: 2, }); }); </script> <script> $(document).ready(function() { $('#id_submissionTimestamp').hide(); $('#id_issueDate').hide(); }); </script> {% endblock page_head %} {% block content %} <form method="POST" class="post-form">{% csrf_token %} <!--some other fields here... --> <div class="ui-widget"> <label for="id_signerIds">Signers: </label> <input id="id_signerIds"> </div> <button type="submit" class="save btn btn-default">Save</button> </form> {% endblock %} -
Django newbie and tutorial
I'm a complete Django newbie and I am following the tutorial: https://docs.djangoproject.com/en/1.11/intro/tutorial01/ I have got to the stage: from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^polls/', include('polls.urls')), url(r'^admin/', admin.site.urls), ] in mysite/urls.py, but when I do: python manage.py runserver I get a 404 error in the browser at the address http://localhost:8000/polls/ I am using python 2.7.6 and Django 1.11.5 Can someone please point out what might be wrong? -
Only allow django admin on site id 1
I want to only show the admin for my site with id 1. In other views I've defined this in the dispatch, but I haven't found a way to do this for the admin. I tried making a custom admin class, but I didn't see a way to do this either. Is there a way to define dispatch for admin, or limiting the sites where an admin shows? The dispatch I'm using: def dispatch(self, *args, **kwargs): try: if get_current_site(self.request).pk != settings.MY_SITE_ID: response = render(self.request, 'my_app/404.html') response.status_code = 404 return response except Site.DoesNotExist: response = render(self.request, 'my_app/404.html', {'site_doesnotexist': True}) response.status_code = 404 return response return super(MyView, self).dispatch(*args, **kwargs) -
How to use collections in Django Template
I have such collection: data[1]['Monday'] = 2 data[1]['Tuesday'] = 2 data[2]['Monday'] = 5 data[2]['Tuesday'] = 7 And would like to use it in django template. When I did: {{ data}} Everything is displaying correct. But if I try e.g.: {{ data.1 }} Then I see empty collection. Does anyone know why ? Thanks in advance, -
Modification in serializer.data format before returning jsonresponse
I am getting- [ { "id": 2, "url": "https://emiactech.com/", "title": "", "blog_post": 0, "index_count": 0, "external_urls": "[{'url': '#', 'page': 'https://emiactech.com/', 'title': u''}, {'url': 'https://www.facebook.com/EMIACTechnologies/', 'page': 'https://emiactech.com/', 'title': u'Facebook'}, {'url': 'https://twitter.com/emiactech', 'page': 'https://emiactech.com/', 'title': u'Twitter'}, {'url': 'mailto:sales@emiactech.com', 'page': 'https://emiactech.com/', 'title': u'sales@emiactech.com'}, {'url': 'http://themeforest.net/item/avada-responsive-multipurpose-theme/2833226?ref=ThemeFusion', 'page': 'https://emiactech.com/about-us/', 'title': u''}, {'url': '#tab-bdf4143f2c7b5609720', 'page': 'https://emiactech.com/services/', 'title': u'Web Design and Development'}, {'url': '#tab-70d2572b15f9a5ac477', 'page': 'https://emiactech.com/services/', 'title': u'Content Development'}, {'url': '#tab-c59a00bf26295e6ed39', 'page': 'https://emiactech.com/services/', 'title': u'Digital Marketing'}, {'url': 'https://emiactech.com', 'page': 'https://emiactech.com/cqpim-client/', 'title': u'Home'}, {'url': 'http://themetf.com', 'page': 'https://emiactech.com/portfolio-items/humsafar-love/', 'title': u' theme-tf'}, {'url': 'http://shades.salon', 'page': 'https://emiactech.com/portfolio_category/jquery/', 'title': u'http://shades.salon'}, {'url': 'http://Project%20URL', 'page': 'https://emiactech.com/portfolio_category/jquery/', 'title': u' View Project '}, {'url': 'http://samacharjagat.com', 'page': 'https://emiactech.com/portfolio_category/jquery/', 'title': u'http://samacharjagat.com'}]", "external_count": 13 }] in serializer.data . external_urls key data is the type of string. I need this key data either in the form of list or dictionary something like this; [{'url': '#', 'page': 'https://emiactech.com/', 'title': u''}, {'url': 'https://www.facebook.com/EMIACTechnologies/', 'page': 'https://emiactech.com/', 'title': u'Facebook'}, {'url': 'https://twitter.com/emiactech', 'page': 'https://emiactech.com/', 'title': u'Twitter'}, {'url': 'mailto:sales@emiactech.com', 'page': 'https://emiactech.com/', 'title': u'sales@emiactech.com'}, {'url': 'http://themeforest.net/item/avada-responsive-multipurpose-theme/2833226?ref=ThemeFusion', 'page': 'https://emiactech.com/about-us/', 'title': u''}, {'url': '#tab-bdf4143f2c7b5609720', 'page': 'https://emiactech.com/services/', 'title': u'Web Design and Development'}, {'url': '#tab-70d2572b15f9a5ac477', 'page': 'https://emiactech.com/services/', 'title': u'Content Development'}, {'url': '#tab-c59a00bf26295e6ed39', 'page': 'https://emiactech.com/services/', 'title': u'Digital Marketing'}, {'url': 'https://emiactech.com', 'page': 'https://emiactech.com/cqpim-client/', 'title': u'Home'}, {'url': 'http://themetf.com', 'page': 'https://emiactech.com/portfolio-items/humsafar-love/', 'title': u' theme-tf'}, {'url': … -
How to build non-linear throttling for authentication APIs in Django rest framework ?
DRF offers in-built throttling system where we can define rate limit. But how can we make it more secure by exponentially increasing the time limit of an API? Ie, if you make more than 10 calls/min to login API next min should allow only 5 API calls and so on. Time between subsequent API calls should increase exponentially until it hits a predefined threshold after which user should be blocked permanently. -
Django file sharing between users
I am creating file sharing app. i have multiple user. plz find below my forms.py from django import forms from django.contrib.auth.models import User from Box.models import user_files class Loginform(forms.Form): username=forms.CharField(max_length=50) password=forms.CharField(widget=forms.PasswordInput) class UserRegistration(forms.ModelForm): password = forms.CharField(label='Password',widget=forms.PasswordInput) password2 = forms.CharField(label='Repeat Password',widget=forms.PasswordInput) class Meta: model=User fields= ('username','first_name','email') def clean_password2(self): cd=self.cleaned_data if cd['password']!=cd['password2']: raise forms.ValidationError('Passwords do not match') return cd['password2'] class Fileupload(forms.ModelForm): class Meta: model= user_files fields = ('Filename','Browse') and my model.py from django.db import models class user_files(models.Model): Filename = models.CharField(max_length=50) Browse = models.FileField() i have used django in built user model to store user data and model user_files for storing files. So now how can i distinguish which file is uploaded by which user? and how can i share among other user? i am stuck at this point. Thanks in advance -
How to add css class to Django admin form
I was wondering if it's possible to add a css class to the Django admin form? For example: @admin.register(SomeFunction) class SomeFunctionAdmin(SortableAdmin): fieldsets = ( (None, { 'fields': ('item1', 'item2', 'item3'), }), ) def get_form(self, request, obj=None, **kwargs): form = super(SomeFunctionAdmin, self).get_form(request, obj, **kwargs) return form class Media: js = ( 'custom.js', ) Now I want to add a css class to SomeFunctionAdmin, let's say I want to add .custom-form-admin class. And in my custom.js file I have some functions which search for this custom css class. How do I add the custom css class programatically to SomeFunctionAdmin? I imagne the code would look something like this: @admin.register(SomeFunction) class SomeFunctionAdmin(SortableAdmin): fieldsets = ( (None, { 'fields': ('item1', 'item2', 'item3'), }), ) def get_form(self, request, obj=None, **kwargs): form = super(SomeFunctionAdmin, self).get_form(request, obj, **kwargs) form.set_css += 'custom-form-admin' return form class Media: js = ( 'custom.js', ) -
Accessing the twitter tweets in Django application creating issues
For integrating my application with tweeter to access the tweets, I have followed this blog: https://simpleisbetterthancomplex.com/tutorial/2016/10/24/how-to-add-social-login-to-django.html I think I have integrated the application but here the error that I am getting: AuthForbidden at /oauth/complete/twitter/ Your credentials aren't allowed Request Method: GET Request URL: http://52.66.181.149:2000/oauth/complete/twitter/?redirect_state=26j2fjzqwJPBVlhv0bZBvlAjLTzp0uJl&oauth_token=krMPogAAAAAA2fYTAAABXut57Og&oauth_verifier=Tbg7RQbbZFLFzWShi19izoQSHLePYSPS Django Version: 1.11.5 Exception Type: AuthForbidden Exception Value: Your credentials aren't allowed Exception Location: /usr/local/lib/python2.7/dist-packages/social_core/utils.py in wrapper, line 257 Python Executable: /usr/bin/python Python Version: 2.7.12 Python Path: ['/home/ubuntu/Personality', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages'] Server time: My time The complete trace back is here : Trace Back Gist Also, I would like to know the following 2 things: 1) What is missing which is causing this issue? 2) What I can do to collect the tweets with django and use it as NLP data set? Kindly, let me know. -
How to run django localhost on another system in same private network
I am using django for my project. Now I want to access my project. Both my system and the another one are in the same private network. I am using VPN to connect to the network. How can I access http://localhost:8000 from another system? What all I did: ALLOWED_HOSTS = ['*'] DEBUG = False python manage.py runserver 0.0.0.0:8000 Using my IP (say 192.168.x.y) from another system to access the page, but no use - I still couldn't access the page. (I can access the page http://192.168.x.y:8000/home from the browser of the same system though) My main motive is to launch the application and to be able to use it from a system - both server and client machine are in same private network connected either by VPN or LAN -
How to design subscription plan(stripe) based permissions in Django rest framework?
I'm building a SaaS product where subscription happens with the integration of Stripe. I have multiple subscription plans and certain APIs are restricted to advanced/premium plans only. How do I build API permissions so that it works well with dynamic plans? Plans can be added or deleted at Stripe's dashboard which gets synced with my backend models. Is there a way to associate certain endpoints to a plan using admin panel without modifying the codebase? -
django sending mail [Errno -2] Name or service not known
i'm using django-registration in my project to sending email when user forgot password. But i got the error [Errno -2] Name or service not known. Below are my settings and traceback.. EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'my@gmail.com' EMAIL_HOST_PASSWORD = 'mypassword' EMAIL_PORT = 587 gaierror at /accounts/password_reset/ [Errno -2] Name or service not known Request Method: POST Request URL: http://localhost:8000/accounts/password_reset/ Django Version: 1.10.5 Exception Type: gaierror Exception Value: [Errno -2] Name or service not known Exception Location: /usr/lib/python2.7/socket.py in create_connection, line 553 Python Executable: /usr/bin/python Python Version: 2.7.6 Python Path: ['/vagrant/ifoswork/ifoswork', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages'] Server time: Thu, 5 Oct 2017 14:38:34 +0800 -
Price model in Django
How can I create a pricing model in Django? Is there any package like django-prices or django-moneyfield? I want to create a model in such a way that user can select the items and price keeps updating as he starts adding the items. For me to have this model, I wanted the price update to happen on the same page as the user adds item so that he can see the changes. Since I am new to Django, I am not sure what model will work for me. Or do I need to manually prepare the code base for estimates? Has anyone worked on such requirement before? -
how i get request objects in django singnals
i used "pre_save" django signal for creating some activity log object in models.py but in my activity log models have created_by and updated_by fields so i want to access user object in that particular django signals @receiver(pre_save, sender=ProjectSow) def change_order_updated(sender, **kwargs): instance = kwargs.get('instance') component_id = instance.pk log = ActivityLog.objects.create(component_id=component_id, component="change_oreder",log="project created_created") so how we do that i also try with created one custom context processor also but it not work -
Where is Django base.html file? Add additional static style sheet
I would like copy & use the admin/base.html file in my templates/accounts folder. So I can hopefully include one additional custom style sheet in the head. I have used the: python -c "import django; print(django.__path__)" previously to locate & copy the user admin forms. When I follow the path generated from the line above I now get a path to .py files rather than .html files. Does anyone have a copy of the base.html file? Or can suggest the cleanest way to include one additional style sheet? This is what I am trying to avoid if possible. base_site.html {% extends "admin/base.html" %} {% block title %}{{ title }} | {{ site_title|default:_('MY SITE') }}{% endblock %} <!--CAN THIS BE ADDED TO THE HEAD OF base.html--> {% block body_head %} <link href="{% static 'css/custom.css' %}" rel="stylesheet"> {% endblock body_head %} {% block branding %} <h1 id="site-name"><a href="{% url 'admin:index' %}">MY SITE</a></h1> {% endblock %} {% block nav-global %}{% endblock %} -
Django & Python AttributeError: 'Retailer' object has no attribute
In my test file: class TestMakeSoup(TestCase): fixtures = ['deals_test_data.json'] def test_string_is_valid(self): s = Retailer.objects.get(pk=1) with open('/home/danny/PycharmProjects/askarby/deals/tests/BestBuyTest.html', 'r') as myfile: text = myfile.read().replace('\n', '') self.assertTrue(s.make_soup(text)) In the file it's testing: class retailer(): ''' Retail site, drawn from database queryset object ''' def __init__(self,r_object): ''' Initializes retailer variables obj -> nonetype Precondition: r_object.currency == 3 Precondition: r_object.name != None ''' assert len(r_object.currency) == 3, "{} must be a three-letter string (eg 'USD').".format(r_object.currency) assert r_object.name != None, "Name must exist." assert r_object.deal_container_css != None, "Title css must exist." assert r_object.title_css != None, "Title css must exist." assert r_object.price_css != None, "Price css must exist." self.name = r_object.name self.base_url = r_object.base_url self.currency = r_object.currency #dict containing css lookup values for various fields self.css = {} self.css['container'] = self.extract_css(r_object.deal_container_css) self.css['title'] = self.extract_css(r_object.title_css) self.css['product_model'] = self.extract_css(r_object.product_model_css) self.css['price'] = self.extract_css(r_object.price_css) self.css['old_price'] = self.extract_css(r_object.old_price_css) self.css['brand'] = self.extract_css(r_object.brand_css) self.css['image'] = self.extract_css(r_object.image_css) self.css['description'] = self.extract_css(r_object.description_css) self.css['exclude'] = self.extract_css(r_object.exclude_css) self.css['shipping'] = self.extract_css(r_object.shipping_css) #dict containing associated clearance urls for retailer self.clearance_urls = self.get_clearance_urls() #dict to house final list of deals self.deals = {} def __str__(self): return self.name def make_soup(self, text): assert isinstance(text,str), "text must be string." soup = bs4.BeautifulSoup(text, "html.parser") if soup: return soup return False The Retailer call refers to the … -
AttributeError: 'CustomUser' object has no attribute 'first_name'
what this error means ? AttributeError: 'CustomUser' object has no attribute 'first_name' custom_user/models.py from time import timezone from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.core.mail import send_mail from django.utils.translation import ugettext_lazy as _ from datetime import datetime now = datetime.now() class CustomUserManager(BaseUserManager): def _create_user(self, email, password, is_staff, is_superuser, **extra_fields): """ Creates and saves a User with the given email and password. """ if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, is_staff=is_staff, is_active=True, is_superuser=is_superuser, last_login=now, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): return self._create_user(email, password, False, False, **extra_fields) def create_superuser(self, email, password, **extra_fields): return self._create_user(email, password, True, True, **extra_fields) class CustomUser(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=254, unique=True) email = models.EmailField(blank=True, unique=True) address1 = models.CharField(max_length=254, blank=True) address2 = models.CharField(max_length=254, blank=True) area_code = models.CharField(max_length=20, blank=True) country_code = models.CharField(max_length=10, blank=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'address1', 'address2', 'area_code', 'country_code'] objects = CustomUserManager() class Meta: verbose_name = _('user') verbose_name_plural = _('users') def get_full_name(self): """ Returns the first_name plus the last_name, with a space in between. """ full_name = '%s %s' % (self.first_name, self.last_name) return full_name.strip() def get_short_name(self): "Returns … -
How do I access the `BLOG_SUG` string?
When I type {{ setting }} on a template and open it with Mezzanine, it shows me {u'MEZZANINE_ADMIN_PREFIX': u'grappelli/'}. I'm trying to access settings.BLOG_SLUG, but cannot get that setting to appear in the template. Here's a small snip of what my template looks like. {% load mezzanine_tags keyword_tags i18n %} {% block main %} {{ settings }} {% endblock %} How do I get my template to display the string stored in setting.BLOG_SLUG? -
How to set a variable using set tag in django?
I want something like this. {% set titles = { 'table': form._meta.model._meta.verbose_name_plural.title(), 'form': form._meta.model._meta.verbose_name.title() } %} {% set dtable = "dt_" + page %} How can I get set tag? Your answer would be helpful for me. -
Django - Starting a MQTT service in INIT prevents me from loading models with "Apps aren't loaded yet." error. Where can I start it?
I'm brand new to Django and Python, and not sure how to get around this problem, but I know what's wrong and why... I'm connecting to a MQTT broker (internet of things messaging protocol / provider) so I can update a webpage with data from some sensors I have. I've started the MQTT service in my init as was suggested below, but I don't know enough to know if that's right or wrong, but it works. https://stackoverflow.com/a/41017210/2408033 My problem happens, when I want to try to update my database with the messages I receive from the MQTT broker. I need to import my model so I can update it, but the model hasn't been loaded yet, and it throws the error - "Apps aren't loaded yet." I was reading that you shouldn't attempt to import models before the Django setup has run (which is after init) so I'm not sure where / how to start the loop for the MQTT broker thread? Where else can I place the code to start the loop where it won't be triggered a second time?