Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: How to delete token after it is used?
In Django, I am generating tokens for account activation. Here is the actual code: 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': default_token_generator.make_token(user), The problem is once it is used it is still valid. Django password reset mechanism (password_reset_confirm() view) somehow invalidates the token after it is used. How can I do the same? -
file upload in angular 2 through django REST
I am trying to file upload in angular 2 through django. I have done the below mentioned code but I am stuck now. I have the following view in django (views.py) def upload_csv(request): mydb = MySQLdb.connect(host='localhost', user='root', passwd='root', db='testtpo') cursor = mydb.cursor() csv_data = csv.reader(file('testingupload.csv')) for row in csv_data: cursor.execute('INSERT INTO testcsv(names, \ classes, mark )' \ 'VALUES("%s", "%s", "%s")', row) mydb.commit() cursor.close() print ("Done") the following dataupload.component.ts import { Http, Headers, Response } from '@angular/http'; import { Observable } from 'rxjs/Rx'; import { OnInit, ElementRef, ViewChild } from '@angular/core'; import { FileUploader, FileItem } from 'ng2-file-upload'; import { BrowserModule } from '@angular/platform-browser'; import { Component, HostListener } from '@angular/core'; import { environment } from '../../../../environments/environment'; import { Services } from '../../../../services/services'; import 'rxjs/add/operator/toPromise'; import 'rxjs/Rx'; @Component({ selector: 'dataupload', templateUrl: './dataupload.html', }) export class NewComponent1 { constructor(private http: Http) { } public modelUploader:FileUploader = new FileUploader({url: environment.serverUrl+'/api/upload_csv'}); public uploadFile(file, fileType: string): void { if(fileType == 'model') { this.modelUploader.uploadItem(file); } else { console.log("It is not happening"); } } } and the following component.html <div class="dropdown-content"> <div class="row"> <div class="col-md-3"> <h3 style="margin-left: 40px; margin-top: -30px ">Model</h3> <input type="file" class="form-control" ng2FileSelect [uploader]="modelUploader" /><br/> </div> <div class="col-md-8" style="margin-bottom: 40px; margin-left: 30px; "> <h4 style="margin-bottom: … -
Mopidy Installation Error
Installing on Mac High Sierra, through a fresh installation of Brew, following the instructions on the website to the letter. It throws this error; Traceback (most recent call last): File "/usr/local/bin/mopidy", line 5, in <module> from pkg_resources import load_entry_point File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 3095, in <module> @_call_aside File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 3081, in _call_aside f(*args, **kwargs) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 3108, in _initialize_master_working_set working_set = WorkingSet._build_master() File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 658, in _build_master ws.require(__requires__) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 959, in require needed = self.resolve(parse_requirements(requirements)) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 846, in resolve raise DistributionNotFound(req, requirers) pkg_resources.DistributionNotFound: The 'Mopidy==2.1.0' distribution was not found and is required by the application Clearly it's not finding the distro even though it's in the default location with all my other packages. Any idea why? -
Nested django form for foreignkey model
I have two models that look something like class Address(models.Model): line1 = models.CharField(max_length=128, help_text="Address Line 1") city = models.CharField(max_length=128) state = USStateField() zipcode = USZipCodeField() class Company(models.Model): name = models.CharField(max_length=100) address = models.ForeignKey('Address', on_delete=models.PROTECT) The actual classes have many more fields and so I would like to automatically generate forms for creating a new company, and so I am using Django's ModelForm. Howevere, I would like to let the user choose between choosing an existing address or creating a new one all in one form. Is there a way to nest a AddressModelForm inside of a ComanyModelForm? class CreateAddressForm(forms.ModelForm): class Meta: model = Address exclude = [] class CreateCompanyForm(forms.ModelForm): class Meta: model = Company exclude = [] # Use nested form for address # custom widget maybe? How should I approach this problem? Thanks! -
i have two projects in django i can not open admin site for my second project,but i can open for my first project,can any one help me
AttributeError at /admin/ 'WSGIRequest' object has no attribute 'user' Request Method: GET Request URL: http://127.0.0.1:8000/admin/ Django Version: 2.0.2 Exception Type: AttributeError Exception Value: 'WSGIRequest' object has no attribute 'user' Exception Location: C:\Users\vaaz\Desktop\venv\lib\site-packages\django\contrib\admin\sites.py in has_permission, line 186 Python Executable: C:\Users\vaaz\Desktop\venv\Scripts\python.exe Python Version: 3.4.3 Python Path: ['C:\Users\vaaz\website1', 'C:\Windows\system32\python34.zip', 'C:\Users\vaaz\Desktop\venv\DLLs', 'C:\Users\vaaz\Desktop\venv\lib', 'C:\Users\vaaz\Desktop\venv\Scripts', 'C:\Python34\Lib', 'C:\Python34\DLLs', 'C:\Users\vaaz\Desktop\venv', 'C:\Users\vaaz\Desktop\venv\lib\site-packages'] Server time: Mon, 12 Mar 2018 10:21:49 +0000 -
Error django permissions
I hav an error with user permissions in django. This view register collaborator blog, create the user and add the permission because appear in auth_user_user_permissions database table, but when user login to admin panel django doesn't appear any model to create. database table django admin view def work_with_our(request): if request.method == 'POST': user_form = forms.CustomRegisterColaboratorForm(data=request.POST) if user_form.is_valid(): blog_colaborator = user_form.cleaned_data.get('blog_colaborator') user = user_form.save(commit=False) user.is_staff = True user.save() if blog_colaborator == True: permissions = Permission.objects.get(name='Can add post') user.user_permissions.add(permissions) else: user_form = forms.CustomRegisterColaboratorForm() return render(request, 'work_with_our.html', { "user_form": user_form }) Please help because i don't know which is the problem. Thanks in advance. -
Creating an abstract model for
I deleted my previous question, since it was terribly worded and my non-working examples were just confusing. I have a series of models, such as Vehicle, Computer, Chair, and whatnot. My goal is to be able to attach an arbitrary number of images to each of them. That's my question: what's the best design pattern to achieve this? What I've tried so far is to create an abstract model, AttachedImage. I then inherit from this model, and create more specific models, like VehicleImage, ComputerImage, or ChairImage. But this doesn't feel like the right way to pursue this. -
NameError: name 'request' is not defined when trying to request user.connection and user.dn
I am trying to request the connection and the dn of the logged in user for my webapp. I currently work with LDAP and I have this ModifiableConnection class in my modify.py. A user should edit his name in a GUI-based app, and it should automatically be changed in the ldap. from ldap3 import Server, Connection, ALL, MODIFY_REPLACE class ModifiableConnection(object): def __init__(self, connection, dn): self.conn = connection self.dn = dn def modify_attr(self, attrname, values): modlist = [(MODIFY_REPLACE, attrname, values)] self.conn.modify(dn, self.conn.user, modlist) @property def firstname(self): pass @firstname.setter def firstname(self, val): self.modify_attr('givenName', [val]) @property def lastname(self): pass @lastname.setter def lastname(self, val): self.modify_attr('sn', [val]) mod_con = ModifiableConnection(request.user.connection, request.user.dn) This is how I call it (views.py): def edit_profile(request): if request.method == 'POST': form = EditProfileForm(request.POST, instance=request.user) if form.is_valid(): mod_con = ModifiableConnection(request.user.connection, request.user.dn) mod_con.firstname = request.POST['first_name'] mod_con.lastname = request.POST['last_name'] form.save() return redirect(reverse('accounts:view_profile')) else: form = EditProfileForm(instance=request.user) args = {'form': form} return render(request, 'accounts/edit_profile.html', args) and this is the error I get: mod_con = ModifiableConnection(request.user.connection, request.user.dn) NameError: name 'request' is not defined The error is in my modify.py. I do not really know if I have to import anything or If I am missing something. If you have any idea, do not hesitate to post … -
Django model inheritance with arguments
I'm trying to define a base, abstract model for "attached images", that I can then hook up to any other model with a foreign key relation to it. My idea is to use an argument that defines which Model will the AttachedImage model be hooked up to through a ForeignKey relation. I have my abstract model defined like so: class AttachedImage(models.Model): parent_object = None uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE) image = models.ImageField(upload_to=image_path) # TO FIX: añadir la ruta is_default = models.BooleanField(default=False) class Meta: abstract = True def __init__(self, parent_model): super().__init__(self) self.parent_object = models.ForeignKey(parent_model, on_delete=models.CASCADE) And then I try to inherit from it like this: class VehicleImage(AttachedImage(Vehicle)): pass But when I try to run my migrations, I get this error: class VehicleImage(AttachedImage(Vehicle)): TypeError: __init__() takes 2 positional arguments but 4 were given First off, why am I getting this error? And second, and much more important: is this the right pattern to achieve my goal? -
sublime text: Django how to view source of imports
I have django project inside a python virtualenv. In one of my models i have: from django.contrib.auth.models import AbstractUser, BaseUserManager I want to see the source code of AbstractUser and BaseUserManager is it possible that sublime text knows where they are located and show me -
How to submit a mock url? (Django)
I have a problem, I can't test my forms by using requests. add_playlist = self.client.post(reverse('new-playlist'), data={'url': 'https://dailyiptvlist.com/dl/it-m3uplaylist-2018-03-11-1.m3u'}) I need to create a mock response for 'https://dailyiptvlist.com/dl/fr-m3uplaylist-2018-03-06.m3u' so it will be acceptable to test adding a channel while the url isn't maintained. So, I need to create a mock response for this url. I can't imagine how to do this. Please help me. -
response.get('X-Frame-Options') on stripe failed payment
I am trying to customize stripe payment gateway using elements, I followed the documentation provided on stripe website and on this tutorial http://zabana.me/notes/how-to-integrate-stripe-with-your-django-app.html. I managed to get my payment charged and I am now testing for defect card such as Charge is declined with an expired_card code that stripe provide but I am getting an error that I do not even understand so hard for me to debugg what is going on ... error : if response.get('X-Frame-Options') is not None: AttributeError: 'tuple' object has no attribute 'get' my code: payment-views.py: from Authentication_project import settings from django.views.generic import TemplateView from django.shortcuts import redirect import stripe stripe.api_key = settings.STRIPE_SECRET_KEY class payment_form(TemplateView): template_name = "transaction.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['stripe_key'] = settings.STRIPE_PUBLIC_KEY return context def checkout(request): if request.method == "POST": token = request.POST.get("stripeToken") print(token) print(request.user.email) try: charge = stripe.Charge.create( amount=2000, currency="usd", source=token, description="SoftScores Team Assessment", receipt_email=request.user.email, ) except stripe.error.CardError as ce: return False, ce else: return redirect('index') Any idea how to solve it ? -
Trouble attaching postgres database to Heroku application
I have a Django application with PostgresQL database. I have successfully deployed the application on heroku (myapp), but getting trouble attaching the local database to it. To attach the local database to my Heroku application (myapp), I followed these steps 1.Created database (db-name) dump file sudo pg_dump -U postgres db-name > db-name.dump 2.Uploaded dump file online where its accessible through link https:url/db-name.dump on following the above link db-name.dump file gets downloaded 3.Used pg:backups:restore command to restore the backup on my heroku application heroku pg:backups:restore 'https:url/db-name.dump' DATABASE_URL --confirm myapp On issuing the above pg:backups:restore command, I am getting an error Restoring... ! ▸ An error occurred and the backup did not finish. ▸ ▸ waiting for restore to complete ▸ pg_restore: [archiver] did not find magic string in file header ▸ pg_restore finished with errors ▸ waiting for download to complete ▸ download finished successfully ▸ ▸ Run heroku pg:backups:info r004 for more details. Any guessed whats going on here.. -
Django: Multiple values in Radio Select Form
I've got a radio select form that displays addresses that the user has saved. Currently, when the user visits the "select address" template, they are only shown the 'street' field for each address that they've saved. This is controlled by the "return self.address" line below as I've established through testing. I'd like user to see the street, city, and state of each of the addresses that he/she has saved. From the list, they'll select the radio button next to the address that they'd like to ship to. models.py class Order(models.Model): user = models.ForeignKey(UserCheckout, null=True, on_delete=models.CASCADE) billing_address = models.ForeignKey(UserAddress, related_name='billing_address', null=True, on_delete=models.CASCADE) order_id = models.CharField(max_length=20, null=True, blank=True) class UserAddress(models.Model): street = models.CharField(max_length=120, null=True, blank=True) city = models.CharField(max_length=120) state = models.CharField(max_length=120, choices=STATE_CHOICES, null=True, blank=True) def __str__(self): return self.address I'm using a class based view. Here are some functions within that view that I belive are controlling the output within the template: def get_addresses(self, *args, **kwargs): user_check_id = self.request.session.get("user_checkout_id") user_checkout = UserCheckout.objects.get(id=user_check_id) b_address = UserAddress.objects.filter(user=user_checkout) return b_address def get_form(self, *args, **kwargs): form = super(AddressSelectFormView, self).get_form(*args, **kwargs) b_address = self.get_addresses() form.fields["billing_address"].queryset = b_address return form Within the template, I've got the following: {% csrf_token %} {{ form }} <input type='submit' value='Select' /> </form> I … -
Serializing nested object in Django Rest Framework
I'm trying to serialize a json that must have a token string and a nested user object (which has its own serializer). I'd like to have something like: class LoginResponseSerializer(serializers.Serializer): token = serializers.CharField(read_only=True) user = UserSerializer(read_only=True) But this is not working, I don't know how should I create this serializer and how to pass the data. Thank you very much -
django: Create custom user with email as login and other fields
I am using Django 2.0.3. I want email as the username and also First Name and Last Name as required fields. Apart from this,later the user can update the gavtar (models.ImageField) and aboutme (models.CharField(max_length=140)), dateofbirth, country, city. So what is the best way to do this in Django. -
Use raw URL or static URL for images?
Is there any difference when using: <img src="{% static 'images/someimage.png' %}" and <img src="https://s3.us-east-2.amazonaws.com/my-bucket/static/images/someimage.png" -
How does django differentiate between 2 management forms on same page?
I have 2 formsets based on 2 different models. While debugging a validation problem where my formsets were failing is_valid validation (see errors below): (Pdb) FormsetItem.errors [{'id': ['Select a valid choice. That choice is not one of the available choices.']}, {'id': ['Select a valid choice. That choice is not one of the available choices.']}, {'id': ['Select a valid choice. That choice is not one of the available choices.']}, {'id': ['Select a valid choice. That choice is not one of the available choices.']}, {'id': ['Select a valid choice. That choice is not one of the available choices.']}, {'id': ['Select a valid choice. That choice is not one of the available choices.']}, {'id': ['Select a valid choice. That choice is not one of the available choices.']}, {'id': ['Select a valid choice. That choice is not one of the available choices.']}, {'id': ['Select a valid choice. That choice is not one of the available choices.']}, {'id': ['Select a valid choice. That choice is not one of the available choices.']}, {'id': ['Select a valid choice. That choice is not one of the available choices.']}, {'id': ['Select a valid choice. That choice is not one of the available choices.']}, {'id': ['Select a valid choice. That … -
how to get item from select option html Django?
I tried to implement 2nd dropdown based on the 1st dropdown and get the item from two dropdowns. <select class="js-example-basic-single" name="select1" id="select1"> <option value="1">Disease</option> <option value="2">Drug</option> <option value="3">Problem</option> <option value="4">Test</option> <option value="5">Treatment</option> </select> <select class="js-example-basic-single" name="select2" id="select2"> {% for item in content1 %} <option value="1" itemY="{{item}}" >{{item}}</option> {% endfor %} {% for item in content2 %} <option value="2" itemY="{{item}}" >{{item}}</option> {% endfor %} {% for item in content3 %} <option value="3" itemY="{{item}}" >{{item}}</option> {% endfor %} {% for item in content4 %} <option value="4" itemY="{{item}}">{{item}}</option> {% endfor %} {% for item in content5 %} <option value="5" itemY="{{item}}">{{item}}</option> {% endfor %} </select> and in JS: <script type="text/javascript"> $("#select1").change(function() { if ($(this).data('options') === undefined) { /*Taking an array of all options-2 and kind of embedding it on the select1*/ $(this).data('options', $('#select2 option').clone()); } var id = $(this).val(); var options = $(this).data('options').filter('[value=' + id + ']'); $('#select2').html(options); $("#select2 option:selected").text(); var conceptName = $('#select2').find(":selected").text(); }); </script> In views.py f2 = request.POST.get('select1',False) f3 = request.POST.get('select2',False) it return the value not item............ I want the item. Based ont he -
Getting error of to many arguments were given - django project
I have a django project with a django app called users. in the projects url settings I have it connected to the users app url python file. I want to connect them and have the urls base off of the url patterns in the users urls file.. WHile doing so, I am getting an error that there were to many arguments that were being passed and I have no idea what it means or any reference as to how I can fix this error. This is the main error that I am getting I am getting the error when i run the following command python manage.py runserver Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x108629378> Traceback (most recent call last): File "/Users/omarjandali/anaconda3/envs/MySplit/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Users/omarjandali/anaconda3/envs/MySplit/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 121, in inner_run self.check(display_num_errors=True) File "/Users/omarjandali/anaconda3/envs/MySplit/lib/python3.6/site-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/Users/omarjandali/anaconda3/envs/MySplit/lib/python3.6/site-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/Users/omarjandali/anaconda3/envs/MySplit/lib/python3.6/site-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/Users/omarjandali/anaconda3/envs/MySplit/lib/python3.6/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "/Users/omarjandali/anaconda3/envs/MySplit/lib/python3.6/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "/Users/omarjandali/anaconda3/envs/MySplit/lib/python3.6/site-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/omarjandali/anaconda3/envs/MySplit/lib/python3.6/site-packages/django/urls/resolvers.py", line 536, in url_patterns patterns = … -
What is happening when I run `python manage.py test` and on which port the django test server is listening?
I wrote a test for for a signup feature. When I do manually, the signup process sends email to the user, but when I do it with test script the email is not sent. So I was wondering what is happening inside? And what is the port for the test server? Is there any relation for the test server to send mail with it? Can I specify the test server port? -
How do you call a user defined function in views.py DJANGO
The requirement is to display the logged in username and his role in the organization in all the pages at the top right corner. The role can be identified by the permissions he is given. My approach: I thought of creating a user-defined function in views.py and call it in each and every other function. The function that I create should check the current user's permissions and based on them his role should be decided. All these details must be sent to base.html so that it will render and display the username and his role every time the page is loaded. Any suggestions on other approaches are welcomed and if my approach is entirely wrong please let me know. -
Django Session Data lost after clearing browser Data
Im using django 1.11.7 and the session objects to store data from users that are login works fine but when I clear the browser data the session object is lost, as far as I know if you use this 'django.contrib.sessions', you're setup to save the session object in the DB and im able to see Data in the Db each time someone logs in but the problem is that for some reason I cant use this data when i fetch it maybe is the way I fetch the data because the data is being saved in the DB here is how I fetch the data in the views: this is the normal way that works until I clear the browser data in_test = request.session['in_test'] then in some reading they suggest that even if the data is being saved in the db some cookies are created to match that data and they use this to some how also get the data from the session obj but same result: in_test = request.session.get('in_test') but at least there is a hint that the browser cookie is obviously missing since I cleared but the question is how to pair or directly fetch the session object … -
how to instantiate recursive foreign key in django?
class Notebook(models.Model): title=models.CharField(max_length=10) father = models.ForeignKey('self', on_delete=models.CASCADE) How to use it? n1=Notebook(title='a', father='???') n2=Notebook(title='b', father=n1) how to set the value for father attribute of n1? -
How to override Django admin `change_list.html` to provide formatting on the go
In Django admin, if I want to display a list of Iron and their respective formatted weights, I would have to do this. class IronAdmin(admin.ModelAdmin): model = Iron fields = ('weight_formatted',) def weight_formatted(self, object): return '{0:.2f} Kg'.format(object.weight) weight_formatted.short_description = 'Weight' I.e: 500.00 Kg The problem with this however is that I would have to write a method for every field that I want to format, making it redundant when I have 10 or more objects to format. Is there a method that I could override to "catch" these values and specify formatting before they get rendered onto the html? I.e. instead of having to write a method for each Admin class, I could just write the following and have it be formatted. class IronAdmin(admin.ModelAdmin): model = Iron fields = ('weight__kg',) def overriden_method(field): if field.name.contains('__kg'): field.value = '{0:.2f} Kg'.format(field.value) I.e: 500.00 Kg