Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
SECRET_KEY setting must not be empty when I set LANGUAGES
Hi here is the error raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. when I remove LANGUAGES from settings file, Then Its running , other wise giving the error, I tried but not able to resolve it please help. Code Structure - config-settings-base.py, local.py, production.py. I set LANGUAGES in base.py. here is the code of base.py setting ``` import os from django.utils.translation import gettext as _ import environ from django.urls import reverse_lazy env = environ.Env() ROOT_DIR = environ.Path(__file__) - 3 APPS_DIR = ROOT_DIR.path('userpeek') READ_DOT_ENV_FILE = env.bool('DJANGO_READ_DOT_ENV_FILE', default=True) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tango_with_django.settings') if READ_DOT_ENV_FILE: # OS environment variables take precedence over variables from .env env_file = str(ROOT_DIR.path('.env')) env.read_env(env_file) ENV = env application_name = env('APPLICATION_NAME') LOG_DIR = env('LOG_DIR') FILE = application_name + '.log' DEBUG = env.bool('DJANGO_DEBUG', False) # Local time zone. Choices are # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # though not all of them may be available with every OS. # In Windows, this must be set to your system time zone. # SECURITY WARNING: keep the secret key used in production secret! USE_THOUSAND_SEPARATOR = True # DATABASES # ------------------------------------------------------------------------------ # DATABASE_ROUTERS = ['manager.router.DatabaseAppsRouter'] # DATABASE_ROUTERS = ['klm.application.router.FailoverRouter'] DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': … -
Is it possible to catch response in a React website which is opening via redirect from another website?
Consider the scenario where I have created a site in Django(website A) and another site in React(website B). I have a button on website A which redirects to website B. While redirecting I am setting up some headers which I want to retrieve from website B when it gets redirected. Is this situation plausible? -
module 'mysite.asgi' has no attribute 'channel_layer' on Heroku and Django application
I'm trying to deploy a Django application to Heroku but i keep getting the following error: 2020-04-13T08:45:00.134349+00:00 app[web.1]: Traceback (most recent call last): 2020-04-13T08:45:00.134389+00:00 app[web.1]: File "/app/.heroku/python/bin/daphne", line 8, in <module> 2020-04-13T08:45:00.134519+00:00 app[web.1]: sys.exit(CommandLineInterface.entrypoint()) 2020-04-13T08:45:00.134524+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/daphne/cli.py", line 191, in entrypoint 2020-04-13T08:45:00.134697+00:00 app[web.1]: cls().run(sys.argv[1:]) 2020-04-13T08:45:00.134699+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/daphne/cli.py", line 252, in run 2020-04-13T08:45:00.134891+00:00 app[web.1]: application = import_by_path(args.application) 2020-04-13T08:45:00.134913+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/daphne/utils.py", line 14, in import_by_path 2020-04-13T08:45:00.135028+00:00 app[web.1]: target = getattr(target, bit) 2020-04-13T08:45:00.135056+00:00 app[web.1]: AttributeError: module 'mysite.asgi' has no attribute 'channel_layer Here is my Procfile: web: daphne WR.asgi:channel_layer --port $PORT --bind 0.0.0.0 -v2 And here is how i defined Redis on my settings.py: CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('https://mytestapp1.herokuapp.com/', 6379)], 'capacity': 1500, 'expiry': 2, }, }, } Can anyone help me find what i'm doing wrong? Can it be the fact that i have to add the Redis heroku addon to my app? -
how to reinstall Django
for some reasons i removed django first i entered >> import django >> django.__path__ and then i entered sudo rm -r path in terminal. and now when im trying to reinstall it i enter these commands $ sudo apt-get update $ sudo apt-get install python3-django i see Reading package lists... Done Building dependency tree Reading state information... Done python3-django is already the newest version (1:1.11.11-1ubuntu1.8). 0 upgraded, 0 newly installed, 0 to remove and 5 not upgraded. and then i enter django-admin --version i see Traceback (most recent call last): File "/usr/local/bin/django-admin", line 5, in from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' what should i do to reinstall it? please help -
post_save signal for specific Profile model for user registration
I have 2 profile models (Profile1 and Profile 2) with a one-to-one relationship with the django User class. I have 2 separate registration forms, 2 different signals, 2 different views / routes for each model. When I register a user with Profile1, it creates the Profile1 instance but it also creates a Profile2 instance. How can I specify the signal to use based on the type of user signing up? Here is my signals.py for Profile1 @receiver(post_save, sender=User) def create_profile1(sender, instance, created, **kwargs): if created: Profile1.objects.create(customer=instance) @receiver(post_save, sender=User) def save_profile1(sender, instance, created, **kwargs): instance.profile1.save() Here is my signals.py for Profile2 @receiver(post_save, sender=User) def create_profile2(sender, instance, created, **kwargs): if created: Profile2.objects.create(customer=instance) @receiver(post_save, sender=User) def save_profile2(sender, instance, created, **kwargs): instance.profile2.save() -
Update field in unrelated table by spanning relationships using Django ORM
I am using Django 3.0.4. I have 6 tables (Vehicle, Tracker, Driver, Contract, Account and Invoice). There are Many Invoices for each Account(1-M). A single Account is opened for every single Contract(1-1). Each Contract is comprised of a Driver and a Vehicle and Driver-Vehicle combination can have only 1 Contract. Each Vehicle is fitted with a single Tracker(1-1). I intend to check the status of the Invoice(I have done this already) and navigating from this particular record of Invoice I need to find the particular Vehicle inorder to update the status of the Tracker. Tracker has no relation to Invoice and select_related does not seem to work. Your assistance is appreciated. class Vehicle(models.Model): registration = models.CharField(max_length=7, unique = True) make = models.CharField(max_length=16) model = models.CharField(max_length=16) class Tracker(models.Model): vehicle = models.OneToOneField('Vehicle', on_delete=models.CASCADE) msisdn = models.PositiveIntegerField() status = models.CharField(max_length=16) class Driver(models.Model): first_name = models.CharField(max_length=16) middle_name = models.CharField(max_length=16, blank=True) last_name = models.CharField(max_length=16) class Contract(models.Model): vehicle = models.ForeignKey('Vehicle', on_delete=models.CASCADE) driver = models.ForeignKey('Driver', on_delete=models.CASCADE) start_date = models.DateTimeField(auto_now=False, auto_now_add=False) end_date = models.DateTimeField(auto_now=False, auto_now_add=False) class Account(models.Model): contract = models.OneToOneField('Contract', on_delete=models.CASCADE) weekly_amount = models.PositiveSmallIntegerField() weeks = models.PositiveSmallIntegerField() paid_amount = models.PositiveIntegerField() class Invoice(models.Model): account = models.ForeignKey('Account', on_delete=models.CASCADE) amount = models.PositiveIntegerField() status = models.CharField(max_length=16, choices=INVOICE_STATUS, default=UNPAID) -
How to display separate titles on each page in Django
I have a Django website where I have separated the html files into a base.html file as so: {% include 'head.html' %} <body> {% include 'nav.html' %} {% block content %} {% endblock content %} {% include 'footer.html' %} {% include 'scripts.html' %} </body> </html> Due to including head.html, the title on each page is the same, since head.html has only 1 title. Here is the head.html file: <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="{% static 'css/materialize.css' %}"> <link rel="stylesheet" href="{% static 'css/materialize.min.css' %}"> <link rel="stylesheet" href="{% static 'css/style.css' %}"> <link rel="stylesheet" href="{% static 'css/custom.css' %}"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <title>mytitle</title> </head> But i want to display different titles for different pages and I dont know how to. Anyone have any idea? -
How to trim the length of a field's value to max_length in Django?
Suppose I have the following Django model: class City(models.Model): name = models.CharField(max_length=5, null=True, blank=False) When doing City(name='Sapporo').save(), is there a way to automatically trim the length of name to max_length such that "sappo" gets saved in database instead of throwing an error? I don't want to manually check the lengths and trim it myself since I have many charFields fields in many tables, all with different max lengths. -
Are there any 'sorl-thumbnail' like Django packages that can do image processing client-side?
I was wondering if you guys are aware of any sorl-thumbnail like (large-scale) Django packages that can do resizing (image processing) client-side. -
using mock on djstripe signal
im having trouble mocking a djstripe web hook signal. The signal in question is: @webhooks.handler("charge.dispute.created") I need to mock this signal being sent so i can test the following method. I use this signal to notify administration that a dispute has been raised. Here is a link to the page on github that contains djstripes signal code: https://github.com/dj-stripe/dj-stripe/blob/master/djstripe/signals.py Here is the method used on the djstripe handler @webhooks.handler("charge.dispute.created") def charge_dispute_created(event, **kwargs): print(event) details = event.data.get("object") charge_id = details['charge'] charge = stripe.Charge.retrieve( charge_id,) order_pk = charge['metadata']['order'] buyer_email = charge['metadata']['buyer'] buyer = User.objects.get(email=buyer_email) seller_email = charge['metadata']['seller'] seller = User.objects.get(email=seller_email) order = Order.objects.get(pk=order_pk) payment_intent = details['id'] #send notification to buyer via notification and email notify.send(sender=order.advert, recipient=buyer, verb=' - A dispute has been raised on this listing due to the payment being flagged. Please contact customer support.', action_object=order) send_mail( 'Payment disputed', 'Unfortunately your payment for %s has had a dispute filed, a dispute on this order has been raised. Please contact your card issuer.' % order.advert, 'accounts@foxlisted.com.au', [buyer_email], fail_silently=False) Here is the test( i haven't included the user creation and order set up to save space: @patch('djstripe.signals.WEBHOOK_SIGNALS[("charge.dispute.created")].send') @patch('stripe.Charge.retrieve') @patch('notifications.signals.notify.send') def test_charge_dispute_created_notifys_users_when_order_completed(self, handler_mock, notify_mock, retrieve_mock): obj = {'charge' : 'ch_1234'} charge = {'metadata' : {'order' … -
Edit a formset in django
In my django app I am trying to understand many to many relationship and I am using formset to store the data like this: Views.py def Team_Form(request): if request.POST: form = TeamForm(request.POST) form.player_instances = PlayerFormset(request.POST) if form.is_valid(): team= Team() team.tname= form.cleaned_data['tname'] team.save() if form.player_instances.cleaned_data is not None: for item in form.player_instances.cleaned_data: player = Player() player.pname= item['pname'] player.hscore= item['hscore'] player.age= item['age'] player.save() team.player.add(player) team.save() else: form = TeamForm() return render(request, 'packsapp/employee/new.html', {'form':form}) Models.py class Player(models.Model): pname = models.CharField(max_length=50) hscore = models.IntegerField() age = models.IntegerField() def __str__(self): return self.pname class Team(models.Model): tname = models.CharField(max_length=100) player= models.ManyToManyField(Player) def __str__(self): return self.tname Forms.py class PlayerForm(forms.Form): pname = forms.CharField() hscore= forms.IntegerField() age = forms.IntegerField() PlayerFormset= formset_factory(PlayerForm) class TeamForm(forms.Form): tname= forms.CharField() player= PlayerFormset() What I failed to understand is that how to edit the formset that I just Saved or to better phrase the question, How to pass the saved instance to the formset to edit it ? -
How to count objects from database filtered by a choice field in django?
I have Porumbei model and it has gender field. In template I must render the number of Porumbei of each gender. For example: Male= x Porumbei, Female= y Porumbei and Unknown = z Porumbei. My model class Porumbei(models.Model): SEXE = [ ('Mascul', 'Mascul'), ('Femelă', 'Femelă'), ('Pui', 'Pui') ] ... gender = models.CharField(max_length=6, choices=SEXE, db_index=True) ... For Total I have: total = Porumbei.objects.count() Below is what I have now: @staticmethod def masculi(crescator=None): """ Numarul de masculi din sistem """ mascul = Porumbei.objects.filter(gender="Mascul", is_active=True, crescator=crescator) return len(mascul) @staticmethod def femele(crescator=None): """ Numarul de femele din sistem """ femela = Porumbei.objects.filter(gender="Femelă", is_active=True, crescator=crescator) return len(femela) @staticmethod def pui(crescator=None): """ Numarul de pui din sistem """ pui = Porumbei.objects.filter(gender="Pui", is_active=True, crescator=crescator) return len(pui) These functions gets me what I want but from my point of view, are not well optimized. This will end up in three similar queries as I saw in django debug toolbar. My question is, how can I get the number of each gender in only one query. Is it possible with another method or this function can be optimized to do a single query in database? I must mention that with the number of each gender, arithmetic operations must be … -
Group objects that share a field value in common in the same line in Django admin result list
I have a model Allocation in which several objects can share the same datetime field. In the admin page with the result list all objects are in a separate line but it makes the list difficult to read, so my question is what could be the solution to group these objects in a single line? I have no idea how to implement such customization and if there is filter to do that as I'm new to Django. I did a try with fieldsets but it modify the object page not the page with the result list. I'm afraid this is not that easy to implement but I wanted to ask. Thanks! class Allocation(models.Model): portfolio = models.ForeignKey( Portfolio, on_delete=models.CASCADE, related_name='allocation', null=True ) datetime = models.DateTimeField( null=True ) instrument = models.CharField( max_length=10, null=True ) This is what I have in the admin list result page: | Portfolio | Datetime | Instrument | ------------------------------------------------ port1 2020/01/01 AAPL port1 2020/01/01 MSF But what I would like is this: | Portfolio | Datetime | Instrument1 | Instrument2 | ------------------------------------------------------------------- port1 2020/01/01 AAPL MSF -
How jinja2 handles list index out of range error?
Think of a list, for example: a = [1,2,3], in python if you access a[4] you will get the 'list index out of range error'. Now, let's pass our list a to a jinja2 template engine and render following values: {{ a[0] }} -> 1 this is as expected {{ a[4] }} -> expected an error but the error is not raised !!! Anyone knows why jinja2 does not raise an error when rendering {{ a[4] }} and quietly pass this obvious error? I could not find anything related in the documentation: https://jinja.palletsprojects.com/en/2.11.x/ -
I couldn't play the audios that were uploaded to admin
I created a new class in my model.py file: class Audio(models.Model): ..... audio_object = models.FileField(default='') And I uploaded my audios to my admin page. However, the audios don't play and I right-clicked to a new browser, it shows "Page Not Found" saying "The current path, appname/“/media/nameoftheaudio.mp3”, didn't match any of the URLconf defined in projectname.urls. I reviewed the answers from Django MEDIA_URL and MEDIA_ROOT but it didn't solve my problems. In my urls.py, I already have: from django.conf import settings from django.conf.urls.static import static urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) And in my setting.py, I have: STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'assets'), ) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Another piece of information is the audios I uploaded to another class work fine! And that is the first class model I created in this project. I can't detect what do I lack for this Audio class. I am using Django 3.0.4 Thank you!! -
Django enclosing substring in string with anchor tags with href attribute
Right now im using regex to search for the substring in a given string then enclosing it in anchor tags with href that is in jinja template pattern = re.compile(rf"({substring})",re.IGNORECASE); anchoredString = mark_safe(re.sub(pattern, "<a href=\"{% url 'url' substring %}\">"+substring+"</a>"),string))) The tags work fine but when I click on the link, it tries to redirect me to the literal "{% url 'url' substring %}" not the "url" path that I defined in my urls.py. Is there a better way of doing this? -
Django/AJAX - New data is not getting rendered after first jQuery AJAX call (i.e. on subsequent calls)
I have tried to set the cache property to false on the AJAX request, but it did absolutely nothing. I am implementing a JS calendar and when you click on any day, it opens a popup overlay that also includes another calendar. This second calendar is opened via ajax, and everything seems to be working on the first call which renders: Then, upon closing the overlay and clicking another date on the calendar, I always get the first overlay, no matter how many times I click. The AJAX call $.ajax( { type:"POST", url: "/teachers/teacherDayAgenda/", data:{ 'event_date': dateClicked }, dataType: 'json', cache: false, success: function( eventData ) { var lessonEvents = []; var lesson = {}; for (var key in eventData) { if (key=="eventDefault") break; lesson = {}; lesson['title'] = "Lesson with "+eventData[key]['teacher_name']; lesson['start'] = formatDate(moment(eventData[key]['timeslot_start']).toDate()); lesson['end'] = formatDate(moment(lesson['start']).add(40, 'm').toDate()); lessonEvents.push(lesson); } console.log(eventData); $('#teacher_schedule').fullCalendar({ header: { left: 'prev,next today', center: 'title', right: 'agendaDay,listWeek' }, defaultDate: eventData['event0']['click_event_date'], navLinks: true, eventLimit: true, events: lessonEvents }); $("#teacher_schedule .fc-agendaDay-button").trigger("click"); /*$('td').removeClass('AddEventPopup_open'); */ } }); The View: @login_required def teacherDayAgenda(request): """ Ajax request for popup overlay, changes to student schedule, see day agenda of availability of teachers """ if request.method == 'POST': click_event_date = request.POST['event_date'] studentid = … -
Suddenly `Error loading MySQLdb module` happens
I am using django system but suddenlyt this error happens. I try to re-install mysqlclient, but situation doesn't change. $pip uninstall mysqlclient $pip install mysqlclient Before it works well but suddenly this error happens. I did rbenv re-install yesterday , is that related??? $python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/whitebear/anaconda3/envs/myapp/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 16, in <module> import MySQLdb as Database File "/Users/whitebear/anaconda3/envs/myapp/lib/python3.7/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: dlopen(/Users/whitebear/anaconda3/envs/myapp/lib/python3.7/site-packages/MySQLdb/_mysql.cpython-37m-darwin.so, 2): Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib Referenced from: /usr/local/opt/mysql@5.7/lib/libmysqlclient.20.dylib Reason: image not found The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/whitebear/anaconda3/envs/myapp/lib/python3.7/threading.py", line 917, in _bootstrap_inner self.run() File "/Users/whitebear/anaconda3/envs/myapp/lib/python3.7/threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "/Users/whitebear/anaconda3/envs/myapp/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Users/whitebear/anaconda3/envs/myapp/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/Users/whitebear/anaconda3/envs/myapp/lib/python3.7/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/Users/whitebear/anaconda3/envs/myapp/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/Users/whitebear/anaconda3/envs/myapp/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Users/whitebear/anaconda3/envs/myapp/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/whitebear/anaconda3/envs/myapp/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/Users/whitebear/anaconda3/envs/myapp/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/Users/whitebear/anaconda3/envs/myapp/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", … -
Issue Connecting to Google Cloud Database
I'm using a postgresql database on the google cloud and I'm trying to create a script to receive API requests using python. This is the error I'm currently getting when I send get requests: 127.0.0.1 - - [12/Apr/2020 22:50:20] "GET / HTTP/1.1" 500 - Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pg8000/core.py", line 1152, in init self._usock.connect(unix_sock) FileNotFoundError: [Errno 2] No such file or directory During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 2285, in _wrap_pool_connect return fn() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 303, in unique_connection return _ConnectionFairy._checkout(self) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 773, in _checkout fairy = _ConnectionRecord.checkout(pool) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 492, in checkout rec = pool._do_get() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqlalchemy/pool/impl.py", line 139, in _do_get self._dec_overflow() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqlalchemy/util/langhelpers.py", line 69, in exit exc_value, with_traceback=exc_tb, File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqlalchemy/util/compat.py", line 178, in raise_ raise exception File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqlalchemy/pool/impl.py", line 136, in _do_get return self._create_connection() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 308, in _create_connection return _ConnectionRecord(self) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 437, in init self.connect(first_connect_check=True) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 657, in __connect pool.logger.debug("Error on connect(): %s", e) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqlalchemy/util/langhelpers.py", line 69, in __exit exc_value, with_traceback=exc_tb, File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqlalchemy/util/compat.py", line 178, in raise_ raise exception File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 652, in connect connection = pool._invoke_creator(self) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqlalchemy/engine/strategies.py", line 114, in connect … -
'WSGIRequest' object has no attribute 'data' in django rest_framework
in model.py create a class in which 3 fields are there class signUp(models.Model): username = models.CharField(max_length=100) email = models.EmailField() password = models.IntegerField() in serializer.py class SignupSerializer(serializers.Serializer): class Meta: model = signUp fields = ('username', 'email', 'password') def create(self, validated_data): email = validated_data['email'], name = validated_data['name'], password = validated_data['password'] return signUp.objects.create(**validated_data) in views.py @csrf_exempt def signup(request): if 'username' not in request.data: response = {'message': 'please enter username'} return Response(response, status=status.HTTP_400_BAD_REQUEST) elif 'email' not in request.data: response = {'message': 'please enter email'} return Response(response, status=status.HTTP_400_BAD_REQUEST) elif 'password' not in request.data: response = {'message': 'please enter password'} return Response(response, status=status.HTTP_400_BAD_REQUEST) if request.method == 'GET': signup = signUp.objects.all() serializer = SignupSerializer(signup, many=True) return JsonResponse(serializer.data, safe=False) if request.method == 'POST': data = JSONParser().parse(request) serializer = SignupSerializer(data=data) if serializer.is_valid(): user = serializer.validated_data.get('username') message = f'successfully signup {user}' return Response({message: message}, status=HTTP_200_OK) i am new in django i want to make api to register user by post method and get details of user by get method ... -
Delete a user's file after some days after the user is deleted in Django
In my Django application, I want to delete a user's media file(their profile picture and other images) after 4-5 days when the user deletes its account. def delete_files(sender, instance, **kwargs): path = str(os.getcwd()) try: pathdl = f"{path}\\data\\media\\{instance.username}" shutil.rmtree(pathdl) except Exception: print(Exception) post_delete.connect(delete_files, sender=User) I used post_delete to delete the files of the user, but how can I delete the file after 4-5 days or a certain time period. -
Hoe to change the position of pagination on django?
I have a pagination bar below but I want it at the top. So I made an HTML file where I will override the template. But I can't understand how to pick that paginator class and how to move it to the top? Any Suggestion or Idea ???? -
Static properties not changing in Django
I have a website that I am working on and I wanted to change the css a bit to fit the content (change height of a container). However, after applying the changes when I reload my page, the change does not appear in the website. I'm pretty sure I have linked the static files in the right way since not doing so would not render my website as expected. I have tried doing the same changes to a separate copy not linked with django, and it worked. Anyone know whats going wrong? -
docker-compose up on Django in Docker container just prints "exited with code 0" rather than "Starting Development Server"
Dockerfile # The first instruction is what image we want to base our container on # We Use an official Python runtime as a parent image FROM python:3.7 FROM registry.gitlab.com/datadrivendiscovery/images/primitives:ubuntu-bionic-python36-v2020.1.9 # The enviroment variable ensures that the python output is set straight # to the terminal with out buffering it first ENV PYTHONUNBUFFERED 1 # create root directory for our project in the container RUN mkdir /bbml # Set the working directory to WORKDIR /bbml # Install any needed packages specified in requirements.txt RUN pip install -r requirements.txt RUN pip install --upgrade pip COPY . /bbml/ CMD [ "python", "./manage.py runserver 0.0.0.0:8000" ] docker-compose.yml version: '3' services: web: build: . volumes: - .:/bbml ports: - "8000:8000" I try to run 'docker-compose up' and according https://docs.docker.com/compose/django/(sort of this is definitely outdated) and all that happens is this $ docker-compose up Starting a7897a5e26de_blackboxmlsolutions_web_1 ... done Attaching to a7897a5e26de_blackboxmlsolutions_web_1 a7897a5e26de_blackboxmlsolutions_web_1 exited with code 0 It's supposedly supposed to start up the server in the container, but it does not. If anyone has any references for running and developing Django in Docker on Windows that'd be great I'm not having much luck getting this working. I don't even have a DB setup and it's … -
Modal to confirm delete
I have a form for creating products and editing existing products. I can submit changes just fine but when I added a delete button that opens a modal to confirm the delete I've run into some unexpected problems. template.html <div class="container-fluid"> <form enctype="multipart/form-data" method="POST"> {% csrf_token %} {{form|crispy}} {{form.errors}} <button type="submit" class="btn btn-primary btn-block"><i class="fa fa-upload"></i> Upload</button> {% if instance %} <button class="btn btn-danger btn-block" data-toggle="modal" data-target="#exampleModalCenter"><i class="fa fa-trash"></i> Delete</button> {% endif %} </form> </div> <div class="m-4"> {% for product in products %} <a href="{% url 'main:update_product_view' slug=product.slug %}"> <h2>{{product.product_title}}</h2> </a> {% endfor %} </div> {% if instance %} <div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle">Confirm Action</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> Are you sure you want to delete {{instance.product_title}}? </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <a href="{% url 'main:delete_product_view' instance.slug %}"><button type="button" class="btn btn-danger"><i class="fa fa-trash"></i> Delete</button></a> </div> </div> </div> </div> {% endif %} views.py def create_product_view(request): if request.method == "POST": form = CreateProductForm(request.POST, request.FILES) if form.is_valid(): product = form.save(commit=False) product.save() return redirect('main:homepage_view') else: form = CreateProductForm context = { "title": "Create - Product", "form": form, } return render(request=request, …