Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django migrations string references must be of the form appname.labelname
When I am running migrations for like this, PS D:\pythonworkspace\WebLite> python manage.py makemigrations masterit I get this following error, PS D:\pythonworkspace\WebLite> python manage.py makemigrations masterit Traceback (most recent call last): File "C:\Users\defuser\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\utils.py", line 11, in make_model_tuple app_label, model_name = model.split(".") ValueError: too many values to unpack (expected 2) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\defuser\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\defuser\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\defuser\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\defuser\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 353, in execute output = self.handle(*args, **options) File "C:\Users\defuser\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\defuser\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\commands\makemigrations.py", line 170, in handle migration_name=self.migration_name, File "C:\Users\defuser\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\migrations\autodetector.py", line 44, in changes changes = self._detect_changes(convert_apps, graph) File "C:\Users\defuser\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\migrations\autodetector.py", line 128, in _detect_changes self.old_apps = self.from_state.concrete_apps File "C:\Users\defuser\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\migrations\state.py", line 214, in concrete_apps self.apps = StateApps(self.real_apps, self.models, ignore_swappable=True) File "C:\Users\defuser\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\migrations\state.py", line 271, in __init__ self.render_multiple(list(models.values()) + self.real_models) File "C:\Users\defuser\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\migrations\state.py", line 306, in render_multiple model.render(self) File "C:\Users\defuser\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\migrations\state.py", line 574, in render return type(self.name, bases, body) File "C:\Users\defuser\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\base.py", line 139, in __new__ new_class.add_to_class(obj_name, obj) File "C:\Users\defuser\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\base.py", line 305, in add_to_class value.contribute_to_class(cls, name) File "C:\Users\defuser\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\fields\related.py", line 735, in contribute_to_class super().contribute_to_class(cls, name, private_only=private_only, **kwargs) … -
Pandas 'Styler' object has no attribute 'pivot_table' pandas
I am trying to implement some styling to an existing dataframe but keep getting an error. I tried following the pandas documentation which seemed pretty straightforward but can't seem to find an answer to this issue: https://pandas.pydata.org/pandas-docs/stable/user_guide/style.html I'm trying to see if the df.style is even working for my table before moving on to my pivot table but it isn't displaying any changes in my template. DataFrame: DATE FINAL_SCORE FN G L MODEL_SCORE R RV SN TC TICKER_id id 0 2019-05-20 1.5 1.5 0.0 0.0 1.5 0.0 1.5 1.5 1.0 EWA 1450 1 2019-05-21 1.5 1.5 0.0 0.0 1.5 0.0 1.5 1.0 1.0 EWA 1451 2 2019-05-22 1.5 1.5 0.0 0.0 1.5 0.0 1.5 1.0 1.0 EWA 1452 3 2019-05-23 1.5 1.5 0.0 0.0 1.5 0.0 1.5 1.0 1.0 EWA 1453 4 2019-05-24 1.5 1.5 0.0 0.0 1.5 0.0 1.5 1.0 1.0 EWA 1454 Here is a portion of my views.py index() and color_negative_red(): def color_negative_red(val): color = 'red' if (-2.0 <= val >= 2.0) else 'black' return 'color: %s' % color def index(request): scores = overall_scores.objects.filter(TICKER__in = countries, DATE = last_date).values() lag_scores_df = pd.DataFrame([x for x in overall_scores.objects.filter(TICKER__in = countries, DATE__gte = lag_date).values()]) lag_scores_df = lag_scores_df.pivot_table(index = 'DATE', columns … -
django login redirects to "/undefined"
Using django, I have a simple login form : login.html : <form id="" method="post" action="{% url 'login' %}" class="form" role="form"> {% csrf_token %} {% bootstrap_form form %} <div class="pull-right"> <button class="btn btn-default pull-right" type="submit"></button> </div> </form> urls.py : urlpatterns = [ path('', MainView.as_view(), name='main'), path('admin/', admin.site.urls), path('accounts/', include('django.contrib.auth.urls')), ] And in settings.py, the following parameter : LOGIN_REDIRECT_URL = 'main' When I log in as a user, I get redirected multiple time and end up at a '/undefined' url : [19/Jul/2019 13:09:53] "GET /accounts/login/ HTTP/1.1" 200 956 [19/Jul/2019 13:09:54] "POST /accounts/login/ HTTP/1.1" 302 0 [19/Jul/2019 13:09:54] "GET / HTTP/1.1" 200 2496 Not Found: /undefined [19/Jul/2019 13:09:54] "GET /undefined HTTP/1.1" 404 2189 What could cause the last redirection ? '/' should be the ending url. -
Django-admin , going to external site with my variables on URL
I have a model and i want to go to a external website with my variables in the url. For example: "www.example.com\ {% object.field %}.com My model class Intervencao(models.Model): freguesia = models.ForeignKey(Freguesia, on_delete=models.CASCADE,verbose_name="Freguesia") rua = models.ForeignKey(Rua, on_delete=models.CASCADE,verbose_name="Rua") I'm changing my change_form_object_tools.html and add a extra li to do something like this: <li> <a href="">Example</a> </li> Now i dont know what to write on my href to go to my external website. -
Add custom tags to sentry event dynamically
I want to add a dynamic tag to all sentry events being logged. Django 1.11 sentry_sdk 0.9.5 python 3.5 def init_sentry_integration(sentry_dsn, app_env, release=None): import sentry_sdk from sentry_sdk.integrations.django import DjangoIntegration sentry_sdk.init( environment=app_env, dsn=sentry_dsn, integrations=[DjangoIntegration()], attach_stacktrace=True, release=release) add_tenant_tag() def add_tenant_tag(): hub = Hub.current logging_integration = hub.get_integration(LoggingIntegration) if not logging_integration: return handler = logging_integration._handler old_emit = handler.emit def new_emit(record): with push_scope() as scope: tenant_schema_name = connection.get_tenant().schema_name scope.set_tag("tenant", tenant_schema_name) return old_emit(record) handler.emit = new_emit Tried monkey patching it but it di -
(Django REST) Override Non-Editable Field in the `create` Method
In my models.py, I create a field that is supposed to be non-editable by the user: request_status = models.CharField( max_length = 100, default = 'received', editable = False ) In the views.py file, I override the create() method (from the generics.ListCreateAPIView and CreateModelMixin superclasses) to activate a docker container and, if it is successfully done, I want to modify the request_status field to something like container_activated and then send back the HTTP response to the user. So... is there a way of modifying a non-editable field? Is there a better way of setting up the model instead? My best guess is that there is a way of modifying the data that gets registered in the API DB through one of the lines of the standard create() method (non-editable fields do not appear in the data property): serializer = self.get_serializer(data = request.data) serializer.is_valid(raise_exception = True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) -
Please why is there a circular import error
I am working on a django project, but it returns the included urlconf "myapp.urls"does not appear to have any patterns in it. I tried checking my views to ensure I imported everything correctly from django.contrib import admin from django.urls import path from .views import home from accounts.views import login_view urlpatterns = [ path('admin/', admin.site.urls), path('',home), path('accounts/login/', login_view), ] I expect the site to run and redirect me to the login page This is my views in the same directory with the urls.py @login_required def home(request): return render(request,"home.html") -
Django contact form modal ? can i pass a form as extra context?
I have a contact form with bootstrap modal.The problem is the form is out of shape and isn't rendered right.so how can i render it right and fix the modal? here's the form class ContactForm(forms.Form): subject = forms.CharField(max_length=720,label="Subject",required=True) message = forms.CharField(widget=forms.Textarea( attrs={'placeholder': 'Enter your message here'}),label="Message",required=True) the views def emailView(request): user = request.user if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = user.email message = form.cleaned_data['message'] try: send_mail(subject, message, from_email, ['admin@example.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('success') return render(request, "email.html", {'form': form}) def successView(request): return HttpResponse('Success! Thank you for your message.') The Template <div class="modal fade" id="modalContactForm" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <form method="POST" action="{% url 'contact' %}"> {% csrf_token %} so how can i render the form right ?can i pass the form as extra context as the form is shown as a modal in the homepage ? <div class="modal-header text-center"> <h4 class="modal-title w-100 font-weight-bold">Write to us</h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="md-form mb-5"> <i class="fas fa-tag prefix grey-text"></i> <label data-error="wrong" data-success="right" for="form32">Subject</label> <input type="text" id="form32" class="form-control validate"> </div> <div class="md-form"> <i class="fas fa-pencil prefix grey-text"></i> <label data-error="wrong" data-success="right" for="form8">Your message</label> <textarea type="text" id="form8" … -
What are the differences between http and socket inside of ini file in uWSGI?
I'm learning nginx and uwsgi to deploy my Django web app. While learning them, I got confused with "socket" and "http". I think I should write .ini like the following. when I use only uwsgi ... http=127.0.0.1:8001 ... when I use uwsgi and nginx and I want to make clients connect to my server through nginx ... socket=127.0.0.1:8001 ... When I only use uwsgi to run my server, I guess I should use "http" instead of "socket" in .ini file http=127.0.0.1:8001 because if i use "socket" it emits errors when clients connect to my server, like this. invalid request block size: 21573 (max 4096)...skip However, when I use nginx with uwsgi, I should use socket instead of http. If I use http, I guess the server emitted timeout error. My codes this is my codes that works in /etc/nginx/sites-available/blog.conf upstream blog{ server 127.0.0.1:8001; } server { listen 80; server_name 127.0.0.1; charset utf-8; client_max_body_size 75M; # adjust to taste location /static { alias /django_static/djProject; } location / { include /etc/nginx/uwsgi_params; uwsgi_pass blog; } } in project directory, app.ini [uwsgi] plugins=python3 chdir={myProject location} module=djProject.wsgi:application # Settings module, relative to the chdir path env='DJANGO_SETTINGS_MODULE=djProject.settings' # Python virtual env path home=/home/su/uwsgi/uwsgi-tutorial # File used … -
i am getting error while integrating angular js code into the django application error:csrf missing
enter image description here above error, I am getting -
Change data visibility and permission on Geonode
I am working on Geonode and when I add a new layer, people who are not logged in are not suppose to see the layers but I would like to change it and allow it to everyone. I saw on an old forum that it was possible by changing the SKIP_PERMS_FILTER in a file and the read_list too, but I am not use to django and I don't know what to change. SKIP_PERMS_FILTER = strtobool(os.getenv('SKIP_PERMS_FILTER', 'False')) def read_list(self, object_list, bundle): permitted_ids = get_objects_for_user( bundle.request.user, 'base.view_resourcebase').values('id') return object_list.filter(id__in=permitted_ids) -
Serializers not displaying foreign key data
My serializers are not showing related Models. I mean the models that have got many-to-one relationship. Please see the code below. Forgive my English. Completely confusing me please help. I am new to django. I am trying to save my Draft js ContentState to the database. I have made the Post model a Foreignkey to my Block models. But When I try to retrieve the data using django-rest-framework serializers the blocks are not displaying. Same applies with the Blocks I tried to serialize them on their own but the inlineStyleRanges and entityRanges data is not coming up. #models.py class Post(models.Model): created_by= models.ForeignKey(User, on_delete=models.CASCADE) cat= models.ForeignKey(Category, on_delete=models.CASCADE) class Block(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) key = models.CharField(max_length=255) text = models.TextField() type = models.CharField(max_length=90) depth = models.IntegerField(default=0) class InlineStyleRange(models.Model): block = models.ForeignKey(Block, on_delete=models.CASCADE) offset = models.IntegerField() length = models.IntegerField() style = models.CharField(max_length=90) class EntityRange(models.Model): block = models.ForeignKey(Block, on_delete=models.CASCADE) offset = models.IntegerField() length = models.IntegerField() key = models.IntegerField() class Data(models.Model): data = models.TextField() class EntityRangeData(Data): enityrange = models.ForeignKey(EntityRange, on_delete=models.CASCADE) #Entity map here we go class EntityEntry(models.Model): key = models.IntegerField() block= models.ForeignKey(Block, on_delete=models.CASCADE) type = models.CharField(max_length=90) mutability = models.CharField(max_length=90) class EntityEntryData(Data): entityentry = models.ForeignKey(EntityEntry, on_delete=models.CASCADE) ```#Serializers.py``` class EntityEntryDataSerializer(serializers.ModelSerializer): class Meta: model = models.EntityEntryData fields = … -
Trying to create an efficient way to produce a cross join with combined results
Let's assume we have these models: class ClassRoom(models.Model): name = models.CharField(max_length=255) class Student(models.Model): name = models.CharField(max_length=255) classroom = models.ForeignKey(ClassRoom...... class Course(models.Model): name = models.CharField(max_length=255) class Grades(models.Model): student = models.ForeignKey(Student.... course = models.ForeignKey(Course.... grade = models.CharField(..... I want to create the crossjoin of the courses and students, but with the grades in the table. | | Student A | Student B | | Course 1 | 8 | | | Course 2 | 6 | 4 | Please note that student B did not receive a grade for course 1 yet! I currently solve this like this query = list(product(courses, students) grades = Grades.objects.all..... for i, query_tuple in enumerate(query): grade = grades.filter(query_tuple[0], query_tuple[1] if grade: # Note 1 # Here I add it to a list of the grades But at the point of '# Note 1' it runs an query each time, which drastically decreases performance (A class can have up to 30 students with each more that 50 courses). Is there a better way to do this? Maybe more in Django-ORM style? -
django security: can an indirect view be called by a non-admin?
Say I have the following methods @staff_member_required def foo(request): return say_hello(request) def says_hello(request): #do secret stuff return "hello And in urls.py path("/hello", foo) As you can see, I have only exposed foo to my admins. From a security standpoint, is it ever possible for a non-admin to call say_hello()? -
How to edit image dimensions before saving to model (database) using ImageField.update_dimension_fields() in Django
I am trying to implement a Django ImageField class function for resizing images however I am not certain where this function accepts my new image dimensions Running on Linux and Python 3.7 I've had a look at this documentation, but can't quite make sense of it: https://docs.djangoproject.com/en/1.11/_modules/django/db/models/fields/files/#ImageField I'd really appreciate it if someone can show me an example of how to use this function. class Posts(models.Model): title = models.CharField(max_length=200, blank=True) body = models.TextField(blank=True) created_at = models.DateTimeField(default=datetime.datetime.now) post_image = models.ImageField(upload_to=get_image_path, blank=True, null=True) def __str__(self): return self.title def save(self, *args, **kwargs): # I would like to use the function beneath to resize my images before I save them to my database self.post_image.update_dimension_fields(self, instance, force=False, *args, **kwargs) super().save(*args, **kwargs) # Call the "real" save() method. class Meta: verbose_name_plural = "Posts" -
Django test if json and if content is present
I have to test if a url returns json, which I can do with self.assertJSONEqual( str(response.content, encoding='utf8'), [{"id": self.group.pk, "text": "Guest", "state": {"opened": True}, "li_attr": {"id": self.group.pk}, "a_attr": {"href": "#"}, "parent": "#"}] ) If the response is huge I have to paste the whole response in the second parameter. Is there a way to test if the response is json, no matter of the content? -
How to you negate a q object within a query?
I want to negate a Q object if a specific condition is met without having to duplicate multiple queries in a view. I have tried breaking the query into multiple functions but I cannot help but think I still have a large amount of duplicated code. query = User.objects.all() if active: query.filter(Q(active=active)) elif active == False: query.filter(Q(active=active) | Q(active__isnull=True)) else: query.filter(Q(active__isnull=True) | Q(setup=False)) -
Make user required to complete profile info first before checking out
I'm very new to Django and trying to create my first e-commerce website. I have a "User" app which the user could go there and enter their name, and address. The problem i'm facing is that I want the user to complete the profile first before they could checkout from the shopping cart. If the user didn't create the profile yet, i want to redirect them to that url. I have a very little knowledge on authentication, so please someone help giving me some clue -
How to join two tables in Django ORM without any column in first table referencing the second
Check the models below Now I want to join the tables and get product name and price I cannot join the tables as I have no column in Product model referencing Price model class Product(models.Model): name = models.CharField(max_length=100) class Price(models.Model): price = models.ForeignKey(Product) -
I need to know the technology used in building a page like this
I want to know the technology used in building a web page like this , a Cisco webpage. webpage link django developers input also required for backend . -
Django ModuleNotFoundError: frozen importlib._bootstrap>", line 953
python3 manage.py makemigrations Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/lib/python3/dist-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/usr/lib/python3/dist-packages/django/core/management/__init__.py", line 308, in execute settings.INSTALLED_APPS File "/usr/lib/python3/dist-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/usr/lib/python3/dist-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/usr/lib/python3/dist-packages/django/conf/__init__.py", line 110, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django_project' import os import netifaces def ip_addresses(): ip_list = [] for interface in netifaces.interfaces(): addrs = netifaces.ifaddresses(interface) for x in (netifaces.AF_INET, netifaces.AF_INET6): if x in addrs: ip_list.append(addrs[x][0]['addr']) return ip_list BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = '...' DEBUG = False ALLOWED_HOSTS = ['...'] INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', 'accounts', 'hashtags', 'tweets', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) ROOT_URLCONF = 'django_project.urls' LOGIN_URL ="/login" LOGIN_REDIRECT_URL ="/" LOGOUT_REDIRECT_URL ="/" TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': … -
django how to get model field as object
Is it possible to get model's field as object For example: I have this model class User(models.Model): name = models.CharField(max_length=255) email = models.TextField(blank=True) phone = models.TextField(blank=True) now I want to use the field as object I want to be able to do this def update_a_field(field): model_field = field query_set = User.objects.values(field.__name__).filter(field__isnull=False) then I can call my function like this update_a_field(name) update_a_field(email) -
When add cors in settings, the server stops working. Error 502 Bad Gateway
I add in project settings INSTALLED_APPS = [ ..., 'corsheaders', ..., ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', ] + MIDDLEWARE CORS_ORIGIN_WHITELIST = [ 'http://url.ru', 'https://url2.ru', 'https://url3.ru', ] After adding - any server url stops working. with the error 502 Bad Gateway nginx/logs/error.logs [error] 1986#1986: *9504 connect() failed (111: Connection refused) while connecting to upstream, client: **.***.***.**, # IP server: server-url, request: "GET /favicon.ico HTTP/1.1", upstream: "http://127.0.0.1:9000/favicon.ico", host: "server-url", referrer: "server-url/api/title/20/" -
cannot import name patterns with Django1.6
Python v2; Django v1.6 when i start server, i get a error 'ImportError: cannot import name patterns' Code: from django.conf.urls import patterns, include, url urlpatterns = patterns( '', url(r'^payment/', include('payment.urls', namespace='payment', app_name='payment')), ) Next: i has tried to change import code like this: from django.conf.urls import * but get another error: 'NameError: name 'patterns' is not defined' pls help -
Django ORM: checking if a field is blank or filled
title = models.ForeignKey(blank=True, null=True) I am trying to check if title filed is filled or blank, how can i achieve this?