Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError - 'RawQuerySet' object has no attribute 'exclude'
I am using raw query because i wanted `select unique rows based on single distinct column - Django context['reports'] = TimesheetEntry.objects.raw('SELECT * FROM timesheet_entry t1 INNER JOIN ( SELECT timesheet_users_id, MAX(id) AS latest_id FROM timesheet_entry GROUP BY timesheet_users_id ) t2 ON t1.timesheet_users_id = t2.timesheet_users_id AND t1.id = t2.latest_id WHERE timesheet_is_running=False') context['reports'] = context['reports'].exclude(pk=36) It is giving me error - AttributeError - 'RawQuerySet' object has no attribute 'exclude' How can i exclude? Or How to Convert above RawQuerySet to QuerySet -
Is it possible to find the username of a client pc using python ?(Not server's username)
Is it possible to find the username of a client pc using python ?(Not server's username) print(socket.gethostname()) it will return the server's username. I want client PC's user name. Thanks in advance. -
django authentication new user created unnecessarily - auth0
So I'm trying to integrate auth0 with my existing django app and sqlite database. Login is working, the problem is I can't get the usernames inputted by auth0 through request to map on to the ones already present in my db. This is the auth0 backend and right now I've hardcoded to return eq3 and 21 respectively for username and user_id. def get_user_details(self, response): # Obtain JWT and the keys to validate the signature id_token = response.get('id_token') jwks = request.urlopen('https://' + self.setting('DOMAIN') + '/.well-known/jwks.json') issuer = 'https://' + self.setting('DOMAIN') + '/' audience = self.setting('KEY') # CLIENT_ID payload = jwt.decode(id_token, jwks.read(), algorithms=['RS256'], audience=audience, issuer=issuer) return {'username': 'eq3', 'user_id': 21} However when I go to views.py and put a print(request.user.username) and print(request.user.id) it prints eq306fa23456g204e8c and 51. When I go into my database, I see that it has indeed created a new user in the auth_user table, even though there's already a user with eq3 and user id 21 in the same table. Furthermore, if I input a random username such as foobar, it will still create a new user, but it won't add the nonsensical alphanumeric string to the username, just foobar. What is going on here? How can I get … -
How to serve wordpress themes when a user creates a page
What is the best way to serve wordpress templates to user accounts with django? Kind of like how shopify lets users pick the template of their website and then make their account that template. I've created the templates but can't seem to figure out how to update each users account specifically with the templates. I just need help with the concept not the code. -
Django: handler403 doesn't work, but 404 does
Here is content of MyProj/urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('general.urls')), # Main app ] handler403 = 'general.views.handler403' handler404 = 'general.views.handler403' As you can see, both handlers point to the same view, and first one, which I need most, doesn't work! For example, data of other's user at /obj/12 shows default browser 403 page: [22/Jan/2019 08:39:14] "GET /obj/12 HTTP/1.1" 403 0 But the second one works well and shows correct page (when try to access some not existing data at /obj/768). Why and how can I solve it? The debug mode is off. My Django version is 2.0.6 -
Exclude All and keep one Django Query
This is my Query where i am getting all users who are manager and employee. User.objects.exclude( Q(userprofile__user_is_deleted = True)| Q(userprofile__user_company__company_is_deleted=True) ).filter( Q(userprofile__user_company =company_name) ) Now i want to query such that when logged in user is manager, then exclude all manager except him (the logged in user which is manager) if request.user.userprofile.user_role.id == 3: # 3 for manager context['users'] = context['users'].exclude() I am not getting how to query. How can i do it. -
Container's content is ignoring the navbar and main banner in mobile view
Good Day Everyone! So I recently finished my first website, however I'm busy polishing it since there is some compatibility issues with some screen sizes. There is one thing I haven't been able to figure out or fix and that is the fact that in my teams page if you look at it in a mobile view (either through a mobile or chrome dev tools) you will notice that my container is ignoring my banner and navbar. This results in a huge space at the bottom of the page. The only solution I've thinked of is perhaps creating margin-top for the container but that would result in a lot of media queries. Is there perhaps a reason why it is ignoring it or a better solution? Thank You! The website: SeveregamingZA The HTML: <html lang="en"> <head> <!-- Title of Page --> <title> Teams - Severe Gaming </title> <!-- Bootstrap CDN and requirements --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css"> <link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Custom CSS --> <link rel="shorcut icon" type="image/png" href="/static/images/favicon.png" /> <link rel="stylesheet" type="text/css" href="/static/css/style.css"> <link rel="stylesheet" href="/static/css/teams.css"/> <script src="/static/scripts/teams.js"></script> … -
How to extend a user model without use profile method?
I want to add a column to django auth_user table. But I do not want to create a new table. As the document peovided for extending User model, there are four ways. proxy model Add a oneToOne field Creating a Custom User Model Extending AbstractUser Creating a Custom User Model Extending AbstractBaseUser It works some time. But How could I add a field to the auth user model it provied? -
How to apply filter to Django rest-framework serializer field?
Say I have three models like these: class Message(models.Model): text = models.TextField() img = models.ForeignKey('Image') class Image(models.Model): deleted = models.BooleanField() url = models.URLField() msg = models.ForeignKey('Message') class Tag(models.Model): deleted = models.BooleanField() name = models.CharField(max_length=10) msg = models.ForeignKey('Message') When serializing Message, I need its tags and urls are not deleted which means deleted field is False. I hope a customized SlugField should work like this: class ValidSlugField(serializers.SlugRelatedField): def __init__(self, *args, **kwargs): super(ValidSlugField, self).__init__(*args, **kwargs) def get_queryset(self): return super(ValidSlugField, self).get_queryset().filter(deleted=False) But get_queryset raised an error. Is it possible to make a 'generic validated' field like this? -
WHEN TRYING TO CREATE HTML FILES IN DJANGO TEMPLATE IT IS CREATING ONE WITH BUT DOES NOT SUPPORT HTML AUTO TAG AND OTHER OPTIONS
I was doing my project. and i needed to include html files in it for that i created a templates folder in my app and created a html file in it. but the created html file has a problem. the icon created does not seem as a html file and the html file is not auto closing the tags and no suggestions for the tags are showing i tried installing auto tag , auto complete and html snippets extensions. i expect there is a solution for this problem. i think i have done the installation right but the html files are not working properly -
Adding returning form_invalid (or something) with custom form errors in custom signup form with django-allauth
I am trying to prohibit duplicate signups from a single ip. Here is my code. class SignupForm(forms.Form): def signup(self, request, user): ip = get_client_ip(request) if UserProfile.objects.filter(registration_ip=ip).exists(): self.add_error( None, "You cannot register more than one account from the same IP") else: user.userprofile.registration_ip = ip user.userprofile.save() user.save() Currently, when a user registers having the same ip as another registered user, the form still validates. I need the form to return an error. Can anyone help? Thanks in advance. -
edit response json python
anyway to editing the response in json django? I'm using view.viewset { "title": "Cloister", "number": 2, "summary": "Erasmas describes several buildings of the Concent, namely the Scriptiorium...", "page_count": 14 }, for example: first I get return in json like this "title": "Cloister", and I want to add something after get string, final result must be: "title": "Cloister+somethinghere"! my task is get the product name, and check if the name >40 characters then just take 40 character and plus "..." after 40character -
How to properly prepopulate ModelForm with data from .csv file?
I'm using data from .csv file to prepopulate options for ModelForm. Let me explain how It should work: I need a simple django-app which will allow user to load data from file to be feed as choices for each form field. After clicking 'Submit' the row data will be serialized in JSON file if all fields are valid, corresponding to abstract models. Otherwise the row should be skipped manually by user and the data from next row should be loaded and form should be "refreshed". I know that the code I've listed below is a complete madness, but yep, I've tried at least. models.py class Article(models.Model): identifier = models.CharField(unique=True, max_length=255) number = models.CharField(max_length=255) ... collection = models.CharField(max_length=255) verified = models.IntegerField() class Meta: abstract = True class ArticleTranslation(models.Model): name = models.CharField(max_length=255, blank=True, null=True) description = models.TextField(blank=True, null=True) ... lightproofness = models.CharField(max_length=255, blank=True, null=True) kind_of_removal = models.CharField(max_length=255, blank=True, null=True) class Meta: abstract = True forms.py class ArticleForm(forms.ModelForm): class Meta: model = Article fields = ['identifier', 'number', ..., 'collection', 'verified'] class ArticleTranslationForm(forms.ModelForm): class Meta: model = ArticleTranslation fields = ['name', 'description', ..., 'lightproofness', 'kind_of_removal'] views.py def mapper(request): data = list(read_file(path='export_full.csv')) row = data.pop() json_data = [] if request.method == 'POST': article_form = ArticleForm(request.POST) … -
Setup SSL for Django with gunicorn on Debian 9 on Compute Engine
I'm working on a project which has been deployed on compute engine on Debian 9 VM instance. Here's are the steps I have performed: Create Instance and ssh into Install Python (3.6) directly by using these commands: a): sudo apt-get update && sudo apt-get upgrade b): sudo apt-get install -y make build-essential libssl-dev zlib1g-dev c): sudo apt-get install -y libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm d): sudo apt-get install -y libncurses5-dev libncursesw5-dev xz-utils tk-dev e): wget https://www.python.org/ftp/python/3.6.4/Python-3.6.4.tgz f): tar xvf Python-3.6.4.tgz and some other build commands to .... Then install virtualenv and activate it Clone the django project from github and install the requirements And run the gunicorn and the project is working fine. But now, I want to set up the ssl for my Django projects, I have googled it but the tutorials are for nginx, I don't have setup nginx on my VM instance, so how can I set up SSL on my instance? I want to use Lets Encrypt. -
Multistep Form in django
I was working with normal crispy forms in django. I changed the form to multi step form, now the submit doesnt work. So when i click on submit data doesnt get stored in the db. This is how the updated template looks like: index.html index.html <ul id="progressbar"> <li class="active">Account Setup</li> <li>Social Profiles</li> <li>Personal Details</li> </ul> <!-- fieldsets --> <fieldset> <h2 class="fs-title">Help me know you better</h2> <h3 class="fs-subtitle">This is step 1</h3> {{ form.associate_image|as_crispy_field}} <input type="button" name="next" class="next action-button" value="Next" /> </fieldset> <fieldset> <h2 class="fs-title">Social Profiles</h2> <h3 class="fs-subtitle">Your presence on the social network</h3> {{ form.title|as_crispy_field}} {{ form.client|as_crispy_field }} {{ form.lob|as_crispy_field }} <input type="button" name="previous" class="previous action-button" value="Previous" /> <input type="button" name="next" class="next action-button" value="Next" /> </fieldset> <fieldset> <h2 class="fs-title">Personal Details</h2> <h3 class="fs-subtitle">We will never sell it</h3> {{ form.gender|as_crispy_field }} {{ form.phone_number|as_crispy_field }} <textarea name="address" placeholder="Address"></textarea> <input type="button" name="previous" class="previous action-button" value="Previous" /> </fieldset> This is the view function : views.py @login_required def save_information(request): associate_id = id_to_numeric(request.user.username) ldap = Ldap() current_user = UserDetails.objects.filter(associate_nbr=associate_id) if current_user.exists(): current_user.delete() associate_details = ldap.search(associate_id=associate_id)[0] details = UserDetails( associate_name=associate_details['name'], associate_nbr=associate_id, associate_email=associate_details['email'], associate_department_id=id_to_numeric(associate_details['department']), associate_mgr=associate_details['xxx'], associate_exec=associate_details['xxx'], associate_org=associate_details['org'], associate_image=request.FILES['associate_image'], gender=request.POST['gender'], title=request.POST['title'], client=request.POST['client'], lob=request.POST['lob'], phone_number=request.POST['phone_number'] , ) details.save() return redirect('/?submit=true') -
Django redirect is not working with dropzone.js
Redirect in Django is not working when files are uploaded using Dropzone.js, so I used windows.href in the Dropzone's success event but I have to pass a parameter. # views.py if request.method == 'POST' and request.FILES['files']: ... if form.is_valid(): .... user = User.objects.get(email=email) id = user.id return redirect(reverse('success', kwargs={'id': id})) <<-- not working #JQuery - Dropzone this.on('success', function() { window.location.href = '/success/'; }) I don't reckon there is a way to pass the 'id' to JQuery in this case, so I have to use redirect in Django. How can it get done? -
Multiple date selection in django-admin
Is it possible to select multiple dates from calendar or DateField in Django-Admin and store? I want to make a calendar using in which user can choose multiple dates from that calendar and store in the database. -
How to make a Bangladeshi phone number field in the model of django?
Is there any package or widgets to do so? Example numbers: [+880][17][59219191], [+880][16][59219090] Here [+880] is country code, which is constant, [14],[16],[17]...etc are service provider numbers [59219090],[59219191]...etc are third part of mobile numbers in Bangladesh. -
Django: how to order query set by OneToOneField's date?
I have two classes: class Foo(models.Model): date = models.DateTimeField(auto_now_add = True) ... class Bar(models.Model): foo = models.OneToOneField( Foo, on_delete = models.CASCADE, primary_key = True ) ... How can I order Bar's objects like this: query_set = Bar.objects.all().order_by('-foo.date') -
Using Django “rules” with CBVs don't work
I am running into a problem using rules with CBV. I initialized rules like this: rules.add_perm('core.change_user', is_myuser) Where: @rules.predicate def is_myuser(user): print('Checking inside from rules') return False And I am calling: class UserUpdateView(PermissionRequiredMixin, UpdateView): model = User form_class = UserForm template_name = 'forms/user_form.html' permission_required = 'core.change_user' However this is not working. I have checked the solution from another question and I correctly have: AUTHENTICATION_BACKENDS = [ 'rules.permissions.ObjectPermissionBackend', 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ] I am not able to figure out the problem here. Even the debug message inside my predicate "is_myuser" doesn't print I also tried changing the permission name and using add_rule(). I am using Django==2.0.8 and rules==2.0 Other pieces of Code: Initialize Permissions in AppConfig: class CoreConfig(AppConfig): name = 'app.core' verbose_name = 'My App Config' def ready(self): from .rules import init_rules import logging logger = logging.getLogger(__name__) logger.info('Initializing permissions') rules.add_perm('core.change_user', is_myuser) I am getting 'Initializing permissions' in logs. When I check for permission in get_context_data of CBV print(f"User has permission: {self.request.user.has_perm(self.permission_required, self.get_object())}") Output: User has permission: True Expected Output: User has permission: False Note: I have created an issue regarding the same on Django-rules. Github -
Django: Selenium not finding image source of simple HTML
Very simple HTML here: <html> <img src={% static '/img/default_profile.png' %} id="profile-thumbnail" class="img-thumbnail"> </html> And a similarly simple test: ... thumbnail_source = self.browser.find_element_by_id("profile-thumbnail").get_attribute("src") self.assertIn('default_profile.png', thumbnail_source) For some reason, I'm getting this error: self.assertIn('default_profile.png', str(thumbnail_source)) AssertionError: 'default_profile.png' not found in 'None' I've tried adding a sleep(5) call before the assert, just in case it was a weird loading issue, but this didn't help anything. Is this some kind of bug by chance, or am I missing something trivial? Selenium finds the element, but apparently the element's src is None. If one watches the browser, it certainly shows up alright. What could be wrong? -
EncodeError at (POST Method ) in django python. Post respose 500
I have my python class below. My question is what this error actually means EncodeError at /api/v1/jobs/apply/ > is not JSON serializable. What is it trying to point based on my code below ? can anyone give an idea? Code class ApplyJob(APIView): def email(self, data): email_ins = Email() c_task.delay(email_ins.new_application, data) authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,IsApplicant) def post(self, request, format=None): data = request.data job_applicant_ser = JobApplicantSerializer(data=data) applicant = get_applicant_ins(request) if applicant.profile_completeness <= 60: return Response("You have not complete filling up your profile yet. Please complete it atleast 80% and above percentage..", status=status.HTTP_400_BAD_REQUEST) if not applicant.resume: return Response("Sorry, Please upload your resume.", status=status.HTTP_400_BAD_REQUEST) job = data.get("job" , None) cover_letter = data.get("cover_letter", None) if not cover_letter or cover_letter == "": return Response("Sorry, please fill your cover letter.", status=status.HTTP_400_BAD_REQUEST) apply_job_checker_ins = JobApplicant.objects.filter(job=job,applicant=applicant).count() if apply_job_checker_ins > 0: return Response("Sorry but you cant apply to this company, it appears that you have already applied.", status=status.HTTP_400_BAD_REQUEST) if job: job = JobModel.objects.get(pk=job) else: return Response("Sorry but there is a problem with the application, please refresh page.", status=status.HTTP_400_BAD_REQUEST) if job_applicant_ser.is_valid(raise_exception=True): job_applicants = job_applicant_ser.save(applicant=applicant,job=job) data = {} data["job"] = job_applicants.job.title data["account_url"] = APP_URL+"/account/job_applicants" data["email"] = job_applicants.job.company.user.email data["resume"] = STATIC_ROOT+"/uploads/resume/"+str(job_applicants.applicant.resume) data["company_email"] = job_applicants.job.company.user.email self.email(data) return Response("You have applied to the … -
Storing and serving different sized images
I have a website where the user will upload their profile picture. The picture will then be separated out to 3 images. 1 as the original image, 2 as a medium sized thumbnail, and 3 as a small sized thumbnail. What is the best way to store a process like this in a database? I was thinking something like this: Image table id user_id size img 1 2 S /img/s/avatars/ex.jpg 2 2 M /img/m/avatars/ex.jpg 3 2 L /img/l/avatars/ex.jpg We take the original image and split them off like this. Does this look like a good idea, or is there a better way to something like this. I am using Django as my backend. -
specify annotate field on subtables
I have a parent table Image and subtable Resized_image, so i have stored images data in resized_image table. I want to filter the data using aspect ratio. This is my model: class Image(models.Model): name=models.CharField(max_length=40,unique=False) class Resized_image(models.Model): img = models.ForeignKey(Image, related_name='images', on_delete=models.CASCADE) image=models.ImageField(upload_to=config.date_format,width_field='width', height_field='height',) width=models.PositiveIntegerField(null=True, blank=False, editable=False) height=models.PositiveIntegerField(null=True, blank=False, editable=False) size=models.IntegerField(null=True, blank=False,editable=False) status = models.CharField(max_length=30, default='inserted') class Meta: db_table = 'resized_images' def __str__(self): return self.status def save(self,force_insert=False, force_update=False, using=None): if not self.image: return super(Resized_image, self).save() self.size = os.stat(str(self.image)).st_size super(Resized_image, self).save() This is my view: class ImagePostAPIView(mixins.CreateModelMixin,generics.ListAPIView): queryset = Image.objects.all() serializer_class = imagesSerializer def get(self, request): print("inside get views.py") return super(mixins.CreateModelMixin,self).get(request) def myfilter(self, queryset, queryparam, queryarg): param = self.request.query_params.get(queryparam, None) #print("param",param) if param is not None: try: newarg = {queryarg : int(param)} #print("newarg",newarg) queryset = queryset.filter(**newarg) except ValueError: pass return queryset def get_queryset(self): queryset = Image.objects.all() queryset = self.myfilter(queryset, 'minheight', 'images__height__gte') queryset = self.myfilter(queryset, 'maxheight', 'images__height__lte') here i am filtering data in GET request using minheight which is present in Resized_image table similarly i want to filter data using aspect ratio i.e., i want to add aspect_ratio field using table_name.objects.annotate and then filter the data... How can i do that?? -
how to remove duplicate varible django view.py
I'm getting a duplicate code in query, how can i merge 2 variable into 1 line def destroy(self, request, pk=None): date_time = datetime.now() user = get_object_or_404(User, pk=request.user.id) transaction = TransactionVariant.objects.filter(transaction__pk=pk).update(deleted_at=date_time) transaction = Transaction.objects.filter(id=pk).update(deleted_at=date_time) serializer = TransactionSerializer(transaction, many=True) return Response(serializer.data, many=True) my model: transaction.py class Transaction(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) address = models.TextField() status = models.CharField(max_length=100) total = models.BigIntegerField() phone_number = models.CharField(max_length=10) created_at = models.DateTimeField(auto_now_add=True, blank=True) updated_at = models.DateTimeField(auto_now_add=True, blank=True) deleted_at = models.DateTimeField(null=True, blank=True) class Meta: db_table = "transaction" transaction_variant.py class TransactionVariant(models.Model): transaction = models.ForeignKey(Transaction, on_delete=models.CASCADE) variant = models.ForeignKey(Variant, on_delete=models.CASCADE) quantity = models.IntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True, blank=True) updated_at = models.DateTimeField(auto_now_add=True, blank=True) deleted_at = models.DateTimeField(null=True, blank=True) class Meta: db_table = "transaction_variant"