Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django static files are not accesible
I have created a django project and tried to use an HTML template; however, I get an error while accessing files in static folder. Here is my configuration: #BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' STATICFILES_DIR = [ os.path.join(BASE_DIR,'static'), ] STATIC_ROOT = os.path.join(BASE_DIR,'assets') I have added static variable at the top of the HTML file as: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>Travello</title> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="description" content="Travello template project"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="{% static 'styles/bootstrap4/bootstrap.min.css' %}"> <link href="{% static 'plugins/font-awesome-4.7.0/css/font-awesome.min.css' %}" rel="stylesheet" type="text/css"> <link rel="stylesheet" type="text/css" href="{% static 'plugins/OwlCarousel2-2.2.1/owl.carousel.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'plugins/OwlCarousel2-2.2.1/owl.theme.default.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'plugins/OwlCarousel2-2.2.1/animate.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'styles/main_styles.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'styles/responsive.css' %}"> .....(cont'd) The following is my folder configuration: -my_project --assets --my_project --static --templates --travello My problem is that: I cannot access images in static folder from browser, that is, when I type http://127.0.0.1:8000/static/images/about_1.jpg, I get an error like Page not found (404) When I type http://127.0.0.1:8000 in order to see the index.html main page, I get the page with lots of errors saying Failed to load resource: the server responded with a status … -
Django Messages framework for default login system (contrib.auth)
I am using Django's default authentication system and I was wondering if there is a way to use Django's messages framework with it to display error messages such as incorrect login details etc. All the posts I have searched through here suggest to override the login system, but is there any easier way to do it? I already have a form which is subclassing the AuthenticationForm to use form_valid method, is there anything I could do there? Any help would be really appreciated. -
Can't find django-html in "Select Language Mode" in VS Code
I'm trying to set django-html as the language for my *.html files so that I can use the snippets for python template literals but I can't find it anywhere. When I look for django html by clicking on "Select Language Mode" in the lower right corner I don't get any result: Here's is a screenshot of the search, Another screenshot However, I've seen in a video that this should be possible: screenshot with the search from the video I'm using VS Code 1.44.1 and Windows 10 -
Update django-dash dashboard with new dataframe data in a Django app
Our Aim We're creating a time series plot in a Django app using dash/plotly. The data being plotted is read from a pandas dataframe which is first pre-processed written to a file, and then sent to the next page via POST request for the interactive dashboard. On updating the dataframe the new plot should be plotted on the dashboard. Problem Even though the data is changed the dashboard doesn't updates. It still shows the plot for the previous dataframe saved in the file. Until or unless the django server is restarted it doesn't updates. dcc.interval() doesn't do the trick, it also requires the server to be restarted even though you can see the dash app reply in the console log plus it removes the zoom in capability for a graph since, it refreshes the plot. The Django version in use is 2.2.9 Here is the django-dash app code: import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output,State import plotly.graph_objs as go from django_plotly_dash import DjangoDash import pandas as pd import dash_table from datetime import datetime app = DjangoDash('chalao') selected_df=pd.read_pickle(r'static/selected_df.pkl') actual_df=pd.read_pickle(r'static/actual_prediction.pkl') datatable_df=actual_df datatable_df.reset_index(inplace=True) datatable_df['START_DATETIME'] = datatable_df['START_DATETIME'].astype(str) datatable_df['Transaction'] = datatable_df['Transaction'].round(decimals=-3) datatable_df['Prediction'] = datatable_df['Prediction'] + 500 datatable_df['Prediction'] = datatable_df['Prediction'].round(decimals=-3) … -
Show data from API on Django tempalte
I'm trying to show the fetched data on an API to the Django template. Here's what I've tried on home.html <h1>Title: {{data.title}}</h1> Here's my views.py which gets the data from services.py class IndexData(TemplateView): def get(self, request): article_data = services.get_data() return render(request, 'pages/home.html', article_data) Here's the services.py def get_data(title, url, description, body, datePublished): url = 'https://contextualwebsearch-websearch-v1.p.rapidapi.com/api/Search/WebSearchAPI' params = {"autoCorrect": "true", "pageNumber": "1", "pageSize": "10", "q": "police", "safeSearch": "true" } headers = {...} r = requests.get(url, headers=headers, params=params) data = r.json() article_data = {'data': data['value']} return article_data The returned json is { "_type":"all", "didUMean":"", "totalCount":2923, "relatedSearch":[ "coronavirus", "new york", "post", "getty", "times", "china", "council", "shares", "americans", "pandemics", "prime", "19 crisis" ], "value":[ { "title":"COVID-19 And The Failure Of Populism", "url":"https://www.forbes.com/sites/riskmap/2020/04/02/covid-19-and-the-failure-of-populism/", "description":"Populist presidents, reliant on their need to constantly convey positive messaging that bolsters their support, have struggled to take the decisive, forward-looking action that the coronavirus crisis demands.", "body":").\nHow will the pandemic play out in these countries?\nSteering countries through the pandemic and an eventual recovery will then be the responsibility of leaders who will have lost credibility, as well as the veneer of their all is well message. The narrative that allowed people in certain countries to latch on to something they … -
Django Login: I'm entering the correct credentials but can't log in
I have a problem while trying to log in with Django. I'm putting the right username and password but I'm still getting the error in Postman: { "non_field_errors": [ "Incorrect username or password." ] } Here is my serializer: from django.contrib.auth import authenticate from rest_framework import serializers from ..models.model_user import * class LoginSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() def validate(self, attrs): user = authenticate(username=attrs['username'], password=attrs['password']) if not user: raise serializers.ValidationError('Incorrect username or password.') if not user.is_active: raise serializers.ValidationError('User is disabled.') return {'user': user} My views: from django.conf import settings from django.contrib.auth import login, logout from rest_framework import views, generics, response, permissions, authentication from ..serializers.serializers_user import * from ..serializers.serializers_login import * class LoginView(views.APIView): permission_classes = (permissions.AllowAny,) def post(self, request): serializer = LoginSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] login(request, user) return response.Response(UserDetailsSerializer(user).data) class LogoutView(views.APIView): def post(self, request): logout(request) return response.Response() My urls: from django.contrib import admin from django.urls import include, path from django.conf.urls import url from django.conf import settings from django.conf.urls.static import static from rest_framework import routers from ea.views import * from rest_framework_simplejwt.views import ( TokenObtainPairView, TokenRefreshView, TokenVerifyView, ) router = routers.DefaultRouter() router.register(r'users', UserViewSet) urlpatterns = [ path('', include('eao.urls')), path(r'', include(router.urls)), path('admin/', admin.site.urls), path(r'login/', LoginView.as_view(), name='user-login'), path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), … -
DRF Form Rendered in SPA
I'm trying to wrap my head around the workings of DRF and I just cannot understand how to achieve this or even where to start with understanding the flow of things. I'm trying to render an HTML form out of DRF to an SPA or static HTML page with JQuery. I have a page /page/ I have a serializer: `class StudentSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Student fields = ('firstName', 'lastName')` Now I need to have a form rendered that has the initial data and allows to POST/PUT. I can do this very successfully with an APIView and HTMLrenderer, but I’m trying to see if I can have multiple rendered forms on a single page without a single APIView page. If the general approach is to hand-code the forms on a SPA front-end then that’s great, I just want to know if that’s the required approach. -
Cloud Build env variables not passed to Django app on GAE
I have a Django app running on Google AppEngine Standard environment. I've set up a cloud build trigger from my master branch in Github to run the following steps: steps: - name: 'python:3.7' entrypoint: python3 args: ['-m', 'pip', 'install', '--target', '.', '--requirement', 'requirements.txt'] - name: 'python:3.7' entrypoint: python3 args: ['./manage.py', 'collectstatic', '--noinput'] - name: 'gcr.io/cloud-builders/gcloud' args: ['app', 'deploy', 'app.yaml'] env: - 'SHORT_SHA=$SHORT_SHA' - 'TAG_NAME=$TAG_NAME' I can see under the Execution Details tab on Cloud Build that the variables were actually set. The problem is, SHORT_SHA and TAG_NAME aren't accessible from my Django app (followed instructions at https://cloud.google.com/cloud-build/docs/configuring-builds/substitute-variable-values#using_user-defined_substitutions)! But if I set them in my app.yaml file with hardcoded values under env_variables, then my Django app can access those hardcoded values (and the values set in my build don't overwrite those hardcoded in app.yaml). Why is this? Am I accessing them/setting them incorrectly? Should I be setting them in app.yaml somehow? I even printed the whole os.environ dictionary in one of my views to see if they were just there with different names or something, but they're not present in there. -
Error when serializing foreign key object with django-rest-framework-gis to geojson
I am trying to serialize into geojson a model with a foreign key that has a geometry field. I am using the django-rest-framework-gis. I am using django 2.2 I'm really stuck on this and none of the other related answers on stackoverflow work for me. e.g. I have tried versions of this: How can I flatten a foreignkey object with django-rest-framework-(gis) Set serializer geo_field as PointField from another model - Django I would be very grateful for help as been literally stuck on this for days. Thank you, kind people. The problem is I get this error: Expected a Response, HttpResponse or HttpStreamingResponse to be returned from the view, but received a <class 'statements.models.Response'> Models: from django.contrib.gis.db import models from django.contrib.gis.geos import Point class Hexgrid_10km2(models.Model): lng = models.FloatField() lat = models.FloatField() polygon = models.MultiPolygonField(srid=4326) centroid = models.PointField(default=Point(0,0), srid=4326) def __str__(self): return f'lng: { self.lng } lat: {self.lat }' class Response(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) statement = models.ForeignKey(Statement, on_delete=models.CASCADE) hexgrid_10km2 = models.ForeignKey(Hexgrid_10km2, on_delete=models.CASCADE, null=True, blank=True) @property def polygon(self): return self.hexgrid_10km2.polygon Views class ResponseHeatmapAPIView(APIView): #ReadOnly def get(self, request, pk): final = Response.objects.all() serializer = ResponseHeatmapSerializer(final, many=True) return Response(serializer.data) Serializers class ResponseHeatmapSerializer(GeoFeatureModelSerializer): """ A class to serialize hex polygons as GeoJSON compatible data … -
Django: Limit choices in a models.Charfield by PrimaryKey
Another question from me tonight and I hope I can explain it adequately: I got three classes in my "models.py": class Customer(models.Model): full_name = models.CharField(max_length=100, null=True, unique=True) short_name = models.CharField(max_length=8, null=True, unique=True) class Project(models.Model): customer = models.ForeignKey(Customer, null=False, on_delete=models.CASCADE) name = models.CharField(max_length=255, null=True, unique=True) ... class Entry(models.Model): user = models.ForeignKey(User, null=True, blank=False, on_delete=models.CASCADE) customer = models.ForeignKey(Customer, null=True, blank=False, on_delete=models.CASCADE) project = models.ForeignKey(Project, null=True, blank=False, on_delete=models.CASCADE) date = models.DateField() shortText = models.CharField(max_length=100, null=False, blank=False) ... Note: One Customer can have multiple Projects. On one of my sites there's a table with buttons beside each "Customer". The plan is, that it should lead me to another page, were the user can write and save his "Entry". Right now, the PrimaryKey inside the Button/Link contains the ID of the "Customer". My question is: is it possible to limit the choices of the "Project" (inside a Drop-Down-Menu) to the "Customer" that has been clicked on? And is creating a ModelForm the right thing to do? Thanks to all of you and a good night! -
How to get return of InLineKeyboardButton with python-telegram-bot
I am working with python-telegram-bot building a menu system. I created a Django project, as shown below, using Webhook to connect to Telegram. I have the button menu built, according to the codes below, but I'm not sure how to interact with the contact when he clicks the button. Can you help me with this? view.py import json from django.http.response import HttpResponse from django.views.decorators.csrf import csrf_exempt from core.message import proccess @csrf_exempt def event(request): json_telegram = json.loads(request.body) proccess(request, json_telegram) return HttpResponse() messages.py import telegram from bot_webhook.settings import TOKEN from telegram import InlineKeyboardMarkup, InlineKeyboardButton bot = telegram.Bot(token=TOKEN) def proccess(request, json_telegram): msg_options(json_telegram) def msg_options(json_telegram): chat_id = json_telegram['message']['from']['id'] first_name = json_telegram['message']['from']['first_name'] last_name = json_telegram['message']['from']['last_name'] button_list = [] button_list.append(InlineKeyboardButton('Button One', callback_data='query_one')) button_list.append(InlineKeyboardButton('Button two', callback_data='query_two')) reply_markup = InlineKeyboardMarkup(build_menu(button_list, n_cols=2)) bot.send_message(text='Hello {0} {1}!\nI have this options:'.format(first_name, last_name), chat_id=chat_id, reply_markup=reply_markup) def build_menu(buttons, n_cols, header_buttons=None, footer_buttons=None): menu = [buttons[i:i + n_cols] for i in range(0, len(buttons), n_cols)] if header_buttons: menu.insert(0, [header_buttons]) if footer_buttons: menu.append([footer_buttons]) return menu -
django.db.utils.ProgrammingError: column "reviewee_id" of relation "Reviews_review" already exists
I keep getting this error when I try to deploy my django app to heroku. Locally, my app works but it uses a sqlite database whereas on heroku I am using postgres. I have tried dropping the database and restarting it as well as faking the migrations but no luck. Any advice? Here is the traceback: Operations to perform: Synchronize unmigrated apps: allauth, django_extensions, google, humanize, messages, staticfiles Apply all migrations: Reviews, Sessions, Users, account, admin, auth, contenttypes, sessions, sites, socialaccount Synchronizing apps without migrations: Creating tables... Running deferred SQL... Running migrations: Applying Reviews.0002_auto_20200415_1350...Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) psycopg2.errors.DuplicateColumn: column "reviewee_id" of relation "Reviews_review" already exists The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 233, in handle fake_initial=fake_initial, File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/executor.py", line 117, in migrate … -
Filter options in one to one field django admin
I have this 2 models from django.db import models def get_upload_path(instance, filename): return '{0}/{1}'.format(instance.imovel.id, filename) # Create your models here. class Imovel(models.Model): nome = models.CharField(max_length=50) descricao = models.CharField(max_length=800) area = models.IntegerField() quartos = models.SmallIntegerField(null=True, blank=True) banheiros = models.SmallIntegerField() disponivel_aluguel = models.BooleanField() disponivel_venda = models.BooleanField() valor_aluguel = models.DecimalField(max_digits=15, decimal_places=2) valor_venda = models.DecimalField(max_digits=15, decimal_places=2) valor_condominio = models.DecimalField(max_digits=15, decimal_places=2) valor_iptu = models.DecimalField(max_digits=15, decimal_places=2) capa = models.OneToOneField('ImagemImovel', related_name='capa', on_delete=models.DO_NOTHING, null=True, blank=True) def __str__(self): return self.nome class Meta: db_table = 'imovel' class ImagemImovel(models.Model): imovel = models.ForeignKey(Imovel, related_name='imagens', on_delete=models.CASCADE) nomeImagem = models.CharField(max_length=20) imagem = models.ImageField(upload_to=get_upload_path) def __str__(self): return self.nomeImagem class Meta: db_table = 'imagemImovel' I have houses and it's pictures and a field named 'capa' to say which one is the main picture. The problem is when I add a house through django admin, save and come back to choose the main one it let me choose images from other houses. How could I filter it to just show images that are related to this specific house? My django admin file from django.contrib import admin from .models import ImagemImovel, Imovel # Register your models here. class ImagemImovelAdmin(admin.TabularInline): model = ImagemImovel class ImovelAdmin(admin.ModelAdmin): inlines = (ImagemImovelAdmin, ) admin.site.register(Imovel, ImovelAdmin) -
How to make a "SELECT" of a model in django?
I am new to django and I am trying to make a django view that will bring me certain values from two models, this would be accomplished by doing a join if done directly in sql. What I intend to do with the obtained data is return it as JSON and use this json in an html page. I just don't know how to structure or if there is any way to get the data like sql. Model device class device(models.Model): device_name = models.CharField(max_length=50, unique=True, help_text='Station Name', validators=[validate_slug]) parent_area_id = models.ForeignKey('area', on_delete=models.CASCADE, null=True, help_text='Parent Area') f2cuid = models.CharField(max_length=100, unique=True, validators=[validate_slug]) ip_address = models.GenericIPAddressField(protocol='both', unpack_ipv4='True', default='127.0.0.1', blank=False, null=False) tower_ip_address = models.GenericIPAddressField(protocol='both', unpack_ipv4='True', default='127.0.0.1', blank=True, null=True) layered_tower = models.BooleanField(default=False, blank=True, help_text='Check if tower is multilayer') layer = models.CharField(max_length=1, unique=False, null=True, default=None, help_text='Layer', choices=layer_choices) target_oee = models.DecimalField(validators=[MinValueValidator(0), MaxValueValidator(100)], help_text='OEE Target', decimal_places=2, max_digits=6, default=0) target_availability = models.DecimalField(validators=[MinValueValidator(0), MaxValueValidator(100)], help_text='Availability Target', decimal_places=2, max_digits=6, default=0) target_performance = models.DecimalField(validators=[MinValueValidator(0), MaxValueValidator(100)], help_text='Performance Target', decimal_places=2, max_digits=6, default=0) target_quality = models.DecimalField(validators=[MinValueValidator(0), MaxValueValidator(100)], help_text='Quality Target', decimal_places=2, max_digits=6, default=0) Model notification_radio class notification_radio(models.Model): device_id = models.ForeignKey('device', on_delete=models.CASCADE, null=False) event_id = models.ForeignKey('event', on_delete=models.CASCADE, null=False) to_address = models.CharField(null=False, blank=False, max_length=100) message = models.CharField(null=False, blank=False, max_length=100, default='ANDON ALERT') notification_type = models.CharField(null=False, blank=False, choices=notification_type_choices, max_length=100) notification_id … -
How to distinguish uploaded PDFs to extract data through regular expression in python Django
Here I will upload pdfs and it will convert it into text. After converting into text I use a regular expression to get some specific data from the pdfs. Now there are various kinds of pdfs and I have to use different types of regular expression for each pdf. but I am facing problem to distinguish the pdf in the if conditions just like below. What I have done here is only going to the first if condition. how can I pass the pdf into its desire place I meant into the specific regular expression I have created. Or is there any other ways to do that mainly I just wanted to build up pdf extractor for some specific datas. ''' def upload(request): if request.method == 'POST': form = PoForm(request.POST, request.FILES) if form.is_valid(): form.save() file_name = form.cleaned_data['pdf'].name print(form.cleaned_data['pdf'].name) text=convert_pdf_to_txt(file_name) text=text.replace('\n','') print(text) path = 'media/pos/pdfs/{}'.format(file_name) print(path) basename = os.path.basename(path) if file_name == basename: print(basename) print(file_name) regex_Quantity ='Quantity:\s?([0-9]+)' regex_style_no ='No:\s\s\s\s?([0-9]+)' elif file_name == basename: print("print2") print(basename) regex_Quantity = 'Total Units\s?([0-9\,]+)' regex_style_no = 'Number:\s?([0-9]+)' elif file_name == basename: print(basename) print("print3") regex_Quantity ='PO\s?([0-9\.]+)' regex_style_no = 'Article-No.:\s?([0-9]+)' ''' -
Django Storages failing to upload static files in nginx and docker configuration
I am unable to get NGINX (which I think is the culprit) to work with django-storages when a media file is uploaded. It will receive static files from my S3 bucket, but it just refuses to post to it. Whenever an image is uploaded to the site I will get a NGINX 500 Internal Server Error. It works with the default django runserver application and I am unsure what is causing this to fail. This is all run in a docker container. Here is what I have: Settings, showing how storages is set-up AWS_STORAGE_BUCKET_NAME = 'sitename-staticfiles' AWS_S3_REGION_NAME = 'us-east-1' AWS_ACCESS_KEY_ID= 'access_key' AWS_SECRET_ACCESS_KEY= 'secret_key' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_QUERYSTRING_AUTH = False STATIC_URL = '/static/' MEDIA_URL = '/media/' AWS_DEFAULT_ACL = None STATICFILES_LOCATION = 'static' STATICFILES_STORAGE = 'custom_storages.StaticStorage' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static', 'sitename')] MEDIAFILES_LOCATION = 'media' DEFAULT_FILE_STORAGE = 'custom_storages.MediaStorage' custom_storages.py from django.conf import settings from storages.backends.s3boto3 import S3Boto3Storage class StaticStorage(S3Boto3Storage): location = settings.STATICFILES_LOCATION class MediaStorage(S3Boto3Storage): location = settings.MEDIAFILES_LOCATION nginx.conf user nobody; worker_processes auto; pid /run/nginx.pid; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; # server_tokens off; # server_names_hash_bucket_size 64; # server_name_in_redirect off; include /etc/nginx/mime.types; default_type … -
Wrapping django queryset update/delete in a transaction
I want to wrap all update/delete calls in a transaction, since there are some post_save signal handlers that need to be done atomically. For a specific model, I can override the save function like so: class ModelA: @transaction.atomic def save(...): super().save(...) how do I apply the same for all .update() querysets involving ModelA? -
Only messages from request.user showing, not from other users
so I'm trying to display messages between two users, however only the messages sent by request.user are currently showing up. So originally, I created an inbox view named messages that displayed current conversations the current user has with other users via the Conversation model which has a manyTOmany field and I created an InstantMessage model which has a foreign key to my conversation model. Anyways, I got the conversations to display, but I am having trouble getting the messages sent by other user's to display for my user. I am not sure if the problem is within my link that sends me to view the contents of the message or within the logic. views.py/message and messages #displays contents of conversation via messages def message(request, profile_id): messages = InstantMessage.objects.filter(Q(sender_id=request.user)).\ values('sender_id','receiver_id', 'message', 'date', ).\ order_by('date',) conversations = Conversation.objects.filter(members=request.user) context = {'messages' : messages, 'conversations':conversations} return render(request, 'dating_app/message.html', context) #displays current conversations def messages(request,profile_id): profile = get_object_or_404(Profile,id=profile_id) conversations = Conversation.objects.filter( members=request.user ).annotate( last_message=Max('instantmessage__date') ).prefetch_related('members').order_by( '-last_message' ) return render(request, 'dating_app/messages.html', {'messages': messages,'profile': profile, 'conversations':conversations,}) messages.html displays conversations and contains my link to content of message {% for conversation in conversations%} <li class="text-right list-group-item"> {% for member in conversation.members.all %}{% if member != user %} … -
bulk insert but ignore conflicts or missing related entity
I have an ingest worker that pulls some logs from datastore (5k+/- every minute) and inserts a slimmer version of them into a posgres instance. The values inside prosgres have about 5-6 relations to other objects. From datastore I get ids of related objects and I insert based on them in order to avoid thousands of queries to the database to verify the existance of each relation. At the end of it all I do a bulk create: sourceiter = iter(objects) while True: batch = list(islice(sourceiter, batch_size)) if not batch: break QueryLogs.objects.bulk_create(batch, batch_size, ignore_conflicts=True) I have ignore_conflicts in place in case of duplicates but what can I do in case of missing relations? Some of those relations may go missing, being deleted by other tasks, users or admins. Right now the whole block stops and throws an exception and I miss all logs instead of just a few. Any recommendations? -
Can't get the detail view of a post in a social network project
I am building a simple social network in django. In the "home" of my social, I have the list of all posts published by all users, with author and publishing date. The publishing date have a link to a url that should return the detail view a specific post published by a user. However, as I click on it, it shows me the list of all posts published by its author (this also works when I click on the author link of the post). So the problem is that both www.mysocial.com/posts/by/ciccio/7/ and www.mysocial.com/posts/by/ciccio/ takes me to the same page, that is ciccio's posts list. I am going to show urls.py, views.py and models.py that all are contained in my "posts" app (myproject > posts) Here is my urls.py # shows all user posts url(r'by/(?P<username>[-\w]+)', views.UserPosts.as_view(), name='for_user'), # shows specific post url(r'by/(?P<username>[-\w]+)/(?P<pk>\d+)/$', views.PostDetail.as_view(), name='single'), my views.py class PostList(SelectRelatedMixin, generic.ListView): model = Post select_related = ('user', 'group') class UserPosts(generic.ListView): model = models.Post template_name = 'posts/user_post_list.html' def get_queryset(self): try: #prende i post fatti dal'username che è lo stesso di quello che è loggato per guardarli self.post_user = User.objects.prefetch_related('posts').get(username__iexact=self.kwargs.get('username')) except User.DoesNotExist: raise Http404 else: return self.post_user.posts.all() def get_context_data(self,**kwargs): context = super().get_context_data(**kwargs) context['post_user'] = self.post_user … -
How to make instance feature in the function
I want to add course.tutor.add(self.request.user) to the function below but don't know how to do that, because i don't know how to do without slug and so on class FormWizardView(SessionWizardView): template_name = 'courses/create_course.html' file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT,'courses')) form_list = (CourseForm1,CourseForm2,CourseForm3,CourseForm4) def done(self, form_list, **kwargs): instance = Course() for form in form_list: for field, value in form.cleaned_data.items(): setattr(instance, field, value) instance.save() return redirect('courses:my_courses',username=self.request.user.username) -
How do I fix django html form sending action to link
Ok so i know the traditional way of handling forms in django but was experimenting something different this time. So I don't know what exactly is going wrong here but its just not working!!! Here is how the error looks error So what I'm tryna do is just a simple login and register system. There is one good thing and one bad thing which I partially get. Login system doesn't work on both chrome and safari, btw I only use chrome was just experimenting with safari Registration system works on safari but bad luck on chrome I have been tryna fix this from the past 3-4 hours, can any pro help me????? here's the code views.py from django.shortcuts import render from django.shortcuts import redirect from django.http import HttpResponse, HttpResponseRedirect from django.contrib.auth import authenticate from django.contrib.auth.models import auth from django.contrib import messages from django.urls import reverse from .forms import * from django.core.cache import cache def register(request): cache.clear() if request.method == 'POST': FirstName = request.POST['FirstName'] LastName = request.POST['LastName'] DP = request.POST.get('DP', False) Username = request.POST['Username'] Email = request.POST['Email'] password = request.POST['password'] if User.objects.filter(Username=Username).exists(): print('Username.taken') elif User.objects.filter(Email=Email).exists(): print('Your Email already exists') else: user = User.objects.create(password=password, Email=Email, Username=Username, DP=DP, LastName=LastName, FirstName=FirstName) user.save() print('Bangaya!!!') return … -
Python __init__.py so that package can be imported without 'from' keyword
Lets say my package looks like this: mydir/a/__init__.py mydir/a/b.py mydir/a/c.py This may be a dumb question, but I haven't worked with __init__.py before. I have a package which has a few .py files in the same directory as __init__.py. Everything involving __init__.py I have tried so far results in imports needing to look like: from a import b from a import c or import a.b import a.c or by using the __all__ variable in __init__.py: from a import * how can I setup the __init__.py so that I can import all packages within 'a' using: import a -
Problem with nested Dict in Python (KeyError)
I try to append data to a complicated Dictionary in Python. The Structure is given, i cannot change this. Example Code: class AutoVivification(dict): def __getitem__(self, item): try: return dict.__getitem__(self, item) except KeyError: value = self[item] = type(self)() return value class Command(BaseCommand): def vorgang(self, lead): payload = AutoVivification() payload['antragsteller1'] = { 'personendaten': { 'anrede': lead.salutation, 'vorname': lead.firstname, 'nachname': lead.lastname, 'email': lead.email, 'telefonPrivat': lead.phone, 'geburtsdatum': str(lead.birthdate) }, 'wohnsituation': { 'anschrift': { 'strasse': lead.address, 'plz': lead.zip, 'ort': lead.city } }, 'beschaeftigung': { 'beschaeftigungsart': lead.employment } } if lead.employment == 'ARBEITER': payload['antragsteller1']['beschaeftigung']['arbeiter']['beschaeftigungsverhaeltnis']['nettoeinkommenMonatlich'] = str(lead.income) elif lead.employment == 'ANGESTELLTER': payload['antragsteller1']['beschaeftigung']['angestellter']['beschaeftigungsverhaeltnis']['nettoeinkommenMonatlich'] = str(lead.income) elif lead.employment == 'ARBEITSLOSER': payload['antragsteller1']['beschaeftigung']['arbeitsloser']['sonstigesEinkommenMonatlich'] = str(lead.income) Error: KeyError: 'angestellter' Why it is not possible to append 'angestellter' at the second elif statement? And how would it be possible? -
Sort based on related objects field in Django
I have two models, Player and Match class Player(PlayerModel): points = models.PositiveIntegerField(default=0) games_played = models.PositiveIntegerField(default=0) wins = models.PositiveIntegerField(default=0) draws = models.PositiveIntegerField(default=0) defeats = models.PositiveIntegerField(default=0) goals_scored = models.PositiveIntegerField(default=0) goals_conceded = models.PositiveIntegerField(default=0) goal_difference = models.IntegerField(default=0) class Match(models.Model): player1 = models.ForeignKey(PlayerLeagueModel, on_delete=models.CASCADE, related_name='player1') player2 = models.ForeignKey(PlayerLeagueModel, on_delete=models.CASCADE, related_name='player2') score1 = models.PositiveIntegerField(null=True, blank=True) score2 = models.PositiveIntegerField(null=True, blank=True) winner = models.ForeignKey(Player, null=True, blank=True, on_delete=models.CASCADE,related_name='winner') I want to sort Player model objects based on their points, if points are equal then on goal_difference, and if goal_difference is equal then I must check to see who won the match between the players with equal points. def head_to_head(): table_list = [] match = Match.objects.all() for m in match: if m.player1 not in table_list: table_list.append(m.player1) if m.player2 not in table_list: table_list.append(m.player2) table_list.sort(key=lambda x: (x.points, x.goal_difference), reverse=True) But I can't figure out how to sort based on head to head matches.