Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModuleNotFoundError: No module named 'firstappdjango'
How can solve this problem? I already install django.all is ok but 1 problem show me again and again that's....ModuleNotFoundError: No Module named 'firstappdjango' how can fix this problem please help me -
how to access following request in view and save multiple checkboxes
GET /buildknowledge/sharing?bid=75&mycheckboxes%5B%5D=16&mycheckboxes%5B%5D=17 HTTP/1.1" 500 14440 I used POST not GET , to explain easily i used GET request views.py def test(request): if request.method == "POST" and request.is_ajax() : if "bid" in request.POST: B_id=request.POST.get("bid") sharewith=request.POST.getlist("mycheckboxes") for user_id in sharewith: Test(B_id=B_id,sharewith=user_id).save() return HttpResponse(json.dumps({'msg': "ok"}), content_type="application/json") else: return render(request,template_name='registration/basetest.html') nothing got saved in database -
Django query time difference
I have a simple MySQL query which I would like to implement at Django, but I fail: select * from customer where ((curdate() - followUpdate ) >2 and (curdate() - followUpdate ) < 8); Is this query possible? -
django-easy-pdf can't override css style
I am using django-easy-pdf for generate PDF file in my django project. Problem is I can't override some element's style, for example <hr> style. My code {% block extra_style %} <style type="text/css"> hr { border-top: dotted 1px; } </style> {% endblock %} {% block content %} <div id="content"> <hr> </div> And line is still solid and black like in default style. What is interesting, some CSS styles work very well, for example body { font-family: 'FontName'; font-size: 12px; } But word-wrap: break-word; in body doesn't work. Could somebody explain me that? -
Django set decimal separator depending on user browser settings
I would like to make decimal separator inside form in Django application dependend on user browser settings. So if user has English leanguage then user should put 1.1 inside input form... If language would be German, then user should put 1,1 inside input form. How do I achive this inside Djnago application. P.S. I am using the standard CreateView with form_class inside the form class I have fields = "__all__" localized_fields = "__all__" -
Freezing timer on power outage or logut
I am developing a client server based exam application using node.JS or Django as back end and Angular as front end. One of the requirement is timer of one hour should freeze in case of power outrage and user should be able to login and resume test. is there any way in node.JS or Django or Firebase to implement this? -
Django-how to run a python script which outputs to html
I have a python script which creates a basic server: import socket HOST = '*IP of server*' # Standard loopback interface address PORT = 15000 # Port to listen on with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind((HOST, PORT)) s.listen() conn, addr = s.accept() with conn: print('Connected by', addr) while True: data = conn.recv(1024) if not data: break print("no data") conn.sendall(data) I also have an Django project which I want to run this script from when I launch the web application. I am also trying to get it to print to a textaera when it has a connection ie print('connected by',addr) Is this possible/how? I have looked around however it seams to be very niche. Thanks all -
How to add a collapsable table (accordion) to Django templates?
I have a table whose rows are dynamically generated (based on user input and an array from the views.py). I have tried several ways of adding collapse to the table. The latest thing I've tried is implementing bootstrap 4 collapse (https://getbootstrap.com/docs/4.1/components/collapse/). When you click on the chevron, it should display the collapsed material; but unfortunately, I haven't had any luck so far. What d'you think my issue is? <tbody> {% for r in result %} <tr class="parent"> <td> <button id="chev" class="fa fa-chevron-right rotate" data-toggle="collapse" data-target="details"> </button> </td> <td> {{ r.split.0 }} </td> <!-- sample word --> <td> {{ r.split.2 }}</td> <!-- ref word --> <td> {{ r.split.4 }}</td> <!-- cost --> <td> {{ r.split.3 }}</td> <!-- sum --> </tr> <tr class = "collapse show" id ="details" hidden> <td align="center" colspan="5">check</td> </tr> {% endfor %} </tbody> -
How to save form to database only if content meets certain criteria
I am looking for a way to check data submitted from a form whether it meets certain criteria – not whether the data is valid, but whether, for example, a certain question is answered 'yes' or 'no', and only if the response is 'yes', should the data be saved to the database. If the submitted data does not meet the criteria, then it should not be saved to the database and a message should be displayed notifying the user. My code thus far: I have a model that stores participant information: class Participant(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) date_of_birth = models.DateField() has_health_cover = models.CharField( choices=( ('0','No'), ('1','Yes) ), default='0', max_length=1 ) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.PROTECT ) date_registered = models.DateTimeField(default=timezone.now) The model is created using a Modelform: class ParticipantRegisterForm(forms.ModelForm): class Meta: model = Participant fields = [ 'first_name', 'last_name', 'date_of_birth', 'has_health_cover', ] Rendered using a generic CreateView object: class ParticipantRegisterView(LoginRequiredMixin, CreateView): model = Participant form_class = ParticipantRegisterForm template_name = 'participants/register.html' def form_valid(self, form): form.instance.provider = self.request.user return super().form_valid(form) I am not sure how to go about taking the POST request data, determining whether the variable has_health_cover was a 0 (No) or a 1 (Yes), and to only save the … -
Unable to import Model defined in another app
I have two apps appointments and clinic in my project myappointments. I have defined a model in appointments/models.py: class Clinicdb(models.Model): clinicid = models.AutoField(primary_key=True, unique=True) name = models.CharField(max_length=60, unique=True) label = models.SlugField(max_length=25, unique=True) email = models.EmailField(max_length=50, default='') mobile = models.CharField(max_length=15, default='') alternate = models.CharField(max_length=15, default='', blank=True) about = models.CharField(max_length=250, blank=True) state = models.CharField(max_length=25) city = models.CharField(max_length=35) locality = models.CharField(max_length=35) pincode = models.IntegerField(default=0) address = models.TextField(max_length=80, default='', blank=True) website = models.URLField(blank=True) logo = models.ForeignKey(ProfilePic, blank=True, null=True, on_delete=models.CASCADE) class Meta: unique_together = ["name", "mobile", "email"] def __str__(self): return self.name In clinic/models.py, I have: from appointments.models import Clinicdb class Album (models.Model): name = models.CharField(max_length=255) photo = models.FileField(upload_to="data/media/%Y/%m/%d") clinicid = models.ForeignKey(Clinicdb, blank=True, null=True, on_delete=models.CASCADE) def __str__(self): return self.photo However when running makemigrations (and runserver) I get: joel@hp:~/myappointments$ python3 manage.py makemigrations Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/joel/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/joel/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/home/joel/.local/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/joel/.local/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/home/joel/.local/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen … -
Visual Studio adds git directory one directory too high
For a Django project, I want the git directory in the same directory as the manage.py file. When I create a new python web project in Visual Studio it creates the git directory one directory above where I would put the manage.py file. How do I put the git directory in the right place? Let's say I create a new project in a folder called "project_dir". The .git directory is placed there. Visual studio creates a sub-folder with the project name (call it project_name) and only allows you to add files and folders within that sub-folder. I want the git data in project_name. project_dir ├───.git ├───.gitignore ├───project_name.sln ├───project_name │ ├───manage.py │ └───project_name.pyproj When I create a new project I do not have "create new directory for solution" checked. -
Django Admin--insert in the Filter Area and Tomorrow
I want to add an extra field in the filter area of the django-admin. Currently on date field, it is showing only Today Past 7 Days etc. I need also to have the Tomorrow field there. Is there a way to add this thing out there? This is my admin: class ParcareModelAdmin(admin.ModelAdmin): list_display = [ "email","user", "location", "parking_on", "parking_off", "venire", "plecare"] list_display_links = ["email", "user" ] list_editable = [ "parking_off", "parking_on","venire", "plecare"] list_filter = ["parking_on", "parking_off"] search_fields = ["location", "name"] class Meta: model = Parcare # def email(self, obj): # return obj.user.email def get_form(self, request, obj=None, **kwargs): form = super().get_form(request, obj, **kwargs) if not obj: user = request.user form.base_fields['user'].initial = user form.base_fields['email'].initial = user.email return form admin.site.register(Parcare, ParcareModelAdmin) -
How to call a function when POST button is pressed on Django Rest Api
I have a Django rest api which you can upload a file and an id: Screenshot I want to call a function when post button is pressed in order to do some stuff with the uploaded file. How can I do this in django rest platform? -
How to link to wagtail routablepage from outside cms?
Currently i'm trying to integrate django wagtail with existing project, i use wagtail for blog. and the i create routablepage within the wagtail. how can i call that page link from my django index page ? -
Problem getting a delete button on an UpdateView to redirect
Python and Django newbie here I've been trying to get a delete button onto a standard UpdateView form from Django and then get that to redirect to the DeleteView if that button is pressed instead of the submit button. I have that working but im not sure how to redirect to the corresponding delete page on click. I expect i need to change the reverse_lazy('app:submission_delete') to include the id somehow but im a bit lost here, and my google fu isnt helping much either. views.py class AssessmentUpdate(UpdateView): model = Submission fields = '__all__' success_url = reverse_lazy('app:index') def form_valid(self, request): if 'Delete' in self.request.POST: reverse_lazy('app:Submission_delete') else: self.object = request.save() return HttpResponseRedirect(self.get_success_url()) urls.py app_name = 'app' urlpatterns = [ re_path(r'^$', views.index, name='index'), path('<int:submission_id>/', views.detail, name='detail'), path('<int:pk>/update/', views.AssessmentUpdate.as_view(), name='Submission_update'), path('<int:pk>/delete/', views.AssessmentDelete.as_view(), name='Submission_delete'), ] -
Django update an entire object (row)
I am trying to update an object named User with the properties username and fullname; my model is below. class User(models.Model): """docstring for User""" fullname = models.TextField() username = models.TextField() password = models.TextField() createdDate = models.DateTimeField(default=timezone.now) publishedDate = models.DateTimeField(blank=True, null=True) def publish(self): self.publishedDate = timezone.now self.save() def __str__(self): return str("\npk= " + self.pk + " | fullname= " + self.fullname + " | username= " + self.username + "\n") I have created an edit page and am able to get the values from that page in my view through request.POST["fullname"] and request.POST["username"]. My question is how do I update the entire object without having to specify a specific property in update or without getting the object and setting my new values and saving the object; my view is below. def editUserByID(request, userID): if (request.method == "POST"): if (request.POST["userID"] != '' and request.POST["fullname"] != '' and request.POST["username"] != ''): user1 = User( pk=request.POST["userID"], fullname=request.POST["fullname"], username=request.POST["username"] ) print(user1) # this only updates 1 property, so for multiple properties I would have to write multiple statements User.objects.filter(pk=user1.pk).update(fullname=user1.fullname) # is this possible? send the entire object and have it update the DB User.objects.filter(pk=user1.pk).update(user1) # this is how I was able to save it, but … -
Editing a previously generated HTML file with Django
I am very new to web development and the following is my use-case : I have a large number of Bokeh charts, each in a separate HTML file. In simple terms, I would like to have a home page, where I can provide links to each one of these charts. However, During runtime, I would like to edit these separate HTML files, so as to provide a link to go back to the home page or to other pages. I would not like to modify the HTML files permanently, so I can make use of them outside of the web page as well for simple visualization on my system. What is the best way to do this ? Are there technologies outside Django, I should be looking at to do something like this ? -
Django project not showing the views on web page,it is not showing any error message
i wrote a django project with the help of youtube channel "https://www.youtube.com/watch?v=fEqOW6FrokA" . In my django app it is not showing the list of saved object on home.html, "https://github.com/peekuz/Django/tree/master/todo" this is the link to the github -
Create modelform from multiple models to add to database?
In my postgressql database i have tables: class Topic(models.Model): Definition = models.TextField(default='Definition') Name = models.TextField(default='Name') def __str__(self): return self.Name class Question(models.Model): Statement = models.TextField(default='Question') def __str__(self): return self.Statement class Planit_location(models.Model): Planit_location = models.CharField(max_length=255, default='Planit_location') def __str__(self): return self.Planit_location class ClientDetail(models.Model): Sector = models.ForeignKey(Sector, on_delete=models.CASCADE) Client_name = models.CharField(max_length=255, default='Client_name') def __str__(self): return self.Client_name class Response(models.Model): Question = models.ForeignKey(Question, on_delete=models.CASCADE) Topic = models.ForeignKey(Topic, on_delete=models.CASCADE) Response = models.TextField(default='Response') Client = models.ForeignKey(ClientDetail, on_delete=models.CASCADE) Planit_Location = models.ForeignKey(Planit_location, on_delete=models.CASCADE) Image = models.ForeignKey(Image, on_delete=models.CASCADE) def __str__(self): return self.Response I want to create a modelform using all these tables so i can add new questions and responses to my database, which are then linked to a topic, location and client (these 3 will be a dropdownlist from data in db). I have managed to create a modelform for just question and response but when i try to submit it i get "null value in column "Question_id" violates not-null constraint" Here is the code: if request.method == 'POST': qform = QuestionForm(request.POST) rform = ResponseForm(request.POST) if qform.is_valid() and rform.is_valid(): qf = qform.save() rf = rform.save() return render(request, 'app/adddatatest.html', { "qform": QuestionForm(), "rform": ResponseForm(), }) -
Django serve static files with user verification
I have a feature to implement - 'User can upload a zip file containing html, css and js which I will extract to a folder and later user can view it'. I could implement the feature by making 'location' rules in nginx proxy server, like if 'location' contains a keyword, say 'userhtml', then serve all the files from a particular dataroot location. But, I want to add authentication to the system, if user is not logged in, he should not be able to see the files even if he know the url. That means all the requests(html,js,css) should pass through Django(can not be served directly by nginx). Can anyone give some pointers about how to do this. - Thanks, -
How to sort the Y axis according to the time in plotly using python?
I am using plot.ly to display the in_time and out_time in respective dates. i used pandas to extract the data frame and fed to the plotly to display the line graph but the problem is that the time displayed in y axis is not sorted and the time data is mixed up def get_emp_graph(e_id): tls.set_credentials_file(username='XXXXX', api_key='YYYYYY') df = pd.DataFrame(list(AttendanceRecord.objects.filter(emp_id=e_id, ).values().order_by('date'))) df['in_time'] = df['in_time'].apply(lambda x: format(datetime.strptime(x, '%H:%M:%S'), '%H:%M:%S')) df['out_time'] = df['out_time'].apply(lambda x: format(datetime.strptime(x, '%H:%M:%S'), '%H:%M:%S')) df['date'] = df['date'].apply(lambda x: datetime.strptime(x, '%Y-%m-%d').date()) df['miti'] = df['miti'].apply(lambda x: datetime.strptime(x, '%Y/%m/%d').date()) print(df['in_time']) print(df['date']) trace1 = go.Scatter( x=df['date'], y=df['in_time'], name='In Time', mode='markers+lines', text=e_id, line=dict(color='#17BECF'), ) trace2 = go.Scatter( x=df['date'], y=df['out_time'], name='Out Time', mode='markers+lines', text=e_id, line=dict(color='#7F7F7F'), ) data = [trace1, trace2] layout = go.Layout(title="Time Analysis", showlegend=True,yaxis=dict(autorange=True)) fig = go.Figure(data=data, layout=layout) div = plt.plot(fig, filename='d3', auto_open=False) print(div) return div Graph -
passing form parameters to 3-party program in django
win7 python2.7 django 1.11 I have written a web using django: when user apply a book via uploading form, the parameters were passed to an 3-party .exe program. I know to use os.system to pass the parametrs but I do not know where I could get the parameters for passing to the .exe program. And where I should store the exe program in the django project? project tree -
Two django projects sharing the same database user tables
I have tried to find the answer to my question and I couldn't so I am giving it a go. My problem is that I want to use the same users-related tables (auth_*, account_userprofile, account_userpermissions) on two completely different projects. I have read the sites framework documentation but still my questions are unanswered. I don't understand how to share the aforementioned models (existing in project_1/account/models.py). Should I copy project_1/account/models.py to project_2/account/models.py and fake project_2 account migrations? What if want to change a field in account_userprofile model? Would I need to make the modifications in both models.py copies and fake project_2's migration? Isn't this ugly? I am sure there is something that I am terribly missing here. What is the proper/best way to use the same user-related tables between two different projects? PS: Using python 3, django 2.0, PostgreSQL 9.5. -
AttributeError : type object '_io.StringIO' has no attribute 'StringIO'
In my model I want to format the imagefield by overridding the save method I have done this in my model from PIL import Image as Img from io import StringIO from django.core.files.uploadedfile import InMemoryUploadedFile class Blog(models.Model): Blog_image= models.ImageField(upload_to="...", blank=True) def save(self, *args, **kwargs): if self.Blog_image: image = Img.open(StringIO.StringIO(self.Blog_image.read())) image.thumbnail((900,300), Img.ANTIALIAS) output = StringIO.StringIO() image.save(output, format='JPEG', quality=150) output.seek(0) self.Blog_image = InMemoryUploadedFile(output,'ImageField', "%s.jpg" %self.Blog_image.name, 'image/jpeg', output.len, None) super(Blog, self).save(*args, **kwargs) But getting this Attribute error AttributeError : type object '_io.StringIO' has no attribute 'StringIO' Can anyone explain me why I am getting this error??? My python version is 3.6.4 My Django version is 2.0.7 -
How to Deserialize a Json Data to Model Object with ForeignKey In Django rest-fram
My Model.py like following: class AForeignKeyClass(models.Model): Key1 = models.CharField(max_length=20, default='') Key2 = models.CharField(max_length=20, default='') And My Main Model Class it's : class TestForeignKeyClass(models.Model): TestKey1 = models.CharField(max_length=20, default='') TestKey2 = models.ForeignKey(AForeignKeyClass,related_name='tracks',on_delete=models.CASCADE,default=0)