Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot start nginx due to false configuration
I am deploying my django project called "converter" on my ubuntu machine and I am following this tutorial: https://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html I have created a configuration file, which is called converter_nginx.conf and I have put it on the folder /etc/nginx/sites-available. This is the content of my configuration file: # converter_nginx.conf # the upstream component nginx needs to connect to upstream django { # server unix:///home/andrea/File-format-converter/converter/converter.sock; # for a file socket server 127.0.0.1:8001; # for a web port socket (we'll use this first) } # configuration of the server server { # the port your site will be served on listen 8000; # the domain name it will serve for server_name 1myIPaddress.com; # substitute your machine's IP address or FQDN charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste # Finally, send all non-media requests to the Django server. location / { uwsgi_pass django; include /home/andrea/File-format-converter/converter/uwsgi_params; # the uwsgi_params file you installed } } and symlinked this file as indicated on the tutorial with this command sudo ln -s ~/home/andrea/File-format-converter/converter/converter_nginx.conf /etc/nginx/sites-enabled/. Despite that when I start nginx I get this error: [....] Starting nginx (via systemctl): nginx.serviceJob for nginx.service failed because the control process exited with error code. See "systemctl … -
Django Admin Site two model combine into 1 model using foreignkey
I have this table StudentProfile and table StudentEnrollmentRecord, I just want to add an column before the Student User just like the picture below, this is my code in model.py class StudentProfile(models.Model): LRN = models.CharField(max_length=500,null=True) Firstname = models.CharField(max_length=500,null=True,blank=True) Middle_Initial = models.CharField(max_length=500,null=True,blank=True) Lastname = models.CharField(max_length=500,null=True,blank=True) class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, related_name='+', on_delete=models.CASCADE,null=True) School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True,blank=True) Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE,blank=True,null=True) and this is my code in admin.py class StudentsEnrollmentRecordAdmin(admin.ModelAdmin): list_display = ('Student_Users', 'School_Year', 'Courses', 'Section', 'Payment_Type', 'Education_Levels') ordering = ('Education_Levels',) list_filter = ('Education_Levels','Section','Student_Users') -
Javascript show more in table
I need to show another tbody of table on Click. I have following table which is in foreach so there will be multiple buttons.: <table class="table" id="call-table"> <tr> <th>Show more buttons</th> </tr> <tbody> {% for global in globals %} <tr> <td class="show-more-button">Show more</td> <tr> <tbody class="show-more"> <tr> <th scope="col">Data</th> <th scope="col">Value</th> </tr> {% for data in dataset %} <tr> <td>Some data....</td> <td>A value..</td> </tr> {% endfor %} </tbody> {% endfor %} </tbody> I'm using python with DjangoFramework. And that's the script i came up with. But it only works for changing the 's text but doesn't show the tbody. <script> $(document).on("click", ".show-more-button", function() { if ($(this).text() == "Show more") { $(this).text("Show less"); $(this).parent().children(".show-more").style.display = "block"; } else { $(this).text("Show more"); $(this).parent().children(".show-more").style.display = "block"; } }); </script> and in CSS: .show-more { display: none; } What error do i have in my script? -
Python Blog Django Vs WordPress
Are there any developers that are running Django and using it as a blog over WordPress? I would like to ask if you have found it to be more resistant compared to the normal attacks they direct at WordPress? I am already building my backend with Django and I wonder if I did integrate the blog part to the backend, including front-end would I at least get less attacks? What are your thoughts? -
AttributeError when running a flask app in flask shell
I have finished a flask app. When I run it by python run.py, the app can work perfectly. But when I want to open flask shell by flask shell or even just flask, it tell me: Traceback (most recent call last): File "f:\programs\anaconda\envs\web\lib\site-packages\flask\cli.py", line 556, in list_commands rv.update(info.load_app().cli.list_commands(ctx)) File "f:\programs\anaconda\envs\web\lib\site-packages\flask\cli.py", line 388, in load_app app = locate_app(self, import_name, name) File "f:\programs\anaconda\envs\web\lib\site-packages\flask\cli.py", line 257, in locate_app return find_best_app(script_info, module) File "f:\programs\anaconda\envs\web\lib\site-packages\flask\cli.py", line 83, in find_best_app app = call_factory(script_info, app_factory) File "f:\programs\anaconda\envs\web\lib\site-packages\flask\cli.py", line 117, in call_factory return app_factory(script_info) File "C:\Users\zkhp\Desktop\flask-bigger-master\backend\startup.py", line 41, in create_app app.config['SECRET_KEY'] = config.get('secret', '!secret!') AttributeError: 'ScriptInfo' object has no attribute 'get' The last sentence is here: def create_app(config): app = Flask( __name__, template_folder=template_folder, static_folder=static_folder ) app.config['SECRET_KEY'] = config.get('secret', '!secret!') The config is a dictionary, which is given by: def start_server(run_cfg=None, is_deploy=False): config = { 'use_cdn': False, 'debug': run_cfg.get('debug', False), 'secret': md5('!secret!'), 'url_prefix': None, 'debugtoolbar': True } app = create_app(config) I am confused with how the dictionary config is transformed to be a ScriptInfo? And what should I do to solve the problem? Thanks for your patient reading! -
How to calculate row value when base on previous row and current (django and postgres)?
I am looking to create row balance where: balance = (balance from previous date) + inflows - outflows There are some answers in SQL (LAG() function most likely) but have a problem how to implement it in Django ORM... Kindly ask for help... Best of luck Artur ''' class Account (models.Model): date = models.DateField(primary_key=True) inflows = models.FileField(null = True, max_length=100) outflows = models.FileField(null = True, max_length=100)''' -
In django, Is there a way to restrict user access to a url and all its children urls?
I am writing a simple Django application. I have an index page and accounts section, the account section can only be seen if the user is logged in. The problem is, that account section have many 'child' urls, like /accounts, /accounts/create, /accounts/update, /accounts/home etc etc. Currently, i am using login_required decorator and some other tests, but the code looks messy when i write the mixins and decorators on every view. Is there a simple way to block a url and all its children for a user? urlpatterns = [ path('',views.index_view,name="index"), url(r'^login/$', auth_views.LoginView.as_view(template_name='login.html' ,form_class=forms.AuthenticationForm), name='login'), url(r'^logout/$', auth_views.LogoutView.as_view(), name='logout'), path('accounts/',views.SellerRegister.as_view(),name="register_seller"), path('accounts/address_create/',views.address_create,name="address_create"), path('accounts/register_buyer/',views.register_buyer,name="register_buyer"), ] -
sessionid missing and session_key=None
For my view, how come I am seeing session_key = None ? @csrf_exempt @api_view(['GET']) def shuffle(request): if request.method == 'GET': request.session['selected'] = [] request.session['words'] = [] response = Response(data={'dice': 2}, status=status.HTTP_200_OK) else: response = Response(status=status.HTTP_405_METHOD_NOT_ALLOWED) return response I thought django would take care of generating everything sessions related as soon as I start modifying the sessions dictionary. In my settings.py I have SESSION_SAVE_EVERY_REQUEST = True as well. Going to check the developer tools, I also don't see the sessionid in my cookies -
Django: How to store in the database a list of dates and the songs someone listen that day?
Imagine I have 2 models Song and Person: class Person(models.Model): name = models.CharField(max_length=128) def __str__(self): return self.name class Song(models.Model): name = models.CharField(max_length=128) def __str__(self): return self.name And I want to create a field inside the Person model to store a list of the dates this person listens to music and what songs they listen to. 2019-10-2 -> (Song 3, Song 25, Song 50) 2019-10-3 -> (Song 4, Song 5, Song 12) 2019-10-7 -> (Song 77, Song 22, Song 11) The ManyToMany field seems to work for linking to one or multiple instances of another model but doesn't seem to be useful for this case. Is there any type of field could I use? Or is there any other way to store all that information? The only other way I can think of is creating a model like this and have a table with all the songs that everyone has listened to and link them to each user: class Song(models.Model): person = models.OneToOneField(Person) date = models.DateField() songs = models.ManyToManyField(Song) I'm pretty new to databases and django so im not really sure which is the proper way of storing this kind of information. Under the person's profile or in a different table? … -
Python 3.7 AttributeError: 'str' object has no attribute 'has'
When i m trying to use this below code-> if not isinstance(math, basestring): math = latex(math) return '{}'.format(math) i want to check object is str or not -> i m using python 3.7.3 , pip 19.3.1 , django 2.2 -> So that i used 'str' instead of 'basestring' ,, then script will generating : str' object has no attribute 'get' error Now i m using this code def format_math_display(self, math): try: if not isinstance(math, basestring): math = latex(math) return '{} '.format(math) except Exception: pass AttributeError at / 'str' object has no attribute 'has' Request Method: POST Request URL: http://127.0.0.1:8000/ Django Version: 2.2.6 Exception Type: AttributeError Exception Value: 'str' object has no attribute 'has' Python Executable: C:\Users\Vasundhara\Envs\calculate\Scripts\python.exe Python Version: 3.7.3 Python Path: ['C:\wamp64\www\Python3Django2\Calculate', 'C:\Users\Vasundhara\Envs\calculate\Scripts\python37.zip', 'C:\Users\Vasundhara\Envs\calculate\DLLs', 'C:\Users\Vasundhara\Envs\calculate\lib', 'C:\Users\Vasundhara\Envs\calculate\Scripts', 'c:\users\vasundhara\appdata\local\programs\python\python37\Lib', 'c:\users\vasundhara\appdata\local\programs\python\python37\DLLs', 'C:\Users\Vasundhara\Envs\calculate', 'C:\Users\Vasundhara\Envs\calculate\lib\site-packages'] Server time: Sat, 26 Oct 2019 04:08:58 +0000 -
How to Run this python script with Django?
// this is a matrix code of python and how should i run it in django enter code here X=[[1,2,3],[4,5,6],[7,8,9]] Y=[[9,8,7],[6,5,4],[3,2,1]] result=[[0,0,0],[0,0,0],[0,0,0]] for i in range(len(X)): for j in range(len(X)): result[i][j]=X[i][j]+Y[i][j] for r in result: print(r) -
Passing kwargs from CBV to Form in Django
I have a ModelForm which needs a user passed in so that the queryset can be updated. I am overriding the __init__ method as such: def __init__(self, *args, **kwargs): # override init to get user's casino's EmployeeType queryset self.user = kwargs.pop('user') print(self.user) super(MemoForm, self).__init__(*args, **kwargs) self.fields['receiver'].queryset = EmployeeType.objects.filter( casino=self.user.casino ) In the View I have a get and a post method. I am trying to pass the **kwargs in as such: class VideoUploadView(LoginRequiredMixin, View): """ Display a form for uploading videos. """ form_class = VideoUploadForm success_url = '/videos' template_name = 'videos/video_upload.html' def get(self, request, *args, **kwargs): form = self.form_class() return render( request, self.template_name, {'form': form, 'user': self.request.user} ) In a CreateView you are able to use the get_form_kwargs method to pass in the **kwargs. How is it done in a normal View? Should we use the __init__ method? The way shown above does not seem to work. -
Django admin site add html link
admin.py @admin.register(StudentsEnrollmentRecord) class StudentsEnrollmentRecord(admin.ModelAdmin): list_display = ('Student_Users', 'School_Year', '<a href="#">Report</a>') ordering = ('Education_Levels',) list_filter = ('Student_Users',) I just want that to add the html link in the adminsite then if the admin click the "report" it will filter what studentenrollmentrecord selected to html file -
What is the term / process in Databases for cascade-like behavior (see details)?
I'm newer to databases and have done tons of research over the last few months and so now everything I've learned is getting muddled. I'm trying to find the terminology for this particular behavior in databases so I can further research it. I'm currently writing a program in Django models I'd like to implement this on but I'd like to also know the terminology generically so I can research it elsewhere as well. Say you have a couple tables, one (we'll call A) who contains a foreign key matching the primary key in another (we'll call B). And let's say if a value in a certain field of A changes, then another field in B needs to change as well (not necessarily to the same value as A). Pretty much what I'm looking for is a way to create functions that are always called if some predefined event happens in one table, that can execute some sort of check, or logic or whatever needs be to determine what the new value should be in another table and then make sure that value is implemented in said other table). I've found lots of things that seem to elude to this sort … -
Django: how to add links to my admin site
I have this code in my admin-site, @admin.register(StudentsEnrollmentRecord) class StudentsEnrollmentRecord(admin.ModelAdmin): #inlines = [InLineStudentsSubmittedDocument,InLineStudentsEnrolledSubject,InLineStudentsStudentsPaymentSchedule] list_display = ('Student_Users', 'School_Year') ordering = ('Education_Levels',) list_filter = ('Student_Users',) admin site i just want to add an html_link here and filter what studentenrollmentrecord selected -
why is get this error ?Manager isn't available; 'auth.User' has been swapped for 'user.User'
I know it's an old question and there are lots of posts replying to this question but I didn't find anywhere mentioning why we get this error. I know that importing get_user_model and User=get_user_model() do the job but why we need to do this? I import like this: from user.models import User and also my user model extends abstractbaseuser. why Django can't understand this is my user model and should use this one? I have also changed the settings like this: AUTH_USER_MODEL = 'user.User' -
Do post-save signals run absolutely after the save method?
I have a form_valid method in a view which contains a couple methods: for group in groups: username = list( users.models.Employee.objects.filter( employee_type=group ) ) for user in username: form.instance.unread.add(user) user.send_sms('memo') user.send_email('memo') which send emails and SMS messages during the creation of a memo. The issue with this is that there is a lag in redirecting to the next page due to these 2 operations running. I assume this is because they wait for a full response from the API I am using. If these methods are put inside post-save signals will they run in the background and allow redirect instead of waiting for a response from the API? -
How to serve protected files on python django development server?
Whoa there brave adventurers!! The first one to answer this question will be rewarded a kings ransom of points!! ::shifty_eyes:: Goal: Use django's view level permissions so people can't search the source code to view a file without the proper view level permissions. I'm using nginx's X-Accel-Redirect header with a URI to serve a video on the page that was uploaded by me, from a particular directory I chose in the projectcontainer on the development server. What I tried so far: All static and media files serve fine from static. Variations of using the os module, and django's File() class/subclasses to get the absolute uri of the file, and put it in the src="{{ uri }}" attribute in the html. Reading every webpage I could on this for 8 hours, like this one, and every related nginx documentation like this one, among many others. Starved myself. Faceplanted my keyboard. Danced around the fire. Begged the computer gods. Cried myself to sleep. All to no avail brave adventurer!! Do any brave souls know why my spells aren't working??? I'm aware the development server is not nginx, but I thought it might have functionality like it. What I have: project structure: projectcontainer/ … -
How to structure models for forecasting app?
In Django, I am looking for recommendations on how to structure models for a forecasting app that is similar to a polling or quiz app - but not quite. Overview of requirements: (1) A quiz will have multiple questions. (2) Questions can take multiple forms - True or False, Multiple Choice with 3 options, Multiple choice with 4 options, etc. (3) Users submit forecasts (aka answers) for each question in the form of probabilities with the constraint that the total probability is 100%. So, for question #1 with three options A-C a user might forecast A: 30%, B: 50%, C: 20% (4) Each question has 1 correct answer. [Questions are scored using Brier scoring, but that is not essential for this discussion.] I am familiar with the Django tutorial polling app and have looked at multiple quiz apps, but none of them address my problem. If I use the structure of the Django polling tutorial with the number of choices being indeterminate, then I can't figure out how organize a user's forecast to a question - since that forecast must have a probability for each choice and the probabilities must add up to 100%. If I create multiple models of … -
django ugettext_lazy not working inside save models.Model
This is my model: class Friend(AbstractBaseModel): """ Table for the friendship of the pets """ STATE_CHOICES = Choices( (0, 'accepted', _('accepted')), (1, 'requested', _('requested')), ) source = models.ForeignKey('pets.Pet', on_delete=models.CASCADE, verbose_name=_('original pet'), help_text=_('the pet that the friendship comes from'), related_name="%(app_label)s_%(class)s_source_items") reciever = models.ForeignKey('pets.Pet', on_delete=models.CASCADE, verbose_name=_('reciever pet'), help_text=_('the pet that the friendship comes at'), related_name="%(app_label)s_%(class)s_reciever_items") state = models.IntegerField(default=0, null=True, blank=True, choices=STATE_CHOICES, verbose_name=_('state of the friendship')) history = HistoricalRecords() class Meta: verbose_name = _('Friend') verbose_name_plural = _('Friends') unique_together = ['source', 'reciever'] def __str__(self): return f'{self.source} friendship with {self.reciever}' def _the_friendship_petition_is_newly_created(self): return self.id is None and self.state == self.STATE_CHOICES.requested def _the_friendship_is_accepted(self): return self.id is not None and self.state == self.STATE_CHOICES.accepted def save(self, force_insert=False, force_update=False, using=None, update_fields=None): if self._the_friendship_petition_is_newly_created(): super().save(force_insert, force_update, using, update_fields) pet_creator = get_object_or_404(RelationshipUserPet.objects.filter(creator=True), pet_id=self.reciever_id) content_of_title = _(f'Your pet {self.reciever} has recieved a friendship invitation') title = (content_of_title[:47] + '..') if len(content_of_title) > 47 else content_of_title WebNotification.objects.create(title=title, description=_(f'Your pet {self.reciever} has recieved a friendship invitation of {self.source}'), # TODO: this url notification needs to change url=WebNotificationRoute.objects.get( fix_id=WebNotificationRoute.FIX_ID_CHOICES.friendship_accept ), user_id=pet_creator.user.id, params=f'{{"friendship": {self.id}, "source": {self.source_id},' f'"reciever": {self.reciever_id}}}', read=False) This is my django.po #: apps/friends/models.py:54 #, fuzzy, python-brace-format #| msgid "Your pet {self.reciever} has recieved a friendship " msgid "" "Your pet {self.reciever} has recieved a … -
GraphQL AttributeError: module 'graphene' has no attribute 'Heroes'
i am a beginner with Django & GraphQL, i had a problem the at first step, i can not reach to GraphiQL, i had an error ImportError at /graphql/ Could not import 'traindjango.schema.schema' for Graphene setting 'SCHEMA'. AttributeError: module 'graphene' has no attribute 'Heroes'. "traindjango/heroes/schema.py" import graphene from graphene_django import DjangoObjectType from .models import Heroes class HeroesType(DjangoObjectType): class Meta: model = Heroes class Query(graphene.ObjectType): heroes = graphene.Heroes(HeroesType) def resolve_links(self, info, **kwargs): return Heroes.objects.all() "traindjango/traindjango/schema.py" import graphene import heroes.schema class Query(heroes.schema.Query, graphene.ObjectType): pass schema = graphene.Schema(query=Query) "traindjango/traindjango/settings.py" INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'heroes', 'graphene_django', ] GRAPHENE = { 'SCHEMA' : 'traindjango.schema.schema', } "traindjango/heroes/models.py" from django.db import models class Heroes(models.Model): name = models.CharField(max_length=100, verbose_name='Name') power = models.IntegerField(default=0) city = models.TextField(max_length=100, verbose_name='City' ,null=True, blank=True) Could you please help me what i can do it? Thanx a lot -
Re-display table after form submit
Good afternoon, I have a simple Django 2.2 application for users to check in equipment they have checked out. A table of users and items they have checked out dominates the top of the page. On the very bottom row, a single text/submit form. I would like this to happen: user enters equipment id and submits page re-displays with: name removed from table (if success), form cleared, success/fail message next to cleared form. I am close. All of my logic and queries work, my item gets checked back in. However, the page re-renders with no table of users, just the form with the old data still in it. views.py class EquipmentReturn(View): def get(self, request, *args, **kwargs): # get checked out items for display table -this works form = ExpressCheckInForm(request.POST) return render(request, 'eq_return.html', context={'master_table': master_table, 'form': form} def post(self, request): if request.method == 'POST' form = ExpressCheckInForm(request.POST) if form.is_valid(): # this checks the item back in (or not) and creates messages-works else: form - ExpressCheckInForm() return render(request, 'eq_return.html', context={'form': form} I know there is a better way to do this. For instance, my form would not appear until I declared it in the get function. How can I make all of … -
Django calling same view out of multiple views for a template
I have a template which calls multiple views. But for some reason, the same view is being called. I'm not able to figure it out. Template : schedule.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Schedule Page</title> </head> <body> <h1>Today's Schedule </h1> <b>Scheduled Appointments:</b> <div> {% for p in schedule %} <p> {{p.id}} {{p.name}} {{p.surname}} {{p.appointment_time }} </p> {% if p.status == "Arrived" %} <p>Patient Arrived</p> <!-- <button>See Patient</button> --> <form action="{% url 'see_patient' p.id %}" method="post"> {% csrf_token %} <input type="hidden" name="appid" value="{{ p.id }}"> <input type="submit" value="See Patient" class="btn btn-primary"> </form> {% elif p.status == 'In Session' %} <p>In Progress</p> <form action="{% url 'complete' p.id %}" method="post"> {% csrf_token %} <input type="hidden" name="app_id" value="{{ p.id }}"> <input type="submit" value="Complete" class="btn btn-primary"> </form> {% elif p.status == 'Complete' %} <p>Completed</p> {% else %} <p>{{p.status}}</p> {% endif %} {% endfor %} </div> </br> </body> </html> views.py: def see_patient(request, appid): print("See Patient", appid) app = CheckAppointments() app.update_appointment_status(appid, {'status' : 'In Session'}) appointment_obj = Appointments.objects.get(appointment_id = appid) appointment_obj.status = "In Session" update_wait_time(request) return redirect('/schedule/') def appointment_complete(request, app_id): print("Complete:", app_id) app = CheckAppointments() app.update_appointment_status(app_id, {'status' : 'Complete'}) appointment_obj = Appointments.objects.get(appointment_id = app_id) appointment_obj.status = "Complete" appointment_obj.save() … -
How do I connect MySQL to my Django Project
I have a Django app with running on the default sqlite3 database, but I want to connect it to a MySQL database. I have created a database in my cpanel host and configured the settings in my Django app settings as follows: 'ENGINE': 'django.db.backends.mysql', 'NAME': 'my_db_name', 'USER': 'my_username', 'PASSWORD': 'my_db_user_password', 'HOST': 'my_domain', 'PORT': '3306', This is the response I get when I try to run my app with the settings above: django.db.utils.OperationalError: (1045, "Access denied for user 'my_username'@'a_certain_IP' (using password: YES)") This certain_IP is not my host Shared IP Address. I am not good with SQL, I need help please. Is there anywhere I need to set to allow password login? -
Does Django CMS support taxonomies or tags?
I am studying Python and Django, my final goal is to create an administration panel that manages 2 things: "dynamic article / item" (which can create types of forms to enter). "dynamic taxonomies / tags" (which can create categories or groupers of the data "of the form type"). I have seen the documentation of DjangoCMS but I cannot find the names of these concepts, could you guide me? thank you