Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I add a url prefix to Django Admin?
I would like to add a prefix to a Django Admin url. For Example: urlpatterns = [ path('bar/admin/', admin.site.urls),] If I add a prefix to an app url it works however I can't get the admin site to load. -
Django json post request parse
My client is passing this json as a post to django server: data={ 'supplier': supplier_name, 'date': date, 'payment':payment, 'materials':[{"name":name,"qtd":qtd,"price":price} {"name":name,"qtd":qtd,"price":price} {"name":name,"qtd":qtd,"price":price}] } My django view handles data like this: supplier=request.POST.get('supplier') date=request.POST.get('date') When I try to do this, the materials content is "none": materials=request.POST.get('materials') How can get a list use in further code? -
Difference between JWT token expiration_delta and JWT Refresh Expiration Delta django jwt
I am using django rest frameworks JWT library http://getblimp.github.io/django-rest-framework-jwt/ There are two settings on JWT token expiration JWT_EXPIRATION_DELTA which is in seconds The docs on it: You can turn off expiration time verification by setting JWT_VERIFY_EXPIRATION to False. Without expiration verification, JWTs will last forever meaning a leaked token could be used by an attacker indefinitely. This is an instance of Python's datetime.timedelta. This will be added to datetime.utcnow() to set the expiration time. Default is datetime.timedelta(seconds=300)(5 minutes). and JWT_REFRESH_EXPIRATION_DELTA Docs: mit on token refresh, is a datetime.timedelta instance. This is how much time after the original token that future tokens can be refreshed from. Default is datetime.timedelta(days=7) (7 days). Im not sure on the different use cases. I set the jwt token expiration delta to 20 seconds. Then got a token saved it to local waited 20 seconds closed my browser window and re navigated to the site expecting to not be logged in because the token would of expired but I was logged in. So then what is the difference between JWT token expiration delta and JWT Refresh Expiration Delta? -
Django, 'cannot import name views' when doing a migration
so I am doing a little project for a class with pythonanywhere.com I am following the instructions given by the teacher, and I entered the following command in the virtualenv console: python .../manage.py makemigrations But I have this error message : 'cannot import name views'. I also had similar error (such as 'cannot import path', etc...), but I was able to fix them searching on this website. Unfortunately, I didn't find any solution that worked for this particular problem. So I'd like help to solve it. And I am also wondering if so many issues while trying to make a migration is normal ? Thank you very much in advance. Here is the full stuff from the virtualenv console. (django2) 16:28 ~ $ python /home/infosgr37a/project/manage.py makemigrations Traceback (most recent call last): File "/home/infosgr37a/project/manage.py", line 15, in execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/init.py", line 367, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/init.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 305, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 353, in execute self.check() File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 385, in check include_deployment_checks=include_deployment_checks, File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 372, in _run_checks return checks.run_checks(**kwargs) File "/usr/local/lib/python2.7/dist-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/usr/local/lib/python2.7/dist-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) File "/usr/local/lib/python2.7/dist-packages/django/core/checks/urls.py", … -
get all user id's Gmail API
My task is to cout all top senders and top recievers of user's email. So the plan is to get all user id's, put them in a dictionary, count their amount and print. I tried this but it doesn't work very well with INBOX label (10 000+ messages): import base64 import email import re import operator from googleapiclient import errors from quickstart import service def find(st): for i in range(0,len(st)): tmp = str(st[i]) for j in range(0,len(tmp)): if tmp[j] == 'T' and tmp[j+1] == 'o' and tmp[j-1] == "'" and tmp[j+2] == "'": return i pass def getTop(n): try: if n == 1: label_ids = "INBOX" else: label_ids = "SENT" user_id = "me" topers = service.users().labels().get(userId = user_id,id = label_ids).execute() count = topers['messagesTotal'] print(count) topers = service.users().messages().list(userId = user_id, labelIds = label_ids).execute() arrId = [] for i in range(0,count): arrId.append(topers['messages'][i]['id']) st = [] for i in range(0,count): message = service.users().messages().get(userId=user_id, id=arrId[i], format = 'metadata').execute() head = message['payload']['headers'] index = find(head) obval = head[index]['value'] tmp = str(obval) tmp =tmp.split('<', 1)[-1] tmp = tmp.replace('>',"") st.append(tmp) cnt = 0 mvalues = {} for mail in st: if not mail in mvalues: mvalues[mail] = 1 else: mvalues[mail]+= 1 sorted_values = sorted(mvalues.items(),key= operator.itemgetter(1)) ln = … -
'NoneType' object has no attribute 'month'
I want to get the month of the next datetime date value, however I get the following error i_real = (actividad.fecha_real_ini.month-1) while i_real <=(actividad.fecha_real_fin.month-1): meses_real[i_real] = True i_real+=1 and I get the following error . 'NoneType' object has no attribute 'month' -
How to create instance of models with circular and null=False relations?
I have models with circular relations and I wanted also have null=False on them. Example below. All this is nice, but how do I create the objects in this case? class Data(models.Model): master = models.ForeignKey('Master', related_name='data', null=False) class Master(model.Model): last = models.OneToOneField('Data', null=False, related_name='+') -
Django & JQuery: Constructing a form - ModelMultipleChoiceField with other dependent fields which filter the queryset (using AJAX)
I've been struggling with this for a while, and just need some direction. I would like to create a form with a ModelMultipleChoiceField (which will be used in a formset_factory, whose choices are dynamically limited (AJAX) by the selection of other fields. This is my model: # models.py class Sound(models.Model): POS_CHOICES = ( ('Consonants', ( ('stop', 'Stop Consonant'), ('fric', 'Fricative'), ('nas', 'Nasal'), ('oth', 'Other'), ) ), ('Vowels', ( ('open', 'Open'), ('clos', 'Closed'), ('mid', 'Middle'), ) ) ) SEX_CHOICES = ( ('M', 'Male'), ('F', 'Female') ) phrase = models.CharField(max_length=300) language = models.CharField(max_length=20) starts_with = models.CharField(max_length=4, choices=POS_CHOICES, default='open') sex = models.CharField(max_length=1, choices=SEX_CHOICES, default='M') My form: # forms.py class SoundTestPairForm(forms.Form): LANGUAGE_CHOICES = [[d['language'], d['language']] for d in Sound.objects.order_by('language').values('language').distinct()] sex = forms.MultipleChoiceField( choices=Sound.SEX_CHOICES, ) starts_with = forms.MultipleChoiceField( choices=Sound.POS_CHOICES ) language = forms.MultipleChoiceField( choices=LANGUAGE_CHOICES ) user_sound = forms.ModelMultipleChoiceField( queryset=Sound.objects.all(), ) My view: # views.py def associate_sounds(request): SoundTestPairFormSet = formset_factory(SoundTestPairForm, extra=0) if request.method == 'POST': formset = SoundTestPairFormSet(request.POST) if formset.is_valid(): return redirect('soundtests:index') else: formset = SoundTestPairFormSet() return render(request, 'soundtests/associate_sounds.html', {'formset': formset}) And, finally, my template: # associate_sounds.html <head> {% load staticfiles %} <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> </head> <body> <script type="text/javascript" src="{{ STATIC_URL }} /static/jquery-3.3.1.min.js"></script> <h1>Create Test - Associate Sounds</h1> For each master sound, please select … -
Create models from json feed in Django
I am making a django app to browse available products at different markets. I am getting data for my models from a JSON url feed, I am not sure on the best approach to turn this data into models as the feed for a single market can contain upwards of 50k items. Models - feel free to suggest any improvements on these # Details of a sellable products class Product(models.Model): item = models.IntegerField(primary_key=True, auto_created=False) name = models.CharField(max_length=40) # Market where products can be bought, some markets will cater to multiple suburbs. class Market(models.Model): id = models.IntegerField(primary_key=True, auto_created=True) name = models.CharField(max_length=40) # Nearby suburbs can share the one market class Suburb(models.Model): name = models.CharField(max_length=30) market = models.ForeignKey(Market, on_delete=models.SET_NULL, null=True) # Actual product for sale class ProductForSale(models.Model): sale = models.IntegerField(primary_key=True) product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) cost = models.IntegerField(default=1) owner = models.CharField(max_length=30) quantity = models.IntegerField(default=1) market = models.ForeignKey(Market,on_delete=models.SET_NULL, null=True ) Feed of markets products example "market_products": [ { "id":11654, "item":123, "owner":"Bob", "suburb":"Springvale", "cost":3, "quantity":1, }, { "id":11655, "item":123, "owner":"Sarah", "suburb":"Sunnyville", "cost":5, "quantity":2, }, This is how I am trying to populate my ProductForSale models - I don't know if this is the correct approach for the Product FK, or how to link the … -
Django: Model class user.models.Users doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
Django version: 2.0 Python: 3.6.5 Error: Model class user.models.Users doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. I have just add model Users to my views. base.py: DJANGO_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites' ] THIRD_PARTY_APPS = [ 'allauth', 'allauth.account', 'allauth.socialaccount', ] LOCAL_APPS = [ 'clockingIn.users.apps.UserConfig', ] INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS views.py: from django.http import HttpResponse from django.contrib.auth.mixins import LoginRequiredMixin from django.views import generic from .models import Users class UsersList(LoginRequiredMixin, generic.ListView): raise_exception = True model = Users def get_queryset(self): return "" class UsersDetail(LoginRequiredMixin, generic.DetailView): raise_exception = True model = Users def get_queryset(self): return "" model.py: class Users(AbstractUser): uuid = models.UUIDField(_('uuid'), primary_key=True, default=uuid.uuid4) first_name = models.CharField(_('first name'), max_length=127, blank=True) last_name = models.CharField(_('first name'), max_length=127, blank=True) email = models.EmailField(_('email'), max_length=127, unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() -
Django Rest Framework - Post Foreign Key
I am new to Django Rest Framework and checked some tutorials. Now I am trying to create my own structure, which is like following. models.py class User(models.Model): name = models.CharField(max_length=32) surname = models.CharField(max_length=32) facebook_id = models.TextField(null=True) is_sms_verified = models.BooleanField(default=False) created = models.DateTimeField(default=timezone.now) updated = models.DateTimeField(default=timezone.now) status = models.BooleanField(default=1) def __str__(self): return self.name+" "+self.surname class Profile(models.Model): user = models.ForeignKey('User',on_delete=models.CASCADE) email = models.CharField(max_length=32) birthday = models.DateField(null=True) bio = models.TextField(null=True) points = models.IntegerField(default=0) created = models.DateTimeField(default=timezone.now) updated = models.DateTimeField(default=timezone.now) def __str__(self): return self.user.name+ " " + self.user.surname serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model=User fields = ('id','name','surname','facebook_id','is_sms_verified',) read_only_fields = ('created','updated') class ProfileSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) class Meta: model=Profile fields=('id','user','email','birthday','gender','bio','points') read_only_fields = ('created','updated') views.py @api_view(['POST']) def profile_create(request): serializer = ProfileSerializer(data=request.data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status = status.HTTP_201_CREATED) return JsonResponse(serializer.errors , status= status.HTTP_400_BAD_REQUEST) data I'm trying to post { "user_id": { "id": 2 }, "email": "xxx@gmail.com", "birthday": "1991-05-28", "bio": "qudur", "points": 31 } The error I get; NOT NULL constraint failed: core_profile.user_id Where am I doing wrong? Thanks! -
How can I create a custom template for a TabularInline admin Formset in Django?
In my Django app (research database), when changing a person object in the admin, I'd like all of the sources for that person to be listed as hyperlinks to the file for that source. I'm trying to do this by creating a custom template for a stacked inline. Here is the custom template so far: <p>Testing</p> {% for form in inline_admin_formset %} {% for fieldset in form %} <h5>Fieldset</h5> {% if fieldset.name %} <h2>{{ fieldset.name }}</h2>{% endif %} {% for line in fieldset %} <h6>Line</h6> {% for field in line %} <h6>Field</h6> {{ field.field }} {% endfor %} {% endfor %} {% endfor %} {% endfor %} A lot of this is just for me to see what's going on. I used the links here and here as sort of a guide. What renders from the {{ field.field }} is what you'd expect from an inline element - a dropdown menu with the source names as choices and some icons for adding/changing. What I really want, however, is just the source name rendered as a hyperlink. How do I get the source name (the actual name of the attribute is source_name) from what I have in the Django template language … -
__init__() missing 1 required positional argument: 'on_delete'
I am getting the error as shown in the question, and I can't figure out why. Even when trying other stackoverflow methods of fixing this it doesn't work. I am using python and django dashboard. I am currently adding facebook authentication to my project and I need to migrate changes to the database and this error popped up from know where. I am pretty sure this is not the problem but i need a temporary fix so i can diagnose the real issue as this part was working fine prior to my changes. from django.db import models from django.contrib.auth.models import User from django.utils import timezone # Create your models here. class Shop(models.Model): """ each shop belongs to one owner/manager and one owner has one shop cascade once user is deleted the shop is also deleted """ user = models.OneToOneField(User, on_delete=models.CASCADE, related_name = 'shop') name = models.CharField(max_length=500) phoneNo = models.CharField(max_length=500) address = models.CharField(max_length=500) pic = models.ImageField(upload_to='shop_pic/', blank=False) def __str__(self): return self.name """ by default the id of the shop object is shown in the database but I need the name given by the user """ class Item(models.Model): shop = models.ForeignKey(Shop) name = models.CharField(max_length=500) short_description = models.CharField(max_length=500) image = models.ImageField(upload_to='item_images/',blank=False) price = … -
The `__init__.py` import multiple modules while they are not utilized within the files
I am reading /django/forms/__init__.py """ Django validation and HTML form handling. """ from django.core.exceptions import ValidationError # NOQA from django.forms.boundfield import * # NOQA from django.forms.fields import * # NOQA from django.forms.forms import * # NOQA from django.forms.formsets import * # NOQA from django.forms.models import * # NOQA from django.forms.widgets import * # NOQA The __init__.py import multiple modules while they are not utilized within the files. I assume they might be employed by others lived in the same dir, How Django achieve this? -
Automatic report posting to Facebook Page
I am sitting on this for over 6h now, it worked some years ago, but now I am always getting: PermissionException: (#200) Requires either publish_actions permission, or manage_pages and publish_pages as an admin with sufficient administrative permission (error code 200) I mean, i don't have the permission combination, I have only manage_pages, but I was able to post with this around two years ago. Also, when I try to add the requested permissions it wants a picture of a example of how I use this permission ... I don't understand what they want to see (code, content?). Anybody knows? My token (page name and app name are the same): Access Token Info App ID xxx : App Name Type Page Page ID xxx : Page Name App-Scoped User ID Learn More xxx : My Acc Name User last installed this app via API N/A Issued Unknown Expires 1525878000 (in 35 minutes) Valid True Origin Web Scopes user_friends, manage_pages, pages_show_list, public_profile And my code: def fetch_app_access_token(): resp = urllib.urlopen( 'https://graph.facebook.com/oauth/access_token?client_id=' + str(APP_ID) + '&client_secret=' + FACEBOOK_APP_SECRET + '&grant_type=client_credentials') if resp.getcode() == 200: return resp.read().split(":")[1].split(",")[0] else: return None def post_to_fb(): app_token = fetch_app_access_token().replace('"','') page_token = "xxx" graph = OpenFacebook(app_token) params = {'message':'helloworld','privacy':{'value':'SELF'}} … -
Dango Rest Framework doesn't work with one to one relationship
I have several view sets working perfectly, but those with a OneToOneField just rise an error. It is weird, because I just copied-pasted and change the model reference several times, and only those that have a one to one field rise the same error: This is the model: class Provider(models.Model): company = models.OneToOneField('Company', on_delete=models.CASCADE, primary_key=True) provider_type = models.ForeignKey('ProviderType', on_delete=models.PROTECT, related_name='type_providers') is_active = models.BooleanField(default=True) This is the serializer: class ProviderSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = models.Provider fields = ('company', 'provider_type', 'is_active') This is the view set: class ProviderViewSet(viewsets.ModelViewSet): queryset = models.Provider.objects.all() serializer_class = serializers.ProviderSerializer I have exactly the same structure for all my model objects, and it works perfectly for all of them, but for those with a one to one field. It works fine even for models with foreign keys (one to many relationship). The error I get is very extensive, but this is the short version: AssertionError at /general/agencies/ The `view_name` argument is required. -
Refactoring path to directory - settings.ROOT_PATH + '/my_files'
How can I refactor this code? Is a better way to set directory path? shutil.rmtree(settings.ROOT_PATH + '/my_files') -
How to redirect to home page when user tries to enter login page after logged in?
I am using django auth for user authentication. I need to redirect to the home page when user tries to enter login page after logged in. For example: If user tries below url after logged in user must be redirected to home. http://localhost:8000/login from django.contrib.auth import views as auth_views urlpatterns = [ url(r'^login$', auth_views.LoginView.as_view(template_name='login.html'), name='login'), url(r'^$', for_views.home, name='home'), ] I mentioned template name in url itself. Is there anyway i can edit login view so i can check user status.How can i achieve this ? -
Django Form: When rendering 'js' attribute in Media class, Django calls <script> on each letter of title?
I've decided to put together what I need myself—this means that I've to implement some javascript in a Django form. My current form looks like this: class SoundTestPairForm(forms.Form): LANGUAGE_CHOICES = [[d['language'], d['language']] for d in Sound.objects.order_by('language').values('language').distinct()] lesson_name = forms.CharField(widget=forms.HiddenInput()) sound_pk = forms.CharField(widget=forms.HiddenInput()) master_phrase1 = forms.CharField(widget=forms.HiddenInput()) master_phrase2 = forms.CharField(widget=forms.HiddenInput()) sex = forms.MultipleChoiceField( choices=Sound.SEX_CHOICES ) starts_with = forms.MultipleChoiceField( choices=Sound.POS_CHOICES ) language = forms.MultipleChoiceField( choices=LANGUAGE_CHOICES ) user_sound = forms.ModelMultipleChoiceField( queryset=Sound.objects.all(), ) class Media: js = ('filter_queryset.js') But when I form_instance = SoundTestPairForm() and call form_instance.media.render, I get: [u'<script type="text/javascript" src="/static/f"></script>', u'<script type="text/javascript" src="/static/i"></script>', u'<script type="text/javascript" src="/static/l"></script>', u'<script type="text/javascript" src="/static/t"></script>', u'<script type="text/javascript" src="/static/e"></script>', u'<script type="text/javascript" src="/static/r"></script>', u'<script type="text/javascript" src="/static/_"></script>', u'<script type="text/javascript" src="/static/q"></script>', u'<script type="text/javascript" src="/static/u"></script>', u'<script type="text/javascript" src="/static/y"></script>', u'<script type="text/javascript" src="/static/s"></script>', u'<script type="text/javascript" src="/static/"></script>', u'<script type="text/javascript" src="/static/j"></script>'] For some reason, it's looking at every letter of the file name instead of the file name as a whole? render_js() gives the same result. Have I found a bug? -
Celery + Django not working at the same time
I have Django 2.0 project that is working fine, its integrated with Celery 4.1.0, I am using jquery to send ajax request to the backend but I just realized its loading endlessly due to some issues with celery. Celery Settings (celery.py) from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'converter.settings') app = Celery('converter', backend='amqp', broker='amqp://guest@localhost//') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) Celery Tasks (tasks.py) from __future__ import absolute_import, unicode_literals from celery import shared_task @shared_task(time_limit=300) def add(number1, number2): return number1 + number2 Django View (views.py) class AddAjaxView(JSONResponseMixin, AjaxResponseMixin, View): def post_ajax(self, request, *args, **kwargs): url = request.POST.get('number', '') task = tasks.convert.delay(url, client_ip) result = AsyncResult(task.id) data = { 'result': result.get(), 'is_ready': True, } if result.successful(): return self.render_json_response(data, status=200) When I send ajax request to the django app it is loading endlessly but when terminate Django server, and i run celery -A … -
Form.is_valid() returns False?
Why am I asking question despite already being asked? I read many question posted on Stack Overflow but I am not able to fix the code as I am new to Python Language. What am I trying to do: Simply trying to take the input from user and return an HttpResponse (if successfully). Otherwise, an error HttpResponse message to return. Problem : The MyForm.is_valid in Forms.py is always returning False! I tried many solutions posted on previous questions and also read the documentary thrice but not able to understand, what am I doing wrong? Views.Py from django.http import HttpResponse from .forms import PostForm . . . <<code here>> def register(request): if request.method == 'POST': Myform = PostForm(request.POST) if Myform.is_valid(): return HttpResponse("<h1>Is_Valid is TRUE.</h1>") else: return HttpResponse("<h1>Is_Valid is False.</h1>") else: return HttpResponse("<h1> GET REQUEST>>>> </h1>") Forms.Py from django.forms import ModelForm from .models import Post class PostForm(ModelForm): class Meta: model= Post fields = ['Username'] Models.Py from django.db import models class Post(models.Model): Username = models.CharField(max_length = 20) def __str__(self): return self.name HTML CODE {% block body %} <div class="container-fluid"> <form method="POST" class="post-form" action="{% url 'submit' %}"> {% csrf_token %} <div class="form-group"> <!-- Full Name --> <label for="Username" class="control-label">Full Name</label> <input type="text" class="form-control" id="Username" … -
`labels = {'text':''}` in Model.Form
I am little puzzbled about the labels = {'text':''} in the following code: from django import forms from .models import Topic class TopicForm(forms.ModelForm): class Meta: model = Topic fields = ['text'] labels = {'text':''} Does labels = {'text':''} means <label for='text'> </label> -
Updating Many-to-Many relation
I have 3 models (simplified): class Product(models.Model): category = models.ForeignKey('Category', related_name='products', to_field='category_name') brand = models.ForeignKey('Brand', related_name='products', to_field='brand_name') class Brand(models.Model): brand_name = models.CharField(max_length=50) categories = models.ManyToManyField('Category', related_name='categories') class Category(models.Model): category_name = models.CharField(max_length=128) I want to change a Category in admin to a bunch of products, i have a custom admin function written for that. After that I need to update Brand-Categories Many-to-Many relation to check if that Category is still available for a specific Brand. I have written this function: def brand_refresh(): brands = Brand.objects.all().prefetch_related('shops', 'categories') products = Product.objects.select_related('shop', 'brand', 'category') for brand in list(brands): for category in brand.categories.all(): if not products.filter(category=category).exists(): brand.categories.remove(category) for product in list(products.filter(brand=brand).distinct('category')): if product.category not in [None, category]: brand.categories.add(product.category) Seems to me this monstro is working, but it takes 2 hours to loop over all cycles (i have ~220k products, 4k+ brands, and ~1k categories). I there any better way to update M2M relation here? I think .prefetch_related() should help here, but what I have now seems have no effect. -
Django application deployed with Heroku/Postgresql - Some Python/JS formulas not working in production only, values jump back to previous values
I deployed a Django application with Heroku. It works fine when I run it locally. It has a Strange behavior in production. For example, when I push a button, the Prod1 variable is supposed to increment by 1. Now sometimes it does +1, sometimes it jumps back to a previous value. I also have a similir problem with time.time() but it might be related to the same issue... That's the Django code in "Prod_settings" used in production: import dj_database_url from traineau.settings import * DEBUG = False TEMPLATE_DEBUG = False DATABASES['default'].update(dj_database_url.config()) MIDDLEWARE += ['whitenoise.middleware.WhiteNoiseMiddleware'] #STATICFILES_STORAGE='whitenoise.storage.CompressedManifestStaticFilesStorage' #SECRET_KEY = os.environ['SECRET_KEY'] ALLOWED_HOSTS = ['xxx.herokuapp.com'] As I say, everything works fine in Local so I assume the problem might be in Prod_settings.. As an exemple, this is the Heroku logs enter image description here Prod1 variable increments correctly a couple time and suddenly returns to 0 for no apparent reason. In this example it's zero but if I would continue it make something like (1,2,3,4,5,0,6,1,2,7,8,9,3,4....) these are the Heroku Config vars: DATABASE_URL = postgres://xxxxx DEBUG_COLLECTSTATIC = 1 DJANGO_SETTINGS_MODULE = traineau.prod_settings this this the settings used locally import os # from django.core.exceptions import ImproperlyConfigured # def get_env_variable(var_name, default_value=None): # try: # return os.environ[var_name] # except KeyError: … -
Django Framework: 'UserView' object has no attribute 'object'
I am using Django Framework for the first time and am also building on a someone else's code who stopped working here, so I am having some trouble... I am trying to create a web form to submit data to a database but am getting the error message 'UserView' object has no attribute 'object' models.py: from django.db import models class UserInfo(models.Model): first_name = models.CharField(max_length=20, verbose_name='First Name', help_text='Your given name. *REQUIRED**') last_name = models.CharField(max_length=100, verbose_name='Last Name', help_text='Your family name. *REQUIRED*.') office_address = models.CharField(max_length=200 ,verbose_name='Office address', help_text='The address where you can be reached rather than your institution’s head office. *REQUIRED*') research_interest = models.CharField(max_length=1000 ,verbose_name='Short summary of your research interests',help_text='In one or two sentences please describe your research interests and how access to the RD-Connect platform is relevant for you. *REQUIRED*' ) institution = models.CharField(max_length=50, verbose_name='Name of institution', help_text='The institution (university, hospital etc.) with which you have your primary affiliation. *REQUIRED*') institute_website = models.URLField(max_length=100, null=True, blank=True, default="", verbose_name='Institute website', help_text='Your institution’s main website.') job_title = models.CharField(max_length=100, null=True, blank=True, verbose_name='Position within institution', help_text='Your job title within your institution.') email = models.EmailField(max_length=100, verbose_name='Institutional email address', help_text='Use of an institutional email address issued by your place of work is part of our validation procedure. If you …