Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework and AWS Cognito
Currently, I am using django-warrant to utilize cognito (JWT) based authentication to access APIs. After creating pool and app, I have set up following in my settings file: AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'django_warrant.backend.CognitoBackend', ] COGNITO_USER_POOL_ID = 'poolid' COGNITO_APP_ID = 'app id' COGNITO_ATTR_MAPPING = { 'email': 'email', 'given_name': 'name', 'family_name': 'last name', } COGNITO_CREATE_UNKNOWN_USERS = False AWS_ACCESS_KEY_ID = 'access_key' AWS_SECRET_ACCESS_KEY = 'access_key_secret' In Midddleware, I have added: MIDDLEWARE = [ ............., 'warrant.django.middleware.APIKeyMiddleware', .............., ] In Installed apps, I have added, INSTALLED_APPS = [ ............, 'django_warrant', ............, ] In urls.py, I have added: path('accounts/', include('django_warrant.urls')) When I try to hit accounts/login url, it is throwing the error of missing templates. As I am using it for the first time, I am clueless how to proceed further with it to map django users with cognito users. I have searched tutorials related to this but found None. Please provide me guidance so that I can manage to proceed further. -
Django ORM When check
I would like to make a query to know whether particular user has relation with specific object. As for example: user = User.objects.first() modelA.objects.annotate(is_following_by_user=Case(When( XXXXXX, then=Value(True)), default=Value(False), output_field=BooleanField()))) XXXX should be replaced with code with checks whether followers_set.values_list('id', flat=True) contains id of given user. -
How to perform queries in django modelform?
I tried this in my modelform: class Ledgerform(forms.ModelForm): class Meta: model = ledger1 fields = ('name', 'group1_Name') def __init__(self, User, Company, *args, **kwargs): self.User = kwargs.pop('User', None) self.Company = kwargs.pop('Company', None) super(Ledgerform, self).__init__(*args, **kwargs) self.fields['name'].widget.attrs = {'class': 'form-control',} self.fields['group1_Name'].queryset = group1.objects.filter(User= self.User,Company = self.Company) In my views.py I have done something like this: class ledger1ListView(LoginRequiredMixin,ListView): model = ledger1 paginate_by = 15 def get_queryset(self): return ledger1.objects.filter(User=self.request.user, Company=self.kwargs['pk']) class ledger1CreateView(LoginRequiredMixin,CreateView): form_class = Ledgerform def form_valid(self, form): form.instance.User = self.request.user c = company.objects.get(pk=self.kwargs['pk']) form.instance.Company = c return super(ledger1CreateView, self).form_valid(form) I want to perform the the same query that I have passed in my ledger1ListView by using queryset in my modelform but my kwargs.pop is not returning the current user or the company... This is my models.py: class ledger1(models.Model): User = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True) Company = models.ForeignKey(company,on_delete=models.CASCADE,null=True,blank=True,related_name='Companys') name = models.CharField(max_length=32) group1_Name = models.ForeignKey(group1,on_delete=models.CASCADE,blank=True,null=True) Do any one know what I am doing wrong in my code? Thank you in advance -
How to handle different versions of design?
We have customers which can create their own profile page. The profile page has a cover image with a specific size. Some customers have already uploaded cover images in the specific size. In the next version of our we application (build in Django) we have made some design improvements which includes the change of the cover image size. What's the best way to handle this situation so old customers have the old design so the cover image still fits, but new customers get the new design? -
unsupported type for timedelta minutes component: F
My model: class ReigstrationToken(models.Model): token = models.CharField(_('Registration Token'), blank=False, null=False, max_length = 16, db_column='token', unique = True) valid_from = models.DateTimeField(_('Valid From'), default=timezone.localtime(timezone.now()), db_column='valid_from', blank=False, null=False) validity_period = models.IntegerField(_('Validity Period'), blank=False, null=False, default=30, db_column='validity_period', help_text = _('(Validity Period in Minutes from Valid From)')) Now I want to filter tokens which are not expire. So my query is like this: ReigstrationToken.objects.filter(valid_from__lt=datetime.now() - timedelta(minutes=F('validity_period'))) And it raises TypeError: unsupported type for timedelta minutes component: F I tried all possible solutions but that didn't work for me. ReigstrationToken.objects.filter(valid_from__lt=datetime.now() - timedelta(minutes=1)*F('validity_period')) It also raises TypeError: Connector must be + or -, not * Does anyone know whats wrong with this query? -
Error was: No module named util in django
import os import mongoengine DATABASES = 'default': { 'ENGINE': 'django_mongodb_engine', 'NAME' : 'newdb', 'USER': 'admin', 'PASSWORD': 'admin', 'HOST': '127.0.0.1', 'PORT': '27017', 'SUPPORTS_TRANSACTIONS': False, }, I'm getting error No module named util ,please help me and Thnak you in advance. -
Add files in Django of all extensions
I am trying to upload a file in django irrespective of its extension. I have followed Documentation But i am only able to store pdf with its correct data. My code is class FileUploadView(APIView): parser_classes = (FileUploadParser,) def put(self, request, filename, id=None, format=None): file_obj = request.FILES['file'] print(file_obj) ext = file_obj.name.split('.') now = round(datetime.datetime.now().timestamp()) paths = str(id)+ '/'+ str(now)+'.'+ext[1] path = default_storage.save(paths, file_obj) print(default_storage.url(path)) tmp_file = os.path.join(settings.MEDIA_ROOT, path) -
One User model for Auth and User Django
Im using the Django auth feature to create users. I also want to extend the user to add things like profile pictures and other information. My problem is that I now have to User models to manage. One from Auth and one from the model I created. Anyway to consolidate into 1 model please? from urls.py: path('accounts/',include('django.contrib.auth.urls')) from models.py: class User(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) firstName = models.CharField(max_length=200) lastName = models.CharField(max_length=200) image= models.ImageField(upload_to='profile_image',default='profile_image/SSMILE.jpg') from views.py class SignUp(generic.CreateView): form_class = UserCreationForm success_url = reverse_lazy('login') template_name = 'signup.html' As you can see I have 2 User models. I have to end up creating the auth user through sign up then in my homepage view do this: if str(request.user) != "AnonymousUser": try: getuser = User.objects.get(user=request.user) print(getuser) except User.DoesNotExist: newUser= User(user=request.user,firstName=request.user,lastName="change") newUser.save() which is a hack I want to avoid doing. Thanks -
Django CSRF verification failed for a form created with AJAX
in my django project i create a huge part of my html page using javascript DOM (with AJAX calls). In one template in particular i create a form inside a lot of other things like this one: var jfrm = document.createElement("FORM"); jfrm.method = "post"; .... jfrm.addEventListener ("submit", function() { postJraEvent(data[index].id,data[index].t_pid,document.getElementById('txt2').value,document.getElementById('txt3').value,document.getElementById('txt5').value); }); whell, the function "postJraEvent" is another js func that using ajax execute some kind of tasks function postJraEvent(id_ev, th_id, j_issue, j_comm, j_file) { $.ajax({ type: "POST", url: "jirapost", data: {evid: id_ev, tid: th_id, jissue: j_issue, jcom: j_comm, jfile: j_file}, success: function (data) { $.each(data, function (index) { j_error = document.getElementById("laberr"); j_error.innerHTML = data[index].j_err; }); } }); } All done, but when i execute my code this error return: Forbidden (403) CSRF verification failed. Request aborted. The problem is i cannot insert the {% csrf_token %} inside the part of my template because i don't have it. (it was created dinamically by javascript) How can i resolve the CSRF verification failed in a case like this? Thanks in advance -
How do I use Loggly and Django to log a unique ID per session?
I have my Django logging setup like this (below). The filter for request ID comes from here, https://github.com/dabapps/django-log-request-id. I set up Loggly following the tutorial here: https://www.loggly.com/docs/python-http/. However, it appears their provided config file overrides the standard formatter, meaning it does not include request_id. Is there a way I can use both request_id and Loggly? Basically, I would like Loggly to always log a request_id which is unique and comes from the plugin log_request_id.filters.RequestIDFilter. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'request_id': { '()': 'log_request_id.filters.RequestIDFilter' } }, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, 'simple': { 'format': '%(levelname)s %(message)s' }, 'json': { 'format': '{ "loggerName":"%(name)s", "timestamp":"%(asctime)s", "fileName":"%(filename)s", "logRecordCreationTime":"%(created)f", "functionName":"%(funcName)s", "levelNo":"%(levelno)s", "lineNo":"%(lineno)d", "time":"%(msecs)d", "levelName":"%(levelname)s", "message":"%(message)s"}', }, 'standard': { 'format': '%(levelname)-8s [%(asctime)s] [%(request_id)s] %(name)s: %(message)s' }, }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'filters': ['request_id'], 'formatter': 'standard', 'stream': sys.stdout, }, 'loggly': { 'level': 'DEBUG', 'class': 'loggly.handlers.HTTPSHandler', 'filters': ['request_id'], 'formatter': 'standard', 'url': 'https://logs-01.loggly.com/inputs/TOKEN/tag/python', }, }, 'loggers': { 'django': { 'handlers': ['console', ], 'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'), }, 'root': { 'handlers': ['loggly', ], 'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'), } } } -
No Reverse Match error No idea what is causing
I am having some trouble rendering the view for editing profile. I'm not sure what is causing it. This is my models.py class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) address = models.CharField(max_length=100) def __str_(self): return self.user.username @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) @receiver(post_save, sender=settings.AUTH_USER_MODEL) def save_user_profile(sender, instance, **kwargs): instance.userprofile.save() My views.py class ProfileEditView(generic.UpdateView): model = UserProfile form_class = UserProfileForm template_name = 'user_profile.html' def get_object(self,*args, **kwargs): user = get_object_or_404(settings.AUTH_MODEL_USER, pk=self.kwargs['pk']) return user.userprofile def get_sucess_url(self, *args, **kwargs): return reverse('edit-user') My urls.py is url(r'^profile/(?P<pk>\d+)/$',views.ProfileEditView.as_view(),name='edit-user') and in my html code I wrote <a class="dropdown-item" href="{% url 'edit-user' %}"> Profile </a> It doesn't give any errors aside from the runtime error of NoReverseMatch with error message Reverse for 'edit-user' with no arguments not found. 1 pattern(s) tried: ['users/profile/(?P\d+)/$'] -
Django: CsrfToken problems with POSTMAN
https://i.imgur.com/auzP67U.png: https://i.imgur.com/auzP67U.png : https://i.imgur.com/ItTNAsV.png I'm sending post request with headers (csrf token), but django says that there is no csrf -
Django Not null constraint failed while posting json data to models
hey i tried this code but still have an error that is Not Null constraint failed i know this is because of my cheque_no that is unique type but how could i remove this error i did not remove my cheque_no is unique because its required. #views.py @csrf_exempt def jsdata(request): table_data = json.loads(request.POST.get('MyData')) # print(table_data) r_data = { 'success': True, } for data in table_data: # Since you are just creating objects you don't need to save created object in a variable. Mvouchar.objects.create(bill_no = data['BillNo'], bill_details=data['BillDetails'],am=data['Amount']) # r_data['success'] = False # IMO Views responding to ajax requests should send JsonResponse if r_data['success']: r_data['msg'] = 'Data Saved' else: r_data['msg'] = 'Not all Data Saved' return JsonResponse(r_data) #models.py class Mvouchar(models.Model): related = models.ForeignKey(Signs, on_delete=models.CASCADE, null=True, blank=True) bill_no = models.CharField(max_length=8000, null=True, blank=True) bill_details = models.CharField(max_length=10000, null=True, blank=True) am = models.CharField(max_length=30000, null=True, blank=True) cheque_no = models.PositiveIntegerField(validators=[MaxValueValidator(6)], unique=True, help_text='integers only') #myjson $("#btnjson").click(function () { var array1 = []; $("tbody tr").each(function () { var firstTableData = {}; firstTableData.BillNo = $(this).find('td').eq(0).text(); firstTableData.BillDetails = $(this).find('td').eq(1).text(); firstTableData.Amount = $(this).find('td').eq(2).text(); array1.push(firstTableData); //} }); alert(JSON.stringify(array1)); $.ajax({ type: "POST", url: "/jsondata/", dataType: 'json', data: {MyData: JSON.stringify(array1)}, success: function(msg){ alert(msg); } }); return false; } ); }); -
Git Clone - Python Forum
I cloned https://github.com/nitely/Spirit - awsome forum by the way. Because I want to use it as a boilerplate to make my own forum... First thing is I want to find out how to replace everything that say's Spirit , with whatever I decide on my blog name. How Can I find in the cloned file's where to replace them - I have already ran the webpage locally and 'inspected' the element.. just cant trace back to the exact html/css/python/js file. Also , I am a newb, this is a common or "ok" thing to do correct - clone someones code and use it as a boiler for another project? I will give credit. -
Django : Error when starting supervisorctl : ImportError at / No module named ___
I have a Django app that I restart with the commands ubuntu@ip-1234:~$sudo supervisorctl restart myapp myapp: stopped myapp: started ubuntu@ip-1234:~$ sudo systemctl restart nginx ubuntu@ip-1234:~$ sudo systemctl reload nginx However, when I got to my domain (debug=True) I get the error: ImportError at / No module named pdfrw However, if I navigate back to my app and try to download the package ubuntu@ip-1234:~$sudo -i -u myapp myapp@ip-1234:~$ pip install pdfrw Requirement already satisfied: pdfrw in ./.local/lib/python2.7/site-packages I'm not sure why it isn't finding this package in production. I used to be able to get this working, I imagine something is wrong with where my packages are being installed. My application works fine if I remove the from pdfrw import PdfDict line I have in my code. Perhaps something to do with permissions? -
Django Migrate from Char Field to Integer Field?
I changed one of my CharField in models.py:: models.CharField(max_length=128, blank=True) into IntegerField --> models.IntegerField(default=0) I have data for that field, mainly empty strings("") or integer as strings(eg: "10"). So I would like to convert these strings to integer while migrate. eg:: if blank string("") convert to 0, else convert to integer. How can i achive that while i do ./manage.py migrate command? here is the migration file created using ./manage.py makemigrations:: # Generated by Django 2.1.2 on 2018-10-25 04:57 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('dashboard', '0002_auto_20181024_1544'), ] operations = [ migrations.AlterField( model_name='aclpermissions', name='ordering', field=models.IntegerField(default=0), ), migrations.AlterField( model_name='submenus', name='ordering', field=models.IntegerField(default=0), ), migrations.AlterField( model_name='subsubmenus', name='ordering', field=models.IntegerField(default=0), ), ] When i run ./manage.py migrate i got error :: psycopg2.DataError: invalid input syntax for integer: "" because there are fields with empty strings "". -
Stopping IDM from accessing the file on website Using Python Script?
I am want to publish my tutorial Videos in my website.Is there anyway to stop the Download the videos from IDM. -
I need to utilize the BooleanField on the front end
I want the user to use the BooleanField to pick which meals said animal eats (breakfast, lunch, dinner, a combination of these possibly). And if the checkbox is checked I then want it to produce a schedule on screen where you can check off if the animal has eaten said meal that day. The issue is whenever I add my schedule, it will not produce a schedule where I can check off if the animal has eaten. (I know this explanation may sound confusing). Here are my models for Animal and Schedule: class Animal(models.Model): """The actual animal, embeded in animaltype""" animal_type = models.ForeignKey(AnimalType, on_delete=models.CASCADE) name = models.CharField(max_length=60, default='') date_added = models.DateTimeField(auto_now_add=True) def __str__(self): if len(self.name)>20: return self.name[:20] + "..." else: return self.name class Schedule(models.Model): """Model for animal eating schedule""" animal = models.ForeignKey('Animal', on_delete=models.CASCADE) breakfast = models.BooleanField(default=False) lunch = models.BooleanField(default=False) dinner = models.BooleanField(default=False) Here is my views for adding a schedule and viewing it(on the animal view): @login_required def new_schedule(request, animal_id): """add a new schedule for the animal""" animal = Animal.objects.get(id=animal_id) if request.method != 'POST': #create 3 different checkboxes for the meals and if they check it, add that meal to their schedule form = ScheduleForm() else: #POST data submitted form … -
aws beanstalk can't find installed django module
I'm trying to deploy a Django app to AWS beanstalk however I run into this error. from django.core.wsgi import get_wsgi_application [Fri Oct 26 03:22:21.523128 2018] [:error] [pid 4511] [remote 127.0.0.1:2336] ModuleNotFoundError: No module named 'django' [Fri Oct 26 03:22:22.526577 2018] [:error] [pid 4511] [remote 127.0.0.1:2336] mod_wsgi (pid=4511): Target WSGI script '/opt/python/current/app/adminsite/wsgi.py' cannot be loaded as Python module. Further down the log file it shows django was successfully installed. [2018-10-26T03:41:56.170Z] INFO [6032] - [Application update app-61bb-181025_214141@8/AppDeployStage0/AppDeployPreHook/03deploy.py] : Completed activity. Result: Requirement already satisfied: django==2.1.2 in /opt/python/run/venv/lib64/python3.6/site-packages (from -r /opt/python/ondeck/app/requirements.txt (line 1)) Requirement already satisfied: psycopg2==2.7.5 in /opt/python/run/venv/lib64/python3.6/site-packages (from -r /opt/python/ondeck/app/requirements.txt (line 2)) Requirement already satisfied: pytz==2018.6 in /opt/python/run/venv/lib/python3.6/site-packages (from -r /opt/python/ondeck/app/requirements.txt (line 3)) What might be causing this issue? -
json to django request
Trying to pass custom json data using jquery to django but django cannot receive data correctly. data sample: var data = {}; data.mylist = [{'a':'b'},{'a':'b'}]; data.myvar = 'something'; data.action = 'submit_invoice' $.post(window.invoice_url, data, function(res){ console.log(res) }); Django view: def foo(request): mylist = request.POST.getlist('mylist',None) myvar = request.POST.get('myvar', None) print(mylist) print(myvar) print(request.POST) the print is something, [] and < QueryDict: {'action': ['submit_invoice'], 'mylist[1][a]': ['b'], 'myvar': ['something'], 'mylist[0][a]': ['b']} > and django cannot get mylist correctly. -
Django Rest Framework Send Data to View Without Serializer
I have a Magic model in my application. I need the user who is attached to this model to go to their email address to verify something before they can access the information. This should happen over a RESTful API. The problem is, the user should not necessarily be logged in to access this feature (for design decisions I had no control over). I have implemented the logic for generating the necessary information and sending the email (only if such an email is registered), authentication once the emailed information is accessed, etc. My question: How do I implement a view that takes a user email in the body (or url)? Approach 1: create a url /magic_api/v1/tdbverification/(?P<email>[\w.@]+)/ and extract the email address and send the email. Problem with 1: I cannot seem to extract the email and I need to return a json object without having a serializer Approach 2: Create a view that takes body: {"email": "<email@here.com>"} Problem with 2: This requires a serializer without a model (as this view is just for sending the email, it does not change model objects). I tried working with a serializers.Serializer class but could not figure out how to incorporate the email sending … -
django-admin-bootstrap works but result are off
I have just upgraded my django admin with django-admin-bootstrap What I did: $ pip install bootstrap-admin and INSTALLED_APPS = ( # ... 'bootstrap_admin', # always before django.contrib.admin 'django.contrib.admin', # ... ) The result below. Can any one point out why the result are off? It looks like the boostrap css is overwritten by something else?! I'm not really sure how this works. -
Correct way to query the children of a child
I have a Homepage with a child of homepage called VideoIndex and then a child of VideoIndex called Videos. Would this be the most efficient way to query those children onto my homepage? def courses(self): return VideoPage.objects.all() Models.py class HomePage(Page): def courses(self): return VideoPage.objects.all() class VideoIndexPage(Page): header = RichTextField(blank=True) body = RichTextField(blank=True) class VideoPage(Page): header = RichTextField(blank=True) body = RichTextField(blank=True) videoURL = models.CharField(blank=True, max_length=250) Homepage.HTML {% for video in page.courses %} <div class="col-lg-3 mb-5"> ... </div> {% endfor %} -
Create object recursive
How i can create object recursive on Django.. This is my code: name = request.POST.get('name') description = request.POST.get('description') category = request.POST.get('category') category = Categoria( name = nombre, name = descripcion, parent = category ) category.save() this code return error: Cannot assign "1L": "Category.parent" must be a "Category" instance. Please some one suggest..thanks -
Setting different list_display options for different models in the same admin
I have multiple models registered to an admin from django.contrib import admin from .models import User, Claim, Caption @admin.register(User, Claim, Caption) class ScopeAdmin(admin.ModelAdmin): pass I want to set the list_display property but that value is different for each model. Is there a way around this or do I need to create an admin per model?