Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Heroku Requirements for Django
I am trying to deploy my Django project via Heroku. I have done: pip freeze > requirements.txt to generate requirement file. While deploying I am getting the below error- ERROR: Could not find a version that satisfies the requirement apturl==0.5.2 (from -r /tmp/build_3fb1fde9_/requirements.txt (line 1)) (from versions: none) ERROR: No matching distribution found for apturl==0.5.2 (from -r /tmp/build_3fb1fde9_/requirements.txt (line 1)) I tried to do pip install that in my system but again I am getting exception- requests.exceptions.HTTPError: 404 Client Error: Not Found for URL: https://pypi.org/simple/apturl/ Note- This is the first time I am deploying my project. I guessed I need to do pip install so I did. If I should be doing something else to fulfil the requirement. Please tell me. Thanks! -
How to customise ModelAdmin UI
How does one go about editing the template(s) shown when using wagtail.contrib.modeladmin? Assuming class EventsAdmin(ModelAdmin): menu_label = 'Events' list_display = ('title',) Say I want to make the titles clickable, how would I go about doing so? I figured I could check the templates in wagtail/contrib/modeladmin/templates and add something like <a href="{{ url }}" /> alas the furthest I got to finding that title section was in wagtail/contrib/modeladmin/templates/modeladmin/includes/result_row_value.html where it outputs the title section through the {{ item }} tag {% load i18n modeladmin_tags %} {{ item }}{{ url }}{% if add_action_buttons %} {% if action_buttons %} <ul class="actions"> {% for button in action_buttons %} <li>{% include 'modeladmin/includes/button.html' %}</li> {% endfor %} </ul> {% endif %} {{ closing_tag }} {% endif %} #modeladmin_tags.py @register.inclusion_tag( "modeladmin/includes/result_row_value.html", takes_context=True) def result_row_value_display(context, index): add_action_buttons = False item = context['item'] closing_tag = mark_safe(item[-5:]) request = context['request'] model_admin = context['view'].model_admin field_name = model_admin.get_list_display(request)[index] if field_name == model_admin.get_list_display_add_buttons(request): add_action_buttons = True item = mark_safe(item[0:-5]) context.update({ 'item': item, 'add_action_buttons': add_action_buttons, 'closing_tag': closing_tag, }) return context Going further I don't really understand how the <td> with the title are put in there nor what I can do to make it clickable or customise that template. A screenshot to illustrate the … -
session in django is not getting expired after browser close
i am new to django and python. I am getting issue with session expiry after user close the web-browser without logout. I can see that session remains active in session table, even after waiting for more than 10 min. I updated custom middleware.py and setting.py file as below: middleware.py from django.contrib.auth import logout from django.contrib import messages import datetime import syslog class SessionIdleTimeout(deprecation.MiddlewareMixin if DJANGO_VERSION >= (1, 10, 0) else object): def process_request(self, request): if request.user.is_authenticated(): current_datetime = datetime.datetime.now() syslog.syslog("This user is authenticated") if ('last_login' in request.session): last = (current_datetime - request.session['last_login']).seconds syslog.syslog("there is last_login present in request.session.") if last > settings.SESSION_IDLE_TIMEOUT: syslog.syslog("calling loggout since last > SESSION_IDLE_TIMEOUT") logout(request, login.html) else: syslog.syslog("no logout yet") request.session['last_login'] = current_datetime return None In setting.py MIDDLEWARE = [ .. 'webapp.middleware.SessionIdleTimeout', .. SESSION_EXPIRE_AT_BROWSER_CLOSE = True INACTIVE_TIME = 10*60 # 10 minutes - or whatever period you think appropriate SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer' SESSION_EXPIRE_AT_BROWSER_CLOSE= True SESSION_COOKIE_AGE = INACTIVE_TIME # change expired session SESSION_IDLE_TIMEOUT = INACTIVE_TIME # logout SESSION_TIMEOUT_REDIRECT = '/logout/' SESSION_SAVE_EVERY_REQUEST = True These are my python and django version: Python 2.7.9 django.VERSION (1, 11, 4, u'final', 0) Can anyone point me out whats is still missing in above code? -
ValueError: Missing staticfiles manifest entry for 'img'
When Debug = True, Everything is perfect in http://127.0.0.1:8000/ and https://parasnathcorporation.herokuapp.com/ and No errors in logs. When I turn Debug = False, it shows Server Error (500) on http://127.0.0.1:8000/ and https://parasnathcorporation.herokuapp.com/ and ValueError: Missing staticfiles manifest entry for 'img' in my logs img is a folder which contains all images of my project located in static/assets/ and I am trying to deploy my app in Heroku STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' from google.oauth2 import service_account GS_CREDENTIALS = service_account.Credentials.from_service_account_file( os.path.join(BASE_DIR,'credential.json')) ###configuration for media file storing and reriving media file from gcloud DEFAULT_FILE_STORAGE='PMJ.gcloud.GoogleCloudMediaFileStorage' GS_PROJECT_ID = '------------' GS_BUCKET_NAME = '-----------------------' MEDIA_ROOT = "media/" UPLOAD_ROOT = 'media/uploads/' MEDIA_URL = 'https://storage.googleapis.com/{}/'.format(GS_BUCKET_NAME) -
How to reset Django transaction after exception during multiprocessing?
How do you reset a Django transaction after a database exception (e.g. IntegrityError) occurs so you can continue to write to the database? I have several workers running in their own processes, all launched via the joblib package, that process database records. They all write their progress to a database via Django's ORM. Generally, they work fine, but occasionally, if one encounters an error, such as trying to write a record with a column that violates a unique constraint, then an IntegrityError is thrown. I have error handling logic to capture these, record the error, and allow it to skip to the next file to process. However, I'm finding that once one of these errors is encountered, that effectively prevents all further database access by that worker, as all further write attempts return the notorious error: django.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. The weird thing is, I'm not directly using atomic(), so I'm assuming this is being implicitly run by Django somewhere. How do I work around this? I know the usual way to avoid this error is to explicitly wrap your writes inside atomic. So I … -
No reverse match django with slug_pattern
So I want to insert a url from urls.py, but because we have a slug_pattern arg, i'm confuse how to do that. Below are the traceback : Environment: Request Method: GET Request URL: http://localhost:8000/universitas-indonesia Django Version: 1.11.20 Python Version: 2.7.15 Installed Applications: ('neliti', 'publisher', 'accounts', 'hal', 'mtam', 'haystack', 'django_countries', 'storages', 'select2', 'modeltranslation', 'tastypie', 'mathfilters', 'fastsitemaps', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.redirects', 'debug_toolbar', 'django_extensions') Installed Middleware: ('corsheaders.middleware.CorsMiddleware', 'django.middleware.locale.LocaleMiddleware', 'publisher.middleware.CustomDomainMiddleware', 'publisher.middleware.IndexingMiddleware', 'django.middleware.gzip.GZipMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.common.CommonMiddleware', 'publisher.middleware.RemoveSlashMiddleware', 'publisher.middleware.ToLowercaseMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.common.BrokenLinkEmailsMiddleware', 'django.contrib.redirects.middleware.RedirectFallbackMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', 'publisher.middleware.NonHtmlDebugToolbarMiddleware') Template error: In template E:\Project\neliti\backend\publisher\templates\publisher\headers\sub-menu\sub_menu_repository.html, error at line 51 Could not parse the remainder: '-indonesia' from 'universitas-indonesia' 41 : <li> 42 : <a href="#">Policies</a> 43 : </li> 44 : <li> 45 : <a href="#">For developers</a> 46 : </li> 47 : </ul> 48 : </div> 49 : 50 : <div class="section"> 51 : <a id="contact" href=" {% url 'organisation_detail' slug=universitas-indonesia %} "> 52 : <div class="header"> 53 : CONTACT 54 : </div> 55 : </a> 56 : </div> 57 : </div> The urls.py look like this we use OrganisationDetailView and slug_pattern slug_pattern = '(?P<slug>[a-z0-9_\\-]+)' url(r'^%s$' % slug_pattern, cache_page(content_page_cache_time)(OrganisationDetailView.as_view()), name='organisation_detail'), prefix_default_language=False ) My Organisation view look like this class OrganisationDetailView(NelitiDetailView): model = Organisation filter_set = 'Publication' template_name … -
Django factory, problem with string primary key
My Django model has string as primary key class ActOfWithdrawal(models.Model): ext_act_id = models.CharField(max_length=256, primary_key=True) ready_to_print = models.BooleanField(default=False) class SapPosition(models.Model): act = models.ForeignKey(ActOfWithdrawal, on_delete=models.CASCADE) solution_for_position = models.CharField(max_length=1) Based on it I created two factories class ActOfWithdrawalFactory(factory.django.DjangoModelFactory): class Meta: model = 'apps.ActOfWithdrawal' django_get_or_create = ('ext_act_id',) ext_act_id = 'M' + str(factory.fuzzy.FuzzyInteger(1, 100000)) ready_to_print = False class SapPositionFactory(factory.django.DjangoModelFactory): class Meta: model = 'apps.SapPosition' act = factory.lazy_attribute(lambda a: ActOfWithdrawalFactory()) solution_for_position = factory.fuzzy.FuzzyText(length=1) But when I try to create SapPositionFactory I got such error self.withdraw_act = factories.ActOfWithdrawalFactory.create( ext_act_id='M3', ) self.sapposition = factories.SapPositionFactory.create( act=self.withdraw_act, solution_for_position='B' ) django.db.utils.DataError: invalid input syntax for type integer: "M3" Does factory boy supports Foreign key in string format? -
Django Time Zone issue
I'm having lot's of troubles with TimeZones in my Django application. For explanation purposes I'll jump right to the example : I have an object which has a TimeField(null=True, blank=True), and I basically want to show this time depending on the users timezone. I have a Middleware class which activates the timezone to the authenticated user : #'middleware.py' import pytz from django.utils import timezone class TimezoneMiddleware(object): """ Middleware to properly handle the users timezone """ def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if request.user.is_authenticated: timezone.activate(pytz.timezone(request.user.timezone)) else: timezone.deactivate() response = self.get_response(request) return response Next to this, I'm pulling timezones from User model field timezone = models.CharField(max_length=128, choices=[(tz, tz) for tz in ['UTC'] + pytz.country_timezones('US')], default="UTC") which basically tells me the timezone user selected. And that's all good until I need to render the time adopted to the users timezone. So In my case user has the 'Pacific/Honolulu' timezone. Object time field was saved to 'American/New_York' timezone, and I'm still getting the same time no matter which timezone I select. What am I doing wrong? (I was fallowing the official docs for this) This is my template : {% load tz %} {% get_current_timezone as TIME_ZONE %} {% for object … -
Please if you know how to use django on pydroid, kindly read and answer this question
Please has anyone used django on pydroid? If you had, please can you describe, how you did it yourself, with examples. -
How to use memcache in Django?
I've seen all over problems using Memcached in Django projects which is considered to be The fastest, most efficient type of cache supported natively by Django For instances, Why doesn't memcache work in my Django? How to configure Memcache for Django on Google cloud AppEngine? Django doesn't use memcached framework memcache on django is not working How to use memcached in django project? How do you confirm django is using memcached? Configuring memcached with django What steps are needed to implement memcached in a Django application? How to use memcached in django project? So, how can we then use it? -
How can we remove null key : value pair from the Django response?
I'm getting the response as where I don't want to send the null key: value pair to the client How can we remove null key : value pair from the Django response? -
NameError: name 'DATABASES' is not defined Heroku
When I try to deploy a Django app at Heroku, I got this error. NameError: name 'DATABASES' is not defined. I have created Postgres from resources, but sill I don't know why I am getting this error -----> Python app detected ! Python has released a security update! Please consider upgrading to python-3.7.9 Learn More: https://devcenter.heroku.com/articles/python-runtimes -----> No change in requirements detected, installing from cache -----> Installing pip 20.1.1, setuptools 47.1.1 and wheel 0.34.2 -----> Installing SQLite3 -----> Installing requirements with pip -----> $ python manage.py collectstatic --noinput Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 345, in execute settings.INSTALLED_APPS File "/app/.heroku/python/lib/python3.7/site-packages/django/conf/__init__.py", line 83, in __getattr__ self._setup(name) File "/app/.heroku/python/lib/python3.7/site-packages/django/conf/__init__.py", line 70, in _setup self._wrapped = Settings(settings_module) File "/app/.heroku/python/lib/python3.7/site-packages/django/conf/__init__.py", line 177, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/app/.heroku/python/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/tmp/build_a013ae50_/main_app/settings.py", … -
Bootstrap Card Shrinks after Search Button Clicked
I am pretty new to Boostrap, I've mainly been doing backend stuff, but am now doing front end work. I have a feature where the user searches a place and a list of nearby venues pops up. I'd like these to pop up in a card. I am using bootstrap cards. At the moment I have 2 problems: On load there is just this big card sitting there all clumsy: When I execute a search the card snaps down to a tiny scrollable version and all the content divs (map/card) seem to drop down a tad. I can probably figure out the javascript needed to make the card appear only when search occurs but I don't know how to set the card at a standard height after search (and prevent the divs from shifting slightly). What I'd like to achieve is a standard height for the card after search. Here is the for the initial card: <div class="card" style="width: 18rem;"> <div class="card-body"> <h5 class="card-title">Places Nearby</h5> <div id="cafes"> <div id="cafe_list"></div> </div> </div> </div> Here is the html for the function that generates the list: <div class="cafe-details d-flex"> <ul> {% for cafe in cafes %} <li> <address> <div> <h6 class="cafe-name" data-id="{{ cafe.id … -
Django Render HTML to PDF
I'm trying to render an html file to pdf however while the pdf functionality is working fine the rendering is working properly, no css. Also it renders the whole page, how can i render specific sections of the html page. I'm using xhtml2pdf. views.py file from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template from django.views import View from xhtml2pdf import pisa def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("utf-8")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None data = { "company": "Name", } #Opens up page as PDF class ViewPDF(View): def get(self, request, *args, **kwargs): pdf = render_to_pdf('listings/listing.html', data) return HttpResponse(pdf, content_type='application/pdf') urls.py file path('pdf_view/', views.ViewPDF.as_view(), name="pdf_view"), html file <section class="p0"> <div class="container"> <div class="row listing_single_row"> <div class="col-sm-6 col-lg-7 col-xl-8"> <div class="single_property_title"> <a href="{{ listing.photo_1.url }}" class="upload_btn popup-img"><span class="flaticon-photo-camera"></span> View Photos</a> </div> </div> <div class="col-sm-6 col-lg-5 col-xl-4"> <div class="single_property_social_share"> <div class="spss style2 mt10 text-right tal-400"> <ul class="mb0"> <li class="list-inline-item"><a href="#"><span class="flaticon-transfer-1"></span></a></li> <li class="list-inline-item"><a href="#"><span class="flaticon-heart"></span></a></li> <li class="list-inline-item"><a href="#"><span class="flaticon-share"></span></a></li> <li class="list-inline-item"><a href="{% url 'pdf_view' %}"><span class="flaticon-printer"></span></a></li> </ul> </div> </div> </div> </div> </div> </section> Thank you! -
Why can't I access my template view when trying to register a user with Django?
I'm trying to implement a login functionality to a small Django project but when I go to the page with signup/signin form I get the 404 error. I am using Django default user model and auth forms. here are the views: def signup(request): if request.user.is_authenticated: return redirect('/') if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') password = form.cleaned_data.get('password1') user = authenticate(username=username, password=password) login(request, user) return redirect('/') else: return render(request, 'signup.html', {'form': form}) else: form = UserCreationForm() return render(request, 'signup.html', {'form': form}) def signin(request): if request.user.is_authenticated: return render(request, 'homepage.html') if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('/') else: form = AuthenticationForm(request.POST) return render(request, 'signin.html', {'form': form}) else: form = AuthenticationForm() return render(request, 'signin.html', {'form': form}) def log_out(request): logout(request) return redirect('/') here are the urls for my views: urlpatterns = [ path('', views.PostList.as_view(), name='home'), path('signup/', views.signup, name='register'), path('signin/', views.signin, name='signup'), path('log_out/', views.log_out, name='log_out'), ] -
How to connect django model using foreignkey to a unique object in another model
Please how do I connect a model to a particular object in another model using either onetoonefield or foreignkey. Example class Post(models.Model): title = models.TextField(max_length=100, null=True) caption = models.CharField(max_length=1000) photo = models.ImageField(upload_to ='posts', null=True) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) likes= models.IntegerField(default=0) dislikes= models.IntegerField(default=0) price = models.DecimalField(max_digits=10, decimal_places=2, null=True) digital = models.BooleanField(default=False, null=True, blank=False) location = models.PointField(srid=4326, null=True) category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.CASCADE) slug = models.SlugField(unique=True, null=True) def __str__(self): return self.title @property def number_of_comments(self): return Comment.objects.filter(post_connected=self).count() class Comment(models.Model): **post_owner = models.OneToOneField( )** content = models.TextField(max_length=150) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) post_connected = models.ForeignKey(Post, on_delete=models.CASCADE) I need to make post_owner in Comment Models, connected to author in Post models and not the entire Post models -
How to set default Field attributes i.e ( max_length) for the whole project - Django
What's the best way to set global default attributes for a model Field in Django ? Say i have many DecimalField() in various models in my app, and i want to set a default max_digits and decimal_places globally so it applies to all my DecimalFields ?? -
How to overwrite default django admin login view
I need to modify default django admin login functionality while keeping the rest untouched. I found the login.html template, but I need to work on some data I receive from modified login template. I see mentions of LoginView, and expected to see something like login method in which all the workflow is done, but see none. -
Django makemigrations return KeyError
So, when I tried makemigrations command I got this error *Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "/home/panasonic/.local/lib/python3.6/site-packages/django/core/management/init.py", line 381, in execute_from_command_line utility.execute() File "/home/panasonic/.local/lib/python3.6/site-packages/django/core/management/init.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/panasonic/.local/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/panasonic/.local/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/home/panasonic/.local/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/home/panasonic/.local/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 234, in handle fake_initial=fake_initial, File "/home/panasonic/.local/lib/python3.6/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/panasonic/.local/lib/python3.6/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/panasonic/.local/lib/python3.6/site-packages/django/db/migrations/executor.py", line 245, in apply_migration state = migration.apply(state, schema_editor) File "/home/panasonic/.local/lib/python3.6/site-packages/django/db/migrations/migration.py", line 114, in apply operation.state_forwards(self.app_label, project_state) File "/home/panasonic/.local/lib/python3.6/site-packages/django/db/migrations/operations/fields.py", line 165, in state_forwards for name, instance in state.models[app_label, self.model_name_lower].fields: KeyError: ('Conversation', 'user_pos')Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "/home/panasonic/.local/lib/python3.6/site-packages/django/core/management/init.py", line 381, in execute_from_command_line utility.execute() File "/home/panasonic/.local/lib/python3.6/site-packages/django/core/management/init.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/panasonic/.local/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/panasonic/.local/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/home/panasonic/.local/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, *kwargs) File "/home/panasonic/.local/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 234, in handle fake_initial=fake_initial, File "/home/panasonic/.local/lib/python3.6/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) … -
Name 'member_one' is not defined error in django
I want to get all Message_thread_private instances from database but I am getting error NameError: name 'member_one' is not defined Models.py: class Message_thread_private(models.Model): member_one = models.ForeignKey(User, related_name='member_one_messages', on_delete=models.CASCADE) member_two = models.ForeignKey(User, related_name='member_two_messages', on_delete=models.CASCADE) content = models.TextField() created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.member_one.username def last_10_messages(): return Message.objects.order_by('-timestamp').all()[:10] views.py: @login_required def room(request, room_name): users = User.objects.filter(is_active=True).exclude(username=request.user.username) messages = Message_thread_private.objects.filter(member_one.username==request.user.username) return render(request, 'chat/room.html', { 'room_name_json': mark_safe(json.dumps(room_name)), 'username': mark_safe(json.dumps(request.user.username)), 'users': users, }) Why am i getting this error and how can I resolve this? -
What is the benefit of learning sql over sqlalchemy?
I was reading this: Using and connecting application through an ORM (Object Relational Mapper) like SQLAlchemy, Django ORM and so on is easier, faster, and more efficient than writing SQL - which means, more likely, it is preferred by the team. Good to have it in your skillset! So, I guess I would work with these platforms easier than the based ones? Can someone explain more smoothly? -
DEADLINE IS NEAR - NOTIFICATION
I'm doing a django-project that manages some projects. Each project has its deadline, and I'd like to implement the fact that when the deadline is in 3 days for example, the system sends a notification to the employee that is working on that project. I haven't decided if the notification should be sent as an email to the worker, or if it should be a notification sent to the worker's profile on my webapp. Could you give me some advice for which is the best way? And in either case how could i do it? Should I use celery or cron-job or something else? -
Celery identify list of worker running on multiple instance
I have celery set up on four different servers. Scheduling task Task #1, Task #2, Task #3 (Each task 10 worker) Task #1, Task #2, Task #3 (Each task 10 worker) Task #1, Task #2, Task #3 (Each task 10 worker) The first server is scheduling a task and the other three servers are executing a task. The setup is quite ok and working flowless. Now I came across one scenario that. Sometimes I need to stop any of the server 2 or 3 or 4. So I want to raise a shutdown broadcast signal for thee of the workers running on a particular server from the first scheduling server. How can I send a shutdown signal to a perticular server's worker? [Django celery, Redis queue] -
How can we use python for loop variable for the django class field?
I am sending ajax data to the below view I want to save it in the model I have created (mentioned below). Problem is, in that model I want 26 fields as the months so I created that by the add_to_class inside for loop. I don't know how much months user will input so I have to loop the list in views and save the data as: a = '100000' b = '120000' c = '15000' where a, b, c are the months and the rest values will be 0 default. Here is the model ''' class sold(models.Model): car = models.ForeignKey(Car, on_delete=models.CASCADE) Buyer = models.ForeignKey(buyer, on_delete=models.CASCADE) total = models.IntegerField() deposit = models.IntegerField() balance = models.IntegerField() months = models.IntegerField(default=12) tracker = models.IntegerField() insurance = models.IntegerField() def __str__(self): return f'{self.car} {self.Buyer} {self.total} {self.balance} for i in ascii_lowercase: sold.add_to_class('%s'%i, models.CharField(default=0, max_length=255,null=True, blank=True))''' NOTE: I have tried range(1, 27) with str and int but it didn't worked out. The views.py def sale_car_data(request): if request.method == 'POST': check = request.POST['car'] # if soldTo.objects.filter(car__chasis=check).exists(): # return HttpResponse('Already Exist') if 1==1: #Some condition here insurance = request.POST['insurance'] month = request.POST['month'] installment = request.POST.getlist('installment') installment = [json.loads(item) for item in installment] sale = sold(car=pro, Buyer=buyer, total=total, deposit=deposit, balance=balance, … -
registration and login form without use django authentications
I have a registration and login form but I dont want to use django authentications. I want to log in using the username and password that the user enters in the registrationform. How can I say that the content of the field inside the template is equal to the fields of my model.Im begginer in django and i hope help me. model.py class Customer (models.Model): CustomerUserName=models.CharField(unique=True,max_length=150) CustomerFirstName=models.CharField( max_length=150) CustomerLastName=models.CharField(max_length=150) CustomerPassWord=models.CharField(max_length=150) CustomerSerialNum=models.CharField(max_length=10) CustomerPhonNum=models.CharField(max_length=11) CustomerAddress=models.TextField(max_length=1000) CustomerEmail=models. EmailField(max_length=256) GENDER=( ('a','male'), ('b','female'), ) CustomerGender=models.CharField(max_length=1,choices=GENDER) CustomerBirthDate=models.DateField(null=True,blank=True) CustomerImage=models.ImageField(upload_to ='upload/userimage/' ) def __str__(self): return '%s %s' % (self.CustomerFirstName, self.CustomerLastName) return self.CustomerUserName.username form.py class SignUpForm(forms.ModelForm): CustomerFirstName = forms.CharField(max_length=150,label='firstname') CustomerLastName = forms.CharField(max_length=150,label=' lastname ') CustomerEmail = forms.EmailField(max_length=256,label=' Email',widget=forms.TextInput( attrs={ 'placeholder': 'example@gmail.com'} )) CustomerPhonNum = forms.CharField(max_length=150,label=' phone number',widget=forms.TextInput( attrs={'class':'phone' ,'placeholder': '09xxxxxxxxx'} )) CustomerPassWord = forms.CharField( label=' password ', widget=forms.PasswordInput( attrs={'class':'psw', 'pattern':'(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}' } )) class Meta: model = Customer fields = ['CustomerUserName','CustomerFirstName', 'CustomerLastName','CustomerEmail','CustomerPhonNum','CustomerPassWord'] class SignInForm(forms.ModelForm): CustomerPassWord = forms.CharField( label=' password', widget=forms.PasswordInput( attrs={'class':'psw', 'pattern':'(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}' } )) class Meta: model = Customer fields = ['CustomerUserName','CustomerPassWord'] view.py def signin(request): form=SignInForm() if request.method== 'POST': form=SignInForm(data=request.POST) if form.is_valid(): UserName = form.cleaned_data['CustomerUserName'] PassWord = form.cleaned_data['CustomerPassWord'] return render(request,'index.html',{'form': form}) else: return HttpResponse('this user is not exist') else: form=SignInForm() return render(request,'signin.html',{'form': form}) def signup(request): form = SignUpForm() if request.method=='POST': …