Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Imported file has a wrong encoding: 'charmap' codec can't decode byte 0x8d in position 4510: character maps to in django import-export
I am trying to import data from a csv. Here is the csv's screenshot as you can see I've imported another csv it was completely ok but. For this csv it's not working. I am getting the error all the time. I am using encoding "utf8" Here is my code: import json import requests from bs4 import BeautifulSoup import pandas as pd from csv import writer url = "https://prowrestling.fandom.com/wiki/New_Japan_Pro_Wrestling/Roster" page = requests.get(url) soup = BeautifulSoup(page.content, 'html.parser') # links = [ # "https://prowrestling.fandom.com/" + a["href"] for a in soup.select("classname a") # ] links = [ "https://prowrestling.fandom.com/" + a["href"] for a in soup.select("td a") ] with open("real/njpw.csv", 'a', encoding="utf8", newline="") as f: print(f) wrt = writer(f) header = ["ring_name", "height", "weight", "born", "birth_place", "trainer", "debut", "resides"] wrt.writerow(header) for link in links: soup = BeautifulSoup(requests.get(link).content, "html.parser") ring_name = soup.h2.text.strip() height = soup.select_one('.pi-data-label:-soup-contains("Height") + div') if height is not None: height = height.text.strip() else: height = "" weight = soup.select_one('.pi-data-label:-soup-contains("Weight") + div') if weight is not None: weight = weight.text.strip() else: weight = "" born = soup.select_one('.pi-data-label:-soup-contains("Born") + div') if born is not None: born = born.text.strip() else: born = "" birth_place = soup.select_one('.pi-data-label:-soup-contains("Birth Place") + div') if birth_place is not None: birth_place = … -
NoReverseMatch problem with UpdateView class in Django
I am trying to create an update view in django, inheriting UpdateView. My view looks like this: class UpdateStudentView(UpdateView): model = Student form_class = StudentForm template_name = "students/students_update.html" success_url = reverse_lazy("students:students") This view takes Student`s primary key as an argument from url path("update/<uuid:pk>/", UpdateStudentView.as_view(), name="update_student"), And here is the template, which should take this primary_key from url and pass it to view. {% block content %} <form action="{% url "students:update_student" pk %}" method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> {% endblock content %} However, it doesn`t work and throws a NoReverseMatch: NoReverseMatch at /students/update/primary_key_here/ Reverse for 'update_student' with arguments '('',)' not found. 1 pattern(s) tried: ['students/update/(?P<pk>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/\\Z'] Could you please explain me why does this happen and how can I avoid this error? Please don`t tell me about using pk_url_kwarg = 'pk', as it is 'pk' by default Thanks in advance! -
Exception Value: Profile matching query does not exist
I have automatically created a profile with signals when a user is created. In this profile you can add followers in the ManyToMany field called followers. But when I try to use the AddFollower or RemoveFollower method I get this error. This only happens with profiles created automatically with signals, those created with the django admin work fine. I'd appreciate your help! My views.py class AddFollower(ListView): def post(self, request, pk , *args, **kwargs ): profile = Profile.objects.get(pk=pk) profile.followers.add(self.request.user) return redirect('profile', username = profile.user.username) class RemoveFollower(ListView): def post(self, request, pk , *args, **kwargs ): profile = Profile.objects.get(pk=pk) profile.followers.remove(self.request.user) return redirect('profile', username = profile.user.username) Urls.py: urlpatterns = [ path('profile', profile,name='profile'), path('profile/<str:username>/', profile,name='profile'), path('add_follower/<int:pk>/', AddFollower.as_view(),name='add_follower'), path('remove_follower/<int:pk>/', RemoveFollower.as_view(),name='remove_follower'), path('all_followers/<int:pk>/', AllFollowers.as_view(), name='all_followers'), path('feed', Feed.as_view(),name='feed'), path('register', register, name='register'), path('login', LoginView.as_view(template_name='network_app/login.html'), name='login'), path('logout', LogoutView.as_view(template_name= 'network_app/logout.html'), name='logout'), path('create_post', CreatePost.as_view(), name='create_post' ), path('following_posts', FollowingPosts.as_view(), name= 'following_posts') ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) html: {% if user.is_authenticated and user != current_user %} {% if is_following %} <h1>{{ is_following }}</h1> <form method="POST" action="{% url 'remove_follower' user.pk %}" > {% csrf_token %} <button type="submit">Unfollow</button> </form> {% else %} <h1>{{ is_following }}</h1> <form method="POST" action="{% url 'add_follower' user.pk %}" > {% csrf_token %} <button type="submit">Follow</button> </form> {% endif %} {% endif %} Profile function: def profile … -
How to download a visiting card with dynamic content?
I am creating a django app, where i wanted to provide our clients a downloadable visiting card inside their account. For that i have a user models as follows: class Country(models.Model): name = models.CharField(max_length=100, unique=True) class CustomUser(models.Model): email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) contact_number = models.CharField(max_length=30) country = models.ForeignKey(Country, on_delete=models.SET_NULL) profile_pic = models.ImageField() def full_name(self): return f'{self.first_name} {self.last_name}' my url is as follows: from django.urls import path from . import views urlpatterns = [ path('visiting-card/<int:vid>', views.visitingCard, name='visiting-card'), ] and i have created a view to get all the content from respective users: def visitingCard(request, mid): user = get_object_or_404(CustomUser, id=vid) context = { 'user': user, } return render(request, 'visitng-card.html', context) and the below code is my visting card landing page html file {% extends 'base.html' %} {% load static %} {% block content %} <div class="container-fluid"> <div class="main-content-body"> <div class="row row-sm"> <div class="col-lg-4"> <div class="card crypto crypt-primary overflow-hidden"> <div class="card-body"> <div style="position: relative;" > <img src="{% static 'dashboard/img/visiting-card-bg.jpg' %}" /> </div> <div style="position: absolute; top: 90px; left: 85px;" > <img src="{{user.profile_pic.url}}" alt="{{user.full_name}}" style="max-width:130px;" class="rounded"> </div> <div style="position: absolute; top: 100px; left: 230px;"> <p> <strong>Name: {{user.full_name}}</strong><br> <strong>Country: {{user.country.name}}</strong><br> <strong>Email: {{user.email}}</strong><br> <strong>Contact: {{user.contact_number}}</strong><br> </p> </div> <div class="pt-3"> <a href="#" … -
Django Celery cannot get access to redis running on another raspberry pi
I'm currently following this tutorial on how to set up celery. I want to use my Raspbery Pi for the redis server, thus I have installed redis on it, and it works. Now, in the Django project I have defined #settings.py CELERY_BROKER_URL = "redis://192.168.0.21:6379" CELERY_RESULT_BACKEND = "redis://192.168.0.21:6379" (where the IP-address is the IP of my Raspberry running the redis server) but my local computer cannot access the redis server; the command python -m celery -A django_celery worker throws the error ERROR/MainProcess] consumer: Cannot connect to redis://192.168.0.21:6379//: DENIED Redis is running in protected mode because protected mode is enabled, no bind address was specified, no authentication password is requested to clients. In this mode connections are only accepted from the loopback interface. If you want to connect from external computers to Redis you may adopt one of the following solutions: 1) Just disable protected mode sending the command 'CONFIG SET protected-mode no' from the loopback interface by connecting to Redis from the same host the server is running, however MAKE SURE Redis is not publicly accessible from internet if you do so. Use CONFIG REWRITE to make this change permanent. 2) Alternatively you can just disable the protected mode by editing … -
relation "django_plotly_dash_statelessapp" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "django_plotly_dash_statel
I am trying to deploy my Django app on render. But there is an error which I don't understand what type of error is this.Please help to solve this error: ProgrammingError at /nickelpure/[relation "django_plotly_dash_statelessapp" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "django_plotly_dash_statel... ^ Error screenshot -
for loop for password add letters in django
so i want to check if my password less from key_bytes (which is 16) then the password will be add "0" until it's have len 16. i was using django. for example password = katakataka. it's only 10. then it will became "katakataka000000" i don't know how to make loop for, so please help me. here's my code key_bytes = 16 if len(key) <= key_bytes: for x in key_bytes: key = key + "0" print(key) -
irregular arbitrarily Cross-Origin request blocked error in Django on Ionos hosting
I am currently making a project for school where I made a quiz. The quiz is supposed to evaluate in the front-end, which works perfectly fine, and after that it should send the information to the backend. The Backend should save the details to the database and after that it should send the information back to the front end. The front end should show a message with some details about how you passed compared to all the others, the information are the one from the database. So, the weird thing about all that is, that it works sometimes and sometimes not... If I test it at the local host, the code works perfectly fine, the error only occurs on the Ionos server (I got a hosting contract so I do not have access to the console...). Here is btw. the Link to my website: https://tor-netzwerk-seminarfach2024.com/ .If you click in the upper left corner and then on the quiz buttonm, you will get to the quiz. If I look at the console and network analytics and I got the "luck" that the error occurs the following message shows up: Cross-Origin request blocked: The same source rule prohibits reading the external resource … -
Django Rest Framework SimpleJWT, custom use case
In DRF SimpleJWT, we need to set a value for when the Refresh Token and the access token would expire. So, the user must log in again after the refresh token expires. But when using Firebase Auth, the user does not need to log in repeatedly. Is there a way to emulate a similar behavior in Django Rest Framework, like in Firebase Authentication. -
Django form and formset are not valid
I'm trying to make a view containing one form and one formset but something does not work. both form and formset after checking if .is_valid returns false. I do not really undersand why it is like that def ProductCreateView(request): context = {} created_product = None form = ProductForm() if request.method == 'POST': form = ProductForm(request.POST) if form.is_valid(): created_product = form.save() print("Successfully created new product: {}".format(created_product)) else: print("form is not valid") #print(request.POST) returns csrfmiddlewaretoken ... #print(request.FILES) returns file : inmemoryuploadedfile ... #print(list(request.POST.items())) context['form'] = form formset = ProductPhotoInlineFormset() if request.method=='POST': formset = ProductPhotoInlineFormset(request.POST or None, request.FILES or None, instance=created_product) if formset.is_valid(): created_images = formset.save() print("Successfully created new imagest: {}".format(created_images)) else: print("formset is not valid") context['formset'] = formset return render(request, "Ecommerce/create_product_test.html", context) my template - create_product_test.html {% extends 'base.html' %} {% block content %} <div id="alert-box"> </div> <div id="image-box" class="mb-3"> </div> <div id="image-box"></div> <div class="form-container"> <button class="btn btn-primary mt-3 not-visible" id="confirm-btn">confirm</button> <form method="POST" enctype="multipart/form-data" action="" id="image-form"> {% csrf_token %} <div> {{form}} {{formset.management_form}} {{formset.as_p}} </div> </form> </div> {% endblock content %} forms.py file ProductPhotoInlineFormset = inlineformset_factory( Product, Photo, fields=('file',), form=PhotoForm, extra=1, ) where is the problem ? -
Two exactly same repositories but different result
Sorry for this weird question but my mind went blank. I can install a script from its original Github repo (project1) in an Ubuntu server: I clone the original repo and start installation in the server, no problem at all. However if I create a repo (project2) in my GitHub account, then copy all the files (except .git) from the original repo (project1) to my new repo (project2), then clone my repo and start installation in the server, installation gives me an error. ango.db.migrations.exceptions.InvalidBasesError: Cannot resolve bases for [<ModelState: 'dictionary.MetaFlatPage'>] This can happen if you are inheriting models from an app with migrations (e.g. contrib.auth) in an app with no migrations; see https://docs.djangoproject.com/en/3.2/topics/migrations/#dependencies for more Those two repositories are the exactly same. I didn't change any file, any line. Do you know what possibly causes this issue? Script is a Django script. -
Get sum of the salary for each user
I am on a django project where the admin assigns work to users by uploading the work to each user, and the user can only see the job they have been assigned. I want a way to get the total amount for all the work the user have done by the end of a month. I have a model Work, and it has a field Pay_Amount, which is the amount for one job, I want a way to add the Pay_Amount of only one user per month. I already have the total amount to pay all the users, I just want the amount to pay a single user for all the jobs he/she has done for one month... Please assist... -
Unknown layer: Patches. Please ensure this object is passed to the `custom_objects` argument
Unknown layer: Patches. Please ensure this object is passed to the custom_objects argument. See https://www.tensorflow.org/guide/keras/save_and_serialize#registering_the_custom_object for details. Anyone please? I have passed the Patches object to the "custom_object"but getting again and again same error. Patches Layer: class Patches(layers.Layer): def __init__(self, patch_size, **kwargs): super(Patches, self).__init__() self.patch_size = patch_size def call(self, images): batch_size = tf.shape(images)[0] patches = tf.image.extract_patches( images=images, sizes=[1, self.patch_size, self.patch_size, 1], strides=[1, self.patch_size, self.patch_size, 1], rates=[1, 1, 1, 1], padding="VALID", ) patch_dims = patches.shape[-1] patches = tf.reshape(patches, [batch_size, -1, patch_dims]) return patches def get_config(self): config = super(Patches, self).get_config() config.update({ 'patch_size': self.patch_size, }) return config Second Layer class PatchEncoder(layers.Layer): def __init__(self, num_patches, **kwargs): super(PatchEncoder, self).__init__() self.num_patches = num_patches self.projection = layers.Dense(units=projection_dim) self.position_embedding = layers.Embedding( input_dim=num_patches, output_dim=projection_dim ) def call(self, patch): positions = tf.range(start=0, limit=self.num_patches, delta=1) encoded = self.projection(patch) + self.position_embedding(positions) return encoded def get_config(self): config = super(PatchEncoder, self).get_config() config.update({ 'num_patches': self.num_patches, }) return config Layer Passing Arguments: loaded_2 = keras.models.load_model(r"E:\FYPProject\Notebooks\vit.h5", custom_objects={"Patches": Patches, "PatchEncoder":PatchEncoder}) print("Loaded Model With Custome Layers/Objects", loaded_2) -
How to display the user id in django
I have a function in which I have to, among other things, pass to the template the ids of the users who conducted the correspondence, but I get an error in the line: pk_list = messages.values('user_from__pk').distinct() views.py: def send_chat(request): resp = {} User = get_user_model() if request.method == 'POST': post =request.POST u_from = UserModel.objects.get(id=post['user_from']) u_to = UserModel.objects.get(id=post['user_to']) messages = request.user.received.all() pk_list = messages.values('user_from__pk').distinct() correspondents = get_user_model().objects.filter(pk__in=list(pk_list)) insert = chatMessages(user_from=u_from,user_to=u_to,message=post['message'],correspondents=correspondents) try: insert.save() resp['status'] = 'success' except Exception as ex: resp['status'] = 'failed' resp['mesg'] = ex else: resp['status'] = 'failed' return HttpResponse(json.dumps(resp), content_type="application/json") models.py: class chatMessages(models.Model): user_from = models.ForeignKey(User, on_delete=models.CASCADE,related_name="sent") user_to = models.ForeignKey(User, on_delete=models.CASCADE,related_name="received") message = models.TextField() date_created = models.DateTimeField(default=timezone.now) correspondents = models.ForeignKey(User, on_delete=models.CASCADE,related_name="correspondents", null=True) def __str__(self): return self.message Error: TypeError: Field 'id' expected a number but got {'user_from__pk': 1}. how can I fix this error? -
Django Channels message read and unread
I am new to django channels and trying to build a chat app, I met some trouble in developing read and unread functioning, I hope you can give me a hand. chat consumer has a very simple structure: room name chat_1 is for user 1 to receive message. whoever connects to it, can send message to user 1, and database save method is defined in consumer which takes self.scope["user"] as sender, and self.room_name as receiver to create message record and mark it as unread user has a friend list, by clicking on the name, load all messages, meanwhile mark all messages to read, I did this by ajax function rather than ws as user click away from talking target. but here is one scenario, where two user is on each other's page and does not click anyone else, I need to init the message with read already when creating to database. let's say user_1 is talking to user_22, user_1 connect to many ws, but currently facing ws_22 to send message to user_22. In the receive method, how can I determine whether user_22 is currently facing ws_1 which waiting for the message? by saying facing, I does not mean connect to … -
django-tenants basics: SHARED_APPS vs TENANT_APPS
I am using django-tenants for a multi-tenant app. In the docs it talks about setting up SHARED_APPS and TENANT_APPS. SHARED_APPS is a tuple of strings just like INSTALLED_APPS and should contain all apps that you want to be synced to public If I want an app (e.g. django.contrib.auth) to be accessible on both the public schema and shared schema, do I include it only in the SHARED_APPS or do I need to include it in both SHARED_APPS and TENANT_APPS? "SHARED" would imply that everything in this list is accessible via all tenants and the public schema, but the docs seem to imply otherwise? -
how to pass user id values to parameters in django?
I have a code where I need to pass the user_from id (the user from whom the message comes), but when I write user_from__pk writes an error that there is no such name NameError: name 'user_from__pk' is not defined My code: views.py: def send_chat(request): resp = {} User = get_user_model() if request.method == 'POST': post =request.POST u_from = UserModel.objects.get(id=post['user_from']) u_to = UserModel.objects.get(id=post['user_to']) messages = request.user.received.all() pk_list = messages.values(user_from__pk).distinct() correspondents = get_user_model().objects.filter(pk__in=list(pk_list)) insert = chatMessages(user_from=u_from,user_to=u_to,message=post['message'], correspondents=correspondents) try: insert.save() resp['status'] = 'success' except Exception as ex: resp['status'] = 'failed' resp['mesg'] = ex else: resp['status'] = 'failed' return HttpResponse(json.dumps(resp), content_type="application/json") models.py: class chatMessages(models.Model): user_from = models.ForeignKey(User, on_delete=models.CASCADE,related_name="sent") user_to = models.ForeignKey(User, on_delete=models.CASCADE,related_name="received") message = models.TextField() date_created = models.DateTimeField(default=timezone.now) correspondents = models.ForeignKey(User, on_delete=models.CASCADE,related_name="correspondents", null=True) def __str__(self): return self.message how can I pass the user_from id in the line: pk_list = messages.values(user_from__pk).distinct() -
Data fetching issues from table which is using jinja2 (django)
I have a table which contains some list of student from my database, I want to fetch data from that html table which contains data from database but I want to add if the student is present or not. I have a code which works perfectly but there is an issue that my functions only takes last row data and skips all other rows. HTML code <div class="container"> <form method="POST" action="takeattendance"> {% csrf_token %} <div class="form-group"> <h4 style="color:white;"> Select Subject For Attendance</h4> <select class="btn btn-success" name="subject"> <option selected disabled="true">Subject</option> {% for sub in subjects%} <option value="{{ sub.id }}">{{sub.subject_name}}</option> {%endfor%} </select> </div> <table class="table"> <thead> <tr> <th scope="col" style="color:white;"><b>Email</b></th> <th scope="col" style="color:white;"><b>Roll No.</b></th> <th scope="col" style="color:white;"><b>First Name</b></th> <th scope="col" style="color:white;"><b>Last Name</b></th> <th scope="col" style="color:white;"><b>Year</b></th> <th scope="col" style="color:white;"><b>Division</b></th> <th scope="col" style="color:white;"><b>Batch</b></th> <th scope="col" style="color:white;"><b>Attendance</b></th> </tr> </thead> <tbody> {% for student in students %} {% if user.staff.class_coordinator_of == student.division and user.staff.teacher_of_year == student.year %} <tr> <td style="color:white;"><input type="hidden" name="student_name" value="{{student.id}}" >{{student.user}}</td> <td style="color:white;">{{student.roll_no}}</td> <td style="color:white;">{{student.user.first_name}}</td> <td style="color:white;">{{student.user.last_name}}</td> <td style="color:white;">{{student.year}}</td> <td style="color:white;">{{student.division}}</td> <td style="color:white;">{{student.batch}}</td> <td> <div class="form-group"> <select class="btn btn-success" name="status" id="status"> <option selected value="Present">Present</option> <option value="Absent">Absent</option> </select> </div> </td> </tr> {% endif %} {% endfor %} </tbody> </table> <div class="form-group"> <button type="submit" class="btn … -
Django form not saving - cannot identify problem with code
Trying to save the below form, but it's not saving. The traceback doesn't identify any problem, and print(form.errors) doesnt not return any issue. I have the exact same code working for another page. So I am not sure what I am missing here. There has to be a typo, I cannot find it. You will notice that I have an autocomplete function in my template. I initially thought autocomplete was not returning data in all the fields, so also tried to input data manually but not luck either. Also tried with and without is_ajax but same result. Models class Venue(models.Model): name = models.CharField(verbose_name="Name",max_length=100, null=True, blank=True) address = models.CharField(verbose_name="Address",max_length=100, null=True, blank=True) town = models.CharField(verbose_name="Town",max_length=100, null=True, blank=True) county = models.CharField(verbose_name="County",max_length=100, null=True, blank=True) post_code = models.CharField(verbose_name="Post Code",max_length=8, null=True, blank=True) country_1 = models.CharField(verbose_name="Country1",max_length=100, null=True, blank=True) country_2 = models.CharField(verbose_name="Country2",max_length=100, null=True, blank=True) longitude = models.CharField(verbose_name="Longitude",max_length=50, null=True, blank=True) latitude = models.CharField(verbose_name="Latitude",max_length=50, null=True, blank=True) phone = models.CharField(max_length=120) web = models.URLField('Website Address') email_address = models.EmailField('Venue Email Address') def __str__(self): return str(self.name) if self.name else '' Form class VenueForm(ModelForm): name = forms.CharField(max_length=100, required=True, widget = forms.TextInput(attrs={'id':"name"})) address = forms.CharField(max_length=100, widget = forms.TextInput(attrs={'id':"address"})) town = forms.CharField(max_length=100, required=True, widget = forms.TextInput(attrs={'id':"town"})) county = forms.CharField(max_length=100, required=True, widget = forms.TextInput(attrs={'id':"county"})) post_code = forms.CharField(max_length=8, required=True, … -
Django - Default on multiple radio buttons
I am making an absence control where you select the presence/absence per user through a radio button. This absence control is already working. But right now, when you save the absences and re-open the page, all the radio buttons are unselected so it is not possible to see what was filled in. How can I fix this so you can see in which way the radio buttons where selected? The absence control is saved through this view: def baksgewijs_attendance(request, baksgewijs_id, peloton_id): peloton = Peloton.objects.get(id=peloton_id) users = peloton.users.all() baksgewijs = Baksgewijs.objects.get(id=baksgewijs_id) random_list = list() for usertje in users: if Absences.objects.filter(date=baksgewijs.date, user=usertje).exists(): random_list.append(getattr(Absences.objects.get(date=baksgewijs.date, user=usertje), "explanation")) else: random_list.append("") zipped_list = zip(random_list, users) if request.method == "POST": print(request.POST) id_list = request.POST.getlist('id') for id in id_list: if request.POST.getlist(id): attendance = Attendance() attendance.user = User.objects.get(pk=id) attendance.attendance = request.POST.getlist(id)[0] attendance.baksgewijs = Baksgewijs.objects.get(id=baksgewijs_id) attendance.save() message = messages.success(request, ("De aanwezigheid is opgeslagen")) return HttpResponseRedirect(reverse("baksgewijs_index"), {"message" : message}) return render(request, "baksgewijs/mbaksgewijs_attendance.html", { "users" : users, "peloton" : peloton, "baksgewijs" : baksgewijs, "zipped_list" : zipped_list }) This is baksgewijs/mbaksgewijs_attendance.html: <form action="{% url 'create_attendance' baksgewijs.id peloton.id %}" method="post"> {% csrf_token %} <div class="table-responsive fixed-length"> <table id = "userTable" class="table table-striped table-hover table-sm table-bordered"> <tbody> {% for reason, user in zipped_list %} <tr> … -
why are my forms not valid (both forms.Form and ModelForm), and why is it not saving data to data base?
views.py my view contains two form, userform which I created with forms.Form and snippetform which I created with ModelForm. from django.shortcuts import render from .forms import Snippetform, Userform from .models import User, Snippet from django import forms # Create your views here. def user(request): form = Userform() if request.method == "POST": form = Userform(request.POST) if form.is_valid(): username = form.cleaned_data["username"] fname = form.cleaned_data["fname"] lname = form.cleaned_data["lname"] email = form.cleaned_data["email"] password = form.cleaned_data["password"] password2 = form.cleaned_data["password2"] new_user = User.objects.create(username,fname,lname,email,password,password2) new_user.save() return render(request,'my_app/user.html',{'form':form}) def snippet(request): form = Snippetform() if request.method == "POST": form = Snippetform(request.POST) if form.is_valid(): form.save() else: print(form.errors.as_data()) return render(request,'my_app/snippet.html',{'form':form}) def thanks(request): return render(request,'my_app/thanks.html',) forms.py from django import forms from . models import Snippet class Userform(forms.Form): username = forms.CharField() fname = forms.CharField(label="First name") lname = forms.CharField(label="Last name") email = forms.EmailField(label="E-mail") password = forms.IntegerField(required=False) password2 = forms.IntegerField(label="Confirm password",required=False) class Snippetform(forms.ModelForm): class Meta: model = Snippet fields = ("name","body") models.py from django.db import models # Create your models here. class User(models.Model): username = models.CharField(max_length=100) fname = models.CharField(max_length=100) lname = models.CharField(max_length=100) email = models.EmailField(max_length=30) password = models.IntegerField() password2 = models.IntegerField() class Snippet(models.Model): name = models.CharField(max_length=50) body = models.TextField(max_length=150) urls.py from django.urls import path from . import views #registered namespace for my app name which … -
Django models for questionaire with questions with different answer types
This question is similar to Designing Django models for questions to have different answer types but hopefully more specific. For my particular case I can see different ways for an implementation but I am not sure what a good way would be. I have a base usermodel. Users are presented with a questionnaire which can be the same for different user but can also be different from one user to another and also might be different on different days for a single user. Each questionnaire has different questions and the questions might have different answer types (text, int, etc). At the end I want a list of the questionnaires with answers for a specific user (e.g. of the past week for user X). I guess one way to implement this would be to only have one answer type (text) and let the form handle the validation and let the view handle the rendering with correct answer formatting: class Question(models.Model): question_text = models.CharField() answer_type = models.CharField() class Questionnare(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) questions = models.ManyToManyField(Question, through='Answer') date = models.DateField(auto_now_add=True) class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) questionnaire = models.ForeignKey(Questionnare, on_delete=models.CASCADE) answer = models.TextField() Maybe another way would be to have different Answer … -
How to integrate Django web application with blockchain? [closed]
I need to integrate a Django application with blockchain. But I can't figure out how to do that. The main theme is I need to store some user information on the blockchain and connect it through a Django table which will link to the blockchain. -
static/home/bootstrap/css/bootstrap.css” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff)
when I run normally code on local machine , it's working fine , but on heroku production from github it shows only html , no js , css working ...enter code here it sends this error I test my application on apple safari, chromium, firefox, google chromes ... The resource from “https://mywebsite.herokuapp.com/static/home/bootstrap/css/bootstrap.css” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff). The resource from “https://mywebsite.herokuapp.com/static/home/js/masonry.pkgd.min.js” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff). -
Is it better to deploy django to production with docker or without docker?
JUST FOR TECHNICAL ADVICE Please the question above is not complex, but I need extra professional advice, I have been using docker for years now and I am thinkng of the possibility of making a switch to dockerless or containerless deployment of django Despite docker has its pros and cons, I need more technical advice on which way to go Using without docker may refer to a single point of failure, but at the same time, I dont know using docker how it can completely match for this case