Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to check whether the value of radio button selected is right or wrong from Django models?
I'm making a quiz app in Django. It is a MCQ type of quiz app where users have to select the answer from a list of multiple answers. Now, in my models.py there are three models: Quiz Question Answer Where Quiz model defines the type of quiz (For example Basic, Intermediate, Advance), Question model has a ForeignKey of Quiz to specify the type of question and a CharField to mention the text of the question. The Answer model is similar to Question model but with ForeignKey of Question to specify the question that answer is related to, CharField for the text of the answer and a BooleanField to specify if that answer is correct or not. models.py from django.db import models # Create your models here. class Quiz(models.Model): q_name = models.CharField(max_length=30) desc = models.CharField(max_length=100) def __str__(self): return self.q_name class Question(models.Model): quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE) label = models.CharField(max_length=1000) def __str__(self): return self.label class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) text = models.CharField(max_length=1000) is_correct = models.BooleanField(default=False) def __str__(self): return self.text views.py from django.shortcuts import render, redirect, reverse from django.contrib import messages from .models import Quiz, Question, Answer def basic_quest(request, quiz_name, ques_no): if request.method == "POST": guess = request.POST.get('answer') ans = Answer.objects.get(text = guess) … -
Registering a dummy model in Django admin to control multiple models data
Is it possible to register a dummy model (Does not exist in db) that will display data from multiple models in one page? Maybe just list all objects and when use click on one, a new webpage is opened with details of the clicked on objects? Which is usually this view: admin:{app_name}/{model_name}/{object_id}/change -
cant open .sqlite file in python django project
what i am trying to do is, i have some .sqlite files a different project created and im trying to read these files in my current django view. path = os.path.join(os.getcwd(), 'output', spider, '{}.sqlite'.format(run_id)) conn = sqlite3.connect(path) but i am getting this error. Traceback (most recent call last): File "<input>", line 1, in <module> sqlite3.OperationalError: unable to open database file on using macbook, python 3.8, tried a few things but nothing is working so far. -
Testing Django Apps On Heroku With Cypress
I'm a hobby web developer looking to build my first product with the django web framework which I will host on Heroku. Cypress looks like a great modern tool for UI testing which I certainly want to use. In local development I am using it within django testing so that the django staticliveservertestcase runs first - which creates a separate development server process, and a test database, if one hasn't been created already. Within this test I then call a bash script which executes a cypress UI test. See the example below. Bash Script - #!/bin/bash echo $1 # the 1st command line argument echo $2 # the 2nd command line argument ./node_modules/.bin/cypress run --env baseUrl=$1 --spec $2 Django Test Code - class ExampleTest(StaticLiveServerTestCase): def test_view_url(self): from subprocess import run exit_code = run([ './cypress/run.sh', f'http://{self.server_thread.host}:{self.server_thread.port}', 'cypress/integration/sample_spec.js' ]) self.assertEqual(0, exit_code.returncode) From my understanding this is the opposite to the standard cypress approach. Normally cypress runs outside of the app independently and simply runs through all the tests which interact with the app. Here the cypress tests are called by the django process. Unless I am mistaken there are obvious advantages to this approach. I can test the UI and whether objects … -
Serving static files from the project directory in Django
I have the following project structure: myproject - myapp - manage.py - myproject - settings.py - urls.py ... - static - templates I want to serve all my static files from within this static folder. In my settings.py, I have the following: STATIC_URL = '/static/' However, in one of my templates, when I call static files using the following... {% load static %} ... <link href="{% static 'css/styles.css' %}" rel="stylesheet" /> ...nothing gets loaded. However, if I add the css file within myapp/static/css/styles.css, then everything works properly. How can I serve static files from my project root folder? Thanks for any help. -
Django Templates - generate and save XML file by chunks (to save RAM)
We generate sometimes huge XML files in the Django project and these files are then saved to the FileField. Since those files are XMLs sometimes built from tens or hundreds of thousands of projects, it consumes a lot of RAM. Is it possible to generate the files by chunks? @classmethod def from_eshop(cls, eshop): content = mark_safe(render_to_string(template_path, context={'products': some_queryset})) ramfile = ContentFile(content) att = ExportFileGenerateAttempt.objects.create(eshop=eshop) att.file.save(utils.files.generate_filename(eshop.name,True),ramfile) return att -
How to stop chrome launched by selenium remote driver?
First, I'm using Django, and I'm building an API. For example, I've route like api/get-some-element. browser_url = cache.get('user_%d.browser_url' % user_id) is_browser_queued = cache.get('user_%d.browser_queued' % user_id) if browser_url: capabilities = DesiredCapabilities.CHROME.copy() return webdriver.Remote( command_executor=browser_url, desired_capabilities=capabilities, options=options, ) if not is_browser_queued: run_browser.delay(user_id) # launch main chrome cache.set('user_%d.browser_queued' % user_id, True, None) On the first access to that route, it will send a task to Celery to launch Selenium Headless Chrome (main chrome). Why I'm using Celery? Because I need to make Chrome always running. (Idk better way, this is what I know). Then, for the next access on that route, it will response with Waiting chrome to launched., until the Celery task got executed (chrome launched properly). After main chrome is launched, then it will launch Selenium Headless Remote Driver immediately (without Celery), the purpose of this remote driver is to access the main chrome. Then, it just grab some element from a website. But, after I got that element, the Remote Driver is still running. How to stop that? -
How to save session in Django?
Hello I am new to django. I created a todo app for practice and also added some users to it but I don't know how to save session for every user? Like if a user logs in he can only see his todo tasks? -
Django Paginator append extra data for each item
How would I change my code to add a liked item to every post returned from paginator. This is my code but it returns a list which I can't check if it .has_next in my template therefore my infinite scroll doesn't work. try: posts_given = paginator.page(page) except PageNotAnInteger: posts_given = paginator.page(1) except EmptyPage: posts_given = paginator.page(paginator.num_pages) results = [] for post in posts_given.object_list: liked = like_post.objects.filter(user=request.user, post=post) results.append((post, liked)) posts_given = results -
what is the difference between using the request.session.flush() and simply using del request.session['key'] to log out the user in Django?
I have used the following: def LogOut(request): request.session.flush() def LogOut(request): try: del request.session['member_id'] except KeyError: pass I looked up the database file and noticed that the former did remove the session data from the table, the latter, however, did not. I can't wrap my head around the difference between the two. Why doesn't the second remove the session data even though i'd assigned the member's id to the aformentioned key while creating the session. -
Is it possible to filter Django objects by custom python metric function?
I'm trying to get Query that contains similar object based on my custom defined function def sessRatio(s1, s2): ratio = L.seqratio([s1.browser_family, s1.device, s1.os_family, s1.os_version, s1.ip, s1.browser_version], [s2.browser_family, s2.device, s2.os_family, s2.os_version, s2.ip, s2.browser_version]) ratio += boolRatio(s1.mobile==s2.mobile, s1.tablet==s2.tablet, s1.touch==s2.touch, s1.pc==s2.pc, s1.bot==s2.bot) if(len(s1.meta)>0 and len(s2.meta)>0): ratio += L.ratio(s1.meta, s2.meta) ratio /= 3 else: ratio /= 2 return ratio so in my view I create one s1 object and want to get theese s2 that sessRatio(s1,s2)>0.5. Django filter works only on raw SQL so probably I can't use my python function there. -
Django - the database backend does not accept 0 as autofield
I am making a page for users to modify their profile. I want them to be able to modify each field individually and save rather than return the whole model every time. Two models are involved, so two model forms. The first one is tied to the User object, the other one to the Users (which should be named profile but I named it stupidly at first and now if i want to change the model name it will be a nightmare in migrations because so many models are using it as a foreign key) I'm using javascript to send in post the value of the field that was modified as a 'modaction' variable. Then it checks whether the variable belongs to one form or the other. If the value belongs to the User form then there is no issue. However if it belongs to the Users form i receive this error stating the db backend doesn't accept the value 0 as blahblah blah. Here is the code in post, some messages are there for debugging, they confirmed that the modified users object was indeed retrieved properly from the db, which really puzzles me as to why it is trying … -
Django Blog Add Comment Text Field Not Showing
I have used django's models and forms to add a comment section to a blog app, however the form's text field will not show when loaded in the in the browser when i try to add a comment to a post. Only the submit button and the title is visible with no textfield to submit with. models.py from django.db import models from django.utils import timezone # Create your models here. class Post(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title class Comment(models.Model): post = models.ForeignKey('blog.Post', on_delete=models.CASCADE, related_name='comments') author = models.CharField(max_length=200) created_date = models.DateTimeField(default=timezone.now) text = models.TextField() def __str__(self): return self.text forms.py from django import forms from .models import Post, Comment class PostForm(forms.ModelForm): class Meta: model = Post fields = ('title', 'text') class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('author', 'text',) views.py from django.contrib.auth.decorators import login_required from django.shortcuts import render, get_list_or_404, get_object_or_404, redirect from django.utils import timezone from blog.forms import PostForm from .models import Post, Comment from .forms import PostForm, CommentForm # Create your views here. def post_list(request): posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date') stuff_for_frontend = {'posts': posts} return render(request, 'blog/post_list.html', stuff_for_frontend) def … -
blocking unwanted urls in django
I have added account app to installed_apps in my django project. also I have added urls of account app as like below: (r"^account/", include("account.urls")) Its working fine. Now I had to override SignupView class of account app. This is also working fine. Now I have created a new class CreateUser(SignupView) and I want that only admin user will be able to create user. So I added a different url for CreateUser(SignupView) view. Now I want that account/signup url with view SignupView will not be accessible anymore. How can I block this particular url by keeping other urls active of account app as this is a library. -
BaseFormSet doesn't work with inlineformset_factory
I wrote my view function to create new entries. The entries consist of a JournalEntry() which then has a number of LineItem()s related to it. I created a BaseFormSet which does validation across the LineItems (checks they sum up correctly). Works greate but when I tried to apply the same BaseFormSet to the inlineformset_factory() in the Update view, that doesn't work (init() got an unexpected keyword argument 'instance'). So does BaseFormSet not work with inline formsets? And if not then how do I validate across the formsets when updating a record? Thank you. # Function to create new entry def entries_new(request): LineItemFormSet = formset_factory(LineItemForm, formset=BaseLineItemFormSet, extra=0, min_num=2, validate_min=True) if request.method == 'POST': journal_entry_form = JournalEntryForm(request.POST) lineitem_formset = LineItemFormSet(request.POST) if journal_entry_form.is_valid() and lineitem_formset.is_valid(): journal_entry = journal_entry_form.save(commit=False) journal_entry.user = request.user journal_entry.type = 'JE' journal_entry.save() lineitems = lineitem_formset for lineitem in lineitems: obj=lineitem.save(commit=False) obj.journal_entry = journal_entry obj.save() messages.success(request, "Journal entry successfully created.") return HttpResponseRedirect(reverse('journal:entries_show_detail', kwargs={'pk': journal_entry.id}) ) else: journal_entry_form = JournalEntryForm(initial = {'date': datetime.date.today().strftime('%Y-%m-%d')}) lineitem_formset = LineItemFormSet() return render(request, 'journal/entries_new.html', {'journal_entry_form': journal_entry_form, 'lineitem_formset': lineitem_formset}) @login_required def entries_update(request, pk): journal_entry = get_object_or_404(JournalEntry, pk=pk) #Convert date format to be suitable for Datepicker input. journal_entry.date = journal_entry.date.strftime('%Y-%m-%d') journal_entry_form = JournalEntryForm(instance=journal_entry) # Doesn't work with BaseForm so … -
Django trans template tag only displaying placeholder constant string
I have the following tag in templates/home.html: {% trans "test" %} Which always prints "test" no matter the language I choose. I know for a fact that the language changes because I print it like this (and the admin's language changes, etc...): {% get_current_language as LANGUAGE_CODE %} {{ LANGUAGE_CODE }} In the project's settings.py I have: LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # modeltranslation settings gettext = lambda s: s LANGUAGES = ( ('en', gettext('English')), ('zh-hans', gettext('Simplified Chinese')), ('zh-hant', gettext('Traditional Chinese')), ) LOCALE_PATHS = [ os.path.join(BASE_DIR, 'locale') ] I wanted to try out the translation to Simplified Chinese so I created the translation thing with python3 manage.py makemessages -l zh-hans and in locale/zh-hans/LC_MESSAGES/django.po I filled the value of test like this: #: templates/home.html:8 msgid "test" msgstr "你好" Then I run python3 manage.py compilemessages. In the templates/_base.html that templates/home.html inherits from, I have {% load static %} {% load static i18n %} {% load i18n %} and in templates/home.html, I have {% extends '_base.html' %} {% load i18n %} Despite this, when I change the language to zh-hans, it always displays test. What could be wrong? I am using django 3.0.1. -
Trying to validate a django model before it get saved in database. Using a POST api to create model objects in the specific model
class ComplianceLaw(TimeStampModel): name = models.CharField(verbose_name=_("Name"), max_length=100) slug = models.SlugField(max_length=40) class Compliance(TimeStampModel): name = models.CharField(verbose_name=_("Name"), max_length=1000) compliance_law = models.ForeignKey( verbose_name=_("Compliance Law"), to=ComplianceLaw, on_delete=models.CASCADE ) class ComplianceGroup(TimeStampModel): name = models.CharField(verbose_name=_("Name"), max_length=1000) compliance_law = models.ForeignKey( verbose_name=_("Category Law"), to=ComplianceLaw, on_delete=models.CASCADE ) compliance = models.ManyToManyField(verbose_name=_("Compliance"), to=Compliance) def clean_fields(self, exclude=None): super().clean_fields(exclude=exclude) compliances = self.compliance.all().values_list("compliance_law_id", "id") errors = [] for compliance, oid in compliances: if compliance != self.compliance_law_id: errors.append("{} is not a valid group element.".format(oid)) if errors: raise ValidationError({self.compliance.name: errors}) I am trying to achieve that a compliance group can belong to one compliance law but can have any number of compliances from that law, but as of now, it creates compliance groups from other compliances laws as well. -
Pyrebase4: how to use stream() method with token?
i'm new in python and django. i'm using django 2.2, python 3.7, pyrebase4, for some secure reason my firebase rule is: "rules": { ".read": "auth != null", ".write": "auth != null", My code when using stream is: def stream(ownerUid,idToken): my_stream = db.child('notifications').order_by_child('to').equal_to(ownerUid).stream(stream_handler,token=idToken,stream_id="Notification") return my_stream def stream_handler(notice): notify = notice['data'] event = notice['event'] getNotify = db.child('notifications').order_by_child('to').equal_to(ownerUid).get(idToken) def postlogin(request): email = request.POST['email'] passwd = request.POST.get('password') try: user = authe.sign_in_with_email_and_password(email, passwd) except: message = 'Invalid Username or Password' return render(request,'login.html',{'messg':message}) user = authe.refresh(user['refreshToken']) user_id = user['idToken'] request.session['uid'] = str(user_id) idToken = request.session['uid'] user = authe.get_account_info(idToken) user = user['users'] user = user[0] ownerUid = user['localId'] stream(ownerUid,idToken) return render(request,'welcome.html') Question is: How can i retrieve data in stream_handler function? Or how can i get idToken in stream_handler function? when user login, i saved idToken to session, so that it need "request" to get idToken Now, when i use stream in pyrebase, they need idToken, so the stream can't be at the global just like: my_stream = db.child("posts").stream(stream_handler). So i need to use it like a function. But with stream_handler , how can pass idToken or how can i retrieve data in this function, i can't use function with request like def stream_handler(request, notice): get something.... … -
Best practices: where to put a scraping file in django framework
I have a scraping script that has to run once in a while (maybe once per day). This script populates a database using django models. There is no url or view calling the script (at the moment), so I would consider it a static file and put it under myapp/static/myapp/scraping/scraping.py. Is this correct? -
Set a IP Whitelist For Each User
I wanted that when users intend to login, if user login from a new IP address , their login failed and an email containing this content: You login form a new IP address (109.169.65.137) Would you like add this IP to you'r allowed IP-LIST" would be send to their email. TIP: If user allowed IP_LIST is None, user can login form any IP address Anyone can guide me to implement this scenario? I'm using a custom user model class CustomUserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, mobile_number, password, **extra_fields): """ Creates and saves a User with the given email and password. """ if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) mobile_number = mobile_number user = self.model(email=email, mobile_number= mobile_number, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, mobile_number, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, mobile_number, password, **extra_fields) def create_superuser(self, email, mobile_number, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_active') is not True: raise ValueError('Superuser must have is_active=True.') if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, mobile_number, password, **extra_fields) class User(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True, … -
Creating multiple user roles in all-auth signup
I would like to create a signup process that create multiple (2) user roles. I am relatively new to Django and trying to use a tutorial to help, while customizing the code where necessary to suit my needs. I would like to create a student and mentor profile in the beginning with just the name and email. Here is the tutorial This is what following the tutorial has translated to in my code: i. catalog/forms.py: from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class User(AbstractUser): is_student = models.BooleanField(default=True) class mentorProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, related_name="mentor_user") name = models.CharField(max_length=100, blank=True) email = models.CHarField(max_length=100, blank=True) class studentProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE, null=True, related_name="student_user" ) name = models.CharField(max_length=100, blank=True) email = models.CharField(max_length=100, blank=True) #create either mentor or student depending on instance @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): print('****', created) if instance.is_student: student.objects.get_or_create(user=instance) else: mentor.objects.get_or_create(user=instance) @receiver(post_save,sender=User) def save_profile(sender,instance, **kwargs): print('_-----') if instance.is_student: instance.is_student.save() else: mentor.objects.get_or_create(user=instance) signup.py: {% extends "account/base.html" %} {% load i18n %} {% load crispy_forms_tags %} {% load static %} {% block head_title %}{% trans "Signup" %}{% endblock %} <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <head> <link rel="stylesheet" href="{% static 'css/base.css' %}"> </head> {% block content %} <h1>{% trans "Sign … -
How do i display billing address for each product that has been successfully delivered to a customer/user
I was able to create a billing address using form, now i want to display the billing address in the customer's account (Order product). so when the customers want to check the information of all the product they have ordered, i want them to also see the billing address for each of the product, for example if they also uses a different billing addresses. I was able to get the address displayed on template, but it address gets duplicated on template, instead of displaying only the address for each product ordered. class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) billing_address = models.ForeignKey('BillingAddress', on_delete=models.SET_NULL, blank=True, null=True) payment = models.ForeignKey('Payment', on_delete=models.SET_NULL, blank=True, null=True) def __str__(self): return self.user.username class BillingAddress(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) street_address = models.CharField(max_length=100) apartment_address = models.CharField(max_length=100) country = CountryField(multiple=False) city = models.CharField(max_length=50) state = models.CharField(max_length=50) phone = models.CharField(max_length=50) def __str__(self): return self.user.username def orders(request): order = Order.objects.filter(user=request.user.id, ordered=True) billing_address = BillingAddress.objects.filter(user=request.user.id) context = { 'order': order, 'billing_address_item': order_billing_address, } return render(request, 'orders.html', context) {% for address in billing_address %} Country: {{ address.street_address|capfirst }} {% endfor %}</p> -
What's the approach to implement a TTL on Django model record?
Can you please tell me the approach to implement a TTL on Django model record? For Example:Remove all values stored over more than x minutes. -
File Upload AngularJS and Django: TypeError at /uploaded_file uploadFile() missing 1 required positional argument: 'request'
I am doing a file upload using angularjs as my front-end and django as my back-end. In my AngularJS, I can successfully detect what the file I've uploaded is. However, I can't seem to pass uploaded file to django. This is the error that I've got TypeError at /uploaded_file uploadFile() missing 1 required positional argument: 'request'. .html: <body ng-app="myApp" ng-controller="appCtrl"> <input type="file" id="file" name="files" accept="text/*" data-url="file" class="inputfile_upload" select-ng-files ng-model="uploadedFile"/> <label for="file"> <span id="chooseFile"></span>Upload a file!</label> <button id="submitBtn" type="submit" ng-click="upload()">Upload</button> </body> directive.js: app.directive("selectNgFiles", function($parse) { return { require: "ngModel", link: function postLink(scope,elem,attrs,ngModel) { elem.on("change", function(e) { var files = elem[0].files; ngModel.$setViewValue(files); }) } } }); controller.js: var app = angular.module('myApp', []) app.controller('appCtrl', function ($scope, $rootScope, $http, fileUploadService){ $scope.upload = function() { var file = $scope.uploadedFile; console.log('file is ' ); console.dir(file); var uploadUrl = "/uploaded_file"; fileUploadService.uploadFileToUrl(file, uploadUrl); $http({ method:'POST', url: '/uploaded_file' }).then(function successCallback(response) { console.log("success"); }, function errorCallback(response){ console.log("failed"); }) }; } service.js: app.factory('fileUploadService', function ($rootScope, $http) { var service = {}; service.uploadFileToUrl = function upload(file, uploadUrl){ var fd = new FormData(); fd.append('file', file); $http.post(uploadUrl, fd, { transformRequest: angular.identity, headers: {'Content-Type': undefined} }).then(function successCallback(response){ console.log("Files added"); }, function errorCallback(response){ console.log("Files not successfully added"); }) } return service; }); urls.py: urlpatterns = [ … -
Which server has Django CMS pre installed
I am looking for a server which has Django CMS pre-installed or has provision to install Django CMS While I find plenty of servers installed with WordPress, Magneto or Joomla, its pretty hard to find a shared server with Django pre-installed.