Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'NoneType' object has no attribute '_meta' while changing models
I am attempting to restructure my database models to include more data than django.contrib.auth.models.User. However, making the changes to models.py and views.py, then running python manage.py makemigrations doesn't properly update my migrations. Apparently, Django still thinks I'm using a proxy model. I had to change users/migrations/0001_initial.py to avoid a dependency error, then I ran python manage.py makemigrations and got No changes detected. users/migrations/0001_initial.py (before changes) # Generated by Django 2.2 on 2019-05-01 03:13 from django.db import migrations import users.managers class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0011_update_proxy_permissions'), ] operations = [ migrations.CreateModel( name='Person', fields=[ ], options={ 'proxy': True, 'constraints': [], 'indexes': [], }, bases=('auth.user',), managers=[ ('objects', users.managers.PersonManager()), ], ), ] users/migrations/0001_initial.py (after changes) # Generated by Django 2.2 on 2019-05-01 03:13 from django.db import migrations import users.managers class Migration(migrations.Migration): initial = True dependencies = [] operations = [] users/models.py (before changes) from django.db import models from django.contrib.auth.models import User from . import managers class Person(User): objects = managers.PersonManager() class Meta: proxy = True users/models.py (after changes) from django.db import models from django.contrib.auth.models import User from users import managers class Profile: user = models.OneToOneField(User, on_delete=models.CASCADE) phone = models.CharField(max_length=30) objects = managers.ProfileManager() users/views.py from django.shortcuts import render, redirect from django.contrib.auth.models … -
django template dynamic table field row data
I want dynamic table list but not working my table html code enter image description here my views.py code enter image description here Help me plese -
error h10 on Heroku installed gunicorn and made Procfile
i'm trying to Doplay a Django app ,even though ive installed gunicorn and made the Procfile it gives me the h10 error 2019-06-07T01:27:16.248676+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=carlosdelgado1.herokuapp.com request_id=24075044-c299-464c-84be-01bf46733bee fwd="24.55.161.5" dyno= connect= service= status=503 bytes= protocol=https -
How can I do a kind of distinct using Djang
I have this array which contains some dictionnaries : a = [{'name': 'Peter', 'email': '', 'color': 'red'}, {'name': 'Peter', 'email': '', 'color': 'red'}, {'name': 'Peter', 'email': '', 'color': 'red'}] But I tried to do this : list(set(a)) and it does not work unfortunately I get this : TypeError: unhashable type: 'dict'. Do you know how can I solve this I mean I would like to have : a = [{'name': 'Peter', 'email': '', 'color': 'red'}] Thank you ! -
How can I align the text and the image like this?
I am very new to python/css/html programing, so please forgive me for asking such a basic question! I am trying to align my text and my image like the one Dev Ed has in this tutorial (with the image on the right and the text on the left): https://www.youtube.com/watch?v=C_JKlr4WKKs&t=624s But, I have not been able to get it to look like that. I have tried display: grid and its functions (not quite sure if I was doing it correctly), flex, and float. Here is my about.html's relevant section: <div class="intro-content"> <span class="intro-text"> <h2>Jinyang Zhang</h2> <p>Hello and nice to meet you! My name is Jinyang Zhang <br> and currently I am a Kamiak High School student. <br> I am interested in software development and AI </p> </span> <img class="image-resize" src="{% static 'img/me.jpg' %}"> </div> Here is my styles.css's relevant section: /*image next to text*/ .image-resize{ width: 50vh; float: right; padding: 150px 100px 0px 0px; margin-right: 200px; } /*introduction text that appears*/ .intro-text{ width: 30%; padding: 100px 0px 0px 40px; /*top right bottom left*/ transition: 1s all ease-in-out; opacity: 0; transform: translateY(20px); float: left; } /*animation for it to text to appear like the tutorial*/ .intro-appear{ opacity: 1; transform: translateY(0px); } I … -
How to filter/reduce a QuerySet to every nth row?
I am storing time-series data from a number of sensors in a MySQL db. Each sensor is associated with a device, and each device can have multiple sensors. The sensors poll every 10 seconds, so for long periods (day/week/month/year), fetching the unnecessarily large dataset becomes problematic. I would like to resample the QuerySet prior to evaluation so that it only fetches every nth row. Is this possible? If not, is there a smarter approach I can take? I suppose I could figure out a where clause that matches 1/n of the possible values for the timestamp's microseconds? device_name = request.GET['device'] device = Datalogger.objects.get(device_name=device_name) sensors = Sensor.objects.filter(datalogger=device).order_by('pk').select_related('type') sensor_models = sensors.values_list('type', flat=True) # get all models of sensor used by this controller sensor_datum_types = list(SensorModelDatumType.objects.filter(sensor__in=sensor_models).order_by('sensor', 'datum_type')) # get all datatypes relating to all models of sensor used # assign each trace (sensor/datum_type combination) an indice for the tuples (zero is used for time/x-axis) bulk_queryset = SensorDatum.objects.filter(sensor__datalogger__device_name=device_name, timestamp__gte=get_filter_start_time(request), timestamp__lte=get_filter_end_time(request)) chart_traces = [] chart_trace_indices = {} chart_trace_data = [None] chart_trace_queryset = SensorDatum.objects.none() next_free_idx = 1 for sensor in sensors: for datum_type in sensor_datum_types: if datum_type.sensor == sensor.type: chart_trace_name = get_chart_trace_name(sensor.sensor_name, datum_type.datum_type.description) chart_traces.append({'sensor': sensor.sensor_name, 'datum_type': datum_type.datum_type.description, 'chart_trace_name': chart_trace_name}) chart_trace_indices.update({chart_trace_name: next_free_idx}) chart_trace_queryset = chart_trace_queryset | bulk_queryset.filter(sensor_id=sensor.id, … -
How to expose Odoo container to LAN
I am currently trying to run a docker Odoo container and expose it to my local network so my team can start testing it out, but I can't access the container from another computer on the same network. How can I host odoo on a windows docker machine that will let my co-workers access and work with Odoo? -
Django CreateView update or create then redirect
Can anyone tell me how to use update_or_create with generic CreateView? and can I make such like return redirect(product:update) with it? -
UpdateAPIView in Django not updating Image Field
In a Django Project I have simple UpdateAPIView class ProfileUpdateAPIView(UpdateAPIView): serializer_class = ProfileUpdateSerializer authentication_classes = ( CsrfExemptSessionAuthentication, BasicAuthentication, TokenAuthentication,) permission_classes = ((IsAuthenticated,)) and a simple model def image_upload_fun(instance, filename): return 'profile_pics/user_{0}.{1}'.format(str(instance.phone_number),filename.split(".")[1]) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,null=True, blank=True) profile_pic = models.ImageField(upload_to=image_upload_fun, null=True, blank=True) phone_number = models.CharField(max_length=12, unique=True, null=False, blank=False) It does neither create new file nor it updates profile_pic_field.Although through admin panel it(image) gets updated or created easily -
Django annotate with standard deviation
I´m trying to annotate a queryset by the Standard deviation. I found this post How to perform STD And read this documentation about querysets I tried this: from django.db.models import StdDev ventas_producto = ventas.values("prod_codigo").annotate(uds_std=StdDev("uds")) But I get the following error: Exception Type: OperationalError Exception Value: no such function: STDDEV_POP Any clues? Thanks! -
Improving performance of counts in a subquery with millions of rows using Prefetch
I have an application that monitors events from websites and part of the user interface shows counts of events per website for a given period of time. Here are what the models look like: class Website(models.Model): name = models.CharField(max_length=64) url = models.TextField() class Event(models.Model): website = models.ForeignKey(Website, related_name="events") created_at = models.DateTimeField(default=timezone.now) ip_address = models.CharField(max_length=64) status = models.CharField(max_length=16) message = models.CharField(max_length=128) These websites generate thousands of events per day, so the Event table is quite large compared to the other tables. Here is what the query looks like that I'm trying to generate: eargs = { "website": OuterRef("pk"), "created_at__gte": some_start_time, "created_at__lt": some_end_time } events = Event.objects.filter(**eargs).values("website") events_count = events.annotate(c=Count("*").values("c")[:1] websites = Website.objects.annotate(events=Coalesce(Subquery(events_count, output_field=IntegerField()), 0) Like I mentioned before, the Events table has millions of rows in it. For a small number of websites, this query doesn't take too long. But when there are 100 or more website, it takes quite a long time. I've done some profiling and the database (internally) is querying for the count for every website. So if I have 100 websites, the database is making 100 queries to generate the counts (there is still one query coming from Django, but Postgres, internally, is making those 100s of … -
ImportError: cannot import name 'authenticate'
When I code from rest_framework.compat import authenticate the pycharm remains me there is an error: File "/Users/yindeyong/PycharmProjects/newsapi/article/serilaizes.py", line 16, in <module> from rest_framework.compat import authenticate ImportError: cannot import name 'authenticate' Django 2.0.4 djangorestframework 3.9.4 Any friend know how to solve this issue? -
Make a thread on Django - Stay in the 'try' action and never complete the 'except' action
I have done a small thread (try - except) on python which is working on a .py file but when I aded it on my Django view.py and using from my front end, the behavior is weird.. It is staying in the 'try' and never test the except action. try: print("############# I am in csv ###################") df = pd.read_csv(...) except Exception as e: print(e) print("############# I am in JSON ###################") df = pd.read_json(...) Actual result is sending me a ValueError: ############# I am in csv ################### arrays must all be same length ############# I am in JSON ################### and it keeps trying on the df = pd.read_csv(...) which send me an error when i'm uploading a json.. Expected result (which I get on a python file) would be: ############# I am in csv ################### arrays must all be same length ############# I am in JSON ################### and df is equal to the data I sent If any of you have encountered the same issue, please, let me know !! I'm stuck on this for too much time now. Thanks you all -
How to create a simple diary/journaling website with Django?
I may have bit off more than I can chew. I am looking for a tutorial or some guidance on creating a journaling/diary website using Django. I am trying to create a website where the user logs in, has some simple dashboard, and the ability to submit journal entries that would be saved into a database for later analysis. I was wondering if anyone could provide guidance on where to start or literature to begin looking at to make this project successful. I have tried multiple methods from: modifying different repos, modifying tutorials, and starting from scratch. Currently I am using the Firefox/Mozilla django tutorial that I am modifying as I go. -
Associate a file with the FileField without creating a copy of the file?
I have the test.csv file sitting in MEDIA_ROOT/file folder. I want to associate this file with FileField of the following model: class Sample(models.Model): data = models.FileField() But if I do the following: from django.shortcuts import render from django.http import JsonResponse from django.conf import settings from django.core.files import File import os from .models import Sample # Create your views here. def index(request): path = os.path.join(settings.MEDIA_ROOT, os.path.join('file', 'test.csv')) with File(open(path)) as f_obj: sample = Sample() filename = os.path.basename(f_obj.name) sample.data.save(filename, f_obj, save=True) return JsonResponse({ 'file_url': sample.data.url, 'file_path': sample.data.path, 'action': 'Model instance saved to database', }) a copy of the file will be created in the MEDIA_ROOT directory and this copy - and not the original - will be associated with the model. Is there a way to not create such copy and just associate the original file with FileField? -
What's the correct way to get another Model's info in Django serializer?
Say I have a serializer A class SerializerA(ModelSerializer): some_field = CharField() some_other_field = CharField() field_require_other_model = SerializerMethodField() class Meta: model = ModelA fields = ('some_field', 'some_other_field', 'field_require_other_model') def get_field_require_other_model(self, instance): other_model_qs = ModelB.objects.filter(email=instance.email) # say I want to get whatever that comes first return other_model_qs.first().useful_info As seen above, SerializerA uses ModelA for getting all the fields except that one in ModelB. I can get the info from ModelB doing what I did, but I don't know if this is the best way getting the data. I'm not sure if I need to hit database so many times or if there's a way to lazily evaluate it. Also, what if I have another SerializerMethodField() that utilizes ModelB but for different info. Is this way still the best way to get the data? -
How to fix "TypeError: argument of type 'ConnectionHandler' is not iterable" when running a django test?
When I do ```python -m unittest`` inside of my users app, I get this error: TypeError: argument of type 'ConnectionHandler' is not iterable I was customizing my User model in django and I wanted to make a test for it. I already did the migrations and the custom User model works good, so I expected to run the test successfully. Here is my test code: from django.test import TestCase from django.contrib.auth import get_user_model # Create your tests here. class UsersManagersTests(TestCase): def test_create_user(self): User = get_user_model() user = User.objects.create_user(email='normal@user.com', password='foo') self.assertEqual(user.email, 'normal@user.com') self.assertTrue(user.is_active) self.assertFalse(user.is_staff) self.assertFalse(user.is_superuser) try: # username is None for the AbstractUser option # username does not exist for the AbstractBaseUser option self.assertIsNone(user.username) except AttributeError: pass with self.assertRaises(TypeError): User.objects.create_user() with self.assertRaises(TypeError): User.objects.create_user(email='') with self.assertRaises(ValueError): User.objects.create_user(email='', password="foo") def test_create_superuser(self): User = get_user_model() admin_user = User.objects.create_superuser('super@user.com', 'foo') self.assertEqual(admin_user.email, 'super@user.com') self.assertTrue(admin_user.is_active) self.assertTrue(admin_user.is_staff) self.assertTrue(admin_user.is_superuser) try: # username is None for the AbstractUser option # username does not exist for the AbstractBaseUser option self.assertIsNone(admin_user.username) except AttributeError: pass with self.assertRaises(ValueError): User.objects.create_superuser( email='super@user.com', password='foo', is_superuser=False) Why does the test fail? -
How to display the result in Django API
I just started working on python based Django. I am following this example to create an API. https://dzone.com/articles/create-a-simple-api-using-django-rest-framework-in Instead of using POSTMAN I am using my web browser to display the result bu I am getting error. Method 'GET' not allowed. I looked into different answers and concluded that I need to add a 'GET' method I tried changing @api_view(["POST"]) from 'POST' to 'GET' but then it throw an error "Expecting value: line 1 column 1 (char 0)". How can I add a GET here in this view. @api_view(["POST"]) def IdealWeight(heightdata): try: height=json.loads(heightdata.body) weight=str(height*10) return JsonResponse("Ideal weight should be:"+weight+" kg",safe=False) except ValueError as e: return Response(e.args[0],status.HTTP_400_BAD_REQUEST) Thanks -
django setting filter field with a variable
I show a model of sales that can be aggregated by different fields through a form. Products, clients, categories, etc. view_by_choice = filter_opts.cleaned_data["view_by_choice"] sales = sales.values(view_by_choice).annotate(........).order_by(......) In the same form I have a string input where the user can filter the results. By "product code" for example. input_code = filter_opts.cleaned_data["filter_code"] sales = sales.filter(prod_code__icontains=input_code) What I want to do is filter the queryset "sales" by the input_code, defining the field dynamically from the view_by_choice variable. Something like: sales = sales.filter(VARIABLE__icontains=input_code) Is it possible to do this? Thanks in advance. -
Can I open up a simple file browser in a django admin action?
I'm a little new to customizing the django admin and maybe what I want is a little advanced but I was wondering if I can launch a file browser in my custom action. Just something simple that will return a list of files. -
How do I embed a live celery beat worker using pytest?
I am using pytest-django and have been able to embed a live worker for one-off tasks using the code below in my conftest.py using these instructions, but I am not sure how to enable an additional beat worker for periodic tasks. @pytest.fixture(autouse=True, scope='session') def celery_config(django_db_setup, django_db_blocker,request): with django_db_blocker.unblock(): return { 'broker_url': 'redis://localhost:6379', 'result_backend': 'redis://localhost:6379' } -
How to insert foreign key with NULL/None
I am trying to insert a record into my table that has a FOREIGN_KEY that should be able to be empty/null. Here is the response I get: django.db.utils.IntegrityError: null value in column "parent_id" violates not-null constraint Here is my model: created_on = models.DateTimeField(default=now) serve_date = models.DateField() name = models.CharField(max_length=100) menu_name = models.CharField(max_length=100) parent = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True, default=None) item_type = models.CharField(max_length=1, default='') Here is my attempt to insert data: meal = MenuItem.objects.create(serve_date=daily_meals['date'], name=kitchen_meal.name) I also checked the column in my table. It has Not NULL? = Yes Really not sure what else should be set. -
Django / Bootstrap rendering differently on Chrome/Edge vs Firefox
I'm using Django and Bootstrap to display some user information. The basic set up is that user accounts all have only one Profile and can have any number of "Avatars". I am displaying this information in Bootstrap Cards. When the display is large or xl (using Bootstrap breakpoints), the Profile card is 8 columns wide, there is a 4-column "utility" card (links and useful text). These two cards always exist. Then, for every Avatar the user has created, there is a 4-column card for that Avatar (in XL, 6-col in large). Everything exists in one row in the HTML. Psuedo-Code: <div class="container"> <div class="row"> <div class="col-md-12 col-lg-8"> <div class="card"> [card contents - Profile] </div> </div> <div class="col-sm-12 col-md-6 col-lg-4"> <div class="card"> [card contents - Utility] </div> </div> {% if has_avatars %} {% for avatars in my_avatar_list %} <div class="col-sm-12 col-md-6 col-lg-6 col-xl-4"> [card contents - Avatar] </div> {% endfor %} {% endif %} Chrome and Edge render this just fine. The Profile card is always large; the utility changes size to fit in; the Avatars change based on the screen size. EXCEPT Firefox only places Avatar cards under the large Profile card. There is empty space under the Utility card. … -
Django using correct view
I have a view, that's already using generic.View like this class ADRemoveGroup(LookupLDAPLocalhostRequiredMixin, generic.View): template_name = "mocks/users/add-delete" def get(self, request, person_id, *args, **kwargs): ## i want to render the template, this acts as a confirmation page. def post(self, request, person_id, *args, **kwargs): person_id = int(person_id) group_name = request.POST.get("group_name") LookupData().remove_group_member(group_name, {"person_id": person_id}) if not request.META.get("HTTP_REFERER"): redirect_url = request.META["HTTP_REFERER"] else: redirect_url = reverse_lazy("mocks:users:ad-detail", kwargs={"person_id": person_id}) messages.success(request, "You successfully removed the group [ad] %s." % group_name) return redirect(redirect_url) How would I also incorpotate get request in generic.View? So I can render my template. -
Create Docker container with Django, npm and gulp
I changed my local dev. to Docker. I use the Django framework. For frontend I use the gulp build command to “create” my files. Now I tried a lot, looked into the Cookiecutter and Saleor project but still having issues to install npm in a way that I can call the gulp build command in my Docker container. I already tried to add: RUN curl -sL https://deb.nodesource.com/setup_10.x | bash - RUN apt-get update && apt-get install -y \ nodejs \ COPY ./package.json /app/ RUN npm install While npm is installed, I still can’t run the command gulp build in my Container. It just says gulp is an unknown command. So it seems npm doesn’t install the defined packages in my package.json file. Anyone here who already solved that and can give me some tips? Dockerfile # Pull base image FROM python:3.7 # Define environment variable ENV PYTHONUNBUFFERED 1 RUN apt-get update && apt-get install -y \ # Language dependencies gettext \ # In addition, when you clean up the apt cache by removing /var/lib/apt/lists # it reduces the image size, since the apt cache is not stored in a layer. && rm -rf /var/lib/apt/lists/* # Set the working directory to …