Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Apply widget dynamically depending on field value
In a Django project, I have a form with a use_format checkbox (unchecked by default) and a post CharField. Because I want to be able to add extra features to the post text field, like text formatting, I have imported a RichTextEditor widget to do so. The thing here is that I only want to use the RichTextEditor widget in post if use_format is checked. class ArticleForm(ModelForm): def __init__(self, *args, **kwargs): super(ArticleForm, self).__init__(*args, **kwargs) if not self.instance.use_format: self.fields['post'] = forms.CharField(widget=forms.Textarea) class Meta: model = Article fields = '__all__' widgets = { 'post': RichTextEditor(options={...}), } So far, what I've been doing when I want to create an article with formatting is to create the article with use_format checked. Save. Then edit the article and there I have the post with the RichTextEditor. I would like to have the post changing automatically between CharField or RichTextEditor as I check or uncheck the use_format checkbox. First, is this possible? What I've been trying: I've added a custom script on my ModelAdmin to detect changes to the use_format value class ArticleAdmin(admin.ModelAdmin): form = ArticleForm class Media: js = ('js/toggleUseFormat.js') toggleUseFormat.js: if (!$) { $ = django.jQuery; } $(document).ready(function () { $("#id_use_format").change(function () { // … -
html file in django project not working properly
I am new to django, i created two folder static and templates in django project, i created a html file in templates folder index.html, but VS code is not working properly here, i.e not showing emmet and html tag suggestion as VS code suggest normally, while on other files of other project not belong to django , VS code working properly , please anyone know about it ? -
Django No Reverse Match Error - Nothing is working
When rendering a new page, the html form action on that new page is stopping the page from being rendered... even though it has nothing to do with the page itself being rendered (if I remove that one line of HTML code, the page loads just fine). I've been working on solving this problem for over 3 days, tried hundreds of possible solutions, nothing works. Please help This is the error: Reverse for 'editgallery' with arguments '('rodneyadmin', '')' not found. 1 pattern(s) tried: ['editgallery/(?P[^/]+)/(?P<gallery_id>[0-9]+)\Z'] This is the line of code being highlighted as cause for error (form action): <form action="{% url 'gallery_app:editgallery' user.username new_gallery.id %} " style="font-weight: bolder;" enctype='multipart/form-data' method='POST' class='gap-2'> Views.py: @login_required def newgallery(request, username): if request.method == 'GET': form = NewGalleryForm context = { 'form': form, 'username': username, } return render(request, 'galleries/newgallery.html', context) def editgallery(request, username): if request.method == "POST": form = NewGalleryForm(request.POST) if form.is_valid(): new_gallery = form.save(commit = False) ## connect the new gallery with the user (foreign key) new_gallery.user = request.user new_gallery.save() url = "https://api.opensea.io/api/v1/assets?order_direction=desc&offset=0&limit=5" params={'owner': new_gallery.wallett_address} headers = { "Accept": "application/json", "X-API-KEY": "" } response = requests.request("GET", url, headers=headers, params=params) response = response.json()["assets"] list_of_nfts = [] for dictionary in response: token_id = dictionary["token_id"] token_address = … -
What Is Can Order In Django Formsets Actually For?
I've spent a fair amount of time the last day or so exploring the can order field with Django Formsets but I can't for the life of me actually figure out what it's for. Apparently it doesn't update the database...and it does put an order number field with the form....but beyond that what is it for? I can't find any useful documentation on how to actually use this field. Do I have to write Javascript in order to get this field to do anything actually meaningful? I get the delete option...and you have to add code in to delete the record...So I guess I'm to take it the same is required for the can_order field? Sorry if this is a silly question but I've spent more time trying to figure this out than what would be reasonable by now. -
CSP error for bootstrap image in navbar hamburger
I just added content security policy to my Django site. I have everything working correctly except these two errors for images that I had no idea what they were I spent a bunch of time trying to figure it out until I noticed that the icon on the bootstrap hamburger menu was gone In the CSS I found this telling me that this must be the image in the navbar causing this error. I found a few workarounds online but they presented security vulnerabilities and i would like to do it properly How can I go about solving this issue. CSP CSP_STYLE_SRC = ("'self'", "https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css", ... ) CSP_SCRIPT_SRC = ("'self'", "https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/", ... ) -
MY 'image' attribute has no file associated with it
With my reading of many answers to questions similar to mine, all of those answers did not find a solution to my problem.. so I will present them so that I may find a solution that fits my problem: my View file: enter image description here my Template File: enter image description here my Admin file: enter image description here The Error: enter image description here enter image description here I tried every solution with no hope. -
Server down when uploading a file in a Django App on DigitalOcean
I have developed an application where a user can upload a zip file, the zip file gets uncompressed and stored in a newly created folder using os.mkdir() On the local machine the process works perfectly, but when uploaded to digitalocean in production mode (gunicorn + nginx), the upload process results in a "Site cannot be reached" browser error, not even an HTTP error where we can trace the problem. Here are all the elements that you might need to see: views.py: @user_passes_test(lambda u: u.is_staff or u.is_superuser) def createCategory(request): if request.method == "POST": name = request.POST.get("name_kw") lang = request.POST.get("lang_kw") moduleid = request.POST.get("module_kw") zip = request.FILES.get("zip_kw") category = Category() category.name = name category.lang = lang category.module = Module.objects.get(id=moduleid) category.zip = zip category.created_by = request.user try: if zip.name.endswith(".zip"): rtn = publish_doc(category.name, zip) if rtn == "No index file found": messages.error( request, "Pas de fichier index.html détecté. Assuez-vous qu'un fichier index.html est présent dans votre fichier ZIP", ) return redirect("categoryList") else: category.root = rtn category.save() messages.success(request, "Catégorie créée avec succès") print("categorie et zip créées") return redirect("categoryList") else: messages.error( request, "Seuls les fichiers .ZIP sont acceptés", ) return redirect("categoryList") except IntegrityError: print("erreuuuuuuuur") messages.error( request, "Une erreur s'est produite. Veuillez réessayer plutard, ou contacter notre équipe … -
Mocking a request object to pass to ViewSet create() method
I'm learning unittest and unittest.mock, and struggling with the concepts and implementations primarily with mock. For context, what I'm playing with is a Django / DRF API and Redis. I'm trying to write tests which require mocking the Redis calls. Here is the test I'm working on: # tests.py import unittest from unittest.mock import patch from core.views import KeysViewSet class KeysViewSetTestCase(unittest.TestCase): def setUp(self): self.json_object = {'key': 'hello', 'value': 'world'} self.view = KeysViewSet() def test_create(self): with patch('core.views.RedisUtil.create') as mocked_create: mocked_create.return_value.data = True created = self.view.create(self.json_object) The views.py: # viefws.py # Third party imports from rest_framework import status, viewsets from rest_framework.response import Response # Croner imports from .serializers import KeysSerializer # Import Redis from .utils import RedisUtil class KeysViewSet(viewsets.ViewSet): """ METHOD URI DESCRIPTION GET /api/keys/<:key>/ Returns specific value from key POST /api/keys/ Creates a new key/value DELETE /api/keys/<:key>/ Deletes a specific key """ def __init__(self, *args, **kwargs): """ Instantiate the RedisUtil object. """ self.redis_util = RedisUtil() def create(self, request): """ Creates a key/pair in the Redis store. """ print(request) # Serialize the request body serializer = KeysSerializer(data=request.data) # If valid, create the key/value in Redis; if not send error message if serializer.is_valid(): return Response(self.redis_util.create(serializer.data)) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) And the utils.py that … -
How to create a button that submit a form and download file in Django
How to create a button that submit a form and download file in Django I know use this code and download file <html> <title>Download File</title> </head> <body> <enter> <h1>Download File using Django</h1> <a href="{% url 'download_pdf_file' filename='CF.pdf' %}">Download PDF</a> </center> </body> </html> I also know how to create a button that submit some data <input type="submit" value='submit' class="btn btn-primary btn-sm"> But how could I combine them into in button The reason why I need to do that is I want to update the exist file and download it in the same page. -
How can I add a voice recorder in webpage from user and save it in filefield at django model?
I am studying for a long on a voice recorder from the webpage and I need that to send this data to the backend. I don't know how to do that. If someone can guide me that would be a great help. Thanks in advance. -
Django AttributeError object has no attribute 'upper'
I am implementing an API for an image labelling app. I have customised a create() method for Tagging. A Tagging contains a tag, which is an object containing a name and a language. To make tags easier to compare to each other, I have to save all tags either in upper or lower case. serializers.py def create(self, validated_data): """Create and return a new tagging""" user = None request = self.context.get("request") if request and hasattr(request, "user"): user = request.user score = 0 tag_data = validated_data.pop('tag', None) if tag_data: tag = Tag.objects.get_or_create(**tag_data)[0] validated_data['tag'] = tag tagging = Tagging( user=user, gameround=validated_data.get("gameround"), resource=validated_data.get("resource"), tag=validated_data.get("tag"), created=datetime.now(), score=score, origin="" ) tagging.save() return tagging I have tried both this tag=validated_data.get("tag").upper() and this: tag=validated_data.get("tag").lower() and I get an AttributeError 'Tag' object has no attribute 'upper' or 'Tag' object has no attribute 'lower'. I want for this tag: { "gameround_id": 65, "resource_id": 11601, "tag": { "name": "TagToTestNow", "language": "de" } } to be saved something like "TAGTOTESTNOW" or "tagtotestnow" to make Tag comparison easier. How can I achieve this? -
Recursive function to calculate the children of a parent
I have a set of data that looks like this: Person1 is the parent of Person2 Person2 is the parent of Person3 and Person4 Person3 is the parent of Person1 If I try to calculate the whole tree for Person1, the max recurssion will be exceeded and the program will terminate in an error. The expected result would be Person1 -> [Person2, Person3, Person4], so basically in the case the the calculation has to be repeated for an element that is already in the list, this has to be ignored. Do you have an idea, how could I solve this problem? My function looks something like this: def compute_children(self): children = [] children.extend(self.child) for child in children: temp = child.compute_children() if 0 < len(temp): children.extend(temp) return children -
How to let the user select multiple choices while filtering data using django-filter?
I have a model: class Radiations(models.Model): patient=models.ForeignKey(Patient, on_delete=CASCADE) patient_type=models.ForeignKey(PatientType, on_delete=CASCADE, default=None) date=models.DateField(default=datetime.date.today) done_fractions=models.IntegerField(default=0) base_value=models.DecimalField(max_digits=10, decimal_places=2, blank=True, default=None) expected_value=models.DecimalField(max_digits=10, decimal_places=2, blank=True, default=None) remarks=models.TextField(max_length=500, blank=True, default=None) radiations_date=models.DateTimeField(auto_now_add=True) modified_on=models.DateTimeField(auto_now=True) Its filter looks like this: class RadiationsFilters(django_filters.FilterSet): patient__name=django_filters.CharFilter(lookup_expr='icontains', label='Name') from_date=django_filters.DateFilter(widget=forms.DateInput(attrs={'type': 'date'}), field_name='date', label='From - Date ', lookup_expr='gte') to_date=django_filters.DateFilter(widget=forms.DateInput(attrs={'type': 'date'}), field_name='date', label='To - Date ', lookup_expr='lte') Now, I want the user to be able to select multiple patients which are saved in the database, how can I bring them into my filter code? Someone please help. Thanks in advance. -
JsonPickle decodes a function into None value
I am using jsonpickle in a django project to store lists, sets or dicts of custom objects in a models.JSONField. I'm running tests to check my code: everything is fine, but goes wrong if I just try to .reload_from_db() an instance containing this kind of JSONField in it. The problem comes from json decoding. After digging this, I found that this string: { "py/set": [ { "py/function": "Main.files.Effects.AddEffectToAttacks.apply.<locals>.remove_effect.<locals>.wrapper" } ] } becomes: {None} let's say: s = '{\n "py/set": [\n {\n "py/function": "Main.files.Effects.AddEffectToAttacks.apply.<locals>.remove_effect.<locals>.wrapper"\n }\n ]\n}' jsonpickle.decode(s) will return {None} when it is obviously not None but a function: Main.files.Effects.AddEffectToAttacks.apply.<locals>.remove_effect.<locals>.wrapper Does someone have an explanation and a solution for this please? -
Django channels tests fails
I have followed the tutorial from readthedocs: https://channels.readthedocs.io/en/stable/tutorial/index.html for django channels. Everything worked fine until the last part of the tutorial, about testing. Here is the test file as well as the traceback. # chat/tests.py from channels.testing import ChannelsLiveServerTestCase from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support.wait import WebDriverWait class ChatTests(ChannelsLiveServerTestCase): serve_static = True # emulate StaticLiveServerTestCase @classmethod def setUpClass(cls): super().setUpClass() try: # NOTE: Requires "chromedriver" binary to be installed in $PATH cls.driver = webdriver.Chrome() except: super().tearDownClass() raise @classmethod def tearDownClass(cls): cls.driver.quit() super().tearDownClass() def test_when_chat_message_posted_then_seen_by_everyone_in_same_room(self): try: self._enter_chat_room('room_1') self._open_new_window() self._enter_chat_room('room_1') self._switch_to_window(0) self._post_message('hello') WebDriverWait(self.driver, 2).until(lambda _: 'hello' in self._chat_log_value, 'Message was not received by window 1 from window 1') self._switch_to_window(1) WebDriverWait(self.driver, 2).until(lambda _: 'hello' in self._chat_log_value, 'Message was not received by window 2 from window 1') finally: self._close_all_new_windows() def test_when_chat_message_posted_then_not_seen_by_anyone_in_different_room(self): try: self._enter_chat_room('room_1') self._open_new_window() self._enter_chat_room('room_2') self._switch_to_window(0) self._post_message('hello') WebDriverWait(self.driver, 2).until(lambda _: 'hello' in self._chat_log_value, 'Message was not received by window 1 from window 1') self._switch_to_window(1) self._post_message('world') WebDriverWait(self.driver, 2).until(lambda _: 'world' in self._chat_log_value, 'Message was not received by window 2 from window 2') self.assertTrue('hello' not in self._chat_log_value, 'Message was improperly received by window 2 from window 1') finally: self._close_all_new_windows() # === Utility === def _enter_chat_room(self, room_name): self.driver.get(self.live_server_url + '/chat/') ActionChains(self.driver).send_keys(room_name + '\n').perform() WebDriverWait(self.driver, … -
How do I make the view to show a multi-step form that has forms and formsets
I want to use a multi-step form combined with some formsets in Django but I realize I need more experience on the subject. I also see that there is hardly much documentation about it and what little I find they take many things for granted. Can you help me understand how to create a view that serves as a multi-step and that saves the values of the forms and formsets? previously I was already using JS for the wizard, the only thing missing is that I save the values in the database. thanks :D Views.py def create_Presupuestos(request): extra_forms = 1 ParteFormSet = formset_factory(PresupuestosParteForm, extra=extra_forms, max_num=20) ManoObraFormSet = formset_factory(PresupuestosManoObraForm, extra=extra_forms, max_num=20) PagosFormSet = formset_factory(PresupuestosPagosForm, extra=extra_forms, max_num=20) presupuestosclientesform=PresupuestosClientesForm(request.POST or None) presupuestosvehiculosform=PresupuestosVehiculosForm(request.POST or None) presupuestosparteform=PresupuestosParteForm(request.POST or None) presupuestosmanoobraform=PresupuestosManoObraForm(request.POST or None) presupuestospagosform=PresupuestosPagosForm(request.POST or None) presupuestosfotosform=PresupuestosFotosForm(request.POST or None) if request.method == 'POST': formset = ParteFormSet(request.POST, request.FILES) manoObra_formset = ManoObraFormSet(request.POST, request.FILES,prefix='manoobra') pagos_formset = PagosFormSet(request.POST, request.FILES, prefix='pagos') if formset.is_valid() and manoObra_formset.is_valid() and pagos_formset.is_valid(): presupuestosclientesform.save() return redirect('presupuestos:index') else: formset = ParteFormSet() manoObra_formset = ManoObraFormSet(prefix='manoobra') pagos_formset = PagosFormSet(prefix='pagos') presupuestosfotosform = PresupuestosFotosForm(request.POST or None) return render(request,'Presupuestos/new-customer.html',{ 'presupuestosclientesform':presupuestosclientesform, 'presupuestosvehiculosform':presupuestosvehiculosform, 'presupuestosparteform':presupuestosparteform, 'presupuestosmanoobraform':presupuestosmanoobraform, 'presupuestospagosform':presupuestospagosform, 'presupuestosfotosform':presupuestosfotosform, 'formset':formset, 'manoObra_formset':manoObra_formset, 'pagos_formset':pagos_formset }) -
django-celery-results are not expiring even though CELERY_RESULT_EXPIRES is set
I have an every minute task running on celery beat and I'm using rabbimq as broker and have postgresql as database. As my task is running every minute and I'm storing task result in database, my database size is increasing continuously day by day. I was looking into expiration of stored task result. As per celery documentation there is a CELERY_RESULT_EXPIRES config which uses celery beat to do a cleanup. Seems like it's not happening as expected. What am I missing or do wrong? Any pointers would be really great help. Following are my celery settings defined in my django settings.py CELERY_BROKER_URL = os.getenv('CELERY_BROKER_URL', 'amqp://localhost') CELERY_RESULT_BACKEND = 'django-db' CELERY_CACHE_BACKEND = 'django-cache' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_ENABLE_UTC = False CELERY_TIMEZONE = 'UTC' CELERY_CREATE_MISSING_QUEUES = False CELERY_DEFAULT_QUEUE = 'celery' CELERY_TASK_TRACK_STARTED = True CELERY_SEND_EVENTS = True CELERY_SEND_SENT_EVENT = True CELERY_WORKER_MAX_TASKS_PER_CHILD = 25 CELERY_TASK_REJECT_ON_WORKER_LOST = True CELERYD_TIME_LIMIT = 60 CELERYD_SOFT_TIME_LIMIT = 50 CELERY_ACKS_LATE = True CELERYD_PREFETCH_MULTIPLIER = 1 CELERY_RESULT_EXPIRES = 1 * 60 Following is my celery.py import django import logging from celery import Celery from celery.schedules import crontab from kombu import Exchange, Queue log = logging.getLogger(__name__) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'xxx.settings') django.setup() app = Celery('xxx') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() app.conf.task_queues = ( … -
Django converting isoformat string datetime to tuple and rising error
I'm trying to update two datetimefields for the Skill entity in my db. I'm sure I'm passing an isoformat datetime string. When creating instead of updating everything works fine but on the update I get: Exception Type: TypeError Exception Value: fromisoformat: argument must be str Here is the code raising the TypeError: # create or update skill created = ibm_date_to_iso(clean_data["skill"]["created"]) updated = ibm_date_to_iso(clean_data["skill"]["updated"]) try: skill = Skill.objects.get( skill_id=clean_data["skill"]["skill_id"], snapshot=clean_data["skill"]["snapshot"] ) # update fields if skills exists already skill.name = clean_data["skill"]["name"], skill.type = clean_data["skill"]["type"], skill.status = clean_data["skill"]["status"], skill.created = created, skill.updated = updated, skill.language = clean_data["skill"]["language"], skill.description = clean_data["skill"]["description"], skill.dialog_settings = clean_data["skill"]["dialog_settings"] skill.uploads.add(u) except Skill.DoesNotExist: skill = Skill( skill_id=clean_data["skill"]["skill_id"], name=clean_data["skill"]["name"], type=clean_data["skill"]["type"], status=clean_data["skill"]["status"], created=created, updated=updated, language=clean_data["skill"]["language"], snapshot=clean_data["skill"]["snapshot"], description=clean_data["skill"]["description"], dialog_settings=clean_data["skill"]["dialog_settings"] ) skill.save() skill.uploads.add(u) # new page for the skill entity page = Page( title="notes for Skill {} snap {}".format( skill.name, skill.snapshot), content="This page is empty..." ) page.save() skill.save() The exception is raised on the last line (skill.save()) only when the DoesNotExist exception is not raised. Here is the Skill model: class Skill(models.Model): skill_id = models.CharField(max_length=36) name = models.TextField() type = models.TextField() status = models.TextField() created = models.DateTimeField() updated = models.DateTimeField() language = models.TextField() snapshot = models.IntegerField() description = models.TextField() dialog_settings = models.TextField() page … -
In Django how to add user to many-to-many filed
I like to add permission to those users who I add to a many-to-many relation. I have a Projekt model where I like to add multiple users like this: class Projekt(models.Model): def __str__(self): return str(self.projekt) projekt = models.TextField(max_length=150) company_name = models.ForeignKey('Company', on_delete=models.CASCADE, default=1) jogosult_01 = models.ManyToManyField(User) date = models.DateField(auto_now_add=True, auto_now=False, blank=True) I add the users in the Django Admin page with holding down cmd then save and it shows everything is OK. If try to get the values like this: {% for u in jogosult %} {{ u.jogosult_01 }} {% endfor %} it say auth.user none. views.py @login_required def projects(request): jogosult = Projekt.objects.filter(jogosult_01_id=request.user).order_by('-date') context = { 'jogosult': jogosult, } return render(request, 'stressz/projects.html', context) -
Django 'NoneType' object has no attribute 'file'
I have my code implemented like this and when there is no file how can i raise exception models.py @api_view(('GET',)) def i_view(request): data = Model.objects.first() response = HttpResponse( data.file, content_type='application/vnd.openxmlformats ) return response -
How to check If any List values Exist in 2 or More Database Tables?
I have following type of Django Model. class ClientPackageMapping(models.Model): user_id=models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, null=False) client_package=models.ForeignKey(ClientPackage,on_delete=models.CASCADE,blank=True, null=True) joined_date = models.DateField(null=True,blank=True) expiry_date = models.DateField(null=True,blank=True) class Meta: abstract=True @property def is_expired(self): if self.expiry_date< date.today(): return True return False class ClientPackageBasicStocks(ClientPackageMapping): stocks = ArrayField(models.CharField(max_length=5),null=True,blank=True) class ClientPackageSilverStocks(ClientPackageMapping): stocks = ArrayField(models.CharField(max_length=5),null=True,blank=True) class ClientPackageGoldStocks(ClientPackageMapping): stocks = ArrayField(models.CharField(max_length=5),null=True,blank=True) class ClientPackagePlatinumStocks(ClientPackageMapping): stocks = ArrayField(models.CharField(max_length=5),null=True,blank=True) Basically The idea is if certain user has stock in basic table but if same stock exists in another table i.e silver or gold there must be validation error. Is there any way I can check the incoming list values with database? if ClientPackagePlatinumStocks.objects.filter(stocks=[*self._data['stocks']]).exists(): raise ValidationError({'duplicate_stocks': f'Duplicate stocks!'}) I tried doing this way but I am not able to build or restrict user from adding package to silver when they already have the same package in basic any help will be very helpful. -
django form doesn't display labels
I'm new in django. I try to create a simple form based on the model. Imputs are displayed fine but i have problem with the labels.They don't appears on the page. I can't figure out where is my mistake. For my it should be working fine. Any idea what's is wrong here? class RecForm (ModelForm): class Meta: model = Rec fields = ['name', 'kind',] labels = { 'name': 'Here put your name', } -
Form only displaying "Save" button
I want to make a textbox, that after I input some text into it, that text to be shown bellow that box, on the same page. But I only get the Save part and not the textbox, how can I fix this? My .html file: https://paste.pythondiscord.com/tivibaxiba.xml My views file: https://paste.pythondiscord.com/zavepigace.py -
How to use multiple username fields to authenticate a user in Django
I am working on a project where I can get a username, email, or phone number as a USERNAME_FIELD, similar to Instagram, but I am kinda stuck and don't really know how to do it, here is my USER model models.py from django.contrib.auth.models import AbstractUser from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ from .managers import UserManager class User(AbstractUser): username = models.CharField(max_length=150, unique=True) email = models.EmailField(_('email address'), unique=True) photo = models.ImageField(upload_to='avatars/', null=True, blank=True) last_updated = models.DateTimeField(null=True, blank=True) about = models.TextField(_( 'about'), max_length=500, blank=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email def save(self, *args, **kwargs): self.last_updated = timezone.now() super(User, self).save(*args, **kwargs) managers.py from django.contrib.auth.base_user import BaseUserManager from django.utils.translation import gettext_lazy as _ class UserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): """ Create and save a SuperUser with the given email and password. """ extra_fields.setdefault('is_staff', True) … -
python: RpiMotorLib in virtual environment with Django - stepper motor is rotating jerky
I´m trying to run a stepper motor (NEMA17) with a DRV8225 stepper motor controller inside a python/Djano app in a virtual environment. The script for running the stepper motor with the RPiMotorLib is the script in this tutorial: https://makersportal.com/blog/raspberry-pi-stepper-motor-control-with-nema-17 When I run the script from command line inside/outside the virtual environment, the motor is rotating smooth. But if I run the script in my Django app, the motor is rotating jerky. In Django, I´m firing the script with a Django signal after updating the database: from django.db.models.signals import pre_save from django.dispatch import receiver from django.utils.crypto import get_random_string from django.utils.text import slugify from steppermotors.models import Steppermotor import RPi.GPIO as GPIO from RpiMotorLib import RpiMotorLib import time @receiver(pre_save, sender=Steppermotor) def run_steppermotor(sender, instance, *args, **kwargs): direction= 22 # Direction (DIR) GPIO Pin step = 23 # Step GPIO Pin EN_pin = 24 # enable pin (LOW to enable) # Declare a instance of class pass GPIO pins numbers and the motor type mymotortest = RpiMotorLib.A4988Nema(direction, step, (21,21,21), "DRV8825") GPIO.setup(EN_pin,GPIO.OUT) # set enable pin as output GPIO.output(EN_pin,GPIO.LOW) # pull enable to low to enable motor mymotortest.motor_go(False, # True=Clockwise, False=Counter-Clockwise "Full" , # Step type (Full,Half,1/4,1/8,1/16,1/32) instance.last_steps, # number of steps .0005, # step delay …