Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Formsets for Creating Multiple Related Model Instances
I have a Ticket model. I've created a Ticket form relating to this model. There is a button to add new forms, so you can create multiple instances of the Ticket model from the same web page. This is managed with a formset. There is also another form (referred to as form2), which allows you to create instances of the TicketAsset form. You should be able to add multiple instances of this form, for each instance of the Ticket form (managed with formset2). For example: if we have two instances of the Ticket Form, it would be possible to add, say, two instances of the TicketAsset Form, which relate to the Ticket instance created in the first instance of the Ticket Form. When we add the second instance of the Ticket form, this should have with it a new instance of the TicketAsset form, as well as another button to add more instances of the TicketAsset form (which all relate to the second instance of the Ticket Form). In this case say we create three instances of the TicketAsset form. Upon submission of the form, the expected outcome would be: Two instances of the Ticket model are created and saved … -
ValueError: 'AccessPolicy' instance needs to have a primary key value before this relationship can be used
I'm upgrading the legacy project from Django 2.2 to Django 4.2. Everything works fine except the model, where ManyToMany field is used. The model: # models.py class AccessPolicy(TimeStampedModel): name = models.CharField(max_length=255, null=False, blank=False) external_id = models.CharField(max_length=255, unique=True, null=True) version_hash = models.CharField(max_length=255, null=False, blank=False) read_only = models.BooleanField(default=False, help_text=('Some text')) users = models.ManyToManyField(User, blank=True) class Meta: verbose_name = 'Access Policy' verbose_name_plural = 'Access Policies' def __str__(self): return f'{self._meta.object_name} Object ({self.pk})' The form: # forms.py class AccessPolicyForm(forms.ModelForm): external_id = forms.CharField(disabled=True, required=False) rules = forms.CharField(widget=QueryBuilderWidget) class Meta: model = AccessPolicy fields = 'name', 'external_id', 'read_only', 'rules', 'users', def clean_external_id(self): external_id = self.cleaned_data.get('external_id') if not external_id: return md5(f"{str(self.instance.created)} {self.cleaned_data.get('name')} {self.data.get('rules')}") return external_id def clean_rules(self) -> CleanedRules: raw_rules: RawRules = json.loads(self.cleaned_data.get('rules')) conditional_serializer = RulesSerializer(data=raw_rules) if not conditional_serializer.is_valid(): raise ValidationError(conditional_serializer.errors) return conditional_serializer.validated_data def save(self, commit=True): self.instance.version_hash = hash_dict(self.cleaned_data.get('rules')) return super().save(commit) def _save_m2m(self): self.instance.rules.all().delete() self._save_condition() self._save_users() def _save_users(self): self.instance.users.clear() self.instance.users.add(*self.cleaned_data.get('users')) def _save_condition(self): root_condition = RulesSerializer().create(self.cleaned_data.get('rules')) root_condition.access_policy = self.instance root_condition.save() The admin file: # admin.py class AccessPolicyAdmin(admin.ModelAdmin): form = AccessPolicyForm list_display = 'name', search_fields = 'name', formfield_overrides = { models.ManyToManyField: { 'widget': FilteredSelectMultiple(attrs={'size': 20}, verbose_name='linked users', is_stacked=False) }, } def get_form(self, request, obj: AccessPolicy = None, change=False, **kwargs): form = super().get_form(request, obj, change, **kwargs) data = self._get_form_data(obj or AccessPolicy()) … -
is possible deploy a Django project with a App instead a Droplet in DigitalOcean?
I need to deploy a Django application, but I only find tutorials using droplets on DigitalOcean, I would like to know if it is possible to deploy it through an App I followed the instructions from this repository, https://github.com/codingforentrepreneurs/Try-Django-3.2, but it didn't work for me -
Django-- Multiple Models with Multiple Databases
I am working on file transformation workflows and the whole project is based on Django. How the project works is , each django app is a new workflow , and once a files comes in it will invoke the workflows one after the another. My question is how to connect multiple databases from single model.py. Below is what I am trying to achieve The Main Project Structure Kappa |--Kappa |--FileTransformSAP |--FileTransformARIBA |--FileTransformWorkday ..... ..... Each of the Apps have a similar Structure listed below. FileTransformSAP |--__init__.py |--admin.py |--apps.py |--models.py |--tests.py |--views.py I have three Databases Namely, Landing, Staging and Final What I am trying to achieve is the model.py file will have three different classes namely, _landing, _staging and _final and this three classes should be able to interact with three different databases and mentioned above. I am already using routers.py to segregate databases for auth and application, but I am getting stuck when single model.py containing various model class needs to be applied to different databases Sample Model.py class <anything>_landing(models.Model): definition class Meta: app_label = '<anything>_landing' class <anything>_staging(models.Model): definition class Meta: app_label = '<anything>_staging' class <anything>_final(models.Model): definition class Meta: app_label = '<anything>_final' Along with this created the following routes.py … -
django restframework sorting
models.py class Entity(BaseFields): entity_name_en = models.CharField(max_length=250) category = models.ForeignKey(Category, on_delete=models.CASCADE,null=True,blank=True) class EntityRelation(models.Model): name = models.CharField(max_length=250) class EntityRelationship(models.Model): entity = models.ForeignKey(Entity, on_delete=models.CASCADE, related_name="entity") relation = models.ForeignKey(EntityRelation,on_delete=models.CASCADE) related_entity = models.ForeignKey(Entity, on_delete=models.CASCADE, related_name="related_entity") EntityRelation contains "Parent" and "Child" serializers.py class EntityListserializer(ModelSerializer): parent = SerializerMethodField(read_only=True) def get_parent(self, obj): relation_obj = EntityRelationship.objects.filter(entity=obj,relation__name="Parent").first() if relation_obj: return {"id":relation_obj.id,"related_entity":{"id":relation_obj.related_entity.id,"name":relation_obj.related_entity.entity_name_en}} class Meta: model = Entity fields = ("id","category","parent") views.py class EnityListView(ListAPIView): permission_classes = [AllowAny,] serializer_class = EntityListserializer def get_queryset(self, *args, **kwargs): sort = json.loads(self.request.GET.get("sort")) parnt = sort.get("parent") queryset_list = Entity.objects.all().order_by("-created_date") if parnt: if parnt == 'asc': queryset_list = queryset_list.order_by(F("related_entity").asc(nulls_last=True)) if parnt == 'desc': queryset_list = queryset_list.order_by("-related_entity") return queryset_list does anyone know how to sort queryset_list with parent field {"id": 1,"category":1,"parent":{"id": 1,"related_entity": {"id": 1,"name": "entity 1"}}} -
Database updates are sometimes working, and sometimes not (Django & Flutter)
I am using the Django Rest Framework to build an API which connects a Flutter app to a MySQL database. I am using PythonAnywhere to host my code, and have the lower tier paid plan. I have two Models: User (which inherits from AbstractUser) and Client. They both have a JsonField named "counters" which follow this key,value structure: {String (an identifier): int (a counter)} I have a view like that looks something like this: class UpdateCounters(APIView): permission_classes = [AllowAny] def post(self, request): username = request.data.get("username") identifier = request.data.get("identifier") user = User.objects.get(username=username) client = Client.objects.get(user_id=user) updates = {} try: with transaction.atomic(): counters = user.counters counters[identifier] = counters.get(identifier, 0) + 1 user.counters = counters updates["user"] = user countersC = client.counters countersC[identifier] = countersC.get(identifier, 0) + 1 client.counters = countersC updates["client"] = client for obj in updates.values(): obj.save() return JsonResponse({'success': True}, status=status.HTTP_200_OK) except IntegrityError as e: return JsonResponse({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST) except Exception as e: return JsonResponse({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST) The thing is, when this call is made, the User object goes through all the desired changes, whereas the Client object, SOMETIMES (approx. 50% of the time), does not. I have tried using the update_fields parameter of the .save() method, but this only made the … -
535330#535330: conflicting server name "www.aniconnect.org" on 0.0.0.0:80, ignored
I have made a django chatting application that uses websockets (django-channels) to implement its chatting functionality. I have used nginx and gunicorn for production for this website. The following is the nginx config file: server { listen 80; server_name www.aniconnect.org; ssl_certificate /etc/letsencrypt/live/www.aniconnect.org/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/www.aniconnect.org/privkey.pem; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/gamedeveloper/anime_chat/anime_chat_app/static/; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } location /ws/ { proxy_pass http://unix:/run/gunicorn.sock; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } The following are the ports I use on this site: gamedeveloper@animechatapp:~$ sudo ufw status Status: active To Action From -- ------ ---- 22/tcp ALLOW Anywhere 80/tcp ALLOW Anywhere 8001/tcp ALLOW Anywhere 443/tcp ALLOW Anywhere 22/tcp (v6) ALLOW Anywhere (v6) 80/tcp (v6) ALLOW Anywhere (v6) 8001/tcp (v6) ALLOW Anywhere (v6) 443/tcp (v6) ALLOW Anywhere (v6) The following is settings.py: from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY ='django-insecure-00ejr3$lw40)nu8ojp70w29ju(c+jgol94_m3-otie-csmt^@t' # SECURITY WARNING: don't run with debug turned on … -
Django Page not found (404) - DetailView with Primary Key [closed]
Bonjour, Je butte depuis quelques jours sur ce problème et je ne vois pas ou est-ce que je me trompé. Je veux afficher une vue detail (DetailView) d'un client ou article. Et j'ai toujours cette erreur: "" Request URL: http://127.0.0.1:8000/papis/viewcustomer/7/' "" Quand j'enlève le "" ' "" juste après le pk, la page s'affiche. "" Request URL: http://127.0.0.1:8000/papis/viewcustomer/7/ "". Voici mon extrait de code. D'avance je vous remercie **urls.py** `app_name = "nrn" urlpatterns = [ path('contact/', signup, name="contact"), # Customer path('', HomeViewCustomer.as_view(), name="home"), path('addcustomer/', AddViewCustomer.as_view(), name="create-customer"), path('viewcustomer/<int:pk>/', DetailViewCustomer.as_view(), name="view-customer"), path('editcustomer/<int:pk>/', EditViewCustomer.as_view(), name="edit-customer"), path('deletecustomer/<int:pk>/', DeleteViewCustomer.as_view(), name="delete-customer"), ` **models.py** `customer_name = models.CharField(max_length=255, unique=True, verbose_name="Nom du Client") gerant = models.CharField(max_length=255, blank=True,null=True, verbose_name="Nom du dirigeant ou son représentant") siret = models.CharField(max_length=100, default="non renseigné", verbose_name= "Numéro siret") def get_absolute_url(self): return reverse("nrn:home") ` **views.py** `from django.views.generic import CreateView, UpdateView, DeleteView, ListView, DetailView from papis_app.models import Customer class DetailViewCustomer(DetailView): """ Vue info/détail d'un client """ model = Customer template_name = "client/detail_client.html" context_object_name = "custome" ` **detail_client.html** `{% block content %} <hr> <div id="client"> <h3> Nom du client: {{ custome.customer_name }} </h3> <h3>Contact: </h3> <div> <ul> <li>{{ custome.gerant }} </li> <li>{{ custome.siret }} </li> </ul> </div> </div> {% endblock %}` -
Django - Custom save method not being applied in loop
I have this model: class AccountingRevenue (models.Model): class AccountingRevenueStatus (models.TextChoices): TORECEIVE = 'A RECEBER', 'A RECEBER' PARTIAL = 'RECEBIDO PARCIAL', 'RECEBIDO PARCIAL' FULL = 'RECEBIDO TOTAL', 'RECEBIDO TOTAL' objects = models.Manager() accpresentation = AccountingRevenueManager() branch = models.ForeignKey(Branchs, on_delete=models.PROTECT) sale_date = models.DateField(blank=True, null=True) accountplan = models.ForeignKey(AccountsPlan, on_delete=models.PROTECT) customer = models.ForeignKey(Customers, on_delete=models.PROTECT, null=True, blank=True) amount_to_receive = models.DecimalField( max_digits=14, decimal_places=2, ) due_date = models.DateField() amount = models.DecimalField( max_digits=14, decimal_places=2, ) status = models.CharField( max_length=16, choices=AccountingRevenueStatus.choices, ) accnotes = models.CharField( max_length=1000, blank=True, null=True, unique=False, error_messages={ 'max_length': 'A observação pode ter 1000 caracteres no máximo.', } ) tax = models.DecimalField( max_digits=5, decimal_places=2, blank=True, null=True, ) term = models.PositiveIntegerField( blank=True, null=True, ) receive_in = models.DateField( blank=True, null=True, ) taxed_amount = models.DecimalField( max_digits=14, decimal_places=2, blank=True, null=True, ) total_taxes = models.DecimalField( max_digits=14, decimal_places=2, blank=True, null=True, ) class Meta: verbose_name_plural = 'AccountingRevenue' def save(self, *args, **kwargs): cards = Cards.objects.all() if 'CARTÃO' in str(self.accountplan): if cards: for item in cards: if self.accountplan_id == item.accountplan_id: self.tax = item.card_tax self.term = item.payment_term self.total_taxes = round(Decimal(self.amount_to_receive * (self.tax / 100)), 2) self.taxed_amount = round(Decimal(self.amount_to_receive - self.total_taxes), 2) self.receive_in = self.sale_date + relativedelta(days=self.term) else: self.tax = 0 self.term = 0 self.total_taxes = 0 self.taxed_amount = self.amount_to_receive self.receive_in = self.sale_date else: self.tax = 0 self.term … -
Reverse accessor clash between Django's auto generated fields
I have a base table that I want to extend in a couple different apps installed in my project. My issue is that I usually want the table to be named the same thing despite what app it is installed in. These apps all live in the same PostGres database, in separate schemas: #App1 ParentModel(models.Model): #fields #App2 ChildModel(ParentModel): #fields #App3 ChildModel(ParentModel): #fields When I try to run makemigrations, it complains about a reverse accessor clash between the auto generated 'childmodel_ptr' fields. It suggests adding a 'related_name' argument. However obviously I cannot do that as this field is being auto generated by Django. Is there a mechanism by which I can supply a 'related_name' argument to whatever django machinery is generating that field? -
django ModuleNotFound during deployment
The error is here: http://18.221.170.83/ When I run python manage.py run server, the all modules work fine. When using django + apache, no module named reportlab is found. I'm pretty sure I'm not using any virtual environments I followed this tutorial: https://docs.bitnami.com/aws/infrastructure/django/get-started/deploy-django-project/ exactly, using the provided custom vhost config. It is below as well. I'm new to django, any suggestions appreciated! <IfDefine !IS_APPNAME_LOADED> Define IS_APPNAME_LOADED WSGIDaemonProcess elijahtai_homepage python-home=/opt/bitnami/python python-path=/opt/bitnami/projects/elijahtai_homepage </IfDefine> <VirtualHost 127.0.0.1:80 _default_:80> ServerAlias * WSGIProcessGroup elijahtai_homepage Alias /robots.txt /opt/bitnami/projects/elijahtai_homepage/static/robots.txt Alias /favicon.ico /opt/bitnami/projects/elijahtai_homepage/static/favicon.ico Alias /static/ /opt/bitnami/projects/elijahtai_homepage/static/ <Directory /opt/bitnami/projects/elijahtai_homepage/static> Require all granted </Directory> WSGIScriptAlias / /opt/bitnami/projects/elijahtai_homepage/elijahtai_homepage/wsgi.py <Directory /opt/bitnami/projects/elijahtai_homepage/elijahtai_homepage> <Files wsgi.py> Require all granted </Files> </Directory> I tried adding it to 'installed_apps' in the settings file, etc. -
period between and compare am and pm
the problem is the system should be check the period is not exists he can do this when the start time and end time be in pm together or am but if the stert time in pm and the end time in am he dosen work like jhon booking from_hour = 22pm to_hour = 2am and lion booking from_hour = 23pm to_hour = 1am The system allows this to happen But there must be an error here, a timing conflict, and the period must have been set before this code is run when the From_hour and to_hour be in pm together or am note(this website booking stadiums by horse) how can be run if the from_hour = pm and to_hour = am my models is : class OpeningHours(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) pitche = models.ForeignKey(Pitche,on_delete=models.DO_NOTHING) made_on = models.DateField() from_hour = models.TimeField() to_hour = models.TimeField() timing = models.CharField(max_length=50,choices=timing) def clean(self): if self.from_hour == self.to_hour: raise ValidationError('Wrong Time') if self.made_on < datetime.date.today(): raise ValidationError('InVaild Date') if ( OpeningHours.objects.exclude(pk=self.pk) .filter( made_on=self.made_on, pitche_id=self.pitche_id, to_hour__gt=self.from_hour, from_hour__lt=self.to_hour, ) .exists() ): raise ValidationError( f'The booked time ({self.from_hour} to {self.to_hour}) is occupied.' ) return super().clean() -
Getting a ValueError from an old migration even though makemigrations command seemed to detect a change in fields
I'm trying to get this change in my fields to properly update so I can work on the rest of the project. This is the model that's causing the issue currently: class Hotel(models.Model): name = models.CharField(max_length=255) address = models.CharField(max_length=255) check_in_date = models.DateField() check_out_date = models.DateField() notes = models.TextField(blank=True) id = models.AutoField(primary_key=True) people = models.CharField(max_length=255) # the people field is the issue rn def __str__(self): return self.name + ", " + str(self.id) Previously, the people field was an ArrayField but I changed it to a CharField because it didn't need to be an array. Here is migration 7 where I added the people field as an ArrayField class Migration(migrations.Migration): dependencies = [ ('project_name', '0006_confirmationentry_alter_hotel_notes'), ] operations = [ migrations.AddField( model_name='hotel', name='people', field=django.contrib.postgres.fields.ArrayField(base_field=models.IntegerField(), default=list, size=None), ), ] Here's migration 8 where I changed it to a CharField class Migration(migrations.Migration): dependencies = [ ('project_name', '0007_hotel_people'), ] operations = [ migrations.AlterField( model_name='hotel', name='people', field=models.CharField(max_length=255), ), ] I've deleted/commented out the people field several times and put it back, and when I do python3 manage.py makemigrations, these changes are detected. But when I do python3 manage.py migrate it gives me this error: Applying project_name.0007_hotel_people...Traceback (most recent call last): File "/Users/me/Desktop/project_name/manage.py", line 22, in <module> execute_from_command_line(sys.argv) … -
Why django signals are not called when I create a new entry in the table?
Created a signal that checks the Robot table for new entries. Then compares the model and version data with the Order table, then sends an email. But nothing works. What could be the problem? @receiver(post_save, sender=Robot) def robot_created(sender, instance, **kwargs): orders = Order.objects.all() for order in orders: robot_exists = Robot.objects.filter(model=order.robot_model, version=order.robot_version).exists() if robot_exists: subject = 'text' message = 'text' from_email = 'text@gmail.com' recipient_list = ['text22@gmail.com'] send_mail(subject, message, from_email, recipient_list) order.models.py class Order(models.Model): customer = models.ForeignKey(Customer,on_delete=models.CASCADE) robot_model = models.CharField(max_length=2, blank=True,null=True) robot_version = models.CharField(max_length=2, blank=True,null=True) robots.models.py class Robot(models.Model): serial = models.CharField(max_length=5, blank=False, null=False) model = models.CharField(max_length=2, blank=False, null=False) version = models.CharField(max_length=2, blank=False, null=False) created = models.DateTimeField(auto_now_add=True) I tried to throw it into different folders, put the print inside the function (nothing came out) -
How can I parse the string representation of a decimal value to decimal (python) from a JSONField?
so I created a Model that contains a JSON field: metadata = models.JSONField(verbose_name=_('Metadata'), blank=True, default=dict, db_index=True, encoder=DjangoJSONEncoder, decoder=JSONDecoder(parse_float=decimal.Decimal)) If I access the metadata field that contains a decimal value I get a string representation of the value (that makes sense, because they are stored internally as strings. But I want that its automatically parsed to the type decimal.Decimal. The json.JSONDecoder has a parameter "parse_float", but Django wants a callable as decoder parameter. I tried to pass a instantiated decoder class (but I got obviously a ValueError, that this must be a callable. I also tried to start working on a subclassed JSONDecoder, but in the parent class I cannot see the code, what I need to adjust to receive a decimal.Decimal. So I am a little bit confused how I can solve my problem. Has someone any idea? -
Query repeated multiple times in a many-to-many relation
I have a problem with a many to many relationship in Django Admin. I have simplified my model so that it does not contain irrelevant fields for the problem. If we take "actor" as an example. If I have, for example, 15 actors for a movie, SQL makes 15 queries instead of one. I have search for a long time now but only finds solutuions for one to many based on the foreignkey thats automaticly created in my "many to many" relation. I am grateful for any help I can get! models.py class Cast(models.Model): firstname = models.CharField(max_length=250, blank=True) lastname = models.CharField(max_length=250, blank=True) class Meta: indexes = [["firstname", "lastname"]] class Meta: abstract= True class Director(Cast): def __str__(self): return self.firstname + ' ' + self.lastname class Actor(Cast): def __str__(self): return self.firstname + ' ' + self.lastname class Film(models.Model): title_eng = models.CharField(max_length=250, verbose_name='Title English') directors = models.ManyToManyField(Director, related_name='directors') actors = models.ManyToManyField(Actor, related_name='actors') def __str__(self): return self.title_eng admin_film.py class DirectorInline(admin.TabularInline): model = Director.directors.through verbose_name_plural = "Film-Director" list_display = ['firstname','lastname'] extra = 0 @admin.register(Director) class DirectorAdmin(admin.ModelAdmin): search_fields = ("firstname",) list_display = ['id', 'firstname', 'lastname', 'get_fullname'] fields = ['firstname', 'lastname', 'fullname'] def get_fullname(self, obj): fullname = "" if (len(obj.firstname) != 0): fullname = obj.firstname return fullname … -
Filepond, How to get file name that user reverted
I have this server configuration of filepond server: { process: (fieldName, file, metadata, load, error, progress, abort) => { ***** }, revert: { url: '{% url "file_revert" %}', headers: { 'FileName': '????????', } }, } How can i get filename of the file that user reverted Thank you for taking the time over this question <3 I've already tried something like this: revert: { url: '{% url "file_revert" %}', headers: { 'FileName': (file) => file.name }, }, But it does not work -
Why does index.html have such a name in Django?
I’m not a native speaker and I don’t understand why the standard name of the initial page in Django applications is index.html. Can someone explain in simple words why this is so, and not, for example, home.html I'm trying to find out the answer to my question. I just need a verbal explanation -
Django Multipart/form-data serialization attrs are empty
I have an issue when trying to serialize multipart/form-data. Code: class View(GenericAPIView): permission_classes = [IsAuthenticated] queryset = QS.objects.all() serializer_class = SampleSerializer parser_classes = (MultiPartParser, FormParser, ) class SampleSerializer(serializers.Serializer): event = serializers.CharField() kwargs = serializers.DictField(required=False) def validate(self, attrs): print(attrs) // result: { event: "request", kwargs: {} } Why do I get empty kwargs in serializer validate method? Do I need a different parser? I tried using different parsers but they doesn't seem to work. The initial data is: -----------------------------23641203962992511458665574039 Content-Disposition: form-data; name="event" request -----------------------------23641203962992511458665574039 Content-Disposition: form-data; name="kwargs[email]" sample email -----------------------------23641203962992511458665574039-- -
Detect when a text editor is run in xterm such as nano,vim etc
I am currently using 5.2.1 version of xterm.js and django in backend. I want to detect when a text editor is run in terminal and log it. My current approach is to filter it using the keywords such as nano,vim etc. The only problem is that the user may use alias so i want to run "alias" command in the background constantly and check if there is any alias of nano or vim and add them to blacklist too. How can i achieve this in the most foolproof way? index.html: <script type="module"> var socket = io.connect({ transports: ["websocket", "polling"] }); const status = document.getElementById("status") const button = document.getElementById("button") const fit = new FitAddon.FitAddon(); var term = new Terminal({ cursorBlink: true, }); term.loadAddon(fit); term.open(document.getElementById('terminal')); fit.fit(); var terminal_line = ''; term.onKey(e => { if (e.key == "\r") { terminal_line = term.buffer.active.getLine(term._core.buffer.y)?.translateToString(); console.log("terminal line: ", terminal_line); socket.emit("log_input", { "user_input": terminal_line }); } socket.emit("pty_input", { "input": e.key }); }) socket.on("pty_output", function (output) { console.log("output: ", output["output"]); term.write(output["output"]); }) socket.on("connect", () => { status.innerHTML = '<span style="background-color: lightgreen;">connected</span>' button.innerHTML = 'Disconnect' }) socket.on("disconnect", () => { status.innerHTML = '<span style="background-color: #ff8383;">disconnected</span>' button.innerHTML = 'Connect' }) function myFunction() { if (button.innerHTML == 'Connect') { location.reload(); } … -
How to create a Django with existing directories, files and etc.?
I am trying to startproject with django-admin startproject <project_name> but it either makes more files that already exists (like manage.py, and other configurations files) or gives an error - CommandError: ~/Dev/r4c/R4C/manage.py already exists. Overlaying a project into an existing directory won't replace conflicting files. My project structure: r4c/ └── R4C/ ├── R4C/ │ └── settings.py └── ... (other configuration files) ├── customers/ │ └── views.py └── ... (other customer-related files) ├── orders/ │ └── views.py └── ... (other customer-related files) └── robots/ └── views.py └── ... (other customer-related files) ├── R4C_README.md ├── R4C_manage.py └── R4C_tasks.md I just need to start the project and apps with already existing directories and files I tried to startproject command but cant get and idea of not just starting project from the beginning, just work with existing ffiles and directories. -
React useContext is undefined in useeffect
I am coding a chat app with django channels and react. I want when a new message is send, to have a className of the current user. I already have the current user in context so I just have to call it and get it. But when I try to get the user in useEffect, it returns {}. const {currentUser} = useContext(AuthContext) useEffect(()=> { chatSocket.onmessage = function(e) { console.log(currentUser) const data = JSON.parse(e.data); setMessages(old => [...old, <p ref={oneRef} className={currentUser[0]?.username}>{data.message}</p>]) }; },[]) Also I need the useEffect so I can't just remove it. I don't wanna to call an axios call every time a new message is sended. And the currentUser is an object. -
Django and VueJS PWA on Nginx
First of all we build the frontend using npm build. We also configure the assetsDir to /static/ui and outputDir to dist/ui. After the build process is complete, we copy the whole build files to another /static directory, where we load static files through django static. We also specify the /static to alias /etc/var... etc. In nginx.conf So everything works fine like this. The problem arise when I made the VueJS app to pwa, it just won't work, I don't know why, but I have even configured nginx to serve the service-worker.js file. And other files like icons and manifest.json also loads correctly. Any help on this will be appreciated. More info: in browser console.log, when we type 'serviceWorker' in navigator returns true if we are hosting (only the VueJS app) through netlify or vercel, in django's case, it already returns false, thus making it not to support pwa. -
How to use jupyter in existing django project
i followed the instruction on the internet to access django apps in jupyter. I tried 2 ways: 1: created a jupyter file and add the django settings to it like below ''' import sys, os print('Python %s on %s' % (sys.version, sys.platform)) import django print('Django %s' % django.get_version()) sys.path.append('D:/VSCODE/GPOSSYS') os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') if 'setup' in dir(django): django.setup() ''' 1 os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') 2 if 'setup' in dir(django): 3 django.setup() File d:\\VSCODE\\GPOSSYS\\.venv\\Lib\\site-packages\\django\\__init__.py:24, in setup(set_prefix) 20 if set_prefix: 21 set_script_prefix("/" if settings.FORCE_SCRIPT_NAME is None else settings.FORCE_SCRIPT_NAME) 24 apps.populate(settings.INSTALLED_APPS) File d:\\VSCODE\\GPOSSYS\\.venv\\Lib\\site-packages\\django\\apps\\registry.py:83, in Apps.populate(self, installed_apps) 78 # An RLock prevents other threads from entering this section. The 79 # compare and set operation below is atomic. 80 if self.loading: 81 # Prevent reentrant calls to avoid running AppConfig.ready() 82 # methods twice. 83 raise RuntimeError("populate() isn't reentrant") 84 self.loading = True 86 # Phase 1: initialize app configs and import app modules. RuntimeError: populate() isn't reentrant 2: I installed jupyter, Django-extensions, added it to settings in installed apps and ran python manage.py shell_plus --notebook in the terminal this is the response i got Traceback (most recent call last): File "D:\VSCODE\GPOSSYS\.venv\Lib\site packages\django_extensions\management\commands\shell_plus.py", line 281, in get_notebook from notebook.notebookapp import NotebookApp ModuleNotFoundError: No module named 'notebook.notebookapp' CommandError: Could … -
Unable to login into django-admin with superuser credentials Using a custom user model
i am using the custom user model my superuser get's created but i am unable to login into the django-admin using the superuser credentials below is the code i wrote to create a custom_user model from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from GOVDairySync.exceptions import * import uuid class UserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): if not email: raise ValueError("The Email field must be set") email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', 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.") user = self.create_user(email=email, password=password, **extra_fields) user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): id = models.UUIDField(default=uuid.uuid4, primary_key=True, unique=True, editable=False) email = models.EmailField( verbose_name="Email", max_length=255, unique=True, ) name = models.CharField(max_length=200) mobile = models.CharField(max_length=10) is_active = models.BooleanField(default=True) is_deactivated = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) # Added this field is_superuser = models.BooleanField(default=False) # Added this field created_at = models.DateTimeField(auto_now_add=True) deleted_at = models.DateTimeField(null=True, blank=True) objects = UserManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = ['name', 'mobile'] def __str__(self): return self.name def has_perm(self, perm, obj=None): return self.is_superuser # Modify as needed def has_module_perms(self, app_label): return self.is_superuser # Modify as needed class Meta: …