Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django models changing
I had a model class Subject(models.Model): subject_title = models.CharField(max_length=255) subject_lesson = models.ForeignKey(Lessons, on_delete=models.PROTECT) Before i had information in the database by this fields then i delete all information from database. Then i added some fields to the table. class Subject(models.Model): subject_title = models.CharField(max_length=255) subject_text = models.CharField(max_length=600) subject_image = models.ImageField(upload_to='uimages', blank=True, null=True, default='uimages/edu-logo-1.png') subject_lesson = models.ForeignKey(Lessons, on_delete=models.PROTECT) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) After this django asking me: You are trying to add the field 'created_at' with 'auto_now_add=True' to subject without a default; the database needs something to populate existing rows . 1) Provide a one-off default now (will be set on all existing rows) 2) Quit, and let me add a default in models.py Select an option: What to enter? -
Dajngo template: group by key
I have list of objs: [{ key:test1 name: name1 }, { key:test1 name: name2 }, { key:test2 name: name3 }] Is it possible to combine values with similar keys without changing the structure? not to be displayed twice test1 in my case {% for item in list %} {{ item.key }} :{{item.name}} {% endfor %} now: test1 : name1 test1 : name2 test2 : name3 desired result: test1 : name1 _____ name2 test2 : name3 -
google oauth2 - Your credentials aren't allowed when using heroku
I am using a simple social login using google oauth2. I have deployed my app on heroku. I have successfull tested the google login on my local machine. However, when using heroku to login via google, It gives me this error, AuthForbidden at /oauth/complete/google-oauth2/ Your credentials aren't allowed I am using the same keys with the same name in heroku config vars. But still not sure why its not identifying login from heroku. -
Date time error in Python
I'm trying to learn the functions of Python but there is one thing I came across which I cannot figure out. calculated_time = '2014.03.08 11:43:12' >>> calculated_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") >>> print calculated_time 2017-09-22 15:59:34 Now when I run: cmpDate = datetime.strptime(calculated_time, '%Y.%m.%d %H:%M:%S') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/_strptime.py", line 332, in _strptime (data_string, format)) ValueError: time data '2017-09-22 16:35:12' does not match format'%Y.%m.%d %H:%M:%S' I can't understand why, if I directly pass this date then it is running but when I pass it after storing in a variable then I've got an error. -
Django, how to implement authorization in different ways
Tell me how to implement it so that some users (user) on login are authorized by phone, and the rest (owner, employee) by email, and all with different access rights? class UserManager(BaseUserManager): def create_user(self, phone, password=None): if not phone: raise ValueError('Please, enter the correct phone number') user = self.model(phone=phone) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, phone, password): user = self.create_user(phone=phone, password=password) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") phone = models.CharField(validators=[phone_regex], blank=True, max_length=15) phone = models.IntegerField(('contact number'), unique=True, db_index=True) # email = models.EmailField(_('email address'), unique=True) is_admin = models.BooleanField('superuser', default=False) is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'phone' def get_full_name(self): return str(self.phone) def get_short_name(self): return str(self.phone) def __unicode__(self): return str(self.phone) -
How to install mod_wsgi on Windows+XAMPP in 2017
Im a trying (hard) to set up environment for Django app on Windows with XAMPP. What I have: Windows 7 64bit Apache/2.4.25 (Win32) Python 3.6.1 Cygwin 2.9.0(0.318/5/3) MOD_WSGI_APACHE_ROOTDIR pointing to apache dir in XAMPP installation What I did already: Tried to install with pip install mod_wsgi but it didn't work because apxs could not be found. So I've installed httpd-devel in Cygwin. Now it rises collect2: error: ld returned 1 exit status error with massive output that I can't understand. According to this, I've downloaded WHL file, exctracted PYD file but when I want to run Apache I get syntax error on LoadModule wsgi_module modules/mod_wsgi.pyd: Cannot load modules/mod_wsgi.pyd into server: The specified module could not be found.. I've tried 3 versions of WHL. I'm new to Python/Django and WSGI and I'm already done ;-) -
Cannot add Django management commands to project on my development environment
I have an existing project with several custom management commands in an app. These commands run fine both locally and in production. When I add a new command (newtask.py) to the folder however, it cannot be found. When I run manage.py newtask, it says: Unknown command: 'newtask' If I open manage.py shell, and I try to import the file directly, like so: from app.management.commands.newtask import Command I get the following: Traceback (most recent call last): File "<console>", line 1, in <module> ImportError: No module named newtask The app in question works fine, and other commands in the same folder also work fine and can be imported. I handed this over to another developer I work with, and he can run newtask on his local machine no problem. I have checked and double checked: Installed Apps I'm in the right virtualenv File permissions are the same as existing commands The file is not open in another application I've also thought to copy existing, working code from another command into a new file. I get exactly the same issue - the new copy of a working command isn't found, cannot be imported, etc. Django just refuses to "see" it even though it's … -
Why am I getting a form error from this CheckboxSelectMultiple (M2M), but not another that's nearly identical?
I'm getting the error Select a valid choice. 1 is not one of the available choices. when I submit this form (with a change in the selection for students): class AdvisorAddForm(forms.ModelForm): class Meta: model = Advisor fields = ['LastName','FirstName','Email','students'] def __init__(self, *args, **kwargs): active_section = kwargs.pop('active_section',None) super(AdvisorAddForm, self).__init__(*args, **kwargs) self.fields['students'].widget = forms.CheckboxSelectMultiple() try: this_school = self.instance.school self.fields['students'].queryset = Student.objects.all().filter(school=this_school,sections__in=[active_section]).order_by('LastName') except: pass But this form works fine: class AssessmentAddForm(forms.ModelForm): class Meta: model = Assessment fields = ['Name','Date','section','standards'] AddToSections = forms.BooleanField(initial=False,required=False,label="Add This Assessment To All Of Your Sections") def __init__(self, *args, **kwargs): standard_list = kwargs.pop('standard_list',None) super(AssessmentAddForm, self).__init__(*args, **kwargs) self.fields['section'].widget=HiddenInput() self.fields['standards'].widget = forms.CheckboxSelectMultiple() try: active_section = self.instance.section self.fields['standards'].queryset = Standard.objects.all().filter(course__in=[active_section.course]) self.fields['standards'].initial = standard_list except: pass It looks like it's getting a pk where it expects an object, but I'm not sure why, or why the other one wouldn't have that issue, too. -
Problems running a test site
I'm new with Python > Django. I have problems running a hello world page on my test website. I'm using pythonanywhere.com to make a test site. I created the site folder and the app folder correctly using these commands: django-admin startproject website python manage.py startapp music Now to show a hello world page i opened the website urls.py and wrote these lines: from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^music/', include('music.urls')), ] music/urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), ] music/views.py from django.http import httpresponse def index(request): return httpresponse("hello world") When I visite mysite.com/music/ I see a 404 error page. Why? -
django create object from recursive model
I have problem with creating object with recursive relation. So the scenario is right after create organization, insert user to just-created organization. # models.py class Organization(models.Model): name = models.CharField(max_length=32) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) code = models.CharField(max_length=4, unique=True) photo_path = models.CharField(max_length=256, null=True) class Meta: db_table = 'organization' def __str__(self): return self.name class OrganizationLevel(models.Model): organization = models.ForeignKey( Organization, on_delete=models.CASCADE, db_index=False ) parent = models.ForeignKey( 'self', on_delete=models.CASCADE, db_index=False ) name = models.CharField(max_length=48) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: db_table = 'organization_level' unique_together = ('name', 'organization') class OrganizationUnit(models.Model): organization_level = models.ForeignKey( OrganizationLevel, on_delete=models.CASCADE, db_index=False ) name = models.CharField(max_length=48) position = models.PointField(geography=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) parent = models.ForeignKey( 'self', on_delete=models.CASCADE, db_index=False ) address = models.CharField(max_length=256) class Meta: db_table = 'organization_unit' unique_together = ('name', 'organization_level') class User(models.Model): email = models.CharField(max_length=64) username = models.CharField(max_length=32) password = models.CharField(max_length=64) token = models.CharField(max_length=32, null=True) tokenexp = models.DateTimeField(null=True) photo_path = models.CharField(max_length=256) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) organization = models.ForeignKey( Organization, on_delete=models.CASCADE ) is_activated = models.BooleanField(default=False) code = models.CharField(max_length=32, null=True) name = models.CharField(max_length=64) birthdate = models.DateTimeField(null=True) sex = models.CharField(max_length=1) address = models.CharField(max_length=80) organization_unit = models.ForeignKey( OrganizationUnit, on_delete=models.CASCADE ) class Meta: db_table = 'user' So from given models, here's the flow: Create organization Create … -
Django: how to validate m2m relationships?
Let's say I have a Basket model and I want to validate that no more than 5 Items can be added to it: class Basket(models.Model): items = models.ManyToManyField('Item') def save(self, *args, **kwargs): self.full_clean() super(Basket, self).save(*args, **kwargs) def clean(self): super(Basket, self).clean() if self.items.count() > 5: raise ValidationError('This basket can\'t have so many items') But when trying to save a Basket a RuntimeError is thrown because the maximum recursion depth is exceeded. Apparently Django's intricacies simply won't allow you to validate m2m relationships when saving a model. How can I validate them then? -
Django Cookie with Login function
I'm trying to set my first cookie with Django when users are logged on my application. When user is logged, the template is well-displayed but none cookie in my application which is named : Cookie My function looks like : def Login(request): error = False if request.method == "POST": form = ConnexionForm(request.POST) if form.is_valid(): username = form.cleaned_data["username"] password = form.cleaned_data["password"] user = authenticate(username=username, password=password) if user: login(request, user) toto = GEDCookie(request) return render(request, 'Home_Homepage.html', {'toto':toto}) else: error = True else: form = ConnexionForm() return render(request, 'Authentication_Homepage.html', locals()) @csrf_exempt def GEDCookie(request): SID = Logger.login("test", "10test") response = HttpResponse("Cookie") response.set_cookie('Cookie', SID, max_age=None) return response I missed something in my script ? -
Django load data dumped from sqlite to mysql - installing fixture, content type does not exist
I've dumped data from my sqlite db using the following command: ./manage.py dumpdata --exclude=contenttypes --exclude=auth.Permission --natural-foreign --natural-primary > initial_data.json however when trying to load the data into my new mysql DB I get the below errors django.core.serializers.base.DeserializationError : Problem installing fixture '/itapp/itapp/initial_data.json': ContentType matching query does not exist.: (auth.group:pk=None) field_value was '['add_circuitfiles', 'networks', 'circuitfiles']' I think this is something to do with permission groups? I'm not sure how to fix this, do I need to edit the JSON file and remove something? Thanks -
Failed to load resource: the server responded with a status of 404 (Not Found) Am I wrong to write directory?
I got an error by using Google validation like Folder structure is testapp (parent app) chosen.jquery.min.js & chosen.min.css & chosen-sprite.png -app (child app) -templates (folder) -menu.js / index.html I wrote in index.html <html> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <script type="text/javascript" src="chosen.jquery.min.js"></script> <link href="chosen.min.css" rel="stylesheet"> </head> <body> <select data-placeholder="Choose" class="chzn-select" style="width:350px;"> <option value="0">---</option> <option value="1" selected>A</option> <option value="2">B</option> <option value="3">C</option> <option value="3">D</option> </select> <select name="type" id="type1"> <option value="1">a-1</option> <option value="2">a-2</option> <option value="3">a-3</option> <option value="4">a-4</option> </select> <select name="type" id="type2"> <option value="5">b-1</option> <option value="6">b-2</option> <option value="7">b-3</option> <option value="8">b-4</option> <option value="9">b-5</option> </select> <select name="type" id="type3"> <option value="10">c-1</option> <option value="11">c-2</option> </select> <select name="type" id="type4"> <option value="10">d-1</option> <option value="11">d-2</option> <option value="11">d-3</option> </select> </body> <script type="text/javascript"> $(".chzn-select").chosen(); $(".chzn-select-deselect").chosen({allow_single_deselect:true}); </script> </html> What is wrong in my code?Am I wrong to write directory?By using Network of Google validation, I found chosen.jquery.min.js was not load.How can I fix this? -
Django Sum Annotation with Foreign key
I am working on a project and noticed that the Django Sum() annotation is not working properly when you use it to make a sum of a field with a foreign key. For example when you have visits to a website on which someone can place an order. The Order model has a link to the Visitmodel because you can place multiple orders in one visit. However, orders that are not coming from the website don't have a website visit. For these orders, the visit will be NULL. When I do the following, the calculation is not correct (the value is far too high). visits = visits.annotate(order_total = Sum('order__total')) When I change Sumto Avg, the calculation is done correctly. Is there a logical explanation for this? -
Why does it take more time to reach view after crossing middleware in Django?
These are following middleware in my project<br> MIDDLEWARE_CLASSES = [ <br> 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'simple_history.middleware.HistoryRequestMiddleware', 'apps.quiz.totaltimemid.TimeCalculateMiddleware', ] ------------- My custom middleware to measure time for reaching process_view of last middleware to my target view(class QuizFetchView(APIView)): class TimeCalculateMiddleware(object): def process_view(self, request, callback, callback_args, callback_kwargs): self.req_start_time = time.time() def process_response(self,request, response): try : response['vreach_time'] = float(response['tt_start']) - self.req_start_time return response except : return response .................................................. class QuizFetchView(APIView): permission_classes = [IsAuthenticated, IsAuthenticatedForRunningQuiz] def get(self, request: Request, key: str) -> Response: tt_start = time.time() .............. .............. ............ Response['tt_start'] = tt_start return Response ########################### For Login request middleware to view take very few milliseconds but subsequent request other than login take 25-35ms to reach view. Please help me, Thank you -
'str' object has no attribute 'client' - Synapse - DJango
I am working within a django project, and I am trying to send a request to the Synapse api. I am trying to link an account and i was wondering if this error has to do with the request call to synapse or something to do within django itself. If so, is there a way for me to fix it. Here is my code: def authorizeLoginSynapse(request, form): currentUser = loggedInUser(request) currentProfile = Profile.objects.get(user = currentUser) user_id = currentProfile.synapse_id synapseUser = retreiveUserSynapse(request) # cd = form.cleaned_data # bank_code = cd['bank_code'] # bank_id = cd['bank_id'] # bank_pw = cd['bank_password'] bank_id = 'synapse_good' bank_pw = 'test1234' bank_code = 'fake' print(bank_code) print(bank_id) print(bank_pw) bank_type = 'ACH-US' args = { 'bank_name':bank_code, 'username':bank_id, 'password':bank_pw, } print(args) linked_account = AchUsNode.create_via_bank_login(user_id, **args) print(linked_account) linked_account.mfa_verified Here is the error: AttributeError at /login_synapse/ 'str' object has no attribute 'client' Request Method: POST Request URL: http://127.0.0.1:8000/login_synapse/ Django Version: 1.11.5 Exception Type: AttributeError Exception Value: 'str' object has no attribute 'client' Exception Location: /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/synapse_pay_rest/models/nodes/ach_us_node.py in create_via_bank_login, line 39 here is the terminal with the printing and tracebacK: fake synapse_good test1234 {'bank_name': 'fake', 'username': 'synapse_good', 'password': 'test1234'} Internal Server Error: /login_synapse/ Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner response … -
Django CORS fails with post request from mobile app
I am using Angular 4 / Ionic 3 for the frontend/mobile app. I am using Django 1.11 for the backend. When i try sending request from the browser as: headers.append('Content-Type', 'application/json'); headers.append('Access-Control-Allow-Origin', '*'); this.http.post('http://0.0.0.0:8000/en/accounts/user/', {} , {headers:headers}) In my Django app i've used django-cors-headers and set: - CORS_ORIGIN_ALLOW_ALL = True - CORS_ALLOW_CREDENTIALS = True From the browser i get the expected response , but when testing from mobile app the CORS request doesn't seem to pass ( returns Response with status: 0 for URL: null ) Any suggestions on this ? -
AttributeError: 'NoneType' object has no attribute 'attname' (Django)
I have a fairly complex model for which the first call to MyModel.objects.create(**kwargs) fails with AttributeError: 'NoneType' object has no attribute 'attname' The stack trace dives down like this (in Django 1.11) django/db/models/manager.py:85: in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) django/db/models/query.py:394: in create obj.save(force_insert=True, using=self.db) django/db/models/base.py:807: in save force_update=force_update, update_fields=update_fields) django/db/models/base.py:837: in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) django/db/models/base.py:889: in _save_table pk_val = self._get_pk_val(meta) django/db/models/base.py:644: in _get_pk_val return getattr(self, meta.pk.attname) django/db/models/query_utils.py:114: in __get__ val = self._check_parent_chain(instance, self.field_name) django/db/models/query_utils.py:131: in __check_parent_chain return getattr(instance, link_field.attname) The model definition looks alright to me. I have checked all the parameters of the create call are just what I want them to be. I'm not keen on stripping down the model to find the problem, because the model is so complex. (All my other models, many of them similar, appear to work fine.) So what might cause this strange message? -
UI for Machine Learning results in Python
I have been working in a project for last 3 months, I have done my analysis over a number of financial datasets such as stock market predictions, I used a number of feature selection techniques and a bunch of algorithms as well. I use Jupyter environment for Python for my analysis and to display my results such as prediction charts, I go for Ipython Dashboard. But,this is not what actually I want. I can run those all things, but now I want to make all my work compiled within a tool that an individual from financial background can use my tool to analyze the datasets. I want to make all my feature engineering and algorithms available in that tool. Broadly Speaking. The following are my requirements. User open the tool. Select the dataset. (The dataset will always be in the same format as the requirement of our model) User selects the training and testing dates User chooses the feature selection techniques and extracts the features. User choose the particular algorithm. User also able to choose the parameters of that particular algo. Results are displayed in UI manner. Test Results are saved. Finally, the user is happy. ;-) See, I have … -
Get related cousin model in a template
I'm struggling finding docs or examples how to get data from a cousin related model. So if the models look like this: class Part(models.Model): name = models.CharField(max_length=550) class Quantity(models.Model): quantity = models.DecimalField(max_digits=10, decimal_places=2) part = models.ForeignKey('Part', related_name='quantity_part') stockarea = models.ForeignKey('StockArea', related_name='quantity_stockarea') class Stock(models.Model): name = models.CharField(max_length=550) class StockArea(models.Model): area = models.CharField(max_length=550) stock = models.ManyToManyField(Stock, related_name='stockarea_stock') def __str__(self): return self.area And in the view I get the part like this: def details(request, part_id): part = get_object_or_404(Part, pk=part_id) context = { 'part': part, } return render(request, 'part/details.html', context) Finally template trying to display the data: {% for a in part.quantity_part.all %} {{ a.quantity }} pcs Find part in area: {{ a.stockarea }} in stock: {{ part.stockarea.stock.name }} {% endfor %} You see how I try to get the name of the stock. I can't figure out how to be able to get hold of the name of the stock. I have a path there from the part. Part have a related_name to the Quantity model called quantity_park. And in the model Quantity I have a relation to model StockArea. And from there I have a relation to model Stock. Guidance is much appreciated =) Maybe I'm totally doing this backwards. Maybe I'm … -
How to get the username from django.contrib.auth (Django built-in login system)?
I am very new to Python and Django, and am looking at a code that uses the Django built-in login system (django.contrib.auth.login). After the user has logged in, I would like to redirect the user to an appropriate URL based on the users privilege. For example, some usernames have admin privileges, while some are just regular users. However, after the "login" button is clicked, the user is always redirected to the same URL. In order to redirect the user differently, I would have to check the username, and check what privileges that user has. However, I can not find any way to fetch the username from django.contrib.auth.login. It is as if the username just disappears after it has been authenticated. Does anyone know how to solve this problem? Thank you! -
add oscar feature to djnago app in google cloud platform
I would like to use Oscar in my Django app at google cloud platform. in the configuration in app.yaml file I have a 'skip_files' tag: - ^env/.*$ But, the oscar installation is in \env\Lib\site-packages\oscar directory. therefore I get the error: "ImportError: No module named oscar.defaults". When I erase this tag I get the error: "ERROR: (gcloud.app.deploy) Error Response:[400] This deployment has too many files." Tried to include as library but this library is not supporeted. Therefore thought maybe to use a regular expression to skip all files not including "oscar" in it, (referencing Regular expression to match a line that doesn't contain a word?). But it doesnt work for me. Please someone can tell me how to solve this? maybe I wrote the regex incorrectly? (This is after I chose working with oscar at my website, but maybe better choosing another platform?) Thank you. -
Detect if model has been added as foreign key to some other model
Say I have some model instance A1 and existing models B1 and B2 have A1 as a foreign key field fk. Is there a way for the model instance A1 to know that another newly created model instance B3 has assigned it as it fk field (without having to set some kind of counter every time a model B uses A1 as its fk and tracking the counter changes)? Ultimately, I'd like behavior similar to how users are notified of new answer or comment (say model B instance) when other users post to their questions (say model A instance). Any advice on doing this efficiently would be appreciated. Thanks :) -
Set Django REST Frmework JWT in cookies
I am using djangorestframework-jwt to authenticate users. I have overridden the builtin JSONWebTokenAPIView to return user details in the response as well. And I am also setting the token in cookies in my view. def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) if serializer.is_valid(): user = serializer.object.get('user') or request.user token = serializer.object.get('token') response_data = { 'access_token': token, 'user': UserInfoSerializer(user).data } response = Response(response_data, status=status.HTTP_200_OK) if api_settings.JWT_AUTH_COOKIE: expiration = (datetime.utcnow() + api_settings.JWT_EXPIRATION_DELTA) response.set_cookie(api_settings.JWT_AUTH_COOKIE, response.data['access_token'], expires=expiration, httponly=True) return response return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) It works fine on Django server. I can see the token in cookies when I verify the api using REST browseable api view. But my frontend (React) app is running on localhost:3000 and when i hit this api from my frontend server I receive the success response but token is not being set in the cookies. Do I need to set the cookie domain as well?