Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NoReverseMatch with keyword arguments not found when the keyword arguments match
I'm getting the error: Reverse for 'search_blog' with keyword arguments '{'search_terms': ''}' not found. 1 pattern(s) tried: ['blog/search/(?P[^/]+)/$'] So, my arguments match and yet I'm getting a NoReverseMatch... I've tried removing the <str:search_terms> pattern from the 'search_blog' path and excluded the kwargs parameter from my reverse call, and that worked. So, the problem must lie solely in the url pattern. I tried renaming the pattern to 'terms' but got the same error: Reverse for 'search_blog' with keyword arguments '{'terms': ''}' not found. 1 pattern(s) tried: ['blog/search/(?P[^/]+)/$'] Here are the relevant snippets: urls.py path('search/', views.nav_search_input, name='nav_search_input'), path('search/<str:search_terms>/', views.search_blog, name='search_blog'), views.py def nav_search_input(request): if request.method == 'POST': form = SearchBlog(request.POST) if form.is_valid(): return HttpResponseRedirect(reverse('search_blog', kwargs={'search_terms': form.cleaned_data['search_terms']})) else: form = SearchBlog() context = { 'form': form } return render(request, 'index.html', context) def search_blog(request, search_terms=''): posts = Post.objects.all() form = SearchBlog() if form.is_valid(): posts = Post.objects.all().filter(title__contains=search_terms) context = { 'form': form, 'posts': posts } return render(request, 'blog/search_blog.html', context) -
Django Selenium Chromedriver Saving Scraped Files to S3 Bucket
I created a scraping script with Selenium and Chromedriver. This is the header in sel.py. I used the example here: Downloading a file at a specified location through python and selenium using Chrome driver options = webdriver.ChromeOptions() prefs = {"profile.default_content_settings.popups": 0, "download.default_directory": DEFAULT_FILE_STORAGE, "directory_upgrade": True} options.add_experimental_option("prefs", prefs) driver = webdriver.Chrome(options=options) driver.get('https://unsplash.com/s/photos/download') I want to save the downloaded file into my S3 Bucket. I followed these tutorials: How to Setup Amazon S3 in a Django Project & Serve Django Static & Media files on AWS S3 | Part 2 Settings.py AWS_ACCESS_KEY_ID = 'xxxxxxxx' AWS_SECRET_ACCESS_KEY = 'xxxxxxxxx' AWS_STORAGE_BUCKET_NAME = 'xxxxxxx' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'static' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) DEFAULT_FILE_STORAGE = 'MyProject.storage_backends.MediaStorage' ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/' AWS_DEFAULT_ACL = None The "download.default_directory": DEFAULT_FILE_STORAGE in the sel.py is not working, because it keeps saving the photos in the downloads folder instead of S3. How can I make my S3 folder the download default directory? -
Does Django have the capability of sharing a field value between a pair of users such as a symmetric key?
I want a user to be able to take plaintext and paste it into a form to submit using a symmetric key and then receive the ciphertext. Then using the ciphertext another user who shares the symmetric key can use that key to decrypt that ciphertext. I'm new to Django and believe I need to setup a user model and use that model somehow to solve the problem but I'm not sure how and cannot find any information to help. I believe I need a special model because that's how you store and retrieve user information but I could be wrong. from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): age = models.PositiveIntegerField(null=True, blank=True) key = models.?????? The actual results should be as follows: A user logs in and chooses from a list of users that they have "befriended" so to speak where they both share the same symmetric key(<--the topic of question). That user then takes plaintext such as a sentence or paragraph and pastes this information into an HTML form where they can click submit. Upon submission the plaintext is encrypted using the key respective of the intended recipient. Then that information runs through a encryption algorithm … -
Django/Apache Server Down but 403
i have a Django Site running on Debian server. The thing is that it crushed out and is giving now a 403 Forbidden error. The site run for 2 years without an issue. I shutdown the apache2 server and while was not running I could still see the 403 error. Normal trick was to see 500 while was down. Can someone pls advise? Why is this caching? I've followed all the steps from other past 403 questions. Options FollowSymLinks AllowOverride None Require all denied <Directory /usr/share> AllowOverride None Require all granted </Directory> <Directory /var/www/> Options Indexes FollowSymLinks AllowOverride None Require all granted </Directory> #<Directory /srv/> # Options Indexes FollowSymLinks # AllowOverride None # Require all granted #</Directory> # AccessFileName: The name of the file to look for in each directory # for additional configuration directives. See also the AllowOverride # directive. # AccessFileName .htaccess # # The following lines prevent .htaccess and .htpasswd files from being # viewed by Web clients. # <FilesMatch "^\.ht"> Require all denied </FilesMatch> -
Disable {% debug %} tag in Django template
Is there a way to prevent Django template from outputting a bunch of debug output? I tried setting DEBUG = False and setting my TEMPLATES option like so: TEMPLATES = [ { ... 'OPTIONS': { 'debug': False, 'context_processors': [ 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], } } ] Despite the above settings, whenever I put {% debug %} into my template, it still outputs a lot of debug information. -
Randomizing again in Django
When I generate a quiz in django, the question value before if request.method == 'POST': is one and then changed. Follow the screenshots. views.py questao = Questao.objects.annotate(resp_count=models.Count(models.Case(models.When(resposta__usuario=request.user, then=1),output_field=models.IntegerField()))).filter(resp_count=0,tipoQuestao=1).order_by("?").first() print (questao) if request.method == 'POST': print (questao) respostaform = RespostaForm(request.POST or None) if respostaform.is_valid(): resp = respostaform.save(commit=False) resp.idQuestao = questao if resp.resposta == questao.respostaQuestao: resp.certaresposta = 1 else: resp.certaresposta = 0 resp.save() return HttpResponseRedirect(request.path_info) -
How to access the human-readable name using get_FOO_display
Hello I have the next code to show to my participants the text of the response that the gave me in a anterior session. J12 = models.IntegerField( choices=[ [-2, 'Muy moralmente inapropiado'], [-1, 'Moralmente inapropiado'], [0, 'No aplica'], [1, 'Moralmente apropiado'], [2, 'Muy moralmente apropiado'], ], widget=widgets.RadioSelect ) TJ12 = models.CharField(max_length=20, choices=J12) When I try to prove this code I get the next error: File "C:\Users\diese\iat\incentivos\models.py", line 140, in <module> class Player(BasePlayer): File "C:\Users\diese\iat\incentivos\models.py", line 216, in Player TJ11 = models.CharField(max_length=2, choices=J11) File "c:\users\diese\appdata\local\programs\python\python37\lib\site-packages\otree\db\models.py", line 386, in __init__super().__init__(max_length=max_length, **kwargs) File "c:\users\diese\appdata\local\programs\python\python37\lib\site-packages\otree\db\models.py", line 217, in __init__ fix_choices_arg(kwargs) File "c:\users\diese\appdata\local\programs\python\python37\lib\site-packages\otree\db\models.py", line 195, in fix_choices_arg choices = expand_choice_tuples(choices) File "c:\users\diese\appdata\local\programs\python\python37\lib\site- packages\otree\common_internal.py", line 118, in expand_choice_tuples if not isinstance(choices[0], (list, tuple)): TypeError: 'IntegerField' object is not subscriptable What Can I do? Someone has experienced the same ? Thanks in advance -
Serialize model with foreign key Django
I have the following json: The problem with it is the 'tipo_envase' field, whose id is being returned in my json, but I do not want the id, but the whole object that is linked to tipo_envase, which is basically this json: I tried to serialize the models this way class TipoEnvaseSerializer(serializers.ModelSerializer): class Meta: model = Tipoenvase fields = ('id','nombre') class PresentationSerializer(serializers.ModelSerializer): class Meta: model = Presentation fields = ('nombre','capacidad','tipo_envase') And the models are these: class Presentation(models.Model): nombre = models.CharField(max_length=100) capacidad = models.CharField(max_length=100) tipo_envase = models.ForeignKey('Tipoenvase', on_delete=models.CASCADE) def __str__(self): return self.nombre + " " + self.capacidad + " " + self.tipo_envase.nombre class Tipoenvase(models.Model): nombre = models.CharField(max_length=100) def __str__(self): return self.nombre In summary the following json structure is required: `{ "nombre":"Frasco" "capacidad":"410 gr" "tipo_envase":{ "id":"1" "nombre":"vidrio" } }` -
Mezzanine Fabric deployment, PSQL issue - "Error: role "project" already exists"
Having huge troubles deploying Mezzanine on digitalocean, and I'm taking it step by step to figure out all the small issues individually. Running "fab create" results in successfully (I guess?) setting up the virtualenv, but when it comes to setting up the PSQL database, it errors with the following (full output): [1xx.xx.xxx.xxx] Executing task 'create' ←[1;32m------ create ------←[0m ←[1;34m$ ←[0m←[1;33mlocale -a←[0m←[1;31m ->←[0m [1xx.xx.xxx.xxx] Login password for 'adm': ←[1;34m$ ←[0m←[1;33mmkdir -p /home/adm/mezzanine/project←[0m←[1;31m ->←[0m ←[1;34m$ ←[0m←[1;33mmkdir -p /home/adm/.virtualenvs←[0m←[1;31m ->←[0m Virtualenv already exists in host server: project Would you like to replace it? [Y/n] y ←[1;34m$ ←[0m←[1;33mrm -rf project←[0m←[1;31m ->←[0m ←[1;34m$ ←[0m←[1;33mvirtualenv project←[0m←[1;31m ->←[0m [1xx.xx.xxx.xxx] out: Using base prefix '/usr' [1xx.xx.xxx.xxx] out: New python executable in /home/adm/.virtualenvs/project/bin/python3 [1xx.xx.xxx.xxx] out: Also creating executable in /home/adm/.virtualenvs/project/bin/python [1xx.xx.xxx.xxx] out: Installing setuptools, pip, wheel... [1xx.xx.xxx.xxx] out: done. [1xx.xx.xxx.xxx] out: [localhost] local: git push -f ssh://adm@1xx.xx.xxx.xxx/home/adm/git/project.git master adm@1xx.xx.xxx.xxx's password: Everything up-to-date ←[1;34m$ ←[0m←[1;33mGIT_WORK_TREE=/home/adm/mezzanine/project git checkout -f master←[0m←[1;31m ->←[0m [1xx.xx.xxx.xxx] out: Already on 'master' [1xx.xx.xxx.xxx] out: ←[1;34m$ ←[0m←[1;33mGIT_WORK_TREE=/home/adm/mezzanine/project git reset --hard←[0m←[1;31m ->←[0m [1xx.xx.xxx.xxx] out: HEAD is now at a1fe1de Droplet reset [1xx.xx.xxx.xxx] out: [1xx.xx.xxx.xxx] out: sudo password: [1xx.xx.xxx.xxx] out: ERROR: role "project" already exists [1xx.xx.xxx.xxx] out: Fatal error: sudo() received nonzero return code 1 while executing! Requested: psql -c … -
How to change a field in parent class while creating chiled class fields in forms.py and views.py?
I'm was creating ModelForm I try to make change the parent class while saving child class fields to the database, in the views.py I made but it didn't save to the database. here is my model.py class Table(models.Model): restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE) book = models.BooleanField(default=False) class People(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) taple = models.OneToOneField(Table, on_delete=models.CASCADE, null=True, blank=True) @receiver(post_save, sender=User) def update_people_profile(sender, instance, created, **kwargs): try: instance.people.save() except ObjectDoesNotExist: People.objects.create(user=instance) Class People is the child class and Table is the parent class so I'm using People class for making forms. here is my forms.py class Booking(forms.ModelForm): class Meta: model = People fields = [ 'taple', ] So I want to make True book field in Table class and save it to the database when saving Booking form. here is my views.py def booking(request): if request.method == 'POST': try: people_instance = People.objects.get(user=request.user) except Table.DoesNotExist: people_instance = People(user=request.user) form = Booking(request.POST, instance=people_instance) if form.is_valid(): user = form.save(commit=False) user.taple.booking = True user.refresh_from_db() user.user = request.user user.taple = form.cleaned_data.get('taple') user.save() print(user.taple.booking, user.taple.id) return redirect('booked') else: form = Booking() return render(request, 'main/booking.html', {'form': form}) Any Idea? -
How to deploy a wep abb within my work network?
I created an API for the company i work however i would like people having access in the same company network, how can i achieve this? I currently modified the allowed host as follow: ALLOWED_HOSTS = ['127.0.0.1', 'localhost','192.168.6.7', '127.0.1.1', '161.19.109.123'] however only work in my computer under IP: 127.0.0.1:8000, any suggestions? FYI i do not have administrator privilege. -
Set up django-celery-email for local dev
It seems the best way to send emails from the django-allauth app asynchronously is to simply install django-celery-email. But the packages warns that This version requires the following versions:Python 2.7 and Python3.5, Django 1.11, 2.1, and 2.2 Celery 4.0 I've only been using python for several months and never encountered a situation where two python version are needed on a project. And I'm using the official recommendation of pipenv for local development. A quick google shows that it isn't possible to have two python interpreters installed in the virtual environment. Since the plugin seems so popular I wondered how others were setting it up? Apologies if I've missed something major that explains this. A bonus answer would also take into account that I am using docker and the docker image will install the python packages like this. RUN pipenv install --system --deploy --ignore-pipfile Many thanks in advance. -
How do I use Django template tags inside javascript
I am using a library called FullCalendar and I want my model data inside my template inside the javascript which I have seen many people do. But for some reason the template tags won't register as template tags and I get an error. <script> document.addEventListener('DOMContentLoaded', function() { var Calendar = FullCalendar.Calendar; var Draggable = FullCalendarInteraction.Draggable; var containerEl = document.getElementById('external-events'); var calendarEl = document.getElementById('calendar'); var checkbox = document.getElementById('drop-remove'); // initialize the calendar // ----------------------------------------------------------------- var calendar = new Calendar(calendarEl, { plugins: [ 'interaction', 'dayGrid', 'timeGrid', 'bootstrap', 'interaction' ], themeSystem: 'bootstrap', selectable: true, select: function(info) { var titleStr = prompt('Enter Title'); var date = new Date(info.startStr + 'T00:00:00'); // will be in local time if (!isNaN(date.valueOf())) { // valid? calendar.addEvent({ title: titleStr, start: date, allDay: true, }); } }, locale: "sv", header: { left: 'prev,next today', right: 'dayGridMonth,timeGridWeek,timeGridDay' }, customButtons: { }, eventClick: function(info) { alert('Event: ' + info.event.title); }, editable: true, droppable: true, events: [ {% for event in events %} { title: "{{ event.name}}", start: '{{ event.start|date:"Y-m-d" }}', end: '{{ event.end|date:"Y-m-d" }}', }, {% endfor %} ], }); calendar.render(); }); </script> the part that is not working is the {% for event in events %} loop, the view parses the … -
How to save objects en la UpdateView class, returning a Json?
I have 2 related models for an fk and to which I access. But to save the instances of the forms in the UpdateView class, I get the error "AttributeError: type object 'Users_up' has no attribute 'object' [10 / Oct / 2019 15:18:17] "POST / PermissionUpdateView / 3 / HTTP / 1.1" 500 "and don't let me save with the post help method please, what am I wrong? viws.py class PermisoUpdateView(UpdateView): model = Permiso second_model = Users template_name = 'plantillas/permisos_update.html' form_class = Permiso_update second_form_class = Users_up def get_context_data(self,*args,**kwargs): context =super(PermisoUpdateView, self).get_context_data(**kwargs) pk = self.kwargs.get('pk', 0) p = self.model.objects.get(id=pk) u = self.second_model.object.get(id=p.usuario_id) if 'form' not in context: context['form'] = self.form_class(instance=p) if 'form2' not in context: context['form2'] = self.second_form_class(instance=u) context['id'] = pk return context def post(self, request,*args, **kwargs): self.object = self.get_object id_Permiso = kwargs['pk'] per = self.model.objects.get(id=id_Permiso) us = self.second_form_class.object.get(id=per.usuario_id) form = self.form_class(request.POST, instance=per) form2 = self.second_form_class(request.POST, instance=us) if form.is_valid and form2.is_valid and request.is_ajax(): form.save() form2.save() return JsonResponse({'status':'true', 'msg':'Datos procesados correctamente'})#retornando JSon en jsConsole else: return JsonResponse({'status':'false', 'msg':'Datos procesados incorrectamente'})#retornando respuesta en jsConsole -
Add context variable as an aggregate or annotate of 2 cols in CBV's get_context_data()
I want to return total value as revenue variable in get_context_data method of ClassBasedView. I also want to return another operation: total - shipping_cost as revenue_no_shipping_cost variable in context. I've tried: from django.db.models import F, Sum class OrdersListView(PermissionRequiredMixin,ListView): model = Order permission_required = 'is_staff' template_name = "order/revenue.html" paginate_by = 10 def get_queryset(self): filter_month = self.request.GET.get('filtromes', '0') if filter_month == "0": return Order.objects.filter(status = 'recibido_pagado') else: return (Order.objects .filter(created__month=filter_month, status = 'recibido_pagado')) def get_context_data(self, **kwargs): context = super(OrdersListView, self).get_context_data(**kwargs) qs = kwargs.pop('object_list', self.object_list) order = self.request.GET.get('orderby', 'created') context = {} revenue = qs.aggregate(revenue=Sum('total')) revenue_no_shipping = qs.annotate(revenue_no_shipping=F('total') + F('shipping_cost')) context['revenue'] = revenue context['revenue_no_shipping'] = revenue_no_shipping context['filtromes'] = self.request.GET.get('filtromes', '0') context['orderby'] = self.request.GET.get('orderby', 'created') context['category'] = "catalogo" return context But in template, I'm getting: For revenue: {'revenue': Decimal('42')} #is 42.00 For revenue_no_shipping: <QuerySet [<Order: 58>]> #Should be 25.00 -
django.core.exceptions.ValidationError: ["'_auth_user_id' value must be an integer."] error on Django
as for the title I have this problem with validation in Django. This error occours when i Logout, it seems like the system is looking for the user id but, because i clear the session with the log out(not sure anyway if this is right, I use django auth for the login/logout system), it can't find any user with same id in the session and is giving me this error. So I tried removing all the user call i have in the code but it is still not working at all. Here as follow the full error log. Internal Server Error: / Traceback (most recent call last): File "C:\Users\gello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\fields\__init__.py", line 941, in to_python return int(value) ValueError: invalid literal for int() with base 10: '_auth_user_id' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\gello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\gello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\gello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\gello\Desktop\Projects\buyit\home\views.py", line 12, in index return render(request, "index.html", {"products": products, "product_reviews": product_reviews}) File "C:\Users\gello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\shortcuts.py", line 36, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\gello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\loader.py", line 62, in render_to_string return … -
Method GET Django and Angular error 500 internal server
I'm building a basic app with login, register, etc. now i try finish the login using Django like backend and fronted with Angular, but i can't end my login because this error, when i try login with the correct credentials and redirect to new page or url show this error. TypeError at /doctor 'list' object is not callable"in network panel" service .ts constructor(private http: Http, private httpClient: HttpClient) { } private headers = new Headers({ 'Content-Type': 'application/json' }); getDoctores(): Promise<Doctor[]> { return this.http.get(this.baseurl + '/doctor?format=json', { headers: this.headers }) .toPromise() .then(response => response.json() as Doctor[]) } component .ts constructor(private dataService: dataService, public dialog: MatDialog, private router: Router) { this.getDoctores(); this.selectedDoctor = { id: -1, nombreDoc: '', apellidoDoc: '', rutDoc: '', direccionDoc: '' , telefonoDoc: '', release_date: '' } } getDoctores(): void { this.dataService .getDoctores() .then(doctores => this.doctores = doctores); } url.py path('auth/login/', obtain_jwt_token), path('auth/refresh-token/', refresh_jwt_token), url(r'^doctor$', views.DoctorList.as_view()), url(r'^doctor/(?P<pk>[0-9]+)$', views.DoctorDetail.as_view()), view.py class DoctorList(generics.ListCreateAPIView): queryset = Doctor.objects.all() serializer_class = DoctorSerializer class DoctorDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Doctor.objects.all() serializer_class = DoctorSerializer -
How to implement User system for job board (I need employers to be able to register and create posts)?
I am creating a job board where users can search a zip code and see jobs in their area. I have the following models.py: class Business(models.Model): name = models.CharField(max_length = 150) address = models.CharField(max_length = 150) city = models.CharField(max_length = 150) zip_code = models.CharField(max_length = 10) state = models.CharField(max_length = 30) phone_number = models.CharField(max_length = 10) class Job(models.Model): business = models.ForeignKey(Business, on_delete = "models.CASCADE") #when the referenced object is deleted, also delete the objects that have references to it. title = models.CharField(max_length = 100) description = models.CharField(max_length = 500) zip_code = models.CharField(max_length = 10) def save(self, *args, **kwargs): zip_code = self.business.zip_code super(Job, self).save(*args, **kwargs) To use the website to look for jobs, you do not have to sign in. However, I obviously need employer's to be able to create an account so that they can register a business and post jobs for said business. I am not sure how to approach this and have seen many different ways to go about it online. Should I have the Business model extend the User model as such: class Business(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) #other fields... and then when an employer registers show a form that includes the User fields as well as … -
Importerror: How to import django-nose package?
Installed django-nose in virtual environment: (venv) user@~/../src$ pip install django-nose DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support Requirement already satisfied: django-nose in /home/user/../venv/lib/python2.7/site-packages (1.4.6) Requirement already satisfied: nose>=1.2.1 in /home/user/../venv/lib/python2.7/site-packages (from django-nose) (1.3.7) (venv) user@~/../src$ Django settings in test.py has django-nose package mentioned as INSTALLED_APPS, shown below: from base import * import os # Installed apps INSTALLED_APPS += ('django-nose', ) TEST_RUNNER = 'django_nose.NoseTestSuiteRunner' TEST_OUTPUT_DIR = os.environ.get('TEST_OUTPUT_DIR', '.') NOSE_ARGS = [ '--verbosity=2', '--nologcapture', '--with-coverage', '--cover-package=todo', '--with-spec', '--spec-color', '--with-xunit', '--xunit-file=%s/unittests.xml' % TEST_OUTPUT_DIR, '--cover-xml', '--cover-xml-file=%s/coverage.xml' % TEST_OUTPUT_DIR, ] # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default':{ 'ENGINE': 'django.db.backends.mysql', 'NAME': os.environ.get('MYSQL_DATABASE', 'xxxxx'), 'USER': os.environ.get('MYSQL_USER', 'xxx'), 'PASSWORD': os.environ.get('MYSQL_PASSWORD', 'xxx'), 'HOST': os.environ.get('MYSQL_HOST', 'localhost'), 'PORT': os.environ.get('MYSQL_PORT', '3306') } } But django-nose package is not getting imported, based on below error: (venv) user@~/../src$ ls db.sqlite3 manage.py todo todobackend (venv) user@~/../src$ python manage.py test --settings=todobackend.settings.test Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/user/../venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 350, in execute_from_command_line utility.execute() File … -
Pytest delete db after tests
I have a test suite in pytest-django and I want to create a database at the start of the test and then delete the same as soon a test is completed in order to simulate the scenario without keeping a huge chunk of data. Any help would be appreciated. Thanks in advance! -
Unable to fetch data from database using django
I have created one small project in django, in which database is connected with django and having 'Reg' as table name in database. In models.py from django.db import models class Reg(models.Model): Name = models.CharField(max_length=10) Email = models.CharField(max_length=20) TUID = models.CharField(max_length=10) Password = models.CharField(max_length=8) In views.py from django.shortcuts import render, redirect from django.contrib.auth.models import User, auth from django.contrib import messages from .models import Reg, Group from django.http import HttpResponse def login(request): raw = Group.objects.all() return render(request, 'login.html', {'raw': raw}) In login.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>login</title> </head> <body> <p>hello....</p> {% for val in raw %} <p>{{ val.Name }}</p> {% endfor %} <p>end...</p> </body> </html> expected result should be data from database, but getting only hello... end... -
DRF - How do I link back from model class with PrimaryKey to model class with ForeignKey
I have two models Job and JobDescription. I have a ForeignKey jobid defined in JobDescription. The django-rest-framework does its magic and finds the automatically created PK id in Job to link to. In serializers.py JobDescriptionSerializer jobid will give me a hyperlink to the Job id. So far so good. At this moment however, this is a one way street (JobDescription -> Job). I would like to add a field to Job model/serializer that will allow hyperlinking the other way around as well (Job -> JobDescription). I went through the Django models documentation around ForeignKey and there are some references to forward/backward relationships, but how do I implement this in the rest-framework models/serializers? Thanks for your help in advance! models.py: class Job(models.Model): title = models.CharField(max_length=100, default='') type = models.CharField(max_length=20, default='') location = models.CharField(max_length=100, default='') created_date = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['id'] def __str__(self): return self.title class JobDescription(models.Model): jobid = models.ForeignKey(Job, related_name='desc2job', on_delete=models.CASCADE) description = models.TextField(blank=False) created_date = models.DateTimeField(default=timezone.now) class Meta: ordering = ['id'] def __str__(self): return str(self.jobid) serializers.py: class JobSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Job fields = ( 'url', 'id', 'title', 'type', 'location', 'created_date') class JobDescriptionSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = JobDescription fields = ('url', 'id', 'jobid', 'description', 'created_date') -
Django Testing - authenticate() returns None
Working on making some unittests with Django, and trying to make some testing with the login process with the login form. I am using modified User model just to make the email field unique; otherwise nothing drastically different. account/views.py def post(self, request): # Retrieve the username and password username = request.POST['username'] password = request.POST['password'] # Create a user object from authentication, or return None user = authenticate(username=username, password=password) # Check if user was created if user is not None: # Rest of the code, irrelevant... account/test_views.py def test_account_login_POST_successful_login(self): # Create a user to test login CustomUser.objects.create_user( username='test_user', email='test_user@intranet.com', password='flibble' ) response = self.client.post(self.login_url, { 'username': 'test_user', 'password': 'flibble' }) self.assertEqual(response.status_code, 301) account/models.py class User(AbstractUser): # Make the email field unique email = models.EmailField(unique=True) project/settings.py # Authentication AUTH_USER_MODEL = 'account.User' Funny thing is that login works normally on the web app, but when testing it always returns None. I've tried to check_password() with the created user, and it returns true in both the test method and the view method. I've also tried putting in AUTHENTICATION_BACKEND = ['django.contrib.auth.backends.ModelBackend'], but no go. -
Celery: different settings for task_acks_late per worker / add custom option to celery
This question is a follow up of Is there any way to find out the hash value of two files? I had a problem with celery (see the question that I follow up) and in order to resolve it I'd like to have two celery workers with -concurrence 1 each but with two different settings of task_acks_late. My current approach is not very beautiful. I am doing the following: in settings.py of my django project: CELERY_TASK_ACKS_LATE = os.environ.get("LACK", "False") == "True" This allows me to start the celery workers with following commands: LACK=True celery -A miniclry worker --concurrency=1 -n w2 -Q=fast,slow --prefetch-multiplier 1 celery -A miniclry worker --concurrency=1 -n w1 -Q=fast What would be more intuitive would be if I could do something like: celery -A miniclry worker --concurrency=1 -n w2 -Q=fast,slow --prefetch-multiplier 1 --late-ack=True celery -A miniclry worker --concurrency=1 -n w1 -Q=fast --late-ack=False I found Initializing Different Celery Workers with Different Values but don't understand how to embed this in my django / celery context. In which files would I have to add the code that's adding an argument to the parser and how could I use the custom param to modify task_acks_late of the celery settings. -
Django populating model in signal with accessing request
I am in trouble in populating a table, at first see my models. from django.contrib.auth.models import User class Group(models.Model): members = models.ManyToManyField( User, through='PersonGroup', related_name='person_of_the_group' ) class PersonGroup(models.Model): group = models.ForeignKey( Group, on_delete=models.CASCADE, related_name='group_person_of_group' ) person = models.OneToOneField( User, on_delete=models.CASCADE, related_name='group_person_of_group' ) I want when I create a group, the PersonGroup should populate automatically, I tried to achieve it in the signal but failed to do it, coz, I couldn't access request.user in signal @receiver(post_save, sender=Group) def create_person(sender, instance, created, **kwargs): if created: PersonGroup.objects.create( # ) Can anyone help to access to request in the signal? I need to solve this problem in signal at any means