Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
idk whats happending but i get an error saying Blacklist.findOne is not a function
const command = client.commands.get(commandName); if (command.devOnly == true && message.author.id !== '696023375788900353') return message.channel.send('You dont have permission to use this as this is a dev command'); let profile = await Blacklist.findOne({ userID: message.author.id }); if (profile) return message.channel.send('You cannot use the commands as you are banned from using my commands'); try { command.execute(message, args, client); } catch (err) { console.log(err); } }, }; -
Django template conditionals not working as intended
I am trying to create a basic view which returns a bunch of posts to be rendered as per the given keyword. I want it to be such that: When it loads initially, it just shows a search bar. When a keyword is supplied for search then it finds the posts with that keyword and renders them. If no posts are found then it should show a message that "no posts for the given keyword were found". I am able to achieve 1 and 2 but for the 3rd one, django is acting strange. Views.py def search(request): if 'keyword' in request.GET and request.GET['keyword'] != '' and request.GET['keyword'] != ' ': res = Post.objects.filter(tag__icontains=request.GET['keyword']) posts = [PostSerializer(x).data for x in res] if len(posts) == 0: return render(request, 'search.html', context={'notfound':True}) return render(request, 'search.html', context={'posts':posts}) return render(request, 'search.html') Template {% if notfound %} <h2> Seems like there are no posts with that keyword </h2> {% endif %} {% for post in posts %} //render posts {% endfor %} Note that here I have used the 'notfound' key as simply checking if posts | length equals 0 was achieving 3 (the 3 points mentioned above) but was also showing the message for 1, which … -
Problem with deploying Django app using Heroku
I am not clear with where to save Procfile in Django app for Heroku my app file structure is like this: coding_site coding_site wsgi.py settings.py Procfile2 readME.md Procfile1 other_files should I save in Procfile1 or Procfile2 location? my Procfile looks like this: in location Procfile1 web: gunicorn coding_site.coding_site.wsgi --log-file - in Procfile2 web: gunicorn coding_site.wsgi --log-file - Errors I got Using Procfile1 location 2021-05-19T18:40:51.423744+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/admin" host=coding-club-jaya.herokuapp.com request_id=71078218-39b0-4b7f-a817-7093078baa08 fwd="123.201.77.16" dyno= connect= service= status=503 bytes= protocol=https Using Procfile2 location 2021-05-19T17:49:21.981719+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/admin" host=coding-club-jaya.herokuapp.com request_id=a47a58e6-4513-44a4-88aa-4425470d8465 fwd="123.201.77.16" dyno= connect= service= status=503 bytes= protocol=https in btw: I changed the settings.py file as shown in different tutorials here are the changes made in the setting.py code import django_heroku import dj_database_url *** MIDDLEWARE =[**, 'whitenoise.middleware.WhiteNoiseMiddleware', **] *** DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'ciba', } } *** STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") STATIC_URL = '/static/' STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' os.makedirs(STATIC_ROOT, exist_ok=True) os.makedirs(STATICFILES_DIRS[0], exist_ok=True) # Activate Django-Heroku. django_heroku.settings(locals()) in case needed here is my requirements.txt file gunicorn==20.1.0 whitenoise==5.2.0 django-heroku==0.3.1 Django==3.0.2 requests==2.22.0 sqlparse==0.2.4 dj-database-url==0.5.0 dj-static==0.0.6 docopt==0.6.2 psycopg2 python-decouple gitignore==0.0.8 pytz==2018.9 static3==0.7.0 Pls help, All my work is done and got stuck in the last step (it's … -
ValueError at /profile/ Required parameter name not set Request Method: GET
After properly deploying my app using Heroku I get this error while accessing my profile. Required parameter name not set Request Method: GET Request URL: https://(domain).herokuapp.com/profile/ Django Version: 3.2.2 Exception Type: ValueError Exception Value: Required parameter name not set Exception Location: /app/.heroku/python/lib/python3.9/site-packages/boto3/resources/base.py, line 118, in __init__ Python Executable: /app/.heroku/python/bin/python Python Version: 3.9.5 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python39.zip', '/app/.heroku/python/lib/python3.9', '/app/.heroku/python/lib/python3.9/lib-dynload', '/app/.heroku/python/lib/python3.9/site-packages'] Server time: Wed, 19 May 2021 18:40:44 +0000 Error during template rendering In template /app/blog/templates/blog/base.html, error at line 10 Required parameter name not set 1 {% load static %} 2 <!DOCTYPE html> 3 <html> 4 5 <head> 6 <link rel="shortcut icon" type="image/png" href="{% static 'favicon.ico' %}"/> 7 8 <!-- Required meta tags --> 9 <meta charset="utf-8"> 10 <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> 11 12 <!-- Bootstrap CSS --> 13 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" 14 integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> 15 16 <link rel="stylesheet" type="text/css" href=" {% static 'blog/main.css' %} "> 17 18 {% if title %} 19 <title>mytitle -{{ title }} </title> 20 {% else %} I don't understand why i keep getting this error. I have also set the environment variables correctly. This is my settings.py import os import django_heroku # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) … -
Load an inclusion tag from context variable name
I have a template which would need to call some inclusion_tag based on a variable in the context. Something like this: <div> {% for section in sections %} {{ section.tagname }} {% endfor %} </div> Can I actually do that somehow? Or do I need to build a big if-elif statement & check names explicitely? EDIT: I also tried something like {% {{ section.tagname }} %} but doesn't work either. -
Lazy Load Plotly Graphs without iFrame
I'm trying to improve my websites Largest Contentful Paint score, and one large problem I'm having is attempting to lazy load plotly graphs. That page in question has 6-8 graphs. At first I created them by using the embed tool on chart studio, which gave me an iFrame for each one. This worked but the issue with the iFrame is it needs to reload the plotly javascript each time which really slowed it down. I'm sure I can implement lazy loading on the iFrame's, but that would still be a big draw and doesn't seem efficient at all. My second attempt I took all the code out of the iFrame, and simply put this at the top of the page: <script src="https://cdn.plot.ly/plotly-latest.min.js"></script> This improved some metrics, such as Time to Interactive, a lot. Unfortunately it actually made Largest Content Paint worse. I'm wondering how I'd be able to either lazy load the graphs or parent divs, or make it so each iFrame doesn't need to reload the plotly javascript independently. Here is an example of each graph being created. <div id="4023a488-b679-4fdd-a482-30d6e6ec851b" style="width: 100%; height: 100%;" class="plotly-graph-div"></div> <script async type="text/javascript"> (function(){ window.PLOTLYENV={'BASE_URL': 'https://plotly.com'}; var gd = document.getElementById('4023a488-b679-4fdd-a482-30d6e6ec851b') var resizeDebounce = null; … -
ValueError: too many values to unpack: error in django models while querying a model
The following is the stack trace- Internal Server Error: /merger/merge/ Traceback (most recent call last): File "C:\Users\Yash\AppData\Local\Continuum\anaconda3\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Yash\AppData\Local\Continuum\anaconda3\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Yash\AppData\Local\Continuum\anaconda3\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "F:\Internship Project\pdf_merger\merger\views.py", line 72, in mergefiles mergedFile = requests.post('https://pdfmergerapi.herokuapp.com/', files = postlist) File "C:\Users\Yash\AppData\Local\Continuum\anaconda3\lib\site-packages\requests\api.py", line 112, in post return request('post', url, data=data, json=json, **kwargs) File "C:\Users\Yash\AppData\Local\Continuum\anaconda3\lib\site-packages\requests\api.py", line 58, in request return session.request(method=method, url=url, **kwargs) File "C:\Users\Yash\AppData\Local\Continuum\anaconda3\lib\site-packages\requests\sessions.py", line 494, in request prep = self.prepare_request(req) File "C:\Users\Yash\AppData\Local\Continuum\anaconda3\lib\site-packages\requests\sessions.py", line 437, in prepare_request hooks=merge_hooks(request.hooks, self.hooks), File "C:\Users\Yash\AppData\Local\Continuum\anaconda3\lib\site-packages\requests\models.py", line 308, in prepare self.prepare_body(data, files, json) File "C:\Users\Yash\AppData\Local\Continuum\anaconda3\lib\site-packages\requests\models.py", line 496, in prepare_body (body, content_type) = self._encode_files(files, data) File "C:\Users\Yash\AppData\Local\Continuum\anaconda3\lib\site-packages\requests\models.py", line 141, in _encode_files for (k, v) in files: ValueError: too many values to unpack (expected 2) This happens when I try to query a model- class userFiles(models.Model): user = models.ForeignKey(user, on_delete=models.CASCADE) filename = models.CharField(max_length=200, null=True) file = models.FileField(storage=fs) where the user model is imported from another app- class user(models.Model): userhandle = models.CharField(max_length=200) phone = models.CharField(max_length=10) username = models.CharField(max_length=200) password = models.CharField(max_length=200) The query is- f = userFiles.objects.get(filename=nameToBeSearched) I have tried passing the foreign-key model both as a string and as … -
Errno 2 No such file or directory: '/img' in Django admin page
I am trying to add and edit objects from my sqlite3 database in Django in the Admin page as I don't want to use the terminal for that. My app is called homepage and my model is Raport: class Raport(models.Model): titlu = models.CharField(max_length=100) descriere = models.TextField() imagine = models.FilePathField(path='/img') The error received when trying to add or change a "Raport" in the Django admin page: Request URL: http://127.0.0.1:8000/admin/homepage/raport/4/change/ Django Version: 3.2.3 Exception Type: FileNotFoundError Exception Value: [Errno 2] No such file or directory: '/img' My admin.py: from django.contrib import admin from .models import Raport @admin.register(Raport) class RaportAdmin(admin.ModelAdmin): list_display = ("titlu", "imagine") My folder structure is homepage/static/img/image.png On the site, the images from Raport are shown correctly, with no errors linked to not finding img directory. Example of working html: {% extends "base.html" %} {% load static %} {% block page_content %} <h1>{{ raport.titlu }}</h1> <div class="row"> <div class="col-md-8"> <img src="{% static raport.imagine %}" alt="" width="100%"> </div> <div class="col-md-4"> <h5>Despre raport:</h5> <p>{{ raport.descriere }}</p> </div> </div> {% endblock %} What am I missing? Thank you! -
Django convert String in Dictionary to Integer for the first 3 keys
Sorry for this newbie questions. I have a dict like this: {'id':'1', 'Book':'21', 'Member':'3', 'Title':'Chameleon vol. 2', 'Author':'Jason Bridge'} I want to convert that dict to: {'id':1, 'Book':21, 'Member':3, 'Title':'Chameleon vol. 2', 'Author':'Jason Bridge'} I need to convert only the first 3 key value to int Thanks in advance -
Going to the first page of a chapter/issue
I'm developing a webcomic using django. I'm trying to implement a feature that if you click on a comic issue or chapter cover it will redirect you to the first page of that issue/chapter. Picture for a reference. Here is what I have managed to do so far. models.py class PagePL(models.Model): create_date = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now= True) number = models.PositiveIntegerField('Page number', unique=True) status = models.IntegerField(choices=STATUS, default=0) issue = models.ForeignKey(IssuePL, on_delete=models.CASCADE, related_name='pages') chapter = models.ForeignKey(ChapterPL, on_delete=models.CASCADE) image = models.ImageField('Page image', upload_to=get_image_pl_filename, blank=True) views.py def ComicPagePL(request, slug, number): comic_page_pl = get_object_or_404(PagePL, chapter__slug=slug, number=number, status=1) context = { 'comic_page_pl': comic_page_pl, } return render(request, 'comics/comic_page_pl.html', context) urls.py urlpatterns = [ path('comics/', views.IssueListPL, name='comics_pl'), path('comics/<slug>/<number>', views.ComicPagePL, name='comic_page_pl'), ] issue list template <div class="container"> <div class="row d-flex justify-content-center"> <div class="col-md-10 mt-3"> {% if issue_pl %} {% for issue in issue_pl %} <a href="#"><img src="{{ issue.cover.url }}" class="issue-thumbnail" alt="{{ issue.title }}" title="{{ issue.title }}" /></a> {% endfor %} {% else %} <div class="container"> <div class="row"> <div class="col-md-12"> <p style="text-align:center">BRAK ZESZYTÓW</p> </div> </div> </div> {% endif %} </div> </div> Now when you go to .../chapter-slug/page-number it works. I would like to make it that if you click on issue one it goes to the first page of … -
Reverse for 'listing' with arguments '('',)' not found. 1 pattern(s) tried: ['listing/(?P<listing_id>[0-9]+)$']
the error occurs at views.py in def categoriess when i passed listingss as "listings"to return render(request, "auctions/index.html", {"listings": listingss, 'categories': 'True'}) the program runs fine when listingss=auction_listings.objects.all() but not listingss=auction_listings.objects.all().values_list('category', flat=True) urls.py from django.urls import path from . import views urlpatterns = [ path("watchlist", views.watchlist, name='watchlist'), path("category/<str:category_>", views.category, name="category"), path("comment/<int:listing_id>", views.comment, name="comment"), path("categories", views.categoriess, name="categories") ] views.py from django.contrib.auth import authenticate, login, logout from django.db import IntegrityError from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from django.contrib.auth.decorators import login_required from django import forms from .models import User, auction_listings, bids, comments from django.core.exceptions import ObjectDoesNotExist def categoriess(request): listingss = list( set(auction_listings.objects.all().values_list('category', flat=True))) return render(request, "auctions/index.html", {"listings": listingss, 'categories': 'True'}) html where I link it <li class="nav-item"> <a class="nav-link" href="{% url 'categories' %}">Categories</a> </li> auctions/index.html {% extends "auctions/layout.html" %} {% block body %} {%for listing in listings%} <div class='border'> <a href="{% url 'listing' listing.id %}"> <h3> {{listing.name}}</h3> <a/> <img src="{{listing.image_url}}" alt="{{listing.name}} photo" style="width:200px;"> {% if listing.bids.last %} <big><b>price: {{listing.bids.last}}</b></big> {% else %} <big><b>price: ${{listing.initial_price}}</b></big> {% endif %} <p>{{listing.description}}</p> <br> created {{listing.date_created}} </div> {%endfor%} {% endblock %} I've also tried setting listingss to list(set(auction_listings.objects.all().values_list('category', flat=True))) so that it return list and not QuerySet -
changeing ListView get_queryset? pagination in django
Good day everyone. I am having some trouble with the paginator in django. I have in my db all the customers info, so what I want to do is to display that info, but I made a search function in which you clic a letter button, for example you clic A and it will filter all the customers that their last name starts with the letter A, if you clic B , it will filter all customers with their last name start with B, and so on. This works correctly, the problem is that I also want to display 10 customers per page, so if I have 20 customers that their last name starts with the letter A, what you will see, will be 10 customers and a bar that says ( <<< page 1 page 2 >>> ) or something like that, and that should be solved with the paginator, I added it, but its not working. I think the problem is that maybe my get function is rewriting the get_query function from ListView perhaps? I tryed different things but I'm not sure. Here is my code in views: class ExpedientView(ListView): queryset = Portfolio.objects.filter(products__isnull=True).order_by('owner__last_name') template_name = 'dashboard-admin/portfoliorecords.html' paginate_by = … -
Django ORM converting date to datetime which is slowing down query 30x
I'm attempting query a table and filter the results by date on a datetime field: .filter(bucket__gte = start_date) where bucket is a datetimefield and start_date is a date object. However django converts the start_date to a timestamp in the raw sql ex 2020-02-01 00:00:00 when I want it just be a date ex 2020-02-01. For some reason casting bucket to a date or casting start_time to a timestamp makes the query 30x slower. When I manually write a query and compare bucket directly to a date ex bucket >= '2020-02-01' the query is blazing fast. How can I get the django orm to do this? -
403 error when sending POST request using ajax (csrf token set)
Django==3.2.3 django-cors-headers==3.7.0 views class LoginView(FormView): form_class = LoginForm template_name = "users/login.html" def form_valid(self, form): ... super().post(self.request) return template <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Login</button> </form> js $.ajax({ type: 'POST', url: "http://localhost:8000/users/login/", processData: false, contentType: false, cache: false, beforeSend: function (xhr) { xhr.setRequestHeader('X-CSRFToken', $('[name=csrfmiddlewaretoken]').val()); }, data: { ... }, }) I look at the network - the token in the header is the same as in the form. Also installed corsheaders INSTALLED_APPS = [ .... "corsheaders", .... ] MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", .... ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_WHITELIST = ["http://127.0.0.1:8000"] CORS_ALLOW_METHODS = ["*"] CORS_ALLOW_HEADERS = ["*"] -
How can I solve Django Rest Framework ParseError in PATCH method?
I am writing an API with Django RF and I am trying to write the PATCH method with update method of the ModelViewSet. Then I am trying it out using the API View in my browser by passing a simple update to the field name. However, I keep getting the ParseError meaning my request.data is malformed. Below you can see that I am actually passing a JSON-like structure to the request. And when setting up a breakpoint in the update method, my request.data looks like {'name': 'Some Name'} (but I guess the single quotes are just because I'm in the breakpoint. Any ideas on what am I missing here? rest_framework.exceptions.ParseError: JSON parse error - Expecting property name enclosed in double quotes: line 3 column 1 (char 29) def update(self, request, pk=None, **kwargs): cm = get_object_or_404(self.get_queryset(), pk=pk) obj = self.serializer_class(cm, data=request.data, partial=True) obj.is_valid(raise_exception=True) obj.update(cm, obj.validated_data) return Response(obj.data) -
Django on the production server (nginx + gunicorn), after changes in the files, sometimes the changes are displayed, sometimes they are not displayed
On the production server (nginx + gunicorn), after changes in the files, sometimes the changes are displayed, sometimes they are not displayed. After restarting the server, everything works correctly. I thought it might be related to caches and tried different options (disabling caches, cleaning caches, etc.), but the problem remained. Also tried deleting the __pycache__ folders in different project directories, but that didn't help either -
Django- Can only concatenate str (not "ManyRelatedManager") to str
I am trying to save my model. But when I try to save my model I throws the following error TypeError at /admin/user/teacher/add/ can only concatenate str (not "ManyRelatedManager") to str My models.py file looks like this class Class(models.Model): Class = models.CharField(max_length=50) section_choices = (('A','A'),('B','B'),('C','C'),('D','D'),('E','E')) Section = models.CharField(max_length=100, choices=section_choices) def __str__(self): return self.Class + "," + self.Section class Subject(models.Model): subject = models.CharField(max_length=100) def __str__(self): return self.subject class Teacher(models.Model): User = models.ForeignKey(User, on_delete=models.CASCADE) Subject = models.ManyToManyField(Subject) Name = models.CharField(max_length=50) Profile = models.ImageField(upload_to = upload_teacher_profile_to, default = 'defaults/teacher_profile.png') Class = models.ManyToManyField(Class) Number = models.IntegerField(blank=True) is_banned = models.BooleanField(default=False) def __str__(self): return self.Name + "of" + self.Class -
I want to write to a Django model from a standalone python script that generates a CSV file but seem to be in the wrong environment
I have a standalone python script that I run regularly to generate a CSV file from external data. I would like if this script could also update a corresponding model in a Django app running in a virtualenv. I have added the following lines to the script from django.conf import settings settings.configure() from app.models import BER_assessors The model is BER_assessors and is defined in the model.py file in the app directory at the root of the django application. The script is also at the root of the django application ( the one that contains the app/authentication/core/env/media etc. folders ) When I run my script I get the error message "django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet." The Django application itself runs fine. I think there is a question of context or environment, i.e. I am not "in" the app and as such cannot write to the models etc. How can I correct this ? Best regards / Colm -
MySQL command line client is Not installed
I have installed msi version of mysql from this link. https://dev.mysql.com/downloads/windows/installer/8.0.html I have installed all the below. I need MySQL command line client but it is not installed and cannot be found either. What should i do, i have tried other methods but they are not working too. I need it for a django project. -
Django Rest Framework ModelSerializer giving error for primary field
I am working on a project where I have created custom user by extending AbstractBaseUser and PermissionMixin, the model class is following. class User(AbstractBaseUser, PermissionsMixin): phone_number = models.CharField( primary_key=True, validators=[MinLengthValidator(10)], max_length=10 ) password = models.CharField( null=False, blank=False, validators=[MinLengthValidator(8)], max_length=225 ) date_joined = models.DateTimeField(null=False, blank=False, default=timezone.now) last_login = models.DateTimeField(null=True, blank=True) last_logout = models.DateTimeField(null=True, blank=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) USERNAME_FIELD = "phone_number" REQUIRED_FIELDS = [] objects = CustomUserManager() @staticmethod def hash_password(sender, instance, *args, **kwargs): if not instance.is_staff and not instance.is_superuser: instance.set_password(instance.password) def get_token(self): return Token.objects.get(user=self) def __str__(self): return self.phone_number # signals for Model User pre_save.connect(User.hash_password, sender=User) And the following ModelSerializer corresponding to it. class UserLoginSerializer(serializers.ModelSerializer): class Meta: model = User fields = ["phone_number", "password"] Now if If I pass the post data as:- { "phone_number":8888888888, "password":12345678 } What I am getting: The serializer.is_valid() is returning False. if I am doing serializer.is_valid(raise_exception=True) then I am getting response as: { "phone_number": [ "user with this phone number already exists." ] } My Doubts are: I know that 8888888888 is already in the DataBase but I still want to access it using serializer.validated_data.get('phone_number', None) I also want to know the reason, why this is happening, it is acting like as if I am … -
Serializer field values based on request
In Haystack, I have the following view set: class ArtistSearchViewSet(HaystackViewSet): index_models = (Artist,) serializer_class = ArtistSearchResultSerializer pagination_class = LimitOffsetPagination This is the serializer: class ArtistSearchResultSerializer(HaystackSerializer): class Meta: index_classes = (ArtistIndex,) fields = ( "id", "name", ) search_fields = ("text",) For each returned search result I want to add a boolean field that indicates whether the corresponding artist has been starred by the current user or not. How would you do that? -
how do i count up when there is a unique value but when there is a duplicate value the count remains the same
Question_id Question part_model_ans part_total_marks answer_mark number 16 What's a potato It's a vegetable 1 5 1 16 What's a potato It's a seed 2 5 1 16 4+4 8 2 5 2 17 What's a dog It's a mammal 1 5 1 17 What's a dog It's a pet 2 5 1 17 8+8 16 2 5 2 SELECT Q.question_id,Q.question, PMA.part_model_ans,QP.part_total_marks,MA.answer_mark DENSE_RANK() over(Partition by QP.question_id) as number FROM "QUESTIONS" Q LEFT JOIN "QUESTIONS_PART" QP ON QP.question_id = Q.question_id LEFT join "PART_MODEL_ANSWER" PMA ON PMA.part_id = QP.part_id LEFT join "MODEL_ANSWER" MA ON MA.question_id = Q.question_id ORDER BY Q.question_id ASC What i would like to do is increase the count when there is a unique question but when there is a duplicate question the count remains the same, the count also resets after every question, i tried using dense rank but it makes the value for all in the column number as 1 -
Inter-app model import lead to RuntimeError doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
Context I need to add an app to an existing django 2.2 project. The existing app is called rest. What I am trying to achieve is to interact with models defined in rest from cluster_service (the new app) emc2_backend/ project/ rest/ cluster_service/ rest/models.py class Fichier(models.Model): checksum = models.CharField(primary_key=True, max_length=64, validators=[ RegexValidator(regex="[a-f0-9]{64}")], help_text="SHA 256 du fichier en guise de clef primaire") nom = models.CharField(max_length=100) chemin = models.CharField(max_length=255) class Meta: unique_together = (('nom', 'chemin'),) abstract = True class InputFile(Fichier): def __str__(self): return "{}".format(self.nom) class FichierPy(Fichier): forked_from = models.ForeignKey( "self", on_delete=models.DO_NOTHING, blank=True, null=True) input_files = models.ManyToManyField(InputFile, blank=True) def __str__(self): return "{}".format(self.nom) All apps have been properly defined in INSTALLED_APPS (to my knowledge) Issue I have no problem importing various models from rest using from emc2_backend.rest.models import Site, Etude However, when it comes to FichierPy InputFile, I get the following error while running my tests: ERROR: cluster_service.tests (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: cluster_service.tests Traceback (most recent call last): File "c:\users\zarebskid\appdata\local\programs\python\python36\lib\unittest\loader.py", line 428, in _find_test_path module = self._get_module_from_name(name) File "c:\users\zarebskid\appdata\local\programs\python\python36\lib\unittest\loader.py", line 369, in _get_module_from_name __import__(name) File "C:\Users\zarebskid\Documents\projects\emc2-backend\emc2_backend\cluster_service\tests.py", line 1, in <module> from emc2_backend.rest.models import Calcul File "C:\Users\zarebskid\Documents\projects\emc2-backend\emc2_backend\rest\models.py", line 31, in <module> class InputFile(Fichier): File "C:\Users\zarebskid\AppData\Local\pypoetry\Cache\virtualenvs\emc2-backend-Ay5lD4CN-py3.6\lib\site-packages\django\db\models\base.py", line 111, in __new__ "INSTALLED_APPS." % (module, … -
Django SocialAuth / Django AllAuth: How to save user details into user profile upon login with Facebook if Account does not exist?
Django SocialAuth / Django AllAuth: How to save user details into user profile upon login with Facebook if Account does not exist? I have set up Django SocialAuth and AllAuth into my project for login using Facebook. This is my Profile model. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=300, blank=True) image_url = models.URLField(max_length=200) email = models.EmailField(max_length=254) profile_url = models.URLField(max_length=200) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) def __str__(self): return self.user How do I get these details when a new user logs in and save them to profile model? Thank you for your time. -
How to use timezones in Django Forms
timezones in Django... I am not sure why this is so difficult, but I am stumped. my settings.py timezone settings look like: LANGUAGE_CODE = 'en-us' TIME_ZONE = 'America/Toronto' USE_I18N = True USE_L10N = False USE_TZ = True I am in Winnipeg, my server is hosted in Toronto. My users can be anywhere. I have a modelfield for each user that is t_zone = models.CharField(max_length=50, default = "America/Winnipeg",) which users can change themselves. with respect to this model: class Build(models.Model): PSScustomer = models.ForeignKey(Customer, on_delete=models.CASCADE) buildStart = models.DateTimeField(null=True, blank=True) ... I create a new entry in the DB using a view like: views.py ... now = timezone.now() newBuild = Build(author=machine, PSScustomer = userCustomer, buildStart = now, status = "building", addedBy = (request.user.first_name + ' ' +request.user.last_name), ... ) newBuild.save() buildStart is saved to the database in UTC, and everything is working as expected. When I change a user's timezone in a view with timezone.activate(pytz.timezone(self.request.user.t_zone)) it will display the UTC time in their respective timezone. All is good (I think) so far. Here is where things go sideways. When I want a user to change buildStart in a form, I can't seem to get the form to save the date to the DB …