Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Facebook: Redirect URI is not whitelisted in the app’s Client OAuth Settings
I realize this is a common problem, but am unable to find an up-to-date solution for this problem. Using social-auth-app-django to login users based on their social accounts. Currently I am focusing on Facebook, but am getting redirect URI errors for Instagram & LinkedIn as well. I am aware of current solutions and have tried the following (to name a few): 1. https://github.com/python-social-auth/social-app-django/issues/130 2. https://help.sharetribe.com/en/articles/1317674-how-to-solve-the-url-blocked-this-redirect-failed-because-facebook-login-error 3. https://github.com/python-social-auth/social-app-django/issues/152 4. python-social-auth and facebook login: what is the whitelist redirect url to include in fb configuration? 5. Facebook login message: "URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings." settings.py INTALLED_APPS = [ ... 'social_django', ... ] MIDDLEWARE = [ ... 'social_django.middleware.SocialAuthExceptionMiddleware', ... ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,"templates")], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] AUTHENTICATION_BACKENDS = [ 'social_core.backends.linkedin.LinkedinOAuth2', 'social_core.backends.instagram.InstagramOAuth2', 'social_core.backends.facebook.FacebookOAuth2', 'django.contrib.auth.backends.ModelBackend', ] LOGIN_URL = 'login' LOGOUT_URL = 'logout' SOCIAL_AUTH_URL_NAMESPACE = 'social' SOCIAL_AUTH_FACEBOOK_KEY = '*****************' SOCIAL_AUTH_FACEBOOK_SECRET = '************************' urls.py urlpatterns = [ ... path('login/', login_page, name="login"), path('social-auth/', include('social_django.urls', namespace="social")) ] login.html .... <a href="{% url 'social:begin' 'facebook' %}">Facebook</a> <br> .... Facebook Developer App Domains: todayatmyinternship.com Site URL: https://www.todayatmyinternship.com/ Valid OAuth Redirect … -
How to solve TypeError: create_superuser() got an unexpected keyword argument 'paid' in django
I am implementing custom user model extending AbstractBaseUser. Here is my account/models.py file. from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) class MyUserManager(BaseUserManager): def create_user(self, email, password=None): """ Creates and saves a User with the given email, date of birth and password. """ if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email) ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): """ Creates and saves a superuser with the given email, password. """ user = self.create_user( email, password=password ) user.paid = True user.is_superuser = True user.is_admin = True user.is_staff = True user.save(using=self._db) return user class MyUser(AbstractBaseUser): email = models.EmailField(max_length=60, unique=True) date_joined = models.DateTimeField(verbose_name="date joined", auto_now_add=True) last_login = models.DateTimeField(verbose_name="last login", auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) paid = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) list_filter = () # Con USERNAME_FIELD = "email" REQUIRED_FIELDS = ("paid",) objects = MyUserManager() def __str__(self): return self.email def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return self.is_admin But I am getting the error while creating super user with the command python manage.py runserver This is what I got from the terminal : Email: i@j.com Paid: True Password: Password (again): Traceback (most recent call last): File … -
Django search model by dictionary (also include between a range)
Hello i'm having trouble trying to figure out how to handle this problem. I have a dict like so(the data key can be anything, but value has 3 types of a string, int or a dictionary with min and max values): { "city":5, "size":{ "max":78693, "min":11202 }, "type":"rent", "ward":229, "price":{ "max":43660474485, "min":7660026858 }, "street":1853, "district":20, "frontend":{ "max":90, "min":18 }, "direction":"ne" } Right now what i'm trying to do is to search a model using filter following the values of the above dictionary, The problem is i don't know how to handle ,if a key has a min and max then i have to find between it's range in the filter. I know that you can search by dict with the following : models.objects.filter(**my_dict) But how do i handle special condiation like min and max range in the filter ? I'm looking to output like this(the field name follow the key of the dictionary): models.objects.filter(city=5, size__range(min, max), type="rent",... other keys and values) Thank for reading -
Suggestion on database schema
I need to creat a database setup where in there are main three roles and use rest framework 1. Data entry : will do data entry and send to reviewer. Entry will be logged. 2. Reviewer: will review data, if any error is found send it back to data entry. When data entry is corrected, raise an ok flag. 3. Approver : will approve data after ok flag by reviewer. Confused about how to set up django model, serializer and how to log all these back and forth data between reviewer and data entry. I can do that on Access/visual basic but I am just starting to use django. Any suggestion please ? -
How to correctly perform django queries of ManyToMAny fields
I am working on an IMDB Clone project for the sake of learning. It has two important models: Movie and Celebrity. Movie model had three MTM fields all related with Celebrity model. class Movie(models.Model): # .. unrelated fields deleted for code brevity .. directors = models.ManyToManyField(celeb_models.Celebrity, related_name='movies_as_director', limit_choices_to=Q(duties__name__icontains='Director')) writers = models.ManyToManyField(to=celeb_models.Celebrity, related_name='movies_as_writer', limit_choices_to=Q(duties__name__icontains='Writer')) casts = models.ManyToManyField(to=celeb_models.Celebrity, through='MovieCast') I would like to delete all three fields and add only one MTM field. class Movie(models.Model): # one 'crews' field takes the place of three fields ('directors', 'writers', 'casts') # but it shows bad query performance. crews = models.ManyToManyField(celeb_models.Celebrity, through='MovieCrew', related_name='movies') And created an intermediate model which has some methods and a custom manager (which should do the magic). class MovieCrewManager(models.Manager): def get_queryset(self): return super().get_queryset() def get_directors(self): qs = self.get_queryset() return qs.filter(duty__name__icontains='Director').select_related('crew') def get_writers(self): qs = self.get_queryset() return qs.filter(duty__name__icontains='Writer').select_related('crew') def get_casts(self): qs = self.get_queryset() return qs.filter(duty__name__icontains='Cast').select_related('crew') class MovieCrew(models.Model): movie = models.ForeignKey(Movie, on_delete=models.CASCADE, related_name='movie_crews') #Movie Model duty = models.ForeignKey(celeb_models.Duty, default=1, on_delete=models.CASCADE) crew = models.ForeignKey(celeb_models.Celebrity, on_delete=models.CASCADE) # Celebrity Model role = models.CharField(max_length=75, default='', blank=True, help_text='e.g. short story, scrrenplay for writer, voice for cast') screen_name = models.CharField(max_length=75, default='', blank=True, help_text="crew's name on movie") objects = MovieCrewManager() def clean(self, *args, **kwargs): if not self.duty in self.crew.duties.all(): raise … -
How to solve error during follow standard output of a systemd unit?
I try to enable all systemd units and check systemd unit status but it shows some error with exit code and spawning. Step 1: To enable systemd sudo systemctl enable rt3-django-server.service Step 2: To check systemd unit status sudo systemctl status rt3-django-server.service Step 3: To follow the standard output of a systemd unit journalctl -fu rt3-django-server.service So when I run this line of command, I got this error. Please look at the picture. How to solve this problem? -
Django 'ifequal' with string comparisons
I currently am trying to compare two strings with an ifequal tag in Django. The current issue is that although the two strings are equal, Django does not run everything inside the if statement. html {% for group in groups %} <h1 class="inverted-popout">{{ group.name }}</h2> <div class="sheets"> {% for sheet in sheets %} {% ifequal sheet.sheetGroupValue group.sheetGroupName %} <!-- This is the issue --> <div class="sheet popout"> <h2><a href="{% url 'sheets:detail' slug='sheet.slug' slug=sheet.slug %}"> {{ sheet.name }} {{ sheet.hitPoints }} / {{ sheet.maxHitPoints }} </a></h2> <h3>{{ sheet.sheetGroupValue }}</h3> <p><i>Lvl {{ sheet.level }} ({{ sheet.xp }})</i></p> <p>{{ sheet.Class }}</p> <p>{{ sheet.background }}</p> <p>{{ sheet.race }}</p> </div> {% endifequal %} {% endfor %} </div> {% endfor %} views.py def sheetList(request): sheets = Sheet.objects.all().order_by('name') groups = SheetGroup.objects.all().order_by('name') return render(request, 'sheets/sheetList.html', { 'sheets': sheets, 'groups': groups }) models.py class SheetGroup(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name def sheetGroupName(self): return str(self.name) class Sheet(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) name = models.CharField(max_length=100) sheetGroup = models.ManyToManyField(SheetGroup) slug = models.SlugField(default="") # there's a bunch of fields but they do not contribute to the error def __str__(self): return self.name def sheetGroupValue(self): groups = '' for group in self.sheetGroup.all(): groups += group.name + " " return groups Here … -
Django Serializer
I have a model with name,age,and a JSONField called nestedobject which holds a json string which holds a scheme like so {color="red",shape=[1,2,3,4]} a standard serializer would do something like this class MyRecordSerializer(serializers.ModelSerializer): class Meta: model = MyRecord fields = ('name','age','nestedobject') What I am after is class MyRecordSerializer(serializers.ModelSerializer): class Meta: model = MyRecord fields = ('name','age','shape') where shape would be that field with in that JSONField. So i would get something like {name="mike",age=10,shape=[1,2,3,4]} I have tried something like this class MyRecordSerializer(serializers.ModelSerializer): shape = serializers.SerializerMethodField('nestedobject')['shape'] class Meta: model = MyRecord fields = ('name','age','shape') Is this even doable ? Any help would be appreciated -
I want to push a Python app to Heroku on Windows 10, but i get "error: command 'gcc' failed with exit status 1"
I enter git push heroku master into the command prompt and all goes well for a while then... WARNING: The Python installation you are using does not appear to have been installed with a shared library, or in the case of MacOS X, as a framework. Where these are not present, the compilation of mod_wsgi may fail, or if it does succeed, will result in extra memory being used by all processes at run time as a result of the static library needing to be loaded in its entirety to every process. It is highly recommended that you reinstall the Python installation being used from source code, supplying the '--enable-shared' option to the 'configure' script when configuring the source code prior to building and installing it. then... gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tmp/pip-build-oxraezk2/mod-wsgi/src/packages/apache/include -I/app/.heroku/python/include/python3.7m -c src/server/mod_wsgi.c -o build/temp.linux-x86_64-3.7/src/server/mod_wsgi.o -I/tmp/pip-build-oxraezk2/mod-wsgi/src/packages/apache/include -I. -I/tmp/pip-build-oxraezk2/mod-wsgi/src/packages/apr/include/apr-1 -I/tmp/pip-build-oxraezk2/mod-wsgi/src/packages/apr-util/include/apr-1 -DLINUX -D_REENTRANT -D_GNU_SOURCE -g -O2 -pthread src/server/mod_wsgi.c: In function ‘wsgi_socket_sendv’: src/server/mod_wsgi.c:10966:44: warning: signed and unsigned type in conditional expression [-Wsign-compare] (nvec < iov_max ? nvec : (int)iov_max)); ^ src/server/mod_wsgi.c: In function ‘wsgi_scan_headers’: src/server/mod_wsgi.c:11125:30: warning: signed and unsigned type in conditional expression [-Wsign-compare] buflen = buffer ? buflen : sizeof(x); ^ gcc -pthread -Wno-unused-result … -
Filtering a Django queryset's related ManyToMany field when using values()
I'm working with a queryset which includes a ManyToMany field brand_groups. Users only have access to a subset of BrandGroups based on their organization. I'm trying to keep that ManyToMany field filtered down while still using values(), which is heavily integrated with the view. The simplified tables I'm working with: class BrandGroup(models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField(max_length=256) organization = models.ForeignKey( Organization, related_name="brand_groups", null=False ) class Fact(models.Model): id = models.CharField(max_length=256, primary_key=True) brand_groups = models.ManyToManyField(BrandGroup, blank=True) What's worked for me in the past is using Prefetch objects to handle this kind of limiting: qs = Fact.objects.prefetch_related( Prefetch("brand_groups", queryset=BrandGroup.objects.filter( organization_id=self.request.META["ORG_ID_HEADER"] ))) But I find that values() seems to ignore prefetches entirely. qs.values("brand_groups__name") The above always includes the full set of associated BrandGroup objects without the filter. I've tried adding to_attr='org_brand_groups' to the Prefetch, but then qs.values("org_brand_groups__name") complains that the field doesn't exist. I've also tried using an annotation to rename the prefetched field in a similar way. I don't get a complaint about the field not existing, but again values() returns the unfiltered queryset. The only way I've managed to accomplish this kind of filtering is by using a subquery: qs = Fact.objects.annotate( brand_group_name=Subquery( BrandGroup.objects.filter( organization_id=self.request.META["ORG_ID_HEADER"], Q(id=OuterRef("brand_groups__id"))).values( "name"[:1],output_field=CharField(),)) # Now it gives … -
How to add Custom Attributes to QuerySets in Django?
consider the following models: class User(AbstractUser): ... def messages(self): return Message.objects.filter(user=self).order_by('-created_on') def unread_count(self): return Message.objects.filter(user=self, read=False).count() class Message(models.Model): user = models.ForeignKey('account.User', related_name='message', on_delete=models.CASCADE) created_on = models.DateTimeField(auto_now=True) data = models.TextField() read = models.BooleanField(default=False) objects = MessageManager() I call both the messages and unread_count methods from within a template, like this: <h1> You have {{ request.user.unread_message_count }} new messages </h1> <ul> {% for message in request.user.messages %} <li>{{ message.body }}</li> {% endfor %} </ul> My assumption is that this is a poor strategy, since splitting this into two separate methods requires 2 separate DB hits, so instead I want to override the QuerySet behavior for the Message model to include an unread_count: class MessageManager(models.Manager): def get_queryset(self): queryset = super().get_queryset() unread_count = queryset.filter(read=False).count() print(unread_count) # this works # these don't work queryset.unread_count = unread_count setattr(queryset, 'unread_count', unread_count) # return queryset The messages method works fine, and the print statement inside the manager executes, but if I try to access the unread_count I get an AttributeError: >>>user = User.objects.get(id=1) >>>messages = user.messages() 2 # this is from the print statement >>>messages.unread_count AttributeError: 'QuerySet' object has no attribute 'unread_count' Note that I want to do this without changing my view. What am I missing here? -
Can't connect to mysqldb in Django "ImportError: cannot import name 'CLIENT' from 'MySQLdb.constants' (unknown location)"
I have been fought all day, but i fail. I have problem with connection to MYSQL database. I using Linux Debian and i try connect to local database, but something went wrong :/. Bellow attached settings.py # settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'dbDjango', 'USER': 'user', 'PASSWORD': '*******', 'HOST': '127.0.0.1', 'PORT': '3306', } But, when i run server using python3.7 manage.py runserver the program call back me error like this: File "/usr/local/lib/python3.7/dist-packages/django/contrib/auth/models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/usr/local/lib/python3.7/dist-packages/django/contrib/auth/base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "/usr/local/lib/python3.7/dist-packages/django/db/models/base.py", line 117, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "/usr/local/lib/python3.7/dist-packages/django/db/models/base.py", line 321, in add_to_class value.contribute_to_class(cls, name) File "/usr/local/lib/python3.7/dist-packages/django/db/models/options.py", line 204, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "/usr/local/lib/python3.7/dist-packages/django/db/__init__.py", line 28, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "/usr/local/lib/python3.7/dist-packages/django/db/utils.py", line 201, in __getitem__ backend = load_backend(db['ENGINE']) File "/usr/local/lib/python3.7/dist-packages/django/db/utils.py", line 110, in load_backend return import_module('%s.base' % backend_name) File "/usr/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "/usr/local/lib/python3.7/dist-packages/django/db/backends/mysql/base.py", line 22, in <module> from MySQLdb.constants import CLIENT, FIELD_TYPE # isort:skip ImportError: cannot import name 'CLIENT' from 'MySQLdb.constants' (unknown location) Mysql as service is runing: ervice mysql status ● mysql.service - MySQL Community Server Loaded: loaded (/lib/systemd/system/mysql.service; disabled; vendor preset: disabled) … -
ModelChoiceField causing decimal.invalidoperation, even with def __str__ on model set to return the name
I have a forms.py and this little nugget here: from mainpage.models import Institution institution = forms.ModelChoiceField(queryset=Institution.objects.all(), empty_label="(Select One)", to_field_name="institution_name", widget=forms.Select( attrs={ 'tabindex':'7','class':'form-control' } ) ) It causes that decimal.invalidoperation once I have this piece of code in it, even though my InstitutionModel is as such (in another app) class Institution(models.Model): objects = models.Manager() institution_id = models.CharField(max_length=10) institution_name = models.CharField(max_length=100) institution_precentages = models.DecimalField(max_digits = 4, decimal_places=2) #might have to change this def __str__(self): return self.institution_name I even tested in the view trying to render all this a quick little p = Institution.objects.first() print(p) Worked fine, not sure what else to try or what I am missing. -
Implementing one to many between and article and page models
I'm trying to setup a wagtail site with an article to pages structure but I'm struggling. A review article for example may have an introduction page, a benchmark page and a conclusion page. I can't work out how to allow this relationship in wagtail and have it so that editors can add multiple pages to the same article on the same page. I imagine the pages interface looking a bit like how you have content, promote and settings on pages but with the ability to add, rename and reorder pages. I've tried using a foreign key on a page model that links to an article but I can't get it to be shown in the admin the way I want. -
Duplicated values after select related field
I have simple forum application: # models class Topic(models.Model): title = models.CharField(max_length=255) class Message(models.Model): text = models.TextField() topic = models.ForeignKey(Topic, related_name='messages') # views class SearchView(ListView): ... def get_queryset(self): search_vector = SearchVector('messages__text') search_query = SearchQuery(self.request.GET.get('query')) topics = Topic.objects.annotate( rank=SearchRank(search_vector, search_query) ).filter(rank__gte=0.0).order_by('-rank') return topics I want have full text search in my forum. Everything works but in topic query results I got duplicated objects. <QuerySet [<Topic: 1>, <Topic 1>, <Topic 2>, <Topic 1>, ...]> I think that it happens because of multiple messages in one topic that gives me different rank values. How can I remove duplicated topics but keep rank ordering? -
How to pass json dictionary from javascript .get to django template?
In the head of my django template I currently have: <script> $.get('get_students/', function (dict) { alert(dict) }) </script> This alerts me of a json dictionary corresponding to dict, which comes from the following django view: def get_students(request): students = Student.objects.all() students_json = serializers.serialize('json', students) return HttpResponse(json.dumps(students_json), content_type='application/json') Is it possible to "escape" dict from the script tag into the normal Django template so that I can iterate over it with something like: {% for d in dict%} <p>d.username</p> {% endfor %} Thanks! -
AJAX loading gif before showing the page for a certain time ,, how to do it?
i want to make an ajax or javascript loading gif image for a certain time before showing any contents of the page in a django project ,, searched alot but still have no idea how to make it .. '''function readText () { var value1 = document.getElementById("trcode").value; var value2 = document.getElementById("trfcode").value; if (value1 === value2) { location.href="trfresultdetails"; } else { alert("You Typed: " + "Wrong Passord");} }''' -
Model inheritance: benefits of explicit OneToOneField vs implicit multi-table inheritance OneToOneField
I read here that multi-table inheritance can cause performance issues, and instead explicit OneToOneField is recommended. Here is my situation: class Product(models.Model): title = models.CharField(max_length=200) description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=10) category = models.ForeignKey('Category', on_delete=models.CASCADE, blank=False) class Book(Product): publisher = models.CharField(max_length=50) author = models.CharField(max_length=50) isbn = models.CharField(max_length=50) class Shoes(Product): size = models.PositiveSmallIntegerField() colour = models.CharField(max_length=20, choices=[('black', 'Black'), ('white', 'White')]) I don't understand why would explicit OneToOneField bring performance gains, when multi-table inheritance is implemented in exactly the same way: place_ptr = models.OneToOneField( Place, on_delete=models.CASCADE, parent_link=True, ) If this is true despite everything, I would like to know how could I alter my models so they use explicit OneToOneField. So, if I create a Book instance, Product.objects.all() should retrieve that instance of Book, too. -
Django - How to link the current authenticated user with the data provided by a form
Sorry if the question is too basic but I've read the documentation and many articles and none of them seem to answer my question. I want to link a posted form by an user with that user into the DB, so I can query the data provided for each particular user and use delete on CASCADE in the event the user is deleted. I tried creating a Model, then a ModelForm based on that Model. I add a field named "user" in the Model as a ForeignKey, so in the ModelForm is translated to ModelChoiceField which by the way is hidden, since the user shouldn't change that value. But when I try to update the user field in the views.py, nothing happens, the form is saved into the database, but the user field remains as None or Null in the DB. models.py class Foo(models.Model): user = models.ForeignKey(User, related_name='+', on_delete=models.CASCADE) forms.py class FooForm(ModelForm): class Meta: model = Foo fields = ['user', 'field1', 'field2'] exclude = ['user'] views.py def index(request): if request.user.is_authenticated: if request.method == 'POST': foo = FooForm(request.POST) if foo.is_valid(): foo.save(commit=False) foo.user = request.user foo.save() I got the posted Form saved into the DB but the user field is NULL. Of … -
Django: is this data migration going to blow the server memory?
I'm trying to migrate the data from an old table to a new table and I'm not sure what the best way would be. There's the simple solution of creating every object: def migrate_data(apps, schema_editor): UserPreferences = apps.get_model("authentication", "UserPreferences") UserPreferencesOld = apps.get_model("authentication", "UserPreferencesOld") for user_preferences_old in UserPreferencesOld.objects.all(): user_preferences = UserPreferences( date_modified=user_preferences_old.date_modified, email_notifications=user_preferences_old.email_notifications, show_message_deadline_summary=( user_preferences_old.show_message_deadline_summary ), user=user_preferences_old.user, ) user_preferences.save() And the bulk create solution: def migrate_data(apps, schema_editor): UserPreferences = apps.get_model("authentication", "UserPreferences") UserPreferencesOld = apps.get_model("authentication", "UserPreferencesOld") UserPreferences.objects.bulk_create( [ UserPreferences( date_modified=user_preferences_old.date_modified, email_notifications=user_preferences_old.email_notifications, show_message_deadline_summary=( user_preferences_old.show_message_deadline_summary ), user=user_preferences_old.user, ) for user_preferences_old in UserPreferencesOld.objects.all() ] ) The table I need to migrate has tens of thousands of entries and I'm afraid that the first option will take forever, making tens of thousands of requests to the database, while the second option will blow the memory on the server. Any suggestions on what would be the better option? Thanks! -
How do you get the current cursor with CursorPagination?
By default, CursorPagination gives you the next and previous cursors. Is there a way to get the current cursor? -
How can you customize object creation in django?
In django rest framework, it's possible to make a function to customize the process of creating an object inside the serializer of that respective model, but I can't figure out how to do that in "vanilla" django, so to speak. What I need to do is take one field and do a bunch of stuff with it. encode it into a 256 character hash is all I have to worry about now. How can I go about doing what I need? I've been basing myself off of an online course and Django's documentation, but I either couldn't interpret it well enough or I just straight up haven't found it there. Here is the code I have so far, at least what I judge is relevant to the question. It's all in models.py: class SpedFile(models.Model): json_file = models.FileField(max_length=100) sped_file = models.FileField(max_length=100) integrity_hash = models.CharField(max_length=256) line_counter = models.CharField(max_length=150000) created_at = models.DateField(auto_now_add=True) @classmethod def create(cls, json_file): file_bearer = json_file m = hashlib.sha256() m.update(file_bearer.encode('utf-8')) integrity_hash = m.hexdigest() new_object = cls(json_file=file_bearer, integrity_hash=integrity_hash) return new_object -
How to write subquery in django
Is it possible to make following sql query in django select * from ( select * from users ) order by id It is just minimal example. I have a long subquery instead of select * from users. But I can't understand how insert it into subquery. -
Django Jinja2 How to get form data on a different view
I am loading my registration form on the base url (localhost:8000/). It's a Jinja2 template and running on top of Django. Let's FrontEnd app is frontend <form class="registration_form" style="display: none" method="POST" action="/"> <div class="form-group"> <input type="text" class="form-control" id="InputFirst" placeholder="First Name"> </div> <div class="form-group"> <input type="text" class="form-control" id="InputLast" placeholder="Last Name"> </div> <div class="form-group"> <input type="email" class="form-control" id="InputEmail" aria-describedby="emailHelp" placeholder="Enter email"> <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small> </div> <div class="form-group"> <input type="password" class="form-control" id="InputPassword" placeholder="Password"> </div> <button type="submit" class="btn btn-primary btn-lg btn-block actions"> Registration</button> </form> Now, I have written my Registration API, on user app and it's accessed via /user/registration/. How can I send the form data on that VIew instead of the front_end view? I am using APIView of DRF for registration API. I have tried to add {{ url_for('user/registration/') }} on actions. It doesn't work For some reason, I can't use any other front-end framework, I have to make do with jinja2. Thanks in Advance. -
celery task in multiple queues not start
i use django with celery and redis to work with asynchronous tasks. I have three task defined which should run in your own queue. My project structure looks like this: django-project |- api |- task.py |- view.py |- django-project |- settings.py |- celery.py |- __init__.py My tasks defined in the task.py in my api app: @shared_task def manually_task(website_id): print("manually_task"); website = Website.objects.get(pk=website_id) x = Proxy(website, "49152") x.startproxy() x = None @periodic_task(run_every=(crontab(hour=19, minute=15)), ignore_result=True) def periodically_task(): websites = Website.objects.all() for website in websites: x = Proxy(website, "49153") x.startproxy() x = None @shared_task def firsttime_task(website_id): website = Website.objects.get(pk=website_id) x = Proxy(website, "49154") x.startproxy() x = None Now here is my init.py __all__ = ('celery_app',) and the celery settings in the settings.py: CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_TIMEZONE = 'Europe/Berlin' CELERY_DEFAULT_QUEUE = 'red' CELERY_TASK_QUEUES = ( Queue('red', Exchange('red'), routing_key='red'), ) CELERY_ROUTES = { 'api.tasks.manually_task': {'queue': 'red'}, } My celery.py looks like this: os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django-project.settings') app = Celery('django-project') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() This was my settings. Now i start all the needed stuff (every line in own terminal): redis-server celery -A django-project worker -Q red python3 manage.py runserver 0.0.0.0:8000 All starts without problems. In the …