Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django.db.utils.OperationalError no such table, but table has been created
I'm working with Django 1.6.5 and I have a problem with the table. I wrote the code (I added a class to the application): class Season(Season): is_active = models.BooleanField(default=False) is_main = models.BooleanField(default=False) I made: python manage.py schemamigration events --auto python manage.py migrate events I get an error: django.db.utils.OperationalError: no such table events_season But when I execute: python manage.py migrate --list everything indicates that the table is created and migrated. -
How to add graph on django admin models which dynamically changes with filterset
Django Admin Model with Graph Integration @admin.register(User) class UserAdmin(admin.ModelAdmin): form = UserAddForm list_display = ['username', 'created', 'first_name', 'last_name', 'mobile', 'email', 'is_active'] search_fields = ('mobile',) How to add a graph for created vs mobile count, using some custom js or 3rd party library both are acceptable. -
connection to a server
This question may seem very broad but I will try my best to explain my situation. I have to connect to a MySql database server (A) which is hosted on a remote server (B). Then execute some queries and display the results/reports on my web browser. using python2.7 & Django 1.10 to achieve this. I have to use Django-Framework and can't connect to the MySql server directly. I don't have much knowledge about servers & socket programming and have no idea to achieve point no.1 above. Can anyone explain me about this scenario, what actually is happening and what django-python modules & tutorials I should go through. Any help would be appreciated. Thanks -
Python tests. Patch method from library in venv
I know how to patch my methods: @patch('common.connections.upload_image') def test_upload(self, mocked_upload_image): mocked_upload_image.return_value = 'Mocked url' This will patch my method upload_image in module connections in folder common (I am using Django, folder common lies in root). But I want to patch serializer from Django Rest framework, which lies in venv.lib.python2.7.site-packages.rest_framework.serializers.BaseSerializer.is_valid So I tried: @patch('venv.lib.python2.7.site-packages.rest_framework.serializers.BaseSerializer.is_valid') def test_upload(self, mocked_is_valid): mocked_is_valid.return_value = True # this doesn't work But it doesn't work. Says ImportError: No module named venv. My venv folder lies in the same folder, where the above mentioned common lies. So how to patch this library method then? -
How to select specific row by foreign key?(sqlite3)
I have two table: class symbol(models.Model): ticker = models.CharField(max_length=40) instrument = models.CharField(max_length=64, default='stock') name = models.CharField(max_length=200) sector = models.CharField(max_length=200, default=None) currency = models.CharField(max_length=64, default='USD') created_date = models.DateTimeField(auto_now=True) last_updated_date = models.DateTimeField(auto_now=True) class daily_price(models.Model): symbol = models.ForeignKey(symbol) price_date = models.DateTimeField() created_date = models.DateTimeField() last_updated_date = models.DateTimeField() open_price = models.DecimalField(max_digits=19, decimal_places=4) high_price = models.DecimalField(max_digits=19, decimal_places=4) low_price = models.DecimalField(max_digits=19, decimal_places=4) close_price = models.DecimalField(max_digits=19, decimal_places=4) adj_close_price = models.DecimalField(max_digits=19, decimal_places=4) volume = models.BigIntegerField() I want to select table strategyceleryapp_daily_price's rows. I want to use read_sql_query to select specific row by symbol's ticker(foreign key) con = sqlite3.connect("/home/leo/github/StrategyCeleryWebsite/db.sqlite3") df = pd.read_sql_query("SELECT * from strategyceleryapp_daily_price", con) # verify that result of SQL query is stored in the dataframe print(df.head()) con.close() How should I write this command? Thank you very much. -
DRF - Serializing a model with multiple foreign Keys
I am working on a CRUD API in Django and I need to serialize a model which Foreign keys in two tables. The model is on the 'many' side on two one-to-many relationships and I don't really see any other way of specifying relationships in this model(I am new to python and Django and I am using Django-Rest-Framework for creating API) So, I have two questions: 1 - Is it a good Idea to have multiple foreign keys in my model or I should refractor my relationships some other way? 2 - If it is fine to have multiple foreign keys in a single model, how do I serialize the model to return the proper JSON? My models are something like this(with a few more fields): class DataSource(models.Model): datasource_name = models.CharField(max_length=50, unique=True) datasource_description = models.CharField(max_length=100) ... class Campaign(models.Model): name = models.CharField(max_length=200) subject = models.CharField(max_length=200) sender = models.EmailField(max_length=200) ... class CampaignDeliveries(models.Model): campaign_id = models.ForeignKey(Campaign) datasource_id = models.ForeignKey(DataSource) delivery_reference_id = models.CharField(max_length=200, primary_key=True) date_sent = models.DateTimeField() A delivery record has a reference to the Campaign for which delivery was made and the Data Source which was selected for that delivery. Data must be returned in a format such as: { campaign_id: 001, datasource_id: … -
ValueError at /indexsendjepp :I/O operation on closed file
I want to upload zip file in 'F:comic\picture\jepp'. I use this code: def sendjepp(request): docuPath ='F:comic\picture\jepp' temp = tempfile.TemporaryFile() f = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED) for dirpath,dirnames,filenames in os.walk(docuPath): for filename in filenames: f.write(os.path.join(dirpath,filename)) f.close() wrapper = FileWrapper(temp) response = HttpResponse(wrapper, content_type='application/zip') response['Content-Disposition'] = 'attachment; filename=test.zip' response['Content-Length'] = temp.tell() temp.seek(0) return response enter image description here can anyone help me ? -
what is the easiest way of passing selected tr data in django template?
in this example how can i access the selected row of the table in django's view in order to save it to DB? -
How do I load my custom CSS in pinax (Django))?
I want to try and overide the default bootstrap css files that I got with pinax, for example change the topnav background color and change the style of <p class="a12" >gggggggg</p> I created. I saw that link in stakoverflow [How to change the pinax(0.9a2) template? ]1 I added my custom css in mysite\static\css\cssmy_custom_stuff.css the css: .a12{ background-color: red; color: green; } .topbar-inner, .topbar .fill { background-color: red; background-image: -webkit-linear-gradient(top, #333, #FF4242); background-image: -o-linear-gradient(top, #333, #FF4242); background-image: linear-gradient(top, #333, #FF4242); } and added the folowing to the homepage.html {% block extra_head %} <link rel="stylesheet" href="{{ STATIC_URL }}css/my_custom_stuff.css"> <p class="a12" >gggggggg</p> {% endblock %} Can someone please help me understand what am I doing wrong? And how should I do it correct Thanks in advance -
Response of serialezer.data vs json?
I am a new develoepr on Django and Angular Stack.If i Return a response in the form of serializer.data like: return Response(serializer.data,status=status.HTTP_200_OK),what type of response i am sending?It is certainly not JSON data. When i try to read this in Angular JS,it gets read.So my doubt is,am i by serializing the data,returning a JSON response only? As Angular JS is able to interpret my response. If howerever i Render my response in json using: content = JSONRenderer().render(serializer.data)) return Response(content,status=status.HTTP_200_OK) data is not read correctly. How is my response interpreted on the front end in both the cases? Can somebody help -
Why does createsuperuser only work with heroku run
I can create do the following command: heroku run python manage.py createsuperuser And it works fine. But when I just run python manage.py createsuperuser I get this error. How come it works with heroku but not my local app? ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. -
How to get List from Database to html in python - Django?
i have few items/List stored in database stored as ['First Form Field', 'Second input Field'] i want all these items of a column as a list in my front end html page I am getting items as ff= form_fields.objects.all() return render(request,'user/index.html',{'message': welcome,'ff': ff}) INDEX: {% for x in ff%} <tr> <td> {{ x.id}} </td> <td> {{ x.name }} </td> <td> {% for y in x.text_field %} <label>{{ y }}</label> {% endfor %} </td> <td> I want that saved list to be in that table as list. -
In which foramt CCAvenue return response?
I want to integrate Cc Avenue in my django project.So I want to know in which format Cc Avenue rerun response so i can d further work??please any one having Cc Avenue integration in Django python reference??? -
Custom queryset/manager for default django User model
I am heavily using custom querysets: https://docs.djangoproject.com/en/1.10/ref/models/querysets/#django.db.models.query.QuerySet.as_manager For all my models and it's working great. I have clean DRY code without any custom queryies all over the place. I'd like to also add some custom queriey to my User object. I am guessing, I should do something like: from django.contrib.auth import get_user_model get_user_model().objects = MyCustomManager() #(or query.as_manager()) While creating MyCustomManager being derived from BaseUserManager: https://docs.djangoproject.com/en/1.10/topics/auth/customizing/#django.contrib.auth.models.BaseUserManager Is that correct approach? If not, how to do it? Thanks! -
Python - extract value from key-value pair
lots of googling done but I'm stumped. I know this is simple but I can't seem to find the format to retrieve the value from a key/value pair when I supply the key in python. I'm using django -- images = Article.objects.filter(pk=self.ID).values("image1", "image2", "image3") fills images with the following object: <QuerySet [{'image3': u'', 'image2': u'', 'image1': u'articleImages/django-allauth.png'}]> So my question is --- I want get get the value for "image1" how do I get that!! I really really really appreciate your help - I want something like image1 = images['image1'] ## clearly this doesn't work -
Displaying validation errors at the right position in a Django page containing multiple form fields
In a Django social networking website I built, users can chat in a general room, or create private groups. Each user has a main dashboard where all the conversations they're a part of appear together, stacked over one another (paginated by 20 objects). I call this the unseen activity page. Every unseen conversation on this page has a text box a user can directly type a reply into. Such replies are submitted via a POST request inside a <form>. The action attribute of each <form> points to different urls, depending on which type of reply was submitted (e.g. home_comment, or group_reply). This is because they have different validation and processing requirements, etc. The problem is this: If a ValidationError is raised (e.g. the user typed a reply with forbidden characters), it gets displayed on multiple forms in the unseen_activity page, instead of just the particular form it was generated from. How can I ensure all ValidationErrors solely appear over the form they originated from? I've been thinking about this problem, and have so far come up without anything. An illustrative example would be great! The form class attached to all this is called UnseenActivityForm, and is defined as such: class … -
Django-scheduler 5th sunday event
How do I create an event in django-scheduler that is for the 5th Sunday (which should happen quarterly)? Thanks, Denise -
Access form data of post method in Django
I want to access post method data in views.py. I am following procedure of using pure html for form not Django form class. I tried the solution MultiValueDictKeyError in Django but still it is not working. Help me out index.html <form action="{% url "Sample:print" %}" method="post"> {% csrf_token %} <input type="text" placeholder="enter anything" id="TB_sample"/><br> <input type="submit" value="submit"> </form> views.py def print(request): value=request.POST['TB_sample'] # value = request.REQUEST.get(request,'TB_sample') # value = request.POST.get('TB_sample','') print(value) return render(request , 'static/Sample/print.html',{"data":"I want to pass here 'Value'"}) I tried all commented types. still i get the many errors . None of these solutions working. -
PostgreSQL login works on local host but not xxxx.compute-1.amazonaws.com
So I open the psql terminal (on Windows). I log into it with the server set on localhost, But when I try to log into it with my production host: xxxx.compute-1.amazonaws.com I get the following error: > psql: FATAL: password authentication failed for user "postgres" > FATAL: no pg_hba.conf entry for host "128.6.37.14", user "postgres", > database "campus", SSL off I tried adding it to the pg_hba.conf, but no luck: # IPv4 local connections: host all all 127.0.0.1/32 md5 host all all 128.6.37.14/32 trust Any idea what the issue is? Is the host correct? It's what I got when I ran heroku config How do I fix this? -
Using Django formsets the right way
In my django website, I have a particular page where I display 20 input forms to users, set in a for loop. The forms are instances of a single forms.Form form class called class UnseenActivityForm (containing two attributes). My problem is that when I display a validation error to the user, it gets displayed across the entire 20 input forms. Researching this has led me to Django formsets. I haven't used them before. So I tried setting them up, but it's a concept I couldn't fully grasp. Can someone give me an illustrative example of how to set up formsets in order to solve my issue? Here's what I originally have: In views.py: def unseen_activity(request, slug=None, *args, **kwargs): form = UnseenActivityForm() notifications = retrieve_unseen_notifications(request.user.id) page_num = request.GET.get('page', '1') page_obj = get_page_obj(page_num, notifications, ITEMS_PER_PAGE) if page_obj.object_list: oblist = retrieve_unseen_activity(page_obj.object_list) else: oblist = [] context = {'object_list': oblist, 'form':form, 'page':page_obj,} return render(request, 'user_interaction.html', context) In user_interaction.html: {% for interaction in object_list %} {% if form.comment.errors %}{{ form.comment.errors.0 }}{% endif %} <form method="POST" action="{% url 'process_reply' %}"> {% csrf_token %} <input type="hidden" name="group_reply" value="111"> {{ form.comment }} </form> {% endfor %} In forms.py: class UnseenActivityForm(forms.Form): comment = forms.CharField(max_length=250) group_reply = forms.CharField(max_length=500) class Meta: … -
MaxMind GeoIP2 single instance in Django
I'm using python wrapper 'geoip2' for MaxMind's GeoIP database. It's said in the docs that you should create only single instance of the database reader, because opening the database is very expensive, and, of course, opening it for every request is a very bad idea. So, if I have Django (1.10) + Gunicorn on my server, how should I create the "singleton" of the database reader? That's generally not a question about geoip2 module, it's question about: How should I create a single object, accessible from the app (not the whole project)? Unfortunately, I don't know much about Gunicorn, so the second question is: how long does worker live? Is it restarting every N minutes/seconds? I'm asking this question because I'm afraid if it respawns workers too often, it would create additional unwanted system load. -
502 Bad Gateway in recent Facebook and Google app Django social login
May I know any of you encounter similar issue above? I changed nothing in the system lately but this issue appeared when I used Google and Facebook account to log in to my apps. My Twitter log-in is fine. Below are my setting and version of plug-in used. # python-social-auth settings AUTHENTICATION_BACKENDS = ( 'social.backends.facebook.Facebook2OAuth2', 'social.backends.google.GoogleOAuth2', 'social.backends.twitter.TwitterOAuth', 'django.contrib.auth.backends.ModelBackend', 'account.authentication.EmailAuthBackend', ) SOCIAL_AUTH_PIPELINE = ( 'social.pipeline.social_auth.social_details', 'social.pipeline.social_auth.social_uid', 'social.pipeline.social_auth.auth_allowed', 'social.pipeline.social_auth.social_user', 'social.pipeline.user.get_username', 'social.pipeline.user.create_user', 'social.pipeline.social_auth.associate_user', 'social.pipeline.social_auth.load_extra_data', 'social.pipeline.user.user_details', 'account.pipeline.user_details.get_profile_picture', ) SOCIAL_AUTH_FACEBOOK_SCOPE = ['email'] -
csrf failure using csrf and Request Context
I have tried all I can gather from the forums, still need help: I keep getting the CSRF token missing or incorrect error when I submit a form. It used to be working fine and then I made some changes and now I cant get back.. I am using {% csrf_token %} and RequestContext. I have tried using reverse, i checked the settings.py middleware for the csrf middleware, tried restarting the server, tried using HttpResponse instead of HttpResponseRedirect and template.render(), tried a url path instead of the {% url %} tag. In other parts of my project I am not even using RequestContext and it works fine.. signup_page.html: <p>Sign Up Below </p> <form action={% url 'signup_page' %} method="post"> {% csrf_token %} .... Email <input type="email" name="email" required="true"><br><br> <input type="submit" value="POST"> </form> views.py def signup_page(request): template = loader.get_template('user_app/signup_page.html') if request.method == "POST": ... email = request.POST['email'] kwargs = { 'username':username, 'password':password, 'first_name':first_name, 'last_name':last_name, 'email':email } new_user = User.objects.create(**kwargs) new_user.save() context = { 'text':"POST", 'first_name':first_name } return HttpResponseRedirect(render('signup_page', context, context_instance =RequestContext(request))) else: return HttpResponse(template.render(RequestContext(request))) -
Internal System communication
I am designing the system which has Django REST for the API (un managed models), some process engine in python (twisted) and C++ Engine. C++ engine get the data from database and python process(to send the data to C++ Engine) and send back to another python process (Receive data from C++ engine). What is the best way to communicate between those processes inside system. I am planning to communicate with xmlrpc protocol. Is there any best way to define communication inside systems. ? -
Getting DUPLICATE error when logging in existing user with Django
I've used Django's authentication system to log in users, the only problem is that I get a 1062 DUPLICATE ENTRY error. def login(request): # this will be the first page someone who isn't signed in will see form = LoginForms(request.POST) username = request.POST.get('username') password = request.POST.get('password') if username and password: #this line returns two values, a user object and a boolean flag 'created', 'true' if user is created and false if user already exists try: user,created = User.objects.get_or_create(username=username, password=password) if created: user.set_password(password) user.save() #if the user already exists user = authenticate(username=username, password=password) auth_login(request, user) return HttpResponse('success') except IntegrityError: user = authenticate(username=username, password=password) auth_login(request, user) return HttpResponse('good') else: return render(request, 'tracker/login.html', {'form': form}) Right now I'm just catching the error and basically telling Django to log in anyway. But I know this isn't a good way of doing it, would it make more sense to use User.objects.get to test the existence of the user combined with User.objects.create_user to make a user if that user doesn't exist?