Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why Am I getting an Integrity Error while uploading csv file to django app?
While uploading a csv file I'm getting an Integrity Error. I have a correctly working QuizApp which has models about Quiz, Questions and Answers. But I've created another app csvs to upload csv file with Questions and Answers. While I'm trying to upload a CSV file I'm getting that error. The file isn't uploaded to the website. IntegrityError at /something/admin/csvs/csv/add/ null value in column "quiz_id" of relation "csvs_csv" violates not-null constraint DETAIL: Failing row contains (11, csvs/example_KLOIQJK.csv, 2022-09-15 05:46:25.666689+00, f, null) csvs.models.py class Csv(models.Model): file_name = models.FileField(upload_to="csvs") uploaded = models.DateTimeField(auto_now_add=True) activated = models.BooleanField(default=False) csvs.forms.py from django import forms from csvs.models import Csv class CsvModelForm(forms.ModelForm): class Meta: model = Csv fields = ("file_name",) csvs.views.py from django.shortcuts import render from django.http import HttpResponse from .forms import CsvModelForm # Create your views here. def upload_file_view(request): form = CsvModelForm(request.POST or None, request.FILES or None) if form.is_valid(): form.save() form = CsvModelForm() return render(request, "csvs/import.html", {"form": form}) quiz.models.py from django.db import models from django.contrib.auth import get_user_model from django.urls import reverse, reverse_lazy import uuid class Quiz(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=200) short_description = models.CharField(max_length=500) resolution_time = models.PositiveIntegerField( help_text="Quiz Duration in minutes", default=15 ) number_of_questions = models.PositiveIntegerField(default=1) author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) is_public = … -
Could not find a version that satisfies the requirement Python
Could not find a version that satisfies the requirement librabbitmq==1.6.1 (from versions: 0.9.0, 0.9.1, 0.9.2, 0.9.3, 0.9.4, 0.9.5, 0.9.6, 0.9.7, 0.9.8, 0.9.9, 1.0.0, 1.0.1, 1.0.2, 1.0.3, 1.5.0, 1.5.1, 1.5.2, 1.6.0, 1.6.1, 2.0.0) I am getting similar error while install librarabbitmq,numpy,supervisor,xattr,MySQL-python there are specific versions i am trying to install and it pops out the same error while the version remain in the packages it can't find those. -
Django-filters , display min price and max price in the placeholder
I have a models price and using class base views, i have added 'django_filters' to settings as well,this is what i have in my project: model.py class Product(models.Model): price = models.IntegerField(default=0) setting.py 'django_filters', views.py class ProductListView(generic.ListView): template_name = "product/product_list.html" queryset = Product.objects.all() filter_set = ProductFilter filters.py class ProductFilter(django_filters.FilterSet): min_price = django_filters.NumberFilter(field_name="price", lookup_expr='gt',widget=RangeWidget(attrs={'placeholder': 'min_price'})) max_price = django_filters.NumberFilter(field_name="price", lookup_expr='lt',widget=RangeWidget(attrs={'placeholder': 'max_price'})) class Meta: model = Product fields = { 'min_price', 'max_price' } everything is working perfectly when using price only in fields without 'min_price', 'max_price', but what i want is to have min_price and max_price show in my placeholder. When i run the code above, i get this error: "TypeError: 'Meta.fields' must not contain non-model field names: min_price, max_price" -
Restarted Apache2 with Ubuntu for a Django Website, and CSS format no longer recognized. The site only shows basic HTML format. Any ideas to fix this?
I had a functional Django Website that uses Materialize CSS apache2 and ubuntu. I made some small changes to the site (like changed text), then restarted the apache2 server sudo service apache2 restart After the restart, the website no longer showed the CSS format. The website is a basic html website now. I'm a quite new to building websites, so hoping there could be some ideas for what changed after the apache restart. -
Can I create Django widgets at an own discretion?
There is a widget in Django, called NumberInput, the type of which can be defined as range. It is an usual range. There is a graphical element – a slider (a range as well) in a website. That's convenient that it has an animated label with number value. A code and an image of the slider will be on the website. I found a supposed code realizing a similar thing, here is the code from that website: import floppyforms as forms class Slider(forms.RangeInput): min = 5 max = 20 step = 5 template_name = 'slider.html' class Media: js = ( 'js/jquery.min.js', 'js/jquery-ui.min.js', ) css = { 'all': ( 'css/jquery-ui.css', ) } I tried to redefine template_name variable with an html-file containing the code and also to point paths to css and js files but an error appears at testing in Django shell (run as python manage.py shell). If to apply a widget in Django form, to take an instance of the form, and to print the instance, then html code must be returned, but an error did. The error is about not existing a template (TemplateDoesNotExist). I think what to do. Can I create Django widgets at an own discretion? … -
Could not resolve URL for hyperlinked relationship django
Tried the solutions provided in question asked by Daniel Costa. Here is my models.py file class Integrations(models.Model): integration_id = models.UUIDField(default=uuid.uuid4, unique=True, editable=False) integration_type = models.CharField(primary_key=True, max_length=256) def __str__(self): return self.integration_type class Meta: ordering = ["integration_type"] verbose_name = "Integration" verbose_name_plural = "Integrations" def get_default_mqtt(): return Integrations.objects.get(integration_type="MQTT") class MQTTSubscription(models.Model): mqtt_subscription_name = models.CharField( max_length=256, verbose_name="Subscription Name" ) mqtt_url = models.CharField(max_length=256, verbose_name="Mqtt Host") integration_type = models.ForeignKey( Integrations, default=get_default_mqtt, on_delete=models.PROTECT ) def __str__(self): return self.mqtt_subscription_name class Meta: ordering = ["mqtt_subscription_name"] verbose_name = "MQTT Subscription" The urls.py integrations_list = IntegrationsViewSet.as_view({"get": "list", "post": "create"}) integrations_detail = IntegrationsViewSet.as_view( {"get": "retrieve", "put": "update", "delete": "destroy"} ) mqtt_list = MQTTSubscriptionViewSet.as_view({"get": "list", "post": "create"}) mqtt_detail = MQTTSubscriptionViewSet.as_view( {"get": "retrieve", "put": "update", "delete": "destroy"} ) urlpatterns = [ path("integrations/", integrations_list, name="integrations_list"), path("integrations/<str:integration_type>/", integrations_detail, name="integrations_detaial"), path("mqttsubscription/", mqtt_list, name="mqtt_list"), path("mqttsubscription/<str:mqtt_subscription_name>/", mqtt_detail, name="mqtt_detail"), ] Views.py class IntegrationsViewSet(viewsets.ModelViewSet): serializer_class = IntegrationsSerializer queryset = Integrations.objects.all() lookup_field = "integration_type" class MQTTSubscriptionViewSet(viewsets.ModelViewSet): serializer_class = MQTTSubscriptionSerializer queryset = MQTTSubscription.objects.all() lookup_field = "mqtt_subscription_name" serializers.py class IntegrationsSerializer(serializers.ModelSerializer): class Meta: model = Integrations fields = ["integration_type"] class MQTTSubscriptionSerializer(serializers.ModelSerializer): lookup_field = "integration_name" class Meta: model = MQTTSubscription fields = [ "mqtt_subscription_name", "mqtt_url", "integration_type", ] The issue here is if "integrations/" is removed from urls.py it does not interpret the mqttsubscription/. While I update the … -
django unit testing timezone
In my settings.py I have implemented timezone as TIME_ZONE = os.environ.get("TIMEZONE", "Europe/London") How would I test if this is working on my test_timezone.py file? -
Django URL in Templates with Apache ProxyPass
I have a Django project behind a ProxyPass server in Apache. The project has an app called 'home', with this url patterns: urls.py urlpatterns = [ path('', views.HomeView.as_view(), name='index'), path('projects', views.HomeView.as_view(), name='dashboard'), path('projects/<int:pid>/members', views.ProjectMembersView.as_view(), name='project.members'), There are two URL that have the same View class (the first used for the root). In the HomeView class uses a template called 'dashboard.html' and get a list of projects to send to the template view class HomeView(LoginRequiredMixin, ListView): template_name = 'home/dashboard.html' context_object_name = 'projects' login_url = 'accounts.login' def get_queryset(self): ... # returns a list of projects The template renders a tablet with some information of the project and an URL to see the employess working on the project template <td class="align-middle text-center text-sm"> <a href="{% url 'project.members' pid=project.id %}">See employees</a> </td> In the case, the project behind the Apache ProxyServer, the URL generated in the template is the form: "https://example.com/4554/members", here, Django doesn't recognizes the URL The other situation, without Apache Proxypass the URL generated is like this: "http://127.0.0.1:8000/projects/4554/members", Django can recognize the URL and return the template when click in the link. The ProxyPass configuration in Apache is in file: "/etc/apache2/sites-enabled/the-projects.conf" proxypass <VirtualHost *:80> ServerName example.com ErrorLog /var/log/apache2/projects_perror.log CustomLog /var/log/apache2/projects_access.log combined RequestHeader … -
sqlite3 table is not updating when trying to add pandas dataframe
I am trying to add a Pandas data frame to a sqlite3 table in my Django project. However, when I try to add it to the table, nothing updates and no errors are printed in the console. For reference, the beginning of my code is correctly formatting the date in the csv file and then I am attempting to add it to an empty but existing table named 'daos_transaction' with the same attributes 'from_address', 'to_address', 'date_time', and 'amount'. import pandas as pd import sqlite3 # Reads data from csv file df = pd.read_csv("correct/path/to/csv/file") # Formats the date for dt in range(len(df['date_time'])): no_t_string = df['date_time'][dt].replace('T', ' ') clean_string = no_t_string.split('+')[0] df['date_time'][dt] = clean_string # Converts the column to a date time field df['date_time'] = df['date_time'].astype('datetime64[ns]') cnx = sqlite3.connect('correct/path/to/db') df.to_sql('daos_transaction', cnx, if_exists='append') -
Django Rest Framework With Djoser Jwt
I was looking into have more secure login and logout using JWT authentication and authorization .But in Djoser ,it has 3 endpoints /jwt/create/,/jwt/refresh/,/jwt/verify/. Here I want user login with jwt token and get verified token simultaneously and when logout refresh comes in to get access token.How could I do this? -
I am getting: TypeError: view must be a callable or a list/tuple in the case of include()
My root urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('webarticles.urls')), ] While I have seen this error answered on stackoverflow before, they don't seem to work for me. Specifically there are 2 components of the answers that confuse me: Why url is used instead of path If I am to import webarticles, how to do that given that my project and app are on the same level Thank you for any help you are able to provide! -
How to send html-styled password reset email with django
I created an html-styled version of a password reset email to be set with django located at 'registration/html_password_reset_email.html'. From other stackoverflows, I learned I needed to add the html_email_template_name parameter for the html version of the email to be sent. However, even with the below code, it is just the text version of the file that is being sent ('registration/password_reset_email.html'). Hints on what I'm doing wrong? from django.contrib import admin from django.urls import include, path from django.contrib.auth import views as auth_views from django.views.generic.base import RedirectView from django.urls import reverse from . import views urlpatterns = [ path('', views.homeview, name="homeview"), path('dashboard/', include('dashboard.urls')), path('admin/', admin.site.urls), path('accounts/', include('django.contrib.auth.urls')), path("register/", views.register_request, name="register"), path('reset_password/', auth_views.PasswordResetView.as_view( template_name='registration/password_reset_form.html', html_email_template_name='registration/html_password_reset_email.html', email_template_name='registration/password_reset_email.html', ), name="reset_password"), # Submit email form path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(), name="password_reset_done"), # Email sent success message path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name="password_reset_confirm"), # Link to password reset form in email path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(), name="password_reset_complete"), # Password successfully changed message ] -
Submitting a Django form using a One-To-Many relationship
I'm trying to implement a One-to-Many relationship between two models in Django, and have been doing so based on this answer. I have a very simple Projects model, and a ProjectNotes model, so one Project can have multiple Notes. My models.py: class Project(models.Model): project_name = models.CharField(max_length=500) project_type = models.CharField(max_length=500) project_leader = models.CharField(max_length=500) class ProjectNotes(models.Model): note_date = models.DateField(default=date.today) assigned_project = models.ForeignKey(Project, related_name='projectnotes', on_delete=models.CASCADE) note = models.TextField(max_length=500) My use case for this is to show a webpage showing the info for a given Project object, and show a textfield form where notes can be added (also showing any notes that may exist). To that end I have my forms.py: class AddProjectNoteForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(AddProjectNoteForm, self).__init__(*args, **kwargs) self.fields['note'].required = True class Meta: model = ProjectNotes fields = ['note'] My template displays the formfield correctly (and I believe would show any notes that existed correctly), however when attempting to submit a note I get an error complaining an id field is null: null value in column "attached_project_id" violates not-null constraint My understanding of this is that the project_id field cannot be blank, but as I don't define it, it is something django handles internally. If that is the case, why is it … -
How to use permissions added using django-rules library in Django App?
I am creating a Django App in which I am using django-rules library to define and add permissions. I have followed the documentation and created the predicates in a separate file called permissions.py. I have also added the permissions in the same file. My permissions.py looks like below: from .models import WorkspaceMembership import rules @rules.predicate def is_workspace_member(user, workspace): workspace_membership = WorkspaceMembership.objects.get_by_member_and_workspace(user, workspace) if workspace_membership is not None: return workspace_membership.is_workspace_member return False @rules.predicate def is_workspace_admin(user, workspace): workspace_membership = WorkspaceMembership.objects.get_by_member_and_workspace(user, workspace) if workspace_membership is not None: return workspace_membership.is_workspace_admin return False @rules.predicate def is_active_member(user, workspace): workspace_membership = WorkspaceMembership.objects.get_by_member_and_workspace(user, workspace) if workspace_membership is not None: return workspace_membership.is_active return False rules.add_perm("accounts.view_workspace", is_workspace_member) rules.add_perm("accounts.view_workspace", is_workspace_admin) rules.add_perm("accounts.view_workspace", is_workspace_member | is_workspace_admin) Now, I want to use these permissions in my class-based views and programmatically like checking below: if user.has_permissions("any-permission") I am unable to figure out that how to use the permissions. Because the predicates will required two objects, one is User instance and another is Workspace instance, in order to work, which are not present in permissions.py file. So, how do I use the permissions, can anybody guide me? -
How do I successfully connect Django to Azure Cache for Redis?
I have a django application that I have just migrated to MS Azure from Digital Ocean, and the app runs perfectly on Azure. However, I'm struggling to implement a cache backend with an Azure Cache for Redis service. I have the following configuration in settings.py: CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": f"redis://<my_redis_service_name>.redis.cache.windows.net:6380,password={secrets.AZURE_REDIS_PASSWORD},ssl=True,abortConnect=False", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "COMPRESSOR": "django_redis.compressors.zlib.ZlibCompressor", }, } } I have replaced my redis service name with <my_redis_service_name>. With this setup and DEBUG=True, I receive the error: ValueError at /accounts/login/ Redis URL must specify one of the following schemes (redis://, rediss://, unix://) Strange since redis:// is in the url. I have verified the keys, and ensured the redis service firewall accepts my VM's IP4 address, as well as making sure port 6380 is open on the VM. I have also tried various permutations of the connection string, such as: "LOCATION": f'redis://:{secrets.AZURE_REDIS_PASSWORD}@<my_redis_service_name>.redis.cache.windows.net:6380,ssl=True,abortConnect=False', No luck. If it's relevant, I'm using Django 4.0.7, Python 3.8, django-cachalot, and jazzband's django-redis pacakge. Azure Cache for Redis states that it's using Redis version 6.0.14. For what it's worth, my development environment works fine with a local daemonized redis cache at "LOCATION": "redis://127.0.0.1:6379/1",. Any help appreciated. -
How Can I filter Django Models To Get Field Values From Different Tables
I am working on Django Ticketing Application where I have a Pin Status Check View. And I want to query the Pin Model to know whether the PIN is activated, and if Activated query the Guest, and Profile Models to get the guest profile information and display in template. I have been able to use Django Forms with search to display the PIN details but NOT able to figure out the logic code for getting the guest profile if PIN is ACTIVATED. Someone may wish to help. thanks. Models code: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null = True) surname = models.CharField(max_length=20, null=True) othernames = models.CharField(max_length=40, null=True) gender = models.CharField(max_length=6, choices=GENDER, blank=True, null=True) phone = PhoneNumberField() image = models.ImageField(default='avatar.jpg', blank=False, null=False, upload_to ='profile_images', ) #Method to save Image def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) #Check for Image Height and Width then resize it then save if img.height > 200 or img.width > 150: output_size = (150, 250) img.thumbnail(output_size) img.save(self.image.path) def __str__(self): return f'{self.user.username}-Profile' class Pin(models.Model): ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE) value = models.CharField(max_length=6, default=generate_pin, blank=True) added = models.DateTimeField(auto_now_add=True, blank=False) reference = models.UUIDField(primary_key = True, editable = False, default=uuid.uuid4) status = models.CharField(max_length=30, default='Not Activated') #Save Reference Number def save(self, … -
Django ValueError: Cannot assign * must be a * instance
I am getting this error but I don't know why. models.py class Year(models.Model): year = models.CharField(max_length=5, unique=True) class Meta: ordering = ['-year'] def __str__(self): return self.year class Photo(models.Model): title = models.CharField(max_length=64) description = models.CharField(max_length=255) created = models.DateTimeField(auto_now_add=True) image = models.ImageField(upload_to='photos/') thumbnail = ResizedImageField(blank=True, size=[360, 360], force_format='JPEG', upload_to='thumbnails/') submitter = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) year = models.ForeignKey(Year, blank=True, on_delete=models.CASCADE) views.py def photo_create_view(request): form = AddPhotoForm() if request.method == 'POST': image = request.FILES['image'] thumbnail = request.FILES['image'] title = request.POST.get('title') description = request.POST.get('description') year = request.POST.get('year') people = request.POST.get('people') tags = request.POST.get('tags') photo = Photo(image=image, thumbnail=thumbnail, title=title, description=description, year=year, people=people, tags=tags, submitter=request.user,) photo.save() return redirect('/photo/?page=1') return render(request, 'photoapp/create.html', context={'form':form}) Cannot assign "123": "Photo.year" must be a "Year" instance. I have checked the Year table and year.id 123 exists. What am I missing? -
Django update multiple objects with options
I want to update the same field for multiple objects with the same value giving the user the available choices for that given field in a view, all this accessible from a custom action. I'm stuck at getting the value selected by the user in the view. I don't want to use the mass_edit package. This would be the custom action in the modeladmin in admin.py: def edit_selected(self, request, queryset, extra_context=None): context = {} labels = models.Label.objects.all() crop_ids = [] for i in queryset.values(): crop_id = i.get('id') crop_ids.append(crop_id) context = { "labels": labels, "ids": crop_ids, } return render(request, template_name="bulk_edit.html",context=context ) my template in bulk_edit.html: {% extends 'admin/base.html' %} {% csrf_token %} {% load spex_template %} {% block content %} {# {% if user.is_autheticated %}#} <div class="row"> <div class="col-md-12"> <form method="get"> {{ filter.form.as_p1 }} <select style="width:100px" name="label" placeholder="Add new Label" id="id_label__id"> <option value="none" selected disabled hidden>New Label</option> {% for label in labels %} <option value="{{ label.id }}">{{ label.id }} - {{label.name}}</option> {% endfor %} </select> <button type="submit">Update</button> <br> </form> <div class="card card-body"> <div><h1>Crop Ids: {% for id in ids %} {{ id }}, {% endfor %} </h1></div> <table class="table table-sm"> <tr> </tr> <br> </table> </div> </div> </div> {# {% endif %}#} … -
Django widget tweaks and variable attributes
Trying to include variables as attributes and values into a form field in a Django app. There is a somewhat related thread but to my understanding it covers one side of the problem I am facing with django-widget-tweaks / custom tags. In my case I not only want to assign a dynamic value to a predefined attribute (which I can do with extra template tags as described for instance here) but to first dynamically create an attribute and assign a value to it for the purpose of htmx requests such as hx-post or hx-delete. Including partials behaves as expected if I specify the type of htmx request directly in render_field and pass the value (in this case URL) via include as well as when I add the attribute and hard code its value using |attr: like so: {% include "partials/input-text.html" with field=form.email|attr:"hx-post:/search/" %} I have tried to apply append_attr the newly created attribute but I'm seeing AttributeError: 'SafeString' object has no attribute 'as_widget' and also getting a sensation that I'm missing the point. Ideally I'm seeking to be able to pass attribute&value as variables (could be via custom template tags), along the lines of {% include "partials/input-text.html" with field|attr:"{{hxaction}}:{{hxurl}}" %} -
Unable to log to STDOUT in django
settings.py LOG_LEVEL = "DEBUG" LOGGING = { "version": 1, "disable_existing_loggers": False, "handlers": { "console": { "level": LOG_LEVEL, "class": "logging.StreamHandler", "stream": sys.stdout, "formatter": "console", }, "rq_console": { "level": LOG_LEVEL, "class": "rq.utils.ColorizingStreamHandler", "formatter": "rq_console", "exclude": ["%(asctime)s"], }, }, "formatters": { "rq_console": { "format": "%(asctime)s | %(name)s | %(levelname)s | %(message)s", "datefmt": "%Y-%m-%d %H:%M:%S", }, "console": { "format": "%(asctime)s | %(name)s | %(levelname)s | %(message)s", "datefmt": "%Y-%m-%d %H:%M:%S", }, }, "loggers": { "": { "handlers": ["console"], "level": LOG_LEVEL, "propagate": True, }, "django": { "handlers": ["console"], "level": "INFO", "propagate": True, }, "rq.worker": { "handlers": ["rq_console"], "level": LOG_LEVEL, }, }, "root": { "handlers": ["console"], "level": LOG_LEVEL, }, } some/api.py logger.info("Got some info") logger.debug("Got some debug") logger.warning("Got some warning") logger.error("Got some error") I'm running Django in debug mode using python manage.py runserver and none of the log statements are logging the console. The API is working just fine. And this is the code path it is taking, I ensured it by intentionally breaking the API using a break. However, I'm unable to get the logging working for some reason! At the start of the some/api.py file I've tried using all the below loggers, and none of them are printing the logs to the console logger = … -
Settting up virtual environment
i installed django on my virtual environment but when i deactivate the env and check my local machine, django is showing on my machine without installing django on it, please what can cause this? steps i used to installed django on my virtual environment i installed virtual env create virtual environment with "virtualenv env" 3 i activate the env by using source env/bin/activate then i installed django i used django-admin to create my first project so as i want to work on my second project i create new environment activate it but to my own suprise when i "pip freeze" to check whats inside the new Environment, it showing django and some other libraries i installed on the previous environment please guys is this normal? -
How to handle the user field in Django when making a Post request to a model that is accessed using an API key?
models.py: class Hosts (models.Model) : host_label = models.CharField (max_length=64, verbose_name = "Host Label" ) host_activation_request = models.CharField (max_length = 400, verbose_name = 'Activation Request', blank=True, null=True) host_developer_email = models.CharField (max_length = 400, verbose_name = 'Developer Email', blank=True, null=True) class Meta: verbose_name = "Available Host" unique_together = [['host_label', 'host_developer_email']] serializers.py: class HostSerializer(serializers.ModelSerializer): class Meta: model = Hosts fields = ('host_label','host_activation_request') views.py: class CreateHost(CreateAPIView): serializer_class = HostSerializer def generate_activation_request(self, feature, customer_ref="Isode"): config = get_active_config() #this function has been imported at the top command_list = [os.path.join(config.generate_activation_binary_directory, "generate_activation_request")] import subprocess proc = subprocess.run(command_list, universal_newlines=True, capture_output=True) self.result = proc.stdout def post(self, request, *args, **kwargs): print(request.data) self.generate_activation_request(feature=request.data["feature"]) request.data['host_activation_request'] = self.result return self.create(request, *args, **kwargs) A user can login to the website and make a Host in there and the host_developer_email field will be their email and the other two fields will be whatever they input in the form, as host_developer_email has been set to be a hidden field. Now, I have created an endpoint called /api/host which I can send a post request to in order to create a Host instance, but I have implemented the djangorestframework-api-key library. So my request from Insomnia (can use Postman too I guess) looks like this: The Header has the … -
docker-compose, reload server each time I make changes to code
I am dockerizing my Django app and I have the following docker-compose.yml file: version: '3' services: # other services as db etc. web: container_name: web build: context: . dockerfile: Dockerfile.web restart: 'always' env_file: - csgo.env ports: - '8000:8000' volumes: - web:/code depends_on: - db volumes: web: App logs: System check identified no issues (0 silenced). web | September 15, 2022 - 01:38:47 web | Django version 4.0.7, using settings 'csgo.settings' web | Starting development server at http://0.0.0.0:8000/ web | Quit the server with CONTROL-C. I want my container (or the app, idk) to reload whenever I let's say make changes to my models or functions etc. For now, I add some functionality to my app, edit some html views, but no changes appears and the app logs doesn't say that it's reloading. I have to rebuild and up my compose again to see my changes. How to do live-reload composing up? How to send changes to docker? Thanks! -
MUI with django framework
Is it possible to use mui with a django framework? I would like to keep it server-side using django. I know typically mui is built with client side rendering by using a react library. I did find a cdn library in muicss.com but i'm afraid this library is outdated. I would like to use the current version 5.0 and all of it's classes/components. Any ideas? -
How can I access my virtual environment created 1 week ago using ubuntu? I just know the name of the virtual environment but idk how access| PYTHON
I installed my first virtual environment using this commands below Commands used: apt-get update -y apt-get install -y python3-venv mkdir awesome_python_project cd awesome_python_project python3 -m venv awesome_venv source awesome_venv/bin/activate but I can't access it again, does anyone knows why?