Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error getting route from urls.py
I'm testing the application. It is necessary to test the method of processing requests coming to the address 'http://127.0.0.1:8000/api/v1/test/api_address/'. Tell me, please, as through reverse () the full address to the client class MyTestCase(APITestCase): def setUp(self): self.message = { 'username': 'user_name', 'password': 'user_password', } def test_get_token(self): response = self.client.post(reverse('api_address'), self.message) self.assertEqual(response.status_code, status.HTTP_201_CREATED) Code for urls.py: users_router = DefaultRouter() users_router.register(r'test', TestViewSet, 'test') users_router.register(r'test/api_address', APIAddressRequestSet, 'api_address') with the current implementation, reverse ('map address') does not work, falling with an error: django.urls.exceptions.NoReverseMatch -
How can I send user ID in Angular using both REST API and websockets
I am going to create chatbot using websockets. Each user can have their own account. I have Django backend and frontend written in Angular. I am not sure how can I send my user_id from frontend to backend, because I use in my project both Django Rest Framework and websockets, so it seems to me that frontend has to authenticate user both using websockets and REST and has to know that it is the same one user. However it seems to me that it is impossible to have one common authentication for REST and websockets. This is example JSON data that my backend has to receive: { "user_id":2, "message":"My message" } Any ideas how can I solve it? This is part of my Angular component: export class HomeComponent { response: string; response2: string; constructor( private chatService: ChatService, private router: Router, private http: Http, ) { chatService.messages.subscribe(msg => { this.response = msg.message; console.log("Response from backend: " + msg.message); }); } private message = { message: 'this is a test message' } sendMsg() { console.log('new message from client to websocket: ', this.message); this.chatService.messages.next(this.message); return this.message.message; } send(msg) { this.message.message = msg; this.sendMsg(); } login() { return this.http.get('/data', ) .map(response => response.json()) .subscribe(response2 … -
Django preventing the loading of django-compressor if DEBUG is True
I am using django-compressor with a remote site on an Ubuntu server. In my local environment, I'm on Windows, where django-compressor doesn't work. Therefore I can't load django-compressor in my installed apps in my development settings (I have a settings folder with a base.py with dev.py and prod.py inheriting from that). The problem is in my base.html template where I need to load the compress module {% load compress %} at the top of the document, and of course compress my css and js files accordingly. Clearly this doesn't work on my local environment, with DEBUG set to True because the app can't exist in my installed apps. What I am trying to do is prevent this app being loaded dependent on the value of settings.DEBUG. I have tried an assignment tag which returns settings.DEBUG but that doesn't work. Is this possible to achieve? Many thanks in advance. -
Using Django with Redis and Backgroundworker, Architectur Explain
I found this Example https://medium.com/@johngrant/raspberry-pi-and-django-channels-8d5cddb36226 I want to understand the system architecture. How is the connection between BackgroundWorker and Redis and how is the connection between Webserver and Redis in context with websocket. I draw a picture about the architecture. But im nut sure about it. Click here for architecture -
django-python3-ldap LDAPInvalidCredential error
I don't know if I'm doing it right, because i'm fairly new to LDAP and django. Here's my settings file: # The URL of the LDAP server. LDAP_AUTH_URL = "url" # The LDAP search base for looking up users. LDAP_AUTH_SEARCH_BASE = "OU=someOU,DC=someDC,DC=someDC,DC=net" LOGGING = { "version": 1, "disable_existing_loggers": False, "handlers": { "console": { "class": "logging.StreamHandler", }, }, "loggers": { "django_python3_ldap": { "handlers": ["console"], "level": "INFO", }, }, } # A tuple of django model fields used to uniquely identify a user. LDAP_AUTH_USER_LOOKUP_FIELDS = ("username",) # Path to a callable that takes a dict of {ldap_field_name: value}, # returning a list of [ldap_search_filter]. The search filters will then be AND'd # together when creating the final search filter. LDAP_AUTH_FORMAT_SEARCH_FILTERS = "app.views.search_filter" Again, I dont know if this is the right thing, but I have a LDAP working code(Python 2.7 and non Django) for reference, If you could look at that and tell me where I should make changes for making the Error go away, that would be very helpful, The below Code is what I did to make ldap authentication in python2.7 work, seeing below, the package:- django-python3-ldap is very confusing to me. username=data['username'].value username=username+"@somecompany.net" password=data['password'].value ldap_server="url" base_dn="OU=someOU,DC=someDC,DC=someDC,DC=net" connect=ldap.open(ldap_server) connect.bind_s(username,password) search_filter="uid="+username … -
the loop does not iterate on factory boy class
I'm using factory boy for the testing my user (Customer). I have created class UserFactoryCustomer for my customer User. # factories.py class UserFactoryCustomer(factory.django.DjangoModelFactory): class Meta: model = User django_get_or_create = ('first_name', 'last_name', 'username', 'email', 'user_type', 'balance') first_name = 'Ahmed' last_name = 'Asadov' username = factory.LazyAttribute(lambda o: slugify(o.first_name + '.' + o.last_name)) email = factory.LazyAttribute(lambda a: '{0}.{1}@example.com'.format(a.first_name, a.last_name).lower()) user_type = 1 balance = 10000.00 # test_serializers.py class ApiSerilizerTestCase(TestCase): def test_get_status_code_200(self): customers = factories.UserFactoryExecutor.objects.all() for customer in customers: self.assertEqual(customer.get('username').status_code, 200) I'm getting this mistake Creating test database for alias 'default'... System check identified no issues (0 silenced). ..E ====================================================================== ERROR: test_get_status_code_200 (tests.test_serializers.ApiSerilizerTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/heartprogrammer/Desktop/freelance-with-api/freelance/tests/test_serializers.py", line 20, in test_get_status_code_200 customers = factories.UserFactoryExecutor.objects.all() AttributeError: type object 'UserFactoryExecutor' has no attribute 'objects' ---------------------------------------------------------------------- Ran 3 tests in 0.246s FAILED (errors=1) I want to bring all my customers who are in the class and UserFactoryCustomer to test them -
Django sub-packages in django Admin
I have a project that I need to split in multiple sections that have a commune denominator. So, I do something similar to Django: INSTALLED_APPS = ( ... 'section1.subapp1', 'section2.subapp2', 'section2.subapp1', 'section2.subapp2', ... ) For example I have a social media section with twitter app, linkedin app, facebook app etc. My question is how I group this apps also as section in Django Admin and not as separate apps ? (for example Social media Panel) -
Compiled Sass files not found by Django-pipeline
I'm having trouble with running django-pipeline because I keep receiving errors similar to: ValueError: The file 'css/main.b7ade0b8392c.css' could not be found with <pipeline.storage.PipelineCachedStorage object at 0x7f66c22ef550>. When I perform an ls operation in my css folder, the css file that is present is called main.c2b6ea9fa0e1.css, which is different from the file that django-pipline is looking for. My django-pipeline configuration looks like this: PIPELINE = { 'PIPELINE_ENABLED': True, 'STYLESHEETS': { 'main': { 'source_filenames': ( 'css/main.scss', ), 'output_filename': 'css/main.css' }, 'COMPILERS': ( 'pipeline.compilers.sass.SASSCompiler', ), 'CSS_COMPRESSOR': 'pipeline.compressors.NoopCompressor', 'JS_COMPRESSOR': 'pipeline.compressors.NoopCompressor' } This problem only seems to be happening when I have DEBUG=False. I try to perform python manage.py collectserver before restarting the Apache server, but to no avail. I'm using Apache, Django 1.9.9, Python 2.7. -
How can I send form data to test.html by using asynchronous communication?
I wanna send form data to test.html by using asynchronous communication. I wrote in index.html <body> <form method="post" action=""> <select id="mainDD" data-placeholder="Choose" class="chzn-select" style="width:600px;"> {% for i in json_data.items.values %} <option value="{{forloop.counter}}">{{ i }}</option> {% endfor %} </select> {% for key, values in preprocessed %} <select name="type" id=type{{forloop.counter}}> {% for counter, value in values %} <option value="{{forloop.counter}}">{{ value }}</option> {% endfor %} </select> {% endfor %} </form> <script type="text/javascript"> $(document).ready(function () { $('#mainDD').on('change', function() { var thisType = "type" + $(this).val(); for(i=1; i<6; i++) { var thisId = "type" + i; if(thisType !== thisId) { $("#"+thisId).hide(); } else { $("#"+thisId).show(); } } }).trigger('change'); }); </script> <form id="postform" action="http://localhost:8000/app/test_view" method="POST"> {% csrf_token %} <input type="submit" value="SEND"> </form> <script type="text/javascript"> $('[name=type]').change(function() { var array1 = []; var array2 =[]; $('[name=main] option:selected').each(function() { array1 = $(this).text(); console.log(array1); }); $('[name=type] option:selected').each(function() { array2 = $(this).text(); console.log(array2); }); }); $.ajax({ url: 'test.html', dataType: 'html', timeout:3000, async: true, success: function(html) { $('.newsarea').html(html).fadeIn(5000); }, error: function() { alert('Error'); } }); </script> </body> I wanna send selected i & value's variables to test.html.Now when I put send button,nothing is shown in test.html. I wrote test.html like <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>RESULT</title> </head> <body> <h2>TOPIC</h2> <div … -
Django: Storing Images Database
Earlier I was using default database sqlite3, but today i've changed it to postgresql. I wants to save the image files in database not in project directory itself. How can I do that? Thank You :) -
Django admin search for multi-word phrase with ^ and = operators
Assume a model admin has: search_fields = ("^name", "=kind") If name is "Leonardo Da Vinci", it can be found using the query Leon or Leonardo, but not Leonardo Da or Leonardo Da Vinci. If kind is e.g. "polymath genius", such a value cannot be found with any query. Ideally, one would be able to post "multiple words" "Leonardo Da" and get this record; but given how Django splits the query, it doesn't do what one might expect. This problem was apparently raised 9 years ago in this ticket, and solved. Then Django got rewritten and apparently this got dropped somewhere. Does anyone have an idea if this is possible? I'm probably thinking I'd need to override ModelAdmin.get_search_results... Anything more elegant? -
Need help in understand Django-Facebook API and the Post extraction form a profile suing Python2
I am working on my machine learning project where I am in a great need to access the textual posts of the people from Facebook, of course with permission, and then process it to find the best personality traits. I am struggling to find a way to merge my application with something that can give me the post of the people from their profiles. Hence, I found something in the documentation of the Django-Facebook API. Here is the link for the documentation: http://django-facebook.readthedocs.io/en/latest/installation.html Here what I am not able to understand is how I can use this for extracting the post of the people? Can anyone give a small example that can be helpful in understanding what I can do to extract the text from the people profile and use it in my application. -
GAE: ImportError while using google-auth
I am using google-auth to allow firebase authentication in my GAE project. Everything works fine when I run the code locally using dev_appserver.py or when I deploy it to google app engine. But I get this ImportError exceptions when I try to use Django's manage.py script to create/run migrations. ```ImportError: Could not import 'firebase.authentication.FirebaseAuthentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'. ImportError: No module named auth.transport.requests. The google-auth module is installed under lib directory and has this structure: - lib - google - auth - oauth2 These import cause the ImportErrors: import google.auth.transport.requests from google.oauth2 import id_token My guess is that there might be naming conflicts as other imports work fine. Please help! -
Reverse for 'about' with no arguments not found
So I'm attempting to Django, and I've gotten a few urls working but one set just wont work. It keeps asking for a argument but it shouldn't require one. Error below. NoReverseMatch at / Reverse for 'about' with no arguments not found. 1 pattern(s) tried: ['$about/'] Error during template rendering In template hub\templates\partials\footer.html, error at line 33 hub\templates\partials\footer.html line 33 <a href="{% url 'hub:about' %}" class="nav__link">About</a> hub/urls.py urlpatterns = [ url(r'^$', views.HomePageView.as_view(), name='index') ] storyarchive/urls.py urlpatterns = [ url(r'^$', include('hub.urls', namespace='hub')) ] It worked before I started to use the {% url %} builtin. Django Version: 1.11.5 Python Version: 3.4.4 -
how to send data from HTML to python and get the result back to HTML?
I know nothing about the interface between HTML and python so I come here to ask for help hope you guys can help me. HTML are now post on apache server,and I visit this web by the address "http://127.0.0.1/name.html". Here is what I want to achieve: There is a form on HTML getting the data,and by clicking the button "submit",the data should be send to python.exe,and the python.exe runs itself and send the result back to HTML(by poping a new dialog). I searched on the Internet and was wondering will Django help?? Is this even possible?Can anybody help me ? -
Adding two fields while filtering and converting a field to an appropriate type
From this link I have Entry.objects.filter(mod_date__gt=F('pub_date') + timedelta(days=3)) While I want to achieve something like Entry.objects.filter(mod_date__gt=F('pub_date') + timedelta(seconds = F('delay'))) Here I have to combine two fields in the table while converting one to timedelta. I couldn't have F object as a timedelta seconds argument where it needs an integer. I want to have a filter where I can convert F type to integer while adding and filtering. Any help is appreciated. -
Django template tags filter by slug
I have a many-to-one relationship between organizations and events. One organization can have many events. I have a template for showing all events that everybody can see filtered by city. But I want the organization detail view to show events belonging only to a specific organization. models.py class Organization(models.Model): name = models.Charfield(max_length=27) slug = models.SlugField(max_length=25, null=True, blank=True) [...] def __unicode__(self): return self.name class Events(models.Model): org = models.ForeignKey(Organization, on_delete=models.CASCADE, default=1) time = models.DateTimeField(null=True, blank=True) city = models.CharField( max_length=25, choices = CITY_CHOICES, default = 'NY' ) [...] def __unicode__(self): return '%s %s' % (self.org, self.time) I use this template tag to filter events by city (NY for this one): @register.inclusion_tag('mysite/event_list.html') def event_ny_tag(event): return {'events': Events.objects.filter(linn='NY')} url.py urlpatterns = [ url(r'^$', HomePageView.as_view(), name='home'), url(r'^organizations/$', OrganizationList.as_view(), name='organizations'), url(r'^events/$', EventList.as_view(), name='events'), url(r'^(?P<slug>[-\w]+)/$', OrgDetailView.as_view(), name='org_detail'), ] But how can I filter events only by one specific organization? There are only two cities but 20 organizations. How to do it without hardcoding it? With a slug? This is not a copy paste. Just a sample code similar to mine. -
Django add aggregate operation to a query result
I'm trying to do an aggregate operation between two tables using Django, my models are: class Cusinetype(models.Model): hometype_en = models.TextField() active = models.BooleanField() hometype_es = models.TextField(blank=True, null=True) class Meta: managed = False db_table = 'cusinetype' class Foodpreferences(models.Model): id_client = models.ForeignKey(Client, models.DO_NOTHING, db_column='id_client') id_cusinetype = models.ForeignKey(Cusinetype, models.DO_NOTHING, db_column='id_cusinetype') created_at = models.DateTimeField() class Meta: managed = False db_table = 'foodpreferences' The query that I'm trying to build is: SELECT ct.id, ct.hometype_en, ct.hometype_es , ((SELECT COUNT(*) FROM foodpreferences fp WHERE fp.id_cusinetype = ct.id AND fp.id_client = 3 ) > 0 ) selected FROM Cusinetype ct I'm trying to generate a model, to store the information of those tables in a single one query, but anything works. Someone has an idea about how to do it? -
I cannot get an array when I put send button
I cannot get an array when I put send button. I wrote index.html <body> <form method="post" action=""> <select id="mainDD" data-placeholder="Choose" class="chzn-select" style="width:600px;"> {% for i in json_data.items.values %} <option value="{{forloop.counter}}">{{ i }}</option> {% endfor %} </select> {% for key, values in preprocessed %} <select name="type" id=type{{forloop.counter}}> {% for counter, value in values %} <option value="{{forloop.counter}}">{{ value }}</option> {% endfor %} </select> {% endfor %} </form> <script type="text/javascript"> $(document).ready(function () { $('#mainDD').on('change', function() { var thisType = "type" + $(this).val(); for(i=1; i<6; i++) { var thisId = "type" + i; if(thisType !== thisId) { $("#"+thisId).hide(); } else { $("#"+thisId).show(); } } }).trigger('change'); }); </script> <form id="postform" action="http://localhost:8000/app/test_view" method="POST"> {% csrf_token %} <input type="submit" value="SEND"> </form> <script type="text/javascript"> $('[name=type]').change(function() { var array = []; $('[name=alphabet] option:selected').each(function() { array.push($(this).text()); }); console.log(array); }); </script> </body> I wanna make a program when I put SEND button, array has variable of i&value are selected.But now array is empty although I selected these buttons, so how can I fix this?What should I write it? -
Multiple versions of web API. Separate models for each version?
I am implementing a web API with each API version defined in a separate Django app: foo.api.v1, foo.api.v2, etc. How should I structure the Django models modules? Separate foo.api.v1.models, foo.api.v2.models, etc.? A single foo.api.models module for all the versions? If it matters, I am using Django REST Framework to define the API. -
Django Security issue
So I have just completed my site, it is a basic social network. Each user has a profile and can edit their profile. However if a logged in user switches the user id in the edit url they can edit another users profile. So if I am logged in as user 1 I can edit my profile here: /user/1/edit However, if logged in as user 1 and I go to user 2's edit profile url here: /user/2/edit I can also edit their profile... How do I stop that?? -
How to inform a user that he is not active in Django login view
I'm creating a custom authentication app to Django, everything is fine, the user needs to verify email to set is_active True, this works like a charm, but once the user send the e-mail and the token expires, the user try to login and receive a message of user or pass incorrect, and I want to show the user has to activate the account and give a link to resend the activation token to his email. I'm using the default Login View: url(r'^login/$', auth_views.LoginView.as_view(template_name='accounts/login.html'), name='account_login') How can i modify this view or other thing to show the user is not active. -
Adding content between form in Formset_Factory = Django
I am working on a django application and more specifically, a formset (group of forms). I have the form set amount set the number of objects retrieved by a query set. What I want to do is make a change to the form set so that in between each of the forms in the formset, include a name for a user related to the form set. What is happening right now is that it is print the entire formset then the names that I want to move to be placed in between each of the forms in the formset. Here is what the form looks like: Add expense - restructured group Please complete the form below Amount: 0 Description: expense Amount: 0 Description: expense Amount: 0 Description: expense josh lifter omar submit I want to move the names to appear before the amount/description inputs Here is the code that I have: this is the views.py: def updateExpenseIndividual(request, groupId, groupName): currentUser = loggedInUser(request) currentProfile = Profile.objects.get(user = currentUser) currentGroup = Group.objects.get(id = groupId) host = Member.objects.filter(group = groupId).filter(status = 2).first() expenses = Expense.objects.filter(group = currentGroup).filter(name = groupName).all() expenses_count = Expense.objects.filter(group = currentGroup).filter(name = groupName).count() SplitFormSet = formset_factory(UpdateExpenseForm, extra=expenses_count) if request.method == … -
How to setup a DJANGO REST that requires information from a POST request?
I am trying to construct a class based Django REST API that takes in data from the POST request and outputs the relevent data. I have a list of buildings in the DB State Building California Golden Gate Bridge New York Empire State California TransAmerica New York Brooklyn Bridge The POST request will specify the state, and the API should output the appropriate building. I guess I'm just having a hard time understand how the class is taking in the request.data ['state_id']. Should I use APIView? So many questions! So far I have this in my view.py class BuildingViewSet(viewsets.ModelViewSet): queryset = BuildingRule.objects.values('building_name').distinct() serializer_class = BuildingSerializer def post(self, request, *args, **kwargs): queryset = BuildingRule.objects.filter(state_name=request.data['state_id']) return Response(queryset.values_list('building_name', flat=True)) This is in my serializer.py class BuildingSerializer(serializers.ModelSerializer): class Meta: model = BuildingRule fields = ('building_name',) This is my url.py: router.register(r'buildings', views.BuildingsViewSet, base_name='Building') -
Accessing user object when creating a user in Django
I'm using Django 1.10.6 and I'm working on a user registration form. During the validation process in my forms.py I'm trying to call the UserAttributeSimilarityValidator from within the clean method, but I'm having some trouble figuring out what the user object argument is that it requires. The request data is a QueryDict, not an object, so I'm confused as to what object I'm supposed to be using. Here is the UserAttributeSimilarityValidator class found in the link I provided class UserAttributeSimilarityValidator(object): DEFAULT_USER_ATTRIBUTES = ('username', 'first_name', 'last_name', 'email') def __init__(self, user_attributes=DEFAULT_USER_ATTRIBUTES, max_similarity=0.7): self.user_attributes = user_attributes self.max_similarity = max_similarity def validate(self, password, user=None): if not user: return for attribute_name in self.user_attributes: value = getattr(user, attribute_name, None) if not value or not isinstance(value, string_types): continue value_parts = re.split('\W+', value) + [value] for value_part in value_parts: if SequenceMatcher(a=password.lower(), b=value_part.lower()).quick_ratio() > self.max_similarity: verbose_name = force_text(user._meta.get_field(attribute_name).verbose_name) raise ValidationError( _("The password is too similar to the %(verbose_name)s."), code='password_too_similar', params={'verbose_name': verbose_name}, ) def get_help_text(self): return _("Your password can't be too similar to your other personal information.") Here's my clean method in forms.py def clean(self): cleaned_data = super(RegisterForm, self).clean() password = cleaned_data.get('password') password_validation.UserAttributeSimilarityValidator().validate(password, USER_OBJET_HERE) I tried to create a user object by using namedtuple like so user = namedtuple('user', 'username …