Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Heroku Django ModuleNotFoundError: No module named 'my_app'
My app (called 'my_app") in Django seems to be present on the Heroku Postgres database, and my_app is running when I python manage.py runserver from the command line. However when I run my_app in Heroku I get the error ModuleNotFoundError: No module named 'my_app' I also get the error [ERROR] Exception in worker process I have had a look at the requirements file and procfile but could see nothing wrong. I also went through the tutorial I used to develop this app and cannot for the life of me find anything amiss. Here is the full code error log for what it's worth: 2020-04-03T18:40:25.066140+00:00 app[web.1]: [2020-04-03 18:40:25 +0000] [4] [INFO] Listening at: http://0.0.0.0:59726 (4) 2020-04-03T18:40:25.066304+00:00 app[web.1]: [2020-04-03 18:40:25 +0000] [4] [INFO] Using worker: sync 2020-04-03T18:40:25.072150+00:00 app[web.1]: [2020-04-03 18:40:25 +0000] [10] [INFO] Booting worker with pid: 10 2020-04-03T18:40:25.086009+00:00 app[web.1]: [2020-04-03 18:40:25 +0000] [10] [ERROR] Exception in worker process 2020-04-03T18:40:25.086011+00:00 app[web.1]: Traceback (most recent call last): 2020-04-03T18:40:25.086011+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker 2020-04-03T18:40:25.086012+00:00 app[web.1]: worker.init_process() 2020-04-03T18:40:25.086012+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 119, in init_process 2020-04-03T18:40:25.086013+00:00 app[web.1]: self.load_wsgi() 2020-04-03T18:40:25.086013+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi 2020-04-03T18:40:25.086014+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2020-04-03T18:40:25.086014+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi 2020-04-03T18:40:25.086015+00:00 app[web.1]: self.callable … -
unindent does not match any outer indentation level error appearing
I am trying to combine these two views. This is what I have. MenuView is to combine with add_to_menu so that if the if statement returns negative, the menuview portion still runs and displays the menu on my html page. If the if statement is positive, it still shows the menu, but also adds the entered information into the database. I can only get one or the other to work at a time. Views.py: class MenuView(ListView): model = Product template_name = 'mis446/edit-menu.html' context_object_name = 'show_menu' def add_to_menu(request): if request.method == 'POST': if request.POST.get('name') and request.POST.get('price') and request.POST.get('nickname'): post=Product() post.name= request.POST.get('name') post.price= request.POST.get('price') post.slug= request.POST.get('nickname') post.save() model = Product context_object_name = {'show_menu'} return render(request, 'mis446/edit-menu.html', context_object_name) else: model = Product context_object_name = {'show_menu'} return render(request,'mis446/edit-menu.html') -
Django model form, adding a user id when creating new note
I'm pretty new to Django, I've been stuck on this view for a little while. My goal with this form is to be able to create a small note on a "Property" about maintenance or other information. The note would log the time, date, note and the user that recorded the note. Any help would be appreciated. View: @login_required(login_url="login") def createNote(request, pk): PropertyNoteFormSet = inlineformset_factory( Property, PropertyNote, fields=('note', 'user',)) property_note = Property.objects.get(id=pk) form = PropertyNoteFormSet(instance=property_note) # form = OrderForm(initial={'customer': customer}) if request.method == "POST": print(request.POST) form = PropertyNoteFormSet( request.POST, instance=property_note) if form.is_valid(): form.save() return redirect("/") context = {"form": form} return render(request, "dashboard/create_note.html", context) Here is the ModelForm: class PropertyNoteForm(ModelForm): class Meta: model = PropertyNote fields = ['note'] exclude = ['user'] Here is the Model: class PropertyNote(models.Model): airbnb_name = models.ForeignKey(Property, blank=True, null=True,on_delete=models.CASCADE) note = models.TextField(blank=True, null=True) user = models.ForeignKey(User, on_delete=models.CASCADE) created_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.note The form comes out with around 4 boxes to fill in. Currently it works, but you have to actually select the user that is posting the note, I would like this part to be handled automatically and use the current logged in user. I think I still have a whole lot of holes in … -
token authentication works fine in localhost but not working on ubuntu server (Djangorestframework)
i write a server in django and i have made an api's in django rest framework. All api's works fine in local host but when i upload my project to the ubuntu server then its token authentication is not working. It always gives {"detail":"Authentication credentials were not provided."} My all code runs perfect on locallost but on ubuntu server it gives me an error. views.py class ManageUserView(generics.RetrieveUpdateAPIView): serializer_class = serializers.UserSerializer authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) def get_object(self): return self.request.user Serializers.py* class UserSerializer(serializers.ModelSerializer): """ Serializer for the users object """ class Meta: model = get_user_model() fields = ('id', 'email', 'password', 'user_type') extra_kwargs = {'password': {'write_only': True, 'min_length': 8}} def create(self, validated_data): """ Create a new user with encrypted password and return it""" print(validated_data) return get_user_model().objects.create_type_user(**validated_data) def update(self, instance, validated_data): """ Update a user, setting the password correctly and return it """ password = validated_data.pop('password', None) user = super().update(instance, validated_data) if password: user.set_password(password) user.save() return user -
How to save custom fields with user data on Django?
I've created a "Account" class so i can get more columns on user information: class Account(AbstractUser): company_name = models.CharField(max_length=50) company_department = models.CharField(max_length=50) company_employees_quantity = models.IntegerField(default=1) def __str__(self): return self.username I've also created a form with this data so i can receive the information on my view. class AccountCreationForm(UserCreationForm): company_name = forms.CharField(max_length=50) company_department = forms.CharField(max_length=50) company_employees_quantity = forms.IntegerField() class Meta: model = Account fields = ('username', 'email') The problem is when the client send the data though the form, i receive all the fields but only the "core" user information is inserted on the database. class SignUpView(CreateView): form_class = AccountCreationForm success_url = reverse_lazy('login') template_name = 'signup.html' If o add a method form_valid on on view o can save the data field by field like this: class SignUpView(CreateView): form_class = AccountCreationForm success_url = reverse_lazy('login') template_name = 'signup.html' def form_valid(self, form): if form.is_valid(): account = form.save() account.company_name = form.cleaned_data["company_name"] account.company_department = form.cleaned_data["company_department"] account.company_employees_quantity = form.cleaned_data["company_employees_quantity"] account.save() return redirect(self.success_url) return super().form_invalid(form) But this look weird to me? the view/form/model shouldn't save my "custom" fields automatically along with the "core" user info? How do i do that? -
django.core.exceptions.FieldError: Unknown field(s) (custom_field) specified for MyUser
I am trying to use the following command: docker-compose exec web python manage.py makemigrations, but I recieve an error as the title of this question: 'django.core.exceptions.FieldError: Unknown field(s) (custom_field) specified for MyUser'. Thanks for your Help! MyUser is a sub class of the AbstractClass. My code: -----------------------------------------users/models.py from django.db import models from django.contrib.auth.models import BaseUserManager, AbstractUser class MyUserManager(BaseUserManager): def create_user(self, email, password=None): """ Creates and saves a User with the given email and password. """ if not email: raise ValueError('The eMail address you typed in, is already in use.') if not password: raise ValueError('You haven\'t typed in a password.') user = self.model( email=self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password=None): """ Creates and saves a superuser with the given email, date of birth and password. """ user = self.create_user( email, password=password, ) user.is_admin = True user.is_superuser = True user.is_staff = True user.save(using=self._db) return user class MyUser(AbstractUser): email = models.EmailField( verbose_name= 'email address', max_length=255, unique=True, ) date_of_birth = models.DateField(verbose_name='birthday') is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) nickname = models.CharField(unique=True, max_length=30) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) nationality = models.CharField(max_length=30) mother_language = models.CharField(max_length=30) father_language = models.CharField(max_length=30) skin_colour = models.CharField(max_length=30) religion = models.CharField(max_length=30) sex = models.CharField(max_length=30) … -
NameError: name 'models' is not defined , help using django custom model
Got no idea what's going on here. First time using a custom user model so I'm having trouble referencing the user object in views. I know I need to use 'get_user_model' , but I'm not sure how to implement it. I tried doing a couple things but I'm still stuck. error = NameError: name 'models' is not defined. It shows up with 'description = models.Profile.objects.get(user=request.user).description' **views.py, part that's giving me an error ** from __future__ import unicode_literals from django.shortcuts import render, redirect, get_object_or_404 from django.http import HttpResponseRedirect, Http404 from django.urls import reverse from django.contrib.auth.decorators import login_required from django.contrib.auth import logout from django.contrib.auth import login, logout, authenticate from dating_app.forms import RegistrationForm,ProfileUpdateForm from .models import Profile from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User import os from django.core import serializers import json from django.contrib.auth import get_user_model User = get_user_model() def mingle(request): try: user = (Profile.objects.exclude(id=request.user.id).exclude(uservote__voter=request.user).order_by('?')[0]) except IndexError: user = None print(User.username) try: description = models.Profile.objects.get(user=request.user).description except models.Profile.DoesNotExist: create = Profile.objects.get_or_create(user = request.user) return redirect('profile') match = models.Profile.objects.get(user=request.user).matches.all() context = dict(user = user, match = match) return render(request, 'dating_app/mingle.html', context) models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser,BaseUserManager, User from dating_project import settings class ProfileManager(BaseUserManager): def create_user(self, username, email,description,photo, password=None): if not … -
Dropdown list from an object attribute in Django template
So what I'm trying to do is a dropdown list in a template, this list consists of the attribute of another object in another app, however, I don't seem to know what's going on in the HTML side, since it doesn't show any attributes, it shows nothing. I'm using class based templates and views Here's what I've done so far: project/models.py class Project(models.Model): projectID = models.AutoField(primary_key=True, db_column="Id", db_index=True, verbose_name='Project ID') description = models.CharField(max_length=900) def __str__(self): return str(self.projectID) def get_description(self): return str(self.description) this is the object that should show the dropdown list model pm/models.py: class Pm(models.Model): pmid = models.AutoField(primary_key=True, db_column="Id", db_index=True) pmnumber = models.CharField(max_length=50, unique=True, db_column="pmnumber") description = models.CharField(max_length=600) projectId = models.ForeignKey(Project, on_delete=models.CASCADE, db_column="ProjectID", related_name='+') def __str__(self): return str(f'{self.PMid}, {self.PMNumber}, {self.description}') this is the form pm/forms.py: class PMForm(forms.ModelForm): class Meta: model = Pm fields = ('pmnumber', 'description', 'projectId') and this is the views archive for that model: class CreatePMView(LoginRequiredMixin, CreateView): template_name = 'pm/new.html' form_class = PMForm success_url = reverse_lazy('project:feed') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['user'] = self.request.user return context def get_description(self): return self.request.project.description And this is the part of the template where I want to render the description from the project and shows nothing: <select class="form-control"> {% for project in … -
Google Storage + JQuery-File-Upload + Django + Signed URL, how should I change submit() and relevant options?
I have the following js code and it uses the signed-url api to get signed urls for uploading content to google storage via Django api. When I use it with the following code : xhr.open("PUT", data.signed_url); xhr.setRequestHeader('Content-Type', file.type); xhr.send(file); It works fine and I am able to upload to Google Storage very large files. But obviously, when I do that, I cannot use any progress-bar features of jquery-file-upload. Can you please suggest on how I should alter the data.submit(), where shall I put it, and how should I change the options or settings prior to submitting. Should I be overriding add or submit callback ? I feel that there is a missing support for Google Storage with Jquery-file-upload as the only example covers only obsolute Google Blobstore in the following link : https://github.com/blueimp/jQuery-File-Upload/wiki/Google-App-Engine $("#fileupload").fileupload({ dataType: 'json', type: 'PUT', sequentialUploads: true, submit: function(e, data) { var $this = $(this); $.each(data.files, function(index, file) { // pack our data to get signature url var formData = new FormData(); formData.append('filename', file.name); formData.append('type', file.type); formData.append('size', file.size); // Step 3: get our signature URL $.ajax({ url: '/api/getsignedurl/', type: 'POST', processData: false, contentType: false, dataType: 'json', headers: { 'X-CSRFToken': Cookies.get('csrftoken'), }, primary_data: data, data: formData }).done(function (data) … -
Best tool for Django recurrent payments?
I am about to add membership plans to my Django website and I was looking for some feedback. Havent decided between paypal or stripe. What do you guys think? If there are more options I will be happy to know them. Thanks! -
Using materialize how do i center a tabs in nav-content
https://i.imgur.com/JBI7id0.png So basically i am having an issue. I have no problem in moving any of the tabs to the right or left side. But when i try to center all the tabs i'm having no luck. So in the image above i am trying to get DROP ME!, TEST 2, DISABLED TAB AND TEST 4 to be centered on the page. I am using the Extended Navbar with Tabs example on their website. <div class="nav-wrapper"> <a href="/" class="brand-logo" >Skolplattform</a> <a href="#" data-target="mobile-demo" class="sidenav-trigger"><i class="material-icons">X</i></a> <ul id="nav-mobile" class="right hide-on-med-and-down"> {% if user.is_authenticated %} <li><a href="/logout">Logout</a></li> <li><a>{{user.username}}</a></li> {% else %} <li><a class="waves-effect waves-light btn" href="/register">Register</a></li> <li><a class="waves-effect waves-light btn" href="/login">Login</a></li> {% endif %} </ul> </div> <div class="nav-content"> <ul class="tabs tabs-transparent"> <li class="tab"><a class='dropdown-trigger' href='#' data-target='dropdown1'>Drop Me!</a></li> <li class="tab"><a href="#test2">Test 2</a></li> <li class="tab"><a href="#test3">Disabled Tab</a></li> <li class="tab"><a href="#test4">Test 4</a></li> </ul> </div> </nav>``` -
Should I go for AbstractBaseUser or AbstractUser? - Django
I am building a web app with Django where different users can create posts, etc. At the moment I am using the default User model along with a Profile model I created. The default User model is sufficient enough, however, I would like the users to be able to only register with a username made up of integers and I would also like to add my own authentication for when registering a new username. Do you suggest I use the AbstractBaseUser model or the AbstractUser? What is the core differences between these and what would be better in my case? -
How do I adjust my Django serializer to accept an array of a field?
I'm using Django 2.0 and Python 3.7. I have the following models (CoopType is a many-to-many field of Coop) ... class CoopTypeManager(models.Manager): def get_by_natural_key(self, name): return self.get_or_create(name=name)[0] class CoopType(models.Model): name = models.CharField(max_length=200, null=False) objects = CoopTypeManager() class Meta: unique_together = ("name",) class CoopManager(models.Manager): # Look up by coop type def get_by_type(self, type): qset = Coop.objects.filter(type__name=type, enabled=True) return qset # Look up coops by a partial name (case insensitive) def find_by_name(self, partial_name): queryset = Coop.objects.filter(name__icontains=partial_name, enabled=True) print(queryset.query) return queryset # Meant to look up coops case-insensitively by part of a type def contains_type(self, types_arr): filter = Q( *[('type__name__icontains', type) for type in types_arr], _connector=Q.OR ) queryset = Coop.objects.filter(filter, enabled=True) return queryset class Coop(models.Model): objects = CoopManager() name = models.CharField(max_length=250, null=False) types = models.ManyToManyField(CoopType) #type = models.ForeignKey(CoopType, on_delete=None) address = AddressField(on_delete=models.CASCADE) enabled = models.BooleanField(default=True, null=False) phone = PhoneNumberField(null=True) email = models.EmailField(null=True) web_site = models.TextField() I don't know how to properly create a serializer to accept the inputs. I have these serializers ... class CoopTypeField(serializers.PrimaryKeyRelatedField): queryset = CoopType.objects def to_internal_value(self, data): if type(data) == dict: cooptype, created = CoopType.objects.get_or_create(**data) # Replace the dict with the ID of the newly obtained object data = cooptype.pk return super().to_internal_value(data) ... class CoopSerializer(serializers.ModelSerializer): type = CoopTypeField() address … -
Django hide slug field to users in custom template
I've built a form with auto-generating slug field with short js code. I'd want to hide the slug field to user to prevent them being edited. //slugify.js const titleInput = document.querySelector('input[name=title'); const slugInput = document.querySelector('input[name=slug]'); const slugify = (val) => { return val.toString().toLowerCase().trim() .replace(/&/g, '-and-') // replacing & with '-and-' .replace(/[\s\W-]+/g, '-') //replcaing spaces, non-word chars and dashes with a single '-' }; titleInput.addEventListener('keyup', (e) => { slugInput.setAttribute('value', slugify(titleInput.value)); }); //models.py slug = models.SlugField(max_length=100, unique = True) as I remove it from forms.py, slugfield becomes blank. I know what the problem is, but I don't know how should I fix it. I've tried removing the slugfield from forms.py, but it would just does not add the slug, because I targeted the slug with the input in slugify.js. I've tried editable = False on slugField, but it would give me an error django.core.exceptions.FieldError: 'slug' cannot be specified for VideoPost model form as it is a non-editable field Would there be any other way that I could hide slugfield from the form and properly save the slug as well? -
Displaying videos in Django Template: Media Link
Currently trying to pull a video from a model, however it appears to be unable to locate the correct url by adding the media directory to the front of the pulled URL. Am I pulling the url from the model correctly? Code + Generated HTML + Console log -
IntegrityError at /signup-login/ duplicate key value violates unique constraint sts
i am getting this "duplicate key value violates unique constraint "myblog_profile_email_3f46e9ef_uniq" DETAIL: Key (email)=() already exists." error every time when i submit my signup form even with new email address.values save inside User table but it not redirect it on home page. models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class Profile(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) first_name=models.CharField(max_length=50,blank=True) last_name=models.CharField(max_length=50,blank=True) email=models.EmailField(max_length=120) bio=models.TextField(blank=True) gender_choices=(('M','Male'),('F','Female'),('S','Special')) gender=models.CharField(max_length=1,choices=gender_choices,default='M') age=models.PositiveIntegerField(default=12) def __str__(self): msg = "Name : {0} {1}|| Email : {2} || gender : {3}".format(self.first_name,self.last_name,self.email,self.gender) return msg @receiver(post_save, sender=User) def ensure_profile_exists(sender, **kwargs): if kwargs.get('created', False): Profile.objects.get_or_create(user=kwargs.get('instance')) forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class SignUpForm(UserCreationForm): # first_name=forms.CharField(max_length=40,help_text="first Name") # last_name=forms.CharField(max_length=40,help_text="first Name") email=forms.EmailField(max_length=120) class Meta: model=User fields=('username','email','password1','password2') views.py from django.shortcuts import render from .forms import SignUpForm from django.shortcuts import redirect from django.contrib.auth import login,authenticate from .models import Profile # Create your views here. def index(request): return render(request,'myblog/home.html') def signUp(request): form=SignUpForm(request.POST) if form.is_valid(): user=form.save() user.refresh_from_db() # user.profile.first_name=form.cleaned_data.get('first_name') # user.profile.lastname=form.cleaned_data.get('last_name') user.profile.email=form.cleaned_data.get('email') user.save() username=form.cleaned_data.get('username') password=form.cleaned_data.get('password1') user=authenticate(username=username,password=password) login(request,user) return redirect('http://127.0.0.1:8000/') else: print('form not submitted successfully \n') form=SignUpForm() return render(request,'myblog/signup.html',{'form':form}) i am new please also help me to explain why thanks in advance -
How to upload and save image and form using django and ajax bootstrap modals?
How to upload and save image and form using django and ajax bootstrap modals I am trying to save an image and form using Django and ajax. When try to save it don't save, and i don't know why. some one can help me why is the reason. I want to save image and form but when i try it to do it and nothing is wrong and i don't know why. so i need to save the image with the form Views.py: def save_all(request,form,template_name): #function save articles data = dict() if request.method == 'POST': form = ArticlesForm(request.POST, request.FILES) if form.is_valid(): form.save() data['form_is_valid'] = True article = Articles.objects.all() data['feed'] = render_to_string('inventory/list_feed.html',{'article':article}) else: data['form_is_valid'] = False context = { 'form':form } data['html_form'] = render_to_string(template_name,context,request=request) return JsonResponse(data) def create_article(request): #function add articles if request.method == 'POST': form = ArticlesForm(request.POST, request.FILES) else: form = ArticlesForm() return save_all(request,form,'inventory/create_article.html') forms.py: #Django from django.contrib.auth.models import User from django import forms #models from inventory.models import Articles class ArticlesForm(forms.ModelForm): #Article Form class Meta(): model = Articles fields = ( 'name','quantity', 'fk_brand','model','fk_category', 'coust_buy','fk_supplier','userful_life','actual_state', 'date_check','fk_user','fk_microbusiness','location','img', 'description') labels = { 'name':'','quantity':'', 'fk_brand':'','model':'','fk_category':'', 'coust_buy':'','fk_supplier':'','userful_life':'','actual_state':'', 'date_check':'','fk_user':'','fk_microbusiness':'','location':'','img':'', 'description':'',} widgets = { 'img': forms.FileInput(attrs={'type': 'file'}), } models.py: class Articles(models.Model): #models article Nuevo = 'Nuevo_1' Semi_nuevo … -
django dictionary of querysets
i made i dictionary of querysets in one of my views : list =[] while(x<100 and i>0): order_qs_1 = Order.objects.filter(timestamp__range=[start_date, end_date]) x = x+1 i=i-j list.append(order_qs_1) context= { 'list':list, } but now i don't know how to access the data inside the dictionary in my template in my template i did something like this : {% for item in list %} {{ item }} </br> {% endfor %} this is what it renders: the random numbers and characters are the order_id in my order model the queryet is a list of orders coming from my order model but this not what i want , i want the access the data inside each queryset -
Django , form rendered twice. User is created without profile. Best practice to process multiple related forms in a single view?
I have 4 separate forms being processed in the same view. 3 of the forms' models are dependent on the 4th. They essential extend a User object When trying to save, I get the following error: no such table: WAD2app_userprofile' In the log I get: <UserProfile: UserProfile object (None)> profile_form <UserProfileForm bound=True, valid=True, fields=(image;postcode;building;address;phone)> and all the other forms are also valid and bound. view registered = False if request.user.is_authenticated: return redirect('WAD2app:profile') if request.method == 'POST': user_form = UserForm(request.POST) profile_form = UserProfileForm(request.POST) preference_form = UserPrefForm(request.POST) life_form = UserLifeForm(request.POST) if user_form.is_valid() and profile_form.is_valid() and preference_form.is_valid() and life_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() #prevents DB integrity errors profile = profile_form.save(commit=False) profile.user = user if 'picture' in request.FILES: profile.picture = request.FILES['picture'] profile.save() pref = preference_form.save(commit=False) pref.user = user pref.save() life = life_form.save() life.user = user life.save() dogs = Dog.objects.all() calcNewUser(user, dogs, True) registered = True messages.success(request, 'Your account has been successfully created! ') return redirect('WAD2app:login') else: print(user_form.errors, profile_form.errors) messages.error(request, 'Something went wrong while trying to register your account. Please try again.') else: user_form = UserForm() profile_form = UserProfileForm() preference_form = UserPrefForm() life_form = UserLifeForm() return render(request, 'wad2App/users/register.html', context = {'user_form': user_form, 'profile_form': profile_form, 'preference_form': preference_form, 'life_form': life_form,'registered': registered}) models class UserProfile(models.Model): user = … -
is there a way to represent several models in a single page?
I am a beginner in django and I am stuck in a small problem, I hope to be able to find help: I have 03 models class ModelA (models.Model): id = models.UUIDfield (primary_key = True, .......) ........ other attributes ....... class ModelB (models.Model): id = models.AutoField (primary_key = True) medelA = models.OneToOneFields ('ModelA', on_delete = models.CASCADE) class ModelC (models.Model): id = models.AutoField (primary_key = True) medelB = models.ForeignKey ('modelB', on_delete = models.CASCADE) I want to put the 03 models in the same pages and I have a problem of passing keys between the forms Thanks for your help -
Using FontAwesome5 in Django
I am using FontAwesome5 in Django. But when I render the html using icon.as_html I only get the icon. <i class="fas fa-hands-helping " aria-hidden="true"></i> Is there a way to add fa-stack-1x fa-inverse? -
How do I connect this JS form that gets the data and push it to my django.view file
I've been struggling for hours to get this java script code data from here to my django.view, I changed the URL but it's still trying to find an original php file '././mail/contact_me.php'. Can anyone let me know how I can do this, I want it to go into the view so then I can feed the data into a django model and then manage it from there, that way I am using the framework in something I know better as javascript is new to me and is very confusing, however if you guys have more effective recommendations I am all ears $(function() { $("#contactForm input,#contactForm textarea").jqBootstrapValidation({ preventSubmit: true, submitError: function($form, event, errors) { // additional error messages or events }, submitSuccess: function($form, event) { event.preventDefault(); // prevent default submit behaviour // get values from FORM var name = $("input#name").val(); var email = $("input#email").val(); var phone = $("input#phone").val(); var message = $("textarea#message").val(); var firstName = name; // For Success/Failure Message // Check for white space in name for Success/Fail message if (firstName.indexOf(' ') >= 0) { firstName = name.split(' ').slice(0, -1).join(' '); } $this = $("#sendMessageButton"); $this.prop("disabled", true); // Disable submit button until AJAX call is complete to prevent duplicate messages … -
Python await outside async function
I'm trying to send data to my client from a Django channels consumer. I tried the following code: class EchoConsumer(AsyncJsonWebsocketConsumer): async def connect(self): await self.accept() await self.send_json('test') var = '' def process_message(message): JSON1 = json.dumps(message) JSON2 = json.loads(JSON1) #define variables Rate = JSON2['p'] Quantity = JSON2['q'] Symbol = JSON2['s'] Order = JSON2['m'] print(Rate) await self.send_json(Rate) bm = BinanceSocketManager(client) bm.start_trade_socket('BNBBTC', process_message) bm.start() The problem with my actual code is that i'm getting the following error: SyntaxError: 'await' outside async function I think this happens because i'm using await inside a synchronous function. The problem is that i don't know how to send the variable Rate in any other way. Can someone help me fix this issue? -
Django classmethod doesn't have a decorator
I saw a couple of classmethod that doesn't have a decorator @classmethod. What's the reason about it? https://github.com/django/django/blob/3.0/django/db/models/base.py#L320 https://github.com/django/django/blob/3.0/django/db/models/manager.py#L20 -
How do I display my static files in my html from django
I have created my static folder and uploaded images into my images folder. The local server runs alright but the image is not able to display when i call the path to it in http://127.0.0.1.8000/static/images/theimage.jpg