Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Password Reset generating http link instead of https
I am using Django's inbuilt password reset mechanism. It sends an email with a link containing a token, which when clicked can be used to reset the password. However, the link being generated is using the template: {% trans "Please go to the following page and choose a new password:" %} {% block reset_link %} {{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %} {% endblock %} Here, the {{ protocol }} is returning http instead of https. My nginx server would redirect any http requests to the https base link (the homepage). Hence, the password reset link does not work since the link generated is wrong. It simply goes to the homepage via nginx. How do I fix this? -
Can I block some dates in the django calender datepicker
I am trying to design a self-scheduling meeting page using Django. I am planning to use DateTime picker and show the available time slots to book. In datepicker how can I block the unavailable time slots? I have check DateFromToRangeFilter filter etc. Seems like these functionalities cannot satisfy my requirement. Can someone guide me how to block few dates in Django DateTime picker? Also, please find that I get the available slot's data from A third party in a form of excel and I dont have it in my Djnago database. Thanks in advance. -
Locking tables causes savepoint issues with django
I am trying to build a Directed-Acyclical-Graph (DAG) in a MySQL database within a Django application. Because this is acyclical, I need to verify that any added elements (vertexes/edges) do not create cycles within the graph. Many clients will attempt to add elements concurrently throughout the day, however these cycle checks need to be atomic, so I have reasoned that I need to use some lock when adding/updating elements. Django doesnt seem to provide anything like this, so I am trying to use a raw LOCK TABLES/UNLOCK TABLES query. Here is the code I use to do that... def lock_tables(): cursor = get_connection(DEFAULT_DB_ALIAS).cursor() tables = [ 'vertex', 'edge' ] lock_query = ', '.join( "{} {}".format(table, 'WRITE') for table in tables ) query = 'LOCK TABLES {}'.format(lock_query) cursor.execute(query) def unlock_tables(): cursor = get_connection(DEFAULT_DB_ALIAS).cursor() cursor.execute('UNLOCK TABLES') And then in my mode's save method... @transaction.atomic() def save(self, *args, **kwargs): print("---INSIDE MODEL SAVE") try: print("---LOCKING TABLES") lock_tables() print("---LOCKED TABLES") super().save(*args, **kwargs) # TODO: Add Cycle check here except Exception as ex: print("---EXCEPTION THROWN INSIDE SAVE: {}".format(ex)) raise finally: print("---UNLOCKING TABLES") unlock_tables() print("---UNLOCKED TABLES") However, something about locking and unlocking these tables is messing with savepoints created using django.db.transaction.atomic... At some point when Django tries … -
Using choices used in Models.py to route the page in Django
I started a project in Django where I am making a new restaurant site. What I thought initially is to make a Model like this: class Menu(models.Model): user = models.ForeignKey(User,default=1, on_delete=models.CASCADE) name = models.CharField("Name of the dish",max_length=30) category = models.CharField(max_length=20,choices=CATEGORY_CHOICES,default='SP') description = models.TextField(max_length=300) dish_image = models.ImageField(upload_to='uploads/') And I have CATEGORY_CHOICES as CATEGORY_CHOICES = [('L','Lunch'),.....] Now I have this button on the index page that routes to menu page. In Menu page, I am thinking of displaying the [n] number of tiles with the [name] ( n = number of elements in category choices and name = the full name of it ex:Lunch) After getting lots of error and figuring out each and every error, I have achieved this task. Now, after that, I want to open the menu of particular category when user clicks in it. Eg: If user clicks 'Lunch' tile, it should route to other page where all the list of the foods with that category are listed. My url pattern is like this: urlpatterns = [ path('', views.index, name="index"), path('menu/', views.menu, name="menu"), path('menu/<str:menu_category>/', views.menu_detail, name="menu_detail"), ] And I have this view : def menu_detail(request, menu_category): menu_list = get_list_or_404(Menu ,category=menu_category) menu_title = Menu.objects.get(category=menu_category) return render(request,'restaurant/menu_detail.html',{'menu_list':menu_list,'menu_title':menu_title}) In the Menu … -
How do I find the cause of duplicate key value violates unique constraint error while key doesn't exist in the DB?
In the table there is a column called previous_transaction_id defined in Django as follows: previous_transaction = models.OneToOneField( 'transactions.Transaction', verbose_name=_('Previous transaction'), on_delete=models.PROTECT, null=True, blank=True, related_name='next_transaction') Due to a bug some rows didn't have the correct value there. After fixing it I updated to the correct values. Now I'm trying to create a new entry and getting an error: IntegrityError: duplicate key value violates unique constraint "transactions_transaction_previous_transaction_id_b7df1bcd_uniq" DETAIL: Key (previous_transaction_id)=(*****) already exists. When I query the DB I don't see any rows that have this value in that column. What might be the problem? -
Multi Tenant Resources
I need some advice about where to find good resources for multi tenant database architecture. I have found this question on SO, but it's a bit specific for .net platform. This application is build with django and we need to expend the database and go towards multi tenant. For Posgresql I found out this question which explain how to start multi tenant approach, or at least it's a good starting point. But in general I didn't found good extensive recourse on the web for it, so any help would be great -
Is there a Django template tag that will convert a percentage to a human readable format?
For example: Convert 0.01 to 1% Convert 0.001 to 0.1% Convert 0.5 to 50% I see in humanize there is nothing and I could not find anything in the Django documentation. I have tried {{ value|multiply:100 }}% without success. I know I can write my own template tag but I prefer to avoid doing that whenever possible. -
Determining of option is initial value in template
I'm manually rendering a modelchoicefield in my form so that I can insert a custom attribute on each option. I'd like to know what template tag I can userto determine if the option is the initial value so that I can set it as the selected option in the dropdown menu on page load. forms.py self.fields['formpricing'].choices = ZERO_BLANK_CHOICE + tuple([(t.id, t) for t in FormPricingMethod.objects.filter(industryname=industry)]) self.fields['formpricing'].queryset = FormPricingMethod.objects.filter(industryname=industry) views.py formpricing = userprofile.formpricing form3 = BasisOfPricingForm(request.POST or None, user=user, initial={'formpricing': formpricing}) template <div class="fieldname">Form Pricing</div> <div class="fieldvalue"> <select name="formpricing" required="" id="id_formpricing"> {% for value, object in form3.formpricing.field.choices %} <option typenumber="{{object.typenumber}}" value="{{value}}"> {{object.title}} </option> {% endfor %} </select> </div> </div> Thanks! -
Heroku RQ (Redis Queue) Django Error: "Apps aren't loaded yet."
I have a functional Django app that has many Google Text-To-Speech API calls and database reads/writes in my view. When testing locally it takes about 3 seconds to load a page, but when I deploy the app live to Heroku it takes about 15 seconds to load the webpage. So I am trying to reduce load time. I came across this article: https://devcenter.heroku.com/articles/python-rq that suggests I should use background tasks by queueing jobs to workers using an RQ (Redis Queue) library. I followed their steps and included their worker.py file in the same directory as my manage.py file (not sure if that's the right place to put it). I wanted to test it out locally with a dummy function and view to see if it would run without errors. # views.py from rq import Queue from worker import conn def dummy(foo): return 2 def my_view(request): q = Queue(connection=conn) for i in range(10): dummy_foo = q.enqueue(dummy, "howdy") return render(request, 'dummy.html', {}) In separate terminals I run: $ python worker.py $ python manage.py runserver But when loading the webpage I received many "Apps aren't loaded yet." error messages in the python worker.py terminal. I haven't tried to deploy to Heroku yet, but … -
Option to restart a service from django admin page
I am using Apache2, Django, Mosquitto. I would like to have an option in my Django admin page to restart Mosquitto MQTT server. I came across the subprocess module but I have no idea how to implement the above-mentioned functionality. Basically, my need is to restart Mosquitto by performing the command sudo service mosquitto restart because sometimes Mosquitto freeze up and restarting it is a temporary fix for this issue. Unfortunately, When this happens, I may not have access to my workstation. So it will be convenient if my Django admin page had an option to restart the Mosquitto server so that I can restart it even from my mobile web browser -
How to classify objects chosen in a ManyToManyField?
I have the following models involved: Team, Stage, Group and LeaderBoard. A Team play in every Stage of a tournament in a Group with other teams and I would a LeaderBoard model to store the rank of the group. I use a leaderboard outside the Group because it could be round-robin (I need it) or knockout (I don't need it). I can't just set a points field in Team because in every Stage it will reset and I need to reuse old ones. So I think (maybe there is a better solution) I need in the LeaderBoard a sort of dictionary where all the teams I choose in the ManyToManyForm are stored with their points. Here my cleaned models.py file (sorry for some Italian in it): class Stage(models.Model): # Fase tournament = models.ForeignKey(Tournament, on_delete=models.CASCADE, related_name='stages') class Group(models.Model): # Girone FORMAT_TYPES = (('Round-Robin', "All'italiana"), ('Elimination', 'Ad eliminazione')) stage = models.ForeignKey(Stage, on_delete=models.CASCADE, related_name='groups') format = models.CharField(max_length=4, choices=FORMAT_TYPES, blank=True) teams = models.ManyToManyField(Team) class LeaderBoard(models.Model): group = models.OneToOneField(Group, on_delete=models.CASCADE, blank=True, null=True) -
How to run an individual Django test in PyDev
PyDev makes it easy to run individual Python unit tests with a contextual menu: right click on the test name, Run as -> Python Unit-test. In a Django project however, the same functionality cannot be used as the default test runner does not load the Django apps before running the tests (so we get an exception AppRegistryNotReady: Apps aren't loaded yet.). It is possible with PyDev to run all tests in a Django project (right click on the project -> Django -> Run Django Tests (manage.py test)) but that can take quite some time for large projects. I would need a UI to call manage.py test myapp.tests.FooTest.test_creation directly. Is there a way to run a single Django unit test in PyDev? -
ACL (Access Control List) Django
How can i edit add permision table from template form. I want to create Access Control List using permission table, similar to the image. Where I want to display permission form with a checkbox. On the check, permission should bbe given to that user and group. Please help me to create ACL. -
conda returns 'Solving environment: failed' a code is attached below
PS C:\Windows\system32> conda update conda Solving environment: failed CondaHTTPError: HTTP 000 CONNECTION FAILED for url https://repo.anaconda.com/pkgs/r/win-64/repodata.json.bz2 Elapsed: - An HTTP error occurred when trying to retrieve this URL. HTTP errors are often intermittent, and a simple retry will get you on your way. If your current network has https://www.anaconda.com blocked, please file a support request with your network engineering team. SSLError(MaxRetryError('HTTPSConnectionPool(host=\'repo.anaconda.com\', port=443): Max retries exceeded with url: /pkgs/r/win-64/repodata.json.bz2 (Caused by SSLError("Can\'t connect to HTTPS URL because the SSL module is not available."))')) -
Rendering of django-bootstrap-datepicker-plus widget on pythonanywhere
I wrote a very simple django application and uploaded it to pythonanywhere. Through this form I'd like to allow the user to setting date and time using django-bootstrap-datepicker-plus (and django-bootstrap3). My problem is that the date-picker widget works fine in debugging mode on my localhost (see a detail of my [local] webpage in this figure), but it does not on pythonanywhere (see the rightmost part of the second entry field: the calendar icon is missing and nothing happens when clicked). The virtual environment on pythonanywhere is set with a requirement.txt file obtained by [pip] freezing my local environment (thus, the python packages are the same). Thanks for any help. -
Django Restful: How do I update my custom user model?
I'm building an API as part of a project for university, However, I have become stuck when working out how to make updates to my custom user model. At present I have a serializer for updating the profile, but when I try to update the table using the serializer, it falls over with error 1406: "Data too long for column 'title' at row 1". I'm not sure how to resolve this at present and was wondering if someone could point me in the right direction model in question: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) title =models.CharField(_('Title'), max_length=8, null=True, blank=True) first_name=models.CharField(_('first name(s)'), max_length=100, blank =True) last_name=models.CharField(_('last name'), max_length=100, blank = True) is_active=models.BooleanField(_('account active'), default=False) is_driver = models.BooleanField(_('driver status'), default=False) is_staff = models.BooleanField(_('staff status'), default =False) is_admin = models.BooleanField(_('admin status'), default =False) dob = models.DateField(auto_now_add= True, blank=True) address_1=models.CharField(_('address line 1'),max_length=60, null=False, blank=False) address_2=models.CharField(_('address line 2'),max_length=60, null=True, blank=True) address_3=models.CharField(_('address line 3'),max_length=60, null=True, blank=True) city = models.CharField(_('city'),max_length=60, null=False, blank=False) county = models.CharField(_('county'),max_length=60, null=False, blank=False) postcode = models.CharField(_('postcode'),max_length=8, blank=False, null=False) phone_no = models.CharField(_('phone number'),max_length=50, null=True, blank=True) mobile_no = models.CharField(_('mobile Number'),max_length=50,null=False, blank=False) drivers_licence_number = models.CharField(max_length=30, null=True, blank=True) taxi_licence_number=models.CharField(max_length=30, null=True, blank=True) driver_photo=models.ImageField(blank=True) date_joined=models.DateField(auto_now_add=True, blank=True) last_update=models.DateField(auto_now_add=True, blank=True) serializer in question: class UserProfileSerializer (serializers.ModelSerializer): model = User … -
Where to place plain python objects in a Django project?
I usually have plain python objects in my Django project that have specific responsabilities like observers, strategy objects, factories, etc. Where should I place those for a more organized file structure? There is a pattern in the industry for that? -
TypeError at /project/login/ : login() missing 1 required positional argument: 'user'
This is my register.view from django.contrib.auth import login, authenticate def register_view(request): if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') the_user = authenticate(username=username, password=password) login(request, the_user) return redirect('') else: form = RegisterForm() return render(request, 'project/register.html', {'form': form}) And this is the line that contains the login.url path('login/', views.login, name='login') However, when I try to run the project at the page login, this is the error I get: TypeError at /project/login/ login() missing 1 required positional argument: 'user' Does anyone know how to solve this? None of the other answers I read helped me. Thank you! -
BooleanField not updating: Django
I am learning Django by building an example app in which students can choose to participate in study sections. The participate action is a BooleanField that I would like the students to be able to check or uncheck and update. It is unchecked by default and I am able to check it and save the form. But when I go to update the form the box is unchecked. How can I set up the form, model, and view so that the participate field can be saved and updated? models.py class StudentAnswer(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name='study_answers') study = models.ForeignKey(Study, on_delete=models.CASCADE, related_name='study_participate', null=True) participate = models.BooleanField('Participate?', default=False) forms.py class ViewStudyForm(forms.ModelForm): class Meta: model = StudentAnswer fields = ('participate', ) views.py @login_required @student_required def participate_study(request, pk): study = get_object_or_404(Study, pk=pk) student = request.user.student total_details = study.details.count() details = student.get_details(study) if request.method == 'POST': form = ViewStudyForm(data=request.POST) if form.is_valid(): with transaction.atomic(): student_answer = form.save(commit=False) student_answer.student = student student_answer.save() messages.success(request, 'Congratulations! You signed up to participate in the study %s!' % (study.name)) return redirect('students:study_list') else: form = ViewStudyForm() progress=100 return render(request, 'classroom/students/past_study_form.html', { 'study': study, 'details': details, 'form': form, 'progress': progress }) -
change django default date template format
I'm a newbie and I have a date format 2017-12-30, but when the date is passed on template it returns Dec. 30, 2017. I tried to do this but it is not working <div class="first-row"> <div class="document-item-title"|date:'Y-m-d'> {{list.document_date.display_name}} </div> <div class="document-item-detail"> <input type="text" id="date" class="select-date" name="{{list.document_date.name}}" value="{{list.document_date.select}}"> </div> </div> What am I doing wrong? Thanks -
How to dynamically add/stop workers from Python code with Celery
I am working with a dockerized Django system which processes buffers for users. Let's say I have 3 users and one of them decides to queue thousands of buffers. I do not want the other 2 to have to wait before all of those are completed. Would it be possible to dynamically start a worker who only processes tasks which are in the queue assigned to that user? I know you can dynamically decide the queue in which a task should be placed upon calling the task. I tried starting workers from within my Django project on startup. But I seem to fail to start more than just one. I attempted doing this in my celery config at first: import os from celery import Celery from celery.bin import worker from django.conf import settings os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings") app = Celery('project1') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) app.conf.ONCE = { 'settings': { 'url': 'redis://' + 'redis', 'blocking': True, 'default_timeout': 60 * 60, 'blocking_timeout': 86400 } } print("Starting worker...") for e in Customer.objects.all(): worker = worker.worker(app=app) worker.run(queues=["Queue" + e.id.__str__(),]) Is this even an legitimate way of doing this? If so how can I create workers from my Python source code? If this is not the way to … -
djang : modelformset not reflecting initial data
queryset is not reflecting in the initial form fields of modelformset.i am trying to give the input to formfields of modelformset from database , the no.of forms created is correct but data is not feeding in input fields. forms.py class skillform(forms.ModelForm): name = forms.CharField(label='Skill',widget=forms.TextInput(attrs={'class': 'form-control',})) level = forms.ChoiceField(choices=(('Novice','Novice'),('Beginner','Beginner'),('Skillful','Skillful'),('Experienced','Experienced'),('Expert','Expert')),label="level",initial='Skillful',widget=forms.Select(),required=False) class Meta: model = userskills_model fields = ('name','level') skillformset = modelformset_factory(userskills_model, form = skillform, extra=0, can_delete=False) models.py class userskills_model(models.Model): userid = models.ForeignKey(user_model, on_delete=models.PROTECT) skills =models.CharField(max_length=264,unique=False,blank=False,null=False) skills_level = models.CharField(max_length=264,unique=False,blank=False,null=False) def __str__(self): return str(self.userid) views.py def skillview(request): qset=userskills_model.objects.filter( userid=user_model.objects.get(userid=userid)) skillformset(queryset = qset) if request.method == 'GET': formset = skillformset(request.GET or None) elif request.method == 'POST': formset = skillformset(request.POST) #validating and saving return render(request, template_name, { 'formset': formset, }) -
Need help mapping a new URL config in Django
So I'm making this portfolio and I´m using Django for the back-end part but I can´t map a new URL configuration. I have "Portfolio" as my project in Django and "Tony" as my app! This is what I already tried: from django.contrib import admin from django.urls import path from django.urls import include from django.conf.urls import url urlpatterns = [ '', path('toni/', include('toni.urls')), path('admin/', admin.site.urls), ] The error it give is too long to input here so this is what it says in the last line: ModuleNotFoundError: No module named 'toni' -
how to add children to a table
I want to create a comment thread system and the problem is that I know how to create a table containing children I followed a tutorial in PHP for the realization of a system of comment and I want to do it in python django $comments = commentary table $comments_by_id = [] empty board foreach($comments as $comment){ $comments_by_id[$comment->id] = $comment;`enter code here` } foreach($comments as $k => $comment){ if($comment->parent_id != 0) { $comments_by_id[$comment->parent_id]->children[] = $comment; unset($comments[$k]) } } python code? -
Django, CORS, CSRF - am I doing it right?
My setup (local) is the following: Vue.js running on localhost:8080 (npm run serve) REST API built with Django running on localhost:8000 (./manage-py runserver) In order to enable this to work I've made the following additions: ALLOWED_HOSTS = [ ... 'localhost', 'localhost:8000', 'localhost:8080', ] INSTALLED_APPS = [ ... 'rest_framework', 'corsheaders', ] MIDDLEWARE = [ ... 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] CORS_ORIGIN_WHITELIST = ( 'localhost:8080', 'localhost:8000', ) CORS_ALLOW_CREDENTIALS = True from corsheaders.defaults import default_headers CORS_ALLOW_HEADERS = default_headers + ( 'credentials', ) One of my API functions: @ensure_csrf_cookie def try_login(request): # this is just to get the initial CSRF token: if request.method == "GET" or request.method == "OPTIONS": return JsonResponse({'status': 'ok'}) # else, an actual login request: else: data = JSONParser().parse(request) user = authenticate(request, username=data['user'] , password=data['pass']) if user is not None: login(request, user) return JsonResponse({'login_succ': 'ok'}); else: return JsonResponse({'login_succ': 'fail'}); Finally, in Vue: api: function(endpoint, method, data) { var headers = new Headers(); headers.append('content-type', 'application/json'); if (... this is not the first request ever ...) { csrftoken = document.cookie.replace(/(?:(?:^|.*;\s*)csrftoken\s*\=\s*([^;]*).*$)|^.*$/, "$1"); headers.append('X-CSRFToken', csrftoken); } method = method || 'GET'; var config = { method: method, body: data !== undefined ? JSON.stringify(data) : null, headers: headers, }; config['credentials'] = 'include'; return fetch(endpoint, config) .then(response …