Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Two Django Views that throw "Internal Error 500" only when in production
I have a website that works perfectly fine in my development environment but throws an Internal Error (500) in production on a Debian 9, Nginx, and Gunicorn setup. Here are the troublesome views: @login_required def post(request): if request.method == "POST": form = ListingForm(request.POST, request.FILES) if form.is_valid(): post = form.save(commit=False) post.lat, post.lng = get_lat_lng(google_api_key, post.street_address + ", " + post.city + ", " + post.state) post.save() return redirect('post_view', pk=post.pk) else: form = ListingForm() return render(request, 'post.html', {'form': form}) @login_required def post_edit(request, pk): post = get_object_or_404(Listing, pk=pk) if request.method == "POST": form = ListingForm(request.POST, request.FILES, instance=post) if form.is_valid(): post = form.save(commit=False) post.lat, post.lng = get_lat_lng(google_api_key, post.street_address + ", " + post.city + ", " + post.state) post.save() return redirect('post_view', pk=post.pk) else: form = ListingForm(instance=post) return render(request, 'post_edit.html', {'form': form, 'post': post}) And here is an example of a view that works completely fine in production with similar functionality: @login_required def new_attorney(request): if request.method == "POST": form = AttorneyForm(request.POST, request.FILES) if form.is_valid(): post = form.save(commit=False) post.save() return redirect('attorney_edit', pk=post.pk) else: form = AttorneyForm() return render(request, 'new_attorney.html', {'form': form}) I'm kind of freaking out because this is a time sensitive project we need live soon, and I have no clue what's causing this error. … -
Error installing psycopg2 python 3.7 on macos 10.15
I tried pip3 install psycopg2 Got these errors, unable to understand what I need to do. Collecting psycopg2==2.7.3.1 Using cached https://files.pythonhosted.org/packages/6b/fb/15c687eda2f925f0ff59373063fdb408471b4284714a7761daaa65c01f15/psycopg2-2.7.3.1.tar.gz Installing collected packages: psycopg2 Running setup.py install for psycopg2: started Running setup.py install for psycopg2: finished with status 'error' ERROR: Command errored out with exit status 1: command: /Users/amolchakane/Desktop/Projects/kisanoauth/venv/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/c7/wshj0hq9637_ddn00y_52y7c0000gp/T/pycharm-packaging/psycopg2/setup.py'"'"'; file='"'"'/private/var/folders/c7/wshj0hq9637_ddn00y_52y7c0000gp/T/pycharm-packaging/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record /private/var/folders/c7/wshj0hq9637_ddn00y_52y7c0000gp/T/pip-record-f050z4mz/install-record.txt --single-version-externally-managed --compile --install-headers /Users/amolchakane/Desktop/Projects/kisanoauth/venv/include/site/python3.7/psycopg2 cwd: /private/var/folders/c7/wshj0hq9637_ddn00y_52y7c0000gp/T/pycharm-packaging/psycopg2/ Complete output (61 lines): running install running build running build_py creating build creating build/lib.macosx-10.9-x86_64-3.7 creating build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/_json.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/extras.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/errorcodes.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/tz.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/_range.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/_ipaddress.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/init.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/psycopg1.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/extensions.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/sql.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/pool.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 creating build/lib.macosx-10.9-x86_64-3.7/psycopg2/tests copying tests/test_transaction.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2/tests copying tests/dbapi20.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2/tests copying tests/test_extras_dictcursor.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2/tests copying tests/test_with.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2/tests copying tests/test_types_basic.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2/tests copying tests/test_bug_gc.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2/tests copying tests/test_module.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2/tests copying tests/test_psycopg2_dbapi20.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2/tests copying tests/test_async.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2/tests copying tests/test_dates.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2/tests copying tests/test_async_keyword.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2/tests copying tests/testutils.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2/tests copying tests/test_connection.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2/tests copying tests/test_copy.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2/tests copying tests/test_bugX000.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2/tests copying tests/init.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2/tests … -
I need to know my social database design is good or need to re-disign
I have a dream to design a social network and I design a database. please wrote opinion to about my schema and if they have problem guide me. thanks. class User(AbstractUser): """ Custom User Model """ id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) bio = models.TextField(max_length=500, blank=True) class UserFriend(models.Model): FRIEND_STATUS = [ ('0' , 'Pending'), ('1' , 'Accepted'), ('2' , 'Declined'), ('3' , 'Blocked'), ] FRIEND_TYPE = [ ('0' , 'Friend'), ('1' , 'Close Friend'), ('2' , 'Classmate'), ('3' , 'Family'), ('4' , 'Follower') ] status = models.CharField(max_length=1, choices=FRIEND_STATUS) type = models.CharField(max_length=1, choices=FRIEND_TYPE) user_id = models.ForeignKey(User, on_delete=models.CASCADE) friend_id = models.ForeignKey(User, on_delete=models.CASCADE) class Profile(models.Model): """ profile model """ GENDER_CHOICES = [ ('M' , 'Male'), ('F' , 'Female'), ] user = models.OneToOneField(User, on_delete=models.CASCADE) gender = models.CharField(max_length=2, choices=GENDER_CHOICES) birthday = models.DateField(null=True, blank=True) birthplace = models.CharField(max_length=150, null=True, blank=True) address = models.CharField(max_length=250, null=True, blank=True) education = models.CharField(max_length=150, null=True, blank=True) skill = models.CharField(max_length=150, null=True, blank=True) language = models.CharField(max_length=150, null=True, blank=True) college = models.CharField(max_length=150, null=True, blank=True) favorite_sport = models.CharField(max_length=150, null=True, blank=True) favorite_food = models.CharField(max_length=150, null=True, blank=True) favorite_movie = models.CharField(max_length=150, null=True, blank=True) I create a user entity class and when user create a post or something else first app create a record in this table and then create record for … -
Cannot download Pillow in Django VSCode project (Windows)
I'm going through Django 2.2 course with Windows / VSCode / Anaconda setup. I've tried to use both Python 3.6 and 3.7 interpreters and tried to download Pillow with commands such as: pip install Pillow python -m pip install pillow pip install Pillow==5.0.0 I've tried to execute this both in is Anaconda Shell Prompt and cmd. Simply put, I get error of missing Pillow package whatever I do. When I try to execute "conda install" it says the the requirement is already satisfied, but it still doesn't recognize the package. See attached pictures about errors. Error1 Error2 -
Invalid Column name error when attempting to delete model instance
A little bit of context: I have a Django site, where I just overwrote the default user model mid project. It appears to be working for everything, except for on the admin page if I try to delete a user instance, it gives an error Invalid column name 'ouser_id'. I tried removing the automatically created delete functionality within the admin site, and adding my own as an action, but that did not work. models.py class OUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(verbose_name='email address', max_length=255, unique=True) username = models.CharField(max_length=150, unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) # a superuser first_name = models.CharField(max_length=100, blank=True, default='') last_name = models.CharField(max_length=100, blank=True, default='') date_joined = models.DateField(auto_now=True) password = models.CharField(max_length=100) REQUIRED_FIELDS = [] # Email & Password are required by default. USERNAME_FIELD = 'username' def __str__(self): return self.username def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible answer: Yes, always return True def has_module_perms(self, app_label): "Does the user have permissions to view the app `app_label`?" # Simplest possible answer: Yes, always return True admin.py class OUserAdmin(BaseUserAdmin): # The forms to add and change user instances form = UserAdminChangeForm add_form = UserAdminCreationForm actions = [deleteOUser, setStaff, setNotStaff, setSuperuser, setNotSuperuser, setActive, setInactive, … -
ImportError: Can't import DEFAULT_CHANNEL_LAYER
I am developing a web service based on Django and channels, I can run the app locally using daphne server, but the problem comes when I deploy it on Heroku, I get import error, the error says cannot import DEFAULT_CHANNEL_lAYER... The app is running locally and it was running on Heroku until I decided to include channels. -
Django different url going to the same page
I am trying to create 2 extra pages on my Django site, I created the first one with no problem (calendar.html) but when I try to create the second one (actionplan.html) it gives me no error, but when I access xxx/actionplan.html , it shows the calendar.html page... I cannot access xxx/actionplan.html This is my urls.py: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls import url from django.conf.urls.static import static from django.views.generic import TemplateView from django.views.generic.detail import DetailView urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')), url(r'xxx', TemplateView.as_view(template_name="calendar.html")), url(r'^xxx/$', DetailView.as_view(template_name="actionplan.html")), url(r'^admin/', admin.site.urls), url(r'^', include('blog.urls'), name="Blog"), ] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) This is my views.py: from django.views import generic from .models import Post class PostList(generic.ListView): queryset = Post.objects.filter(status=1).order_by('-created_on') template_name = 'index.html' class PostDetail(generic.DetailView): model = Post template_name = 'post_detail.html' class Calendar(generic.DetailView): model = Post template_name = 'calendar.html' class Planoacao(generic.DetailView): model = Post template_name = 'actionplan.html' I have tried: url(r'^xxx/$', DetailView.as_view(template_name="actionplan.html")), url(r'^xxx', DetailView.as_view(template_name="actionplan.html")), url(r'^xxx$', DetailView.as_view(template_name="actionplan.html")), url(r'xxx', DetailView.as_view(template_name="actionplan.html")), I am officially out of ideas now... can anyone spot a problem? -
Chromium print-to-pdf adding space above images
The background I have a simple document making system which is part of a Python Django application. The PDF download uses Chromium's print-to-pdf function running from a Docker container by passing in the URL of the document page from the Django app. The HTML is edited using TinyMCE. The problem Large gaps are appearing above some images with no obvious difference between the ones that do and the ones that don't have gaps. I have put borders around HTML tags with differing colours to try and see what is containing the empty space: div: red p: green span: blue img: black td: orange The evidence The offending section of the page looks like this in the browser: The resulting PDF looks like this with a big gap in the middle: The HTML for that section is: <div class="content flex None"> <div class="docsection flex"> <div class="wrapper"> <div class="header" style="position: relative;"> <!-- the trigger element if no value set yet --> <a href="" id="docsection_title70-btn" class="text-darken-2 inplace-editor-trigger error" style="" data-for="docsection_title70"> Add title </a> <!-- the actual output content if there is any yet --> <h2 class="inplace-editor-content tooltip title" data-position="top" data-tooltip="Click to edit" data-for="docsection_title70"> </h2> </div> <div class="copy tinymce" style="position: relative;"> <!-- the trigger … -
Please explain the line of code I Mentioned
This is a mixin which I had seen in a book. from django.core.cache import caches from django.views.decorators.cache import cache_page from django.views.decorators.vary import vary_on_cookie class CachePageVaryOnCookieMixin: cache_name = 'default' @classmethod def get_timeout(cls): if hasattr(cls, 'timeout'): return cls.timeout cache = caches[cls.cache_name] return cache.default_timeout @classmethod def as_view(cls, *args, **kwargs): view = super().as_view(*args, **kwargs) view = vary_on_cookie(view) view = cache_page(timeout = cls.get_timeout(), cache = cls.cache_name)(view) return view In as_view() view = cache_page(timeout = cls.get_timeout(), cache = cls.cache_name)(view) what is the use of (view) at last. Is it a type casting? -
Django: How do I check if a queryset is empty?
I have the following try catch block on a query that I am making: # We only want SurfGroups per SurfInstructor for a forward looking date: try: surf_groups = SurfGroup.objects.filter( instructor__uuid=uuid, date__gte=datetime.date.today() ) except SurfGroup.DoesNotExist: # Handle exception here However, even if the surf_groups queryset is empty, returning no results, the exception can not be handled as it is not thrown on a objects.filter() call. So, my question is, how would I handle an empty queryset? -
Call an another method right after calling model class constructor (Django)
I want to set my Order Object's total amount with the total of selected products (order_items) prices at that time. I want to call an another method right after Order constructor, So that the amount won't change when change in Product price My Order Class is: class Order(models.Model): user = models.ForeignKey(User, on_delete=models. order_items = models.ManyToManyField(OrderItem, related_name="order_items") amount = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) ......... My OrderItem Class is: class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) ........ My Product Class is: class Product(models.Model): name = models.CharField(max_length=30, default=None) price = models.DecimalField(max_digits=10, decimal_places=2) product_type = models.ForeignKey(ProductType, on_delete=models.SET_DEFAULT,default = None, null=True, blank=True) ...... -
How to use token form of django-otp in django for admin verification
I would like to implement a 2 factor authentication system for the admin page in django using django-otp's token form i.e it will ask for a generated otp to verify the authenticated user . I am unaware of how to do this though. As always, I greatly appreciate your suggestions! Note: I am using django 2.2 with python 3.6 I am going make the otp available to admins via email Also, if you need any other reasonable info, feel free to ask! -
is there way for add paginator to search results when i using 'chain' (multi models ) in django
i want to ask if there any way for add paginator to my search results when i'm using chian i mean like this (Multi Databases) i have tried many ways for do this but it's doesn't work i have this in views.py def search(request): if request.method == 'GET': query= request.GET.get('q') submitbutton= request.GET.get('submit') if query is not None: home_database= Homepage.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) pcprograms_database= PCprogram.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) androidapk_database= AndroidApks.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) androidgames_database= AndroidGames.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) antiruvs_database= Antivirus.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) systems_database= OpratingSystems.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) pcgames_database= PCgames.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) results= list(chain(home_database,pcprograms_database,androidapk_database,androidgames_database,antiruvs_database,systems_database,pcgames_database)) paginator = Paginator(results, 2) # Show 25 rows per page page = request.GET.get('search-page') results = paginator.get_page(page) context={'results': results, 'submitbutton': submitbutton} return render(request, 'html_file/enterface.html', context) else: return render(request, 'html_file/enterface.html') else: return render(request, 'html_file/enterface.html') and this in html : {% if submitbutton == 'Search' and request.GET.q != '' %} {% if results %} <h2> Results for <b><i style="color:#337ab7">{{ request.GET.q }}</i></b> : </h2> <br/><br/> {% for result in results %} <label id="label_main_app"> <img style="margin-top:.3%;margin-left:.3%" id="img_main_app_first_screen" src="{{result.app_image.url}}" alt="no image found !" height="160" width="165" > {{result.name}} <br><br> <p id="p_size_first_page"> {{result.app_contect}} … -
How can I show selenium web driver process on my django web site?
I am trying to scrap through a dozen websites and show thier result on my own website. My first idea was to put each result url on a iframe. I am using selenium for python which shows you the process of scraping on a browser (web driver) Is there a way to show this process on website in different iframes or something else? I am using django for the website. -
How can to start tasks with celery-beat?
Why i can't run a periodic tasks? proj/settings.py REDIS_HOST = 'localhost' REDIS_PORT = '6379' CELERY_BROKER_URL = 'redis://localhost:6379' BROKER_URL = 'redis://' + REDIS_HOST + ':' + REDIS_PORT CELERY_BEAT_SCHEDULE = { 'task-first': { 'task': 'app.tasks.one', 'schedule': timedelta(seconds=1) }, 'task-second': { 'task': 'app.tasks.two', 'schedule': crontab(minute=0, hour='*/3,10-19') } } proj/celery.py os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') app = Celery('proj') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) proj/__init.py__ from .celery import app as celery_app __all__ = ['celery_app'] celery -A proj worker -l info [2019-10-31 16:57:57,906: INFO/MainProcess] Connected to redis://localhost:6379// [2019-10-31 16:57:57,912: INFO/MainProcess] mingle: searching for neighbors [2019-10-31 16:57:58,927: INFO/MainProcess] mingle: all alone [2019-10-31 16:57:58,951: INFO/MainProcess] celery@lexvel-MS-7A72 ready. Tasks are found celery -A proj beat -l info Configuration -> . broker -> redis://localhost:6379// . loader -> celery.loaders.app.AppLoader . scheduler -> celery.beat.PersistentScheduler . db -> celerybeat-schedule . logfile -> [stderr]@%INFO . maxinterval -> 5.00 minutes (300s) [2019-10-31 16:58:02,851: INFO/MainProcess] beat: Starting... The celerybeat.pid and celerybeat-shedule files are created. But besides these lines nothing more is displayed. tasks @task() def one(): print('start 1', datetime.now()) driver = init_driver() parse(driver) driver.close() driver.quit() @task() def two(): print('start 2', datetime.now()) driver = init_driver() parse2(driver) driver.close() driver.quit() print('end 2', datetime.now()) -
Heroku logs says: "No web processes running"
I made a website with django and tried deploying it using Heroku. After deploying, I can't access to it and Heroku log shows the following error : at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=pur-beurre-oc8.herokuapp.com request_id=9e33d4c8-83d6-4214-baf8-e4d1023b43ff fwd="176.134.6.63" dyno= connect= service= status=503 bytes= protocol=https After looking through some similar problems, I tried: heroku ps:scale web=1 and got: Scaling dynos... ! ▸ Couldn't find that process type (web). I tried to remove and add buildpacks: heroku buildpacks:clear heroku buildpacks:add --index heroku/python but this last command return to me: Error: Expected an integer but received: heroku/python at Object.parse (/snap/heroku/3832/node_modules/@oclif/parser/lib/flags.js:17:19) at Parser._flags (/snap/heroku/3832/node_modules/@oclif/parser/lib/parse.js:152:49) at Parser.parse (/snap/heroku/3832/node_modules/@oclif/parser/lib/parse.js:113:28) at Object.parse (/snap/heroku/3832/node_modules/@oclif/parser/lib/index.js:25:27) at Add.parse (/snap/heroku/3832/node_modules/@oclif/command/lib/command.js:83:41) at Add.run (/snap/heroku/3832/node_modules/@heroku-cli/plugin-buildpacks/lib/commands/buildpacks/add.js:7:36) at Add._run (/snap/heroku/3832/node_modules/@oclif/command/lib/command.js:44:31) So I do not know what I'm doing wrong My Proficle is like this: web: gunicorn pur_beurre.wsgi I tried to change Procfile like this: web: gunicorn pur_beurre:app or this: web gunicorn pur_beurre:app but heroku ps:scale web=1 still not working -
order_by() and latest() returning different queryset values
Quering the database using order_by('date') and latest('date') returning different instance.....Which is the best method to get the latest the instance. I am using python 2.7 and django1.8.19 from apps.model import MyModel def function(): using_latest = MyModel.objects.filter(member=member).latest('date').date using_latest = MyModel.objects.filter(member=member).order_by('date')[:1].values('date') -
Saving a row to database with active user id in Django
My model has a user field, which is Django's auth_user_model: class MyModel(models.Model): managed = True db_table = 'mymodeltable' user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING) In the view, I try to save a new row to the database, I get the following error: null value in column "user_id" violates not-null constraint However, I actually save new row with active user object class MyModelView(viewsets.ModelViewSet): @action(methods=['post']) def create(self, request): # Get active user: user = self.request.user serializer = MyModelSerializer(data={user: user}) # I also tried user.id if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) In the related serializer, I return created instance: class MyModelSerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = ('status', ) def create(self, validated_data): my_model_instance = MyModel.objects.create(status=False, **validated_data) return my_model_instance What am I missing? -
Deploying Django app on hosting platforms
Im very new to Django, i wanted to ask what exactly does a Django app come with? From looking at the documentations, it seems a lot of the Django code is very high level and abstracts out a lot of the native python calling code. I wanted to ask, does a Django app also provide a web server and the Django app + web server code is hosted on a machine during deplyoment or is the Django app code uploaded and hosting platforms run their own server code and embedded your Django app? -
How to extract or parse particular line of text from notepad using python?
Below I have a Multitext in notepad.txt File where I want to extract all the values of external_uid column only and print all the value in a list variable external_value using python script. Can anybody help me with the script code? For Example: external_value = ['0114e606-df6c-4657-8a57-ae104a541787', '0144d28b-95ac-4b06-8f24-678635a68f63', ......, '25b30794-ce69-4538-8675-bb568dac1296'] -
Django test.py model object instance is limited to one test
Okay this is pretty strange. This is my code that works: test.py from django.test import TestCase from django.urls import reverse, resolve from django.utils import timezone import datetime from ..models import Realtor, Listing, Contact from ..views import listing from django.test import override_settings from PIL import Image from io import BytesIO from django.core.files import File import tempfile def get_image_file(name='test.png', ext='png', size=(50, 50), color=(256, 0, 0)): file_obj = BytesIO() image = Image.new("RGB", size=size, color=color) image.save(file_obj, ext) file_obj.seek(0) return File(file_obj, name=name) class RealestateListingViewTest(TestCase): @override_settings(MEDIA_ROOT=tempfile.TemporaryDirectory(prefix='mediatest').name) def setUp(self): image_file = get_image_file Realtor.objects.create(name='sample_realtor', photo=get_image_file()) Listing.objects.create(title='listing_sample', address='sample', realtor=Realtor.objects.get(pk=1), city='sample', state='sample', zipcode='1234', price='555555', bedrooms='1', bathrooms='1', garage='1', sqft='123', lot_size='123', photo_main=get_image_file(), photo_1=get_image_file(), photo_2=get_image_file(), photo_3=get_image_file(), photo_4=get_image_file(), photo_5=get_image_file(), photo_6=get_image_file()) url = reverse('btre:listing', kwargs={'listing_id': 1}) self.response = self.client.get(url) def test_listing_status_code(self): self.assertEquals(self.response.status_code, 200) The above code works but whenever I add another test to the mix, like: def test_listing_url_resolves_listing_view(self): view = resolve('/realestate/listing/1') self.assertEqual(view.func, listing) I get this error: realestate.models.Realtor.DoesNotExist: Realtor matching query does not exist. Anyone have an idea how or why this is happening? Also note that it works as long as there is only one test existing in the TestCase class which is why it is very strange to me. Also I have tried this method for the image file creation: class RealestateListingViewTest(TestCase): … -
How to use server side in django datatables?
I have datatables to present some data. I already make the serializer, viewset, and the ajax for datatables. serializer.py class UserSerializer(dserializers.DynamicModelSerializer): """UserSerializer class.""" organisation = DynamicRelationField('oree.serializers.organisation.OrganisationSerializer', embed=True, deferred=True) # id = dserializers.IntegerField(read_only=True) class Meta: # noqa D106 model = User name = 'user' fields = ('id', 'username', 'email', 'organisation', 'date_joined', 'is_staff') datatables_always_serialize = ('id', 'email') views.py class UserViewSet(dviewsets.DynamicModelViewSet): """UserViewSet.""" serializer_class = UserSerializer queryset = User.objects.order_by('email') filter_fields = ('username', 'email',) def get_options(self): """Helper method on datatables. see: https://django-rest-framework-datatables.readthedocs.io/en/latest/tutorial.html """ return "options", { "user": [{'label': obj.email, 'value': obj.pk} for obj in User.objects.all()], "organisation": [{'label': obj.name, 'value': obj.pk} for obj in Organisation.objects.all()] } class Meta: """Meta class for viewset.""" datatables_extra_json = ('get_options',) ajax.js var KTDatatablesDataSourceAjaxServer = function() { var initTable1 = function() { var table = $('#kt_datatable'); // begin first table table.DataTable({ serverSide: true, ajax: { 'type': 'GET', 'url': '/v1/users?format=datatables&include%5B%5D=organisation', // 'data' : { 'format': 'datatables' }, 'dataSrc': function(jsonObj){ if(!jsonObj.data || !jsonObj.data.users){ // console.log(jsonObj.data) return []; } console.log(jsonObj) return jsonObj.data.users; } }, columns: [ {data: 'username', searchable:true, name: 'username'}, {data: 'email', orderable: true, searchable:true, name: 'email'}, {data: 'organisation.name', searchable:true, name: 'organisation.name'}, {data: 'date_joined', orderable: true, searchable:false}, {data: 'is_staff', orderable: true, searchable: false}, ], columnDefs: [ {targets: [0,1,2,3], render: function(data){ if (!$.trim(data)) { return … -
What's happening behind django migrations?
I know what django migrations are. I want to know what happens when we run python manage.py migrate. Which tables are changed by django migrations? Why is it necessary to change those tables? When i write from myapp.models import some_model, how does django know which database table maps to which model? Did migrate add any entry for it in db? -
Why event loop not shared in thread?
I wrote a class as below. The purpose of this class is to make async call as simple as multiprocessing. class AsyncPool(object): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) def __init__(self, pool_size=1000): self.task_list = list() self.running_task = list() self.pool_size = pool_size self.current_pool_size = 0 def add_task(self, func, *args, **kwargs): self.task_list.append({ 'call': func, 'kwargs': kwargs, 'args': args }) def run(self): for item in self.task_list: if self.current_pool_size < self.pool_size: self.current_pool_size += 1 func = item.get('call') args = item.get('args') kwargs = item.get('kwargs') self.running_task.append( asyncio.ensure_future( func(*args, **kwargs) ) ) else: self.loop.run_until_complete(asyncio.wait(self.running_task)) self.current_pool_size = 0 The example usage will be like below pool = AsyncPool(pool_size=10) for num in range(1, 101): pool.add_task(hello_world, num) pool.run() The hello_world here can be any func defined by async. For example: async def hello(id, *args, **kwargs): await asyncio.sleep(5) This run well in script. But when I call it in django view. It report error as below: RuntimeError: There is no current event loop in thread 'Thread-13'. My guess is that django implement each request in seperate thread. Alough I intialize the loop attribute in the class and make it a class attribute. But the loop object can not be shared between thread. But I do not know if it is right. So could you … -
Signals do not seem to work, honestly tried a lot
creating a user model auth for website, used signals to auto create but seems to not get triggered, confused user is created, but not profile can someone help me this time models.py class InterestChoice(models.Model): INTEREST_CHOICES = ( ('A', 'traveling'), ('B', 'exercise'), ) interest = models.CharField(max_length=1, choices=INTEREST_CHOICES, unique=True) def __str__(self): return self.get_interest_display() class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=50) dob = models.DateField() image = models.ImageField(default='default.jpg', upload_to='profile_pics') GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) gender = models.CharField(max_length=1, choices=GENDER_CHOICES, null=True) interests = models.ManyToManyField(InterestChoice) def __str__(self): return f"{self.user.username} Profile" def save(self): super().save() signals.py from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user = instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() here's the apps.py code apps.py from django.apps import AppConfig class UsersConfig(AppConfig): name = 'users' def ready(self): import users.signals