Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to update a manytomany field in Django without deleting the previous object?
I have seen this question before, but mine is a bit more restricted in terms of getting the object and filtering. I have these classes in models.py: class Title(models.Model): title = models.TextField(null=True) def __str__(self): return self.title class XMLGraph(models.Model): #only one title per graph title = models.OneToOneField( to=Title, blank=True, null=True, on_delete=models.CASCADE) XMLGraph = models.TextField(null=True) def __str__(self): return str(self.XMLGraph) class Member(User): XMLGraph = models.ManyToManyField(blank=True, to=XMLGraph, symmetrical=False, related_name='related_to') title = models.ManyToManyField(blank=True, to=Title, symmetrical=False, related_name='related_to') def __str__(self): return self.username One Member can store multiple XMLGraphs which are basically text files stored in the database. I have a functionality where the user can save and save as the XMLGraph. The save function should create a new object of the XMLGraph if there is nothing in the database or update the current XMLGraph. So, when the user presses save, it should update the data stored in the XMLGraph. So, I took this approach: Save function in views.py def saveData(request, user): if request.method == "POST": xmlData = request.POST['xml'] member = Member.objects.get(username=user) XMLGraph.objects.all().delete() xml, _ = XMLGraph.objects.get_or_create(XMLGraph = xmlData) member.XMLGraph.add(xml) return render_to_response("fastcookapp/index.html", content_type="text/xml;") return HttpResponse('POST is not used') However, now the issue is that the Save As function should generate a new object for XMLGraph and Title which … -
django project 3 from (https://docs.djangoproject.com/en/2.1/intro/tutorial03/)
Question id not showingHi I am following along with project number 3 on djangoprojects.com. I dropped a link in the title of the specific page I'm on so far. As the picture titled "Question id not showing" clearly shows, the numbered questions are not showing up on the screen after I type in the url along with the question id (2) as seen below: http://127.0.0.1:8000/polls/2 -
Django - Model Instance Not Being Saved
I’m trying to create an instance of Listing so I can have user populate in the admin. I’m new to Django and thought I had it but looks like I’m wrong somewhere. How do I create an instance of Listing to populate in admin? Any help i gladly appreciated, thanks. Code Below: user_profile/models from django.db import models from django.urls import reverse from django.contrib.auth.models import AbstractUser, UserManager from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.conf import settings from users.forms import CustomUserCreationForm, CustomUserChangeForm from users.models import CustomUser class Listing (models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=True) created = models.DateTimeField(auto_now_add=True, null=True) updated = models.DateTimeField(auto_now=True) name = models.CharField(max_length=100) address = models.CharField(max_length=100) zip_code = models.CharField(max_length=100) mobile_number = models.CharField(max_length=100) cc_number = models.CharField(max_length=100) cc_expiration = models.CharField(max_length=100) cc_cvv = models.CharField(max_length=100) def create_profile(sender, **kwargs): if kwargs['created']: user_profile = Listing.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) user_profile/admin.py from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from user_profile.forms import HomeForm from users.forms import CustomUserCreationForm, CustomUserChangeForm from user_profile.models import Listing from users.models import CustomUser # Register models here. class UserProfileAdmin(admin.ModelAdmin): list_display = ['name', 'address', 'zip_code', 'mobile_number', 'created', 'updated', 'user'] list_filter = ['name', 'zip_code', 'created', 'updated', 'user'] admin.site.register(Listing, UserProfileAdmin) -
How to Run Query Against Multiple Django Models in a View
How can I run a query against multiple Django models and display them through a template? I have created two models, which I can query independently and render a response in their respective templates. However, what I want to do is submit my query through my Django form, have the query run against both models, and then have the results, if any, displayed on a single template. How can I achieve this? Models: class State(models.Model): text = models.TextField(null=True) topic_list = models.TextField(null=True) class Hearings(models.Model): url = models.TextField(primary_key=True) title = models.TextField(null=True) text = models.TextField(null=True) Views: def state(request,query): data = state.objects.filter(text__icontains=query).values('text','topic_list') return render(request,'State.html',context={'data':data}) def hearings(request,query): data = Hearings.objects.filter(data__icontains=query).values('url','title', 'text') return render(request,'Hearings.html',context={'data':data}) Currently, I can query the models separately through my views. I want to run my query through a single view against both models. How should I do this? -
500 server error when debug=False in production
I have been trying for several weeks to resolve an issue with my deployment settings. When debug=True the Heroku app works fine, however, when I change debug to =False I always get a 500 server error. I have tried every suggestion on the other stackoverflow threads regarding this issue and none seem to work for me. Please let me know if you have any suggestions. """ Django settings for scipertise_demo project. Generated by 'django-admin startproject' using Django 2.0.5. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os import django_heroku import dj_database_url # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ #API_KEY ='46235562' # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'SECRET_KEY' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'pages', 'users', 'search', 'taggit', 'booking', 'bootstrap4', 'bootstrap_datepicker_plus', 'widget_tweaks', 'sendgrid', ] #HAYSTACK_CONNECTIONS = { # 'default': { # 'ENGINE': 'haystack.backends.elasticsearch2_backend.Elasticsearch2SearchEngine', # 'URL': 'http://127.0.0.1:9200/', # 'INDEX_NAME': 'haystack', # … -
django AttributeError: dict object has no attribute 'pk'
I'm making a simple django rest framework project. This is just creating a new user, and logging in. When I used django basic auth user model, everything worked well. But after changing basic user model to custom user, dict object has no attribute 'pk' this error comes out when creating a new user. Custom user model is made referred to django docs.(https://docs.djangoproject.com/ko/2.1/topics/auth/customizing/) Error says that File "/home/seokchan/server/mdocker/lib/python3.5/site-packages/django/contrib/auth/init.py", line 100, in login if _get_user_session_key(request) != user.pk or ( AttributeError: 'dict' object has no attribute 'pk' This seems to say that user model has no pk, but I don't get it. models.py class MyUserManager(BaseUserManager): def create_user(self, username, email, password=None): if not email: raise ValueError('Users must have an email address') if not username: raise ValueError('Users must have an user name') user = self.model( email=self.normalize_email(email), username = username ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, email, password): user = self.create_user( username, password=password, email = email, ) user.is_admin = True user.save(using=self._db) return user class MyUser(AbstractBaseUser): id = models.AutoField(primary_key=True) username = models.CharField( verbose_name='user name', max_length=30, unique=True, ) email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) sth_test = models.TextField(blank = True) objects = MyUserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] … -
Error NET::ERR_CERT_COMMON_NAME_INVALID from google when using Django 2.0 for password recovery through email
I am creating a "password recovery" system using django 2.0 auth. When I send the email containing the password reset link, I get redirected to a google page with an error that looks like this: "Your connection is not private" NET::ERR_CERT_COMMON_NAME_INVALID I looked into the error a bit, and I've read that google has deprecated the use of the COMMON_NAME field. How can I change my settings in order to account for this error? Or am I doing something inherently wrong? django say to use a template name password_reset_email.html and password_reset_complete to generate the link in email and the password change form destination. Here is my code: password_reset_email.html {% autoescape off %} Dear {{user.first_name}}, You are receiving this message because you have requested to have your password changed for your account on ___. To initiate the password reset process for your account, please click the link below: {{protocol}}://{{domain}}{% url 'password_reset_confirm' uidb64=uid token=token %} Your username is "{{user.username}}"" in case you've forgotten. If clicking the link above doesn't work, please copy and paste the URL in a new browser window instead. Sincerely, _____ {% endautoescape %} password_reset_confirm.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} {% if … -
Facets from many to many fields do not display in template
I tried to use faceting with Haystack on a many to many field. I tried many options to finally end up to a road block. I am able to make it work (apparently) as shown below through the shell. However, when implementing into the template the faceted fields do not show up. Extract from Django Shell from haystack.query import SearchQuerySet sqs = SearchQuerySet().facet('type') sqs.facet_counts() {'fields': {'type': [('Soccer', 2), ('Basketball', 1), ('Golf', 1), ('Swimming', 1)]}, 'dates': {}, 'queries': {}} Search Index.py class EventIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) name = indexes.CharField(model_attr='name') owner = indexes.CharField(model_attr='user') created_on = indexes.DateTimeField(model_attr='created_on') type = indexes.MultiValueField(faceted=True) def get_model(self): return Event def prepare_type(self, obj): return [(t.name) for t in obj.type.all()] def index_queryset(self, using=None): return self.get_model().objects.prefetch_related('type').all() Template <!-- Begin faceting. --> <div> {% if facets.fields.type %} <h5>Categories</h5> {# Provide only the top 5 categories #} {% for category in facets.fields.type|slice:":5" %} <a href="{{ request.get_full_path }}&amp;selected_facets=type_exact:{{ type.0|urlencode }}"> {{ type.0 }} </a> ({{ type.1 }}) {% endfor %} {% else %} <p>No categories.</p> {% endif %} </div> event_text.txt {{ object.name }} {{ object.description }} {% for type in event.type.all %} {{ event.type }} {% endfor %} I should be able to see the different types as facets (soccer, basketball, etc..). … -
How to fix 403 "Access Denied" response when trying to access files from Google Cloud Storage
The Problem When trying to load the static content for my web application from a Google Cloud Storage bucket, a handful of files return a 403 response code, while all others are downloaded successfully. The Setup The application is a Django-powered (2.1.3) Python (3.7) application hosted on Google App Engine, using service account credentials that have been given Editor permissions in IAM. We use Bootstrap 3.3.7 for our frontend, hosting its source files in our GCS bucket, and the django-storages (1.7.1) plugin for interfacing with the GCS API. The troublesome files are the Glyphicon images provided with Bootstrap, as well as a CSS map. All other Bootstrap resources load without issue. I've tried: Giving the service account numerous combinations of IAM permissions Recreating the service account and the key file we use to authenticate it Disabling and reenabling the Google Cloud Storage API Creating a new bucket and reloading all the static files to it using the service account credentials Granting AllUsers read access to the problematic files (as the policies are currently set) Granting AllUsers read access to the entire bucket The last fix attempt (#6) did enable access to the glyphicons, but isn't an acceptable solution. The Code … -
inlineformset: how to add parent form?
I have two entities: pizza and topping. I also created an extra table to associate the amount of topping for each pizza. # models.py class Topping(models.Model): name = models.CharField(max_length=50) class Pizza(models.Model): name = models.CharField(max_length=50) class PizzaTopping(models.Model): pizza = models.ForeignKey('Pizza') topping = models.ForeignKey('Topping') amount = models.FloatField() # forms.py class IngredientForm(forms.ModelForm): class Meta: model = Ingredient class IngredientRecipeForm(forms.ModelForm): class Meta: model = IngredientRecipe class RecipeForm(forms.ModelForm): class Meta: model = Recipe Problem: I want to create a form to let the user create a pizza and topping. What I tried: inlineformset_factory(Pizza, PizzaTopping) But the form that results from this won't have the fields associated with Pizza. I couldn't find any information on how to add these fields and create the Parent and Child objects at the same time using this feature. My next attempt would be overriding BaseInlineFormSet, but I didn't find it well documented and before I embrace this adventure I thought it'd be wiser to ask here. -
Django tests giving random assert result
I'm running one confidential app on my machine... This is irrelevant, but I cannot share the code. The basic issue is... The app is on Python, have lots of unit tests... but two tests are a little bit different of all others... The test just give random results... $ run... test fail... $ run... test fail... $ run... test pass... $ run... test pass... $ run... test pass... $ run... test pass... $ run... test fail... $ run... test pass... $ run... test fail... $ run... test fail... $ run... test pass... $ run... test pass... All other functions that the unit tested class is calling are on unit test also, none of they are giving any fail... None of those tests depends on random numbers or calcs... None of they uses Threads... All are simple class that run some action, interact with database, run another action and done. But, when runs this test, that calls 3 other functions, it fails... Maybe you will say, ok, one of they doesn't cover an situation.. but no errors are raised... On result of run, the function should update the database, setting the current user balance for log purposes. All runs, no exceptions, … -
How can DRF browsable API upload a file and send nested JSON data?
I would like to use the browsable developer web API provided by django-rest-framework to interact with a WritableNestedModelSerializer that contains both an ImageField as well as a nested Serializer. Using this sample code: from django.db import models from drf_writable_nested import WritableNestedModelSerializer from rest_framework.serializers import ModelSerializer from django.urls import include, path from rest_framework import routers, viewsets class House(models.Model): image = models.ImageField() class Cat(models.Model): house = models.ForeignKey(House, related_name='cats', on_delete=models.CASCADE, null=True) name = models.CharField(max_length=50) class CatSerializer(ModelSerializer): class Meta: model = Cat fields = '__all__' class HouseSerializer(WritableNestedModelSerializer): cats = CatSerializer(many=True) class Meta: model = House fields = '__all__' class HouseViewSet(viewsets.ModelViewSet): queryset = House.objects.all() serializer_class = HouseSerializer router = routers.DefaultRouter() router.register(r'houses', HouseViewSet) urlpatterns = [ path('', include(router.urls)), ] With this version of Python packages: $ pip freeze Django==2.1.4 django-rest-framework==0.1.0 djangorestframework==3.9.0 drf-writable-nested==0.5.1 pytz==2018.7 The HTML form doesn't support nested JSON serialization: And the Raw data form doesn't support sending binary files: -
Does the first instance of a model have an id of 0 or 1?
I'm wondering if the very first instance of a model has an id of 0 or 1? Thanks! -
bootstrap + django, wrapping cards
I have a quick question. I am going to loop through DB records and print one card for each record. The problem is, if I can't set a new row for each, I end up with this horrible squashed layout between the two rows of cards How can I loop through, make a card for each & still make it look nice? Thanks!! <div class="row"> <div class="col-4"> <div class="card" style="width: 18rem;"> <div class="card-body"> <h5 class="card-title">Card title</h5> <h6 class="card-subtitle mb-2 text-muted">Card subtitle</h6> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> <a href="#" class="card-link">Card link</a> <a href="#" class="card-link">Another link</a> </div> </div> </div> <div class="col-4"> <div class="card" style="width: 18rem;"> <div class="card-body"> <h5 class="card-title">Card title</h5> <h6 class="card-subtitle mb-2 text-muted">Card subtitle</h6> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> <a href="#" class="card-link">Card link</a> <a href="#" class="card-link">Another link</a> </div> </div> </div> <div class="col-4"> <div class="card" style="width: 18rem;"> <div class="card-body"> <h5 class="card-title">Card title</h5> <h6 class="card-subtitle mb-2 text-muted">Card subtitle</h6> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> <a href="#" class="card-link">Card link</a> <a … -
How to solve err 'dict' object has no attribute 'save' when trying to make an update on DB
I'm getting a problem working with django and its model system. I'm new working with django and I'm stuck since I've probably making the things wrong. I'm trying to make an update to my DB and I get this error: "'dict' object has no attribute 'save'" I'm only trying to set a field to be active or inactive depending on a check input on my html. I'm sending the right value on the request. I'm getting a dictionary instead of a model object, but I don't really know how to change this, I think I followed the django docs. step by step. models.py: from django.db import models class Flags(models.Model): num = models.IntegerField(null=False) deliver= models.CharField(max_length=1, null=False) class Meta: db_table ="FLAGS" views.py: from django.http import HttpResponse from Logistic.models import Flags def updateDisponibilidad(request): flag = request.GET.get("flag") print(flag) disp = Flags.objects.using('default').values('num', 'deliver').get(num__exact=1) print(disp) disp['deliver'] = str(flag) disp.save() return HttpResponse(disponibilidad) Django docs. says I can acces to the values putting (in this case) disp.deliver, but when I do that, i get a different error: 'dict' object has no attribute 'deliver' It would be fantastic if anyone can help me so I be able to use this code: disp.deliver = flag disp.save() And work with that. -
How can I add an additional unique_together constraint to Django Guardian object level permissions?
Using the example from the docs, let's assume I have a Task model: class Task(models.Model): summary = models.CharField(max_length=32) content = models.TextField() reported_by = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) class Meta: permissions = ( ('view_task', 'View task'), ) Let's say I have many users on my app, and I want to make sure of the following at the database level: No user has a duplicate task, i.e., a user can only have one task called "Sweep the floor." Users do not share tasks. For instance, if two users have a task "Sweep the floor.", there should be two tasks with the summary "Sweep the floor." on the backend, one for each of the two users I cannot add a user field on the Task model - I have to assign ownership of Task objects via permissions Out of the box, the django_guardian UserObjectPermission has this unique_together constraint: unique_together = ['user', 'permission', 'object_pk'] I think what I am looking for is a unique_together constraint that is more like this pseudo-code: unique_together = ['user', 'permission', 'object_pk', 'task__summary'] Or, is there another way to enforce this type of uniqueness at the database level using Django Guardian permissions? -
My view started to works with error after trying to make my template work on ajax
After remake my view to my post on my website, when i tryed to make my template working properly with ajax, there are some new problems appeared in my view. Here is my code of my view def post(request, slug): post_inst = get_object_or_404(InfoPost, slug=slug) q = QueryDict('', mutable=True) if request.method == 'POST': data = json.loads(request.body) q.update(data) comment_form = CommentsForm(q) print(comment_form.is_valid()) if comment_form.is_valid(): com = comment_form.save(commit=False) com.author = request.user com.post = post_inst parent_obj = None try: parent_id = int(data['parent_id']) except: parent_id = None if parent_id: parent_qs = PostComment.objects.filter(id=parent_id) if parent_qs.exists() and parent_qs.count() == 1: parent_obj = parent_qs.first() com.reply_to = parent_obj com.save() #return render(request, "MainPage/Post.html", {'comment_form': comment_form, 'post': post_inst}) return redirect('post', slug=post_inst.slug) else: comment_form = CommentsForm() return render(request, 'MainPage/Post.html', {'comment_form': comment_form, 'post': post_inst}) And here is a new error appeared: Traceback (most recent call last): File "E:\Env\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "E:\Env\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "E:\Env\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\hell_\PyCharmProjects\django_site_2\MainPage\views.py", line 92, in post print(comment_form.is_valid()) File "E:\Env\Python\Python37-32\lib\site-packages\django\forms\forms.py", line 185, in is_valid return self.is_bound and not self.errors File "E:\Env\Python\Python37-32\lib\site-packages\django\forms\forms.py", line 180, in errors self.full_clean() File "E:\Env\Python\Python37-32\lib\site-packages\django\forms\forms.py", line 383, in full_clean self._post_clean() File "E:\Env\Python\Python37-32\lib\site-packages\django\forms\models.py", line 398, in … -
Prefetch_related failing against SQL Server
Using Django 2.X, and Pyodbc driver (installed from anaconda conda-forge django-pyodbc-azure) against MS Sql Server (not sure which version), I regularly have bugs using prefetch_related. An example looks simply like: for obj in MyORMType.objects.prefetch_related('otherormtype_set').all(): pass where OtherOrmType has a simple foreign key to MyOrmType, the error is: ... /opt/conda/lib/python3.6/site-packages/django/db/backends/utils.py in _execute(self, sql, params, *ignored_wrapper_args) 83 return self.cursor.execute(sql) 84 else: ---> 85 return self.cursor.execute(sql, params) 86 87 def _executemany(self, sql, param_list, *ignored_wrapper_args): /opt/conda/lib/python3.6/site-packages/sql_server/pyodbc/base.py in execute(self, sql, params) 544 self.last_params = params 545 try: --> 546 return self.cursor.execute(sql, params) 547 except Database.Error as e: 548 self.connection._on_error(e) ProgrammingError: ('The SQL contains -2098 parameter markers, but 128974 parameters were supplied', 'HY000') I can fall back to the dumb equivalent: for obj in MyORMType.objects.all(): other_objs = obj.otherormtype_set.all() but this is obviously quite slow. This bug occurs regularly for me under many different circumstances in this particular setup (always same Django version, driver, and DB), it's not a one-off annoyance. Is this my fault or an issue with SQL Server or Pyodbc (or Django)? Is there a way to work around the error without having to fetch each obj.otherormtype_set one at a time? -
Django - How do I check how post_save is being called?
I’m trying to create an instance of Listing so I can have user populate in the admin. I’m new to Django so I’ve been crashing but I’m starting to get the hang of it slowly. How do I check if this signal is being called on creation or on update? Thanks! Code Below: user_profile/models from django.db import models from django.urls import reverse from django.contrib.auth.models import AbstractUser, UserManager from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.conf import settings from users.forms import CustomUserCreationForm, CustomUserChangeForm from users.models import CustomUser class Listing (models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=True) created = models.DateTimeField(auto_now_add=True, null=True) updated = models.DateTimeField(auto_now=True) name = models.CharField(max_length=100) address = models.CharField(max_length=100) zip_code = models.CharField(max_length=100) mobile_number = models.CharField(max_length=100) cc_number = models.CharField(max_length=100) cc_expiration = models.CharField(max_length=100) cc_cvv = models.CharField(max_length=100) def create_profile(sender, **kwargs): if kwargs['created']: user_profile = Listing.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) user_profile/admin.py from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from user_profile.forms import HomeForm from users.forms import CustomUserCreationForm, CustomUserChangeForm from user_profile.models import Listing from users.models import CustomUser # Register models here. class UserProfileAdmin(admin.ModelAdmin): list_display = ['name', 'address', 'zip_code', 'mobile_number', 'created', 'updated', 'user'] list_filter = ['name', 'zip_code', 'created', 'updated', 'user'] def __str__(self): return self.user.username admin.site.register(Listing, UserProfileAdmin) -
Why does heroku local produce a server error when debug is False?
I followed the getting started tutorial. Everything works fine until I set DEBUG=False (as advised for production). Then running heroku local to test the app produces a server error (500) when I visit /admin. I have not changed anything else. What's going on? -
How to continue a URL for a new view with already selected primary key (pk) in Django / Django Rest Framework
From my index view I list the available "clubs" in my database, when a user select a club it re-directs them to the club home page. I have included a player registration page but I have no idea how I can render this page based on what club the user selected previously in the index. So what I would like to do is output the url like so: http://127.0.0.1:8000/account/club_home/3/player_registration/ "3" being the primary key of the selected club. urls.py: url(r'^club_home/$', views.club_home, name='club_home'), url(r'^club_home/(?P<pk>\d+)/$', views.club_home, name='club_home_with_pk'), url(r'^club_home/player_registration/$', views.RegisterPlayer.as_view(), name='player_register'), views.py: class Index(TemplateView): template_name = 'index.html' def get(self, request): users = User.objects.all() clubs = ClubInfo.objects.all() args = {'users': users, 'clubs': clubs} return render(request, self.template_name, args) def club_home(request, pk=None): if pk: club = ClubInfo.objects.filter(pk=pk) user = request.user else: club = ClubInfo.objects.filter(user=request.user) user = request.user args = {'club': club, 'user': user } return render(request, 'club_home_page.html', args) class RegisterPlayer(APIView): renderer_classes = [TemplateHTMLRenderer] template_name = 'player_registration.html' def get(self, request): serializer = PlayerRegistrationSerializer() return Response({'serializer': serializer}) def post(self, request): serializer = PlayerRegistrationSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response({'serializer': serializer}) -
integrating daphne in docker-compose and adjusting nginx to work with webservices.
I have a working dummy webservice in django under my development that once a user clicks a button a "Hello World" message will appear with a random number. How did I do that? the index.html in the front_end <button onclick="myFunction()">Click me</button> <p id="this_id"></p> <script> function myFunction() { socket = new WebSocket("ws://" + window.location.host + "/personal/my_random_number/"); console.log("===>"+window.location.host) socket.onmessage = function(e) { <!-- alert(e.data); --> document.getElementById("this_id").innerHTML = e.data; } socket.onopen = function() { socket.send("hello world #"); } } the backend: setting.py CHANNEL_LAYERS = { "default": { "CONFIG": { 'hosts': [(REDIS_IP, 6379)], }, "BACKEND": "channels_redis.core.RedisChannelLayer", }, } ASGI_APPLICATION = 'CRM2.routing.application' routing: from django.urls import path from channels.http import AsgiHandler from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from .consumers import EchoConsumer application = ProtocolTypeRouter({ "websocket": AuthMiddlewareStack( URLRouter([ path("personal/my_random_number/", EchoConsumer), ]), ), }) Cunsomer (EchoConsumer.py) import random from channels.consumer import AsyncConsumer class EchoConsumer(AsyncConsumer): async def websocket_connect(self, event): print ("yes ------------------------ websocket connect") await self.send({ "type": "websocket.accept", }) async def websocket_receive(self, event): print ("HELLO HELLO WS") rand = random.randint(1,100) my_reply = event["text"]+" "+str(rand) await self.send({ "type": "websocket.send", "text": my_reply, }) The Problemwhen I move to production, this doesn't work! From what I understood (and I might be wrong) I need to: integrate daphne in … -
Cant find the right way to install mysqlclient
I've been trying to install mysqlclient for my python 3.7.2 for quite some time now. Currently using windows 10, python 3.7.2 and wamp server 2.1 I tried using the following 1) pip install mysqlclient 2) pip install c:\mysqlclient‑1.3.13‑cp36‑cp36m‑win_amd64.whl and everything along those lines Checked this link: Installing mysqlclient in Python 3.6 in windows 3)pip install "mysqlclient==1.3.12" 4) pip install --only-binary :all: mysqlclient 5)pip install mysql-connector-python I tried doing all of the above using cmd (as administrator) and that failed as well. Anyone with any sort of solution for this problem are welcome! Thank you in advance! -
Updating and fetching a Django model object atomically
I want a capability to update-and-read an object atomically. For example, something like a first() on top of update() below: obj = MyModel.objects.filter(pk=100).update(counter=F('counter') + 1).first() I know it is awkward construct. But just want to show my need. For the record I have used class method like: @classmethod def update_counter(cls, job_id): with transaction.atomic(): job = (cls.objects.select_for_update().get(pk=job_id)) job.counter += 1 job.save() return job where I would call as below and get my updated obj. my_obj = my_obj.update_counter() But the question is, is there any other django model technique given such read back are common and likely used by multiple threads to conclude something based on, say, the final count. -
Django Password Reset generating http link instead of https
I am using Django's inbuilt password reset mechanism. It sends an email with a link containing a token, which when clicked can be used to reset the password. However, the link being generated is using the template: {% trans "Please go to the following page and choose a new password:" %} {% block reset_link %} {{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %} {% endblock %} Here, the {{ protocol }} is returning http instead of https. My nginx server would redirect any http requests to the https base link (the homepage). Hence, the password reset link does not work since the link generated is wrong. It simply goes to the homepage via nginx. How do I fix this?