Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can Django recognize language changes in a multilingual web page implemented in Django?
I have already implemented a web page in English using Django. I now have a question when I'm trying to create a web page in Chinese. Pages in Chinese will be separated by prefix(/ch/). I plan to implement a button to change the language, but the question is how Django remembers the changed page. Assuming my domain is 'domain.com', if the language is set to Chinese via the button I would like to have 'domain.com/ch' open when users access 'domain.com'. However, clicking on a button does not seem to be able to control the urlpatterns of Django(urls.py), and it seems necessary to store the variable corresponding to language in javascript. I would appreciate your advice. -
Django Shared database
I have a database on a server "A" with tables : IP, Server and roles. And I wanna ask this database from mulltiple other servers if there is an available ip. I was thinking with a webservice but I'm not sure if it's a good idea. I wanted to use in a loop every 5 secondes asking the server A until there is one but I think it's a bad idea. What kind of solution there is for that, multiple databases and accessing directly? Thanks -
Django save image in folder
I´ve got a piece of code that creates an image using matplotlib in Django and saves it to the root directory. I need to change the folder where matplotlib saves the image to /static/img folder. if (len(funcion) == 2): plotter = plot_regions([ [(lambda x: (matrizRestricciones[0][2]-matrizRestricciones[0] [0]*x)/matrizRestricciones[0][1],True), (lambda x: (matrizRestricciones[1][2]-matrizRestricciones[1] [0]*x)/matrizRestricciones[1][1],True)]], xlim=(0, 10), ylim=(0,10)) plt.grid() plt.savefig("/static/img/imagen.png") plt.close() Any idea how to save them there? Thanks in advance. -
Django Tastypie API Response
I have 2 model classes AppContacts and Contacts as given below - AppContacts Model- class AppContacts(DecoupledModel): app_contact_id = models.AutoField(primary_key=True) uaid = models.ForeignKey(Applications, db_column='uaid', blank=True, null=True) contact_type = models.CharField(max_length=45, blank=True) modified_on = models.DateTimeField(auto_now=True) #contact = models.ForeignKey(Contacts) #modified_by = models.ForeignKey(Contacts, related_name='%(class)s_modified_by') contact_id = models.IntegerField(db_index=True) modified_by_id = models.IntegerField() Contacts Model - class Contacts(DecoupledModel): contact_id = models.AutoField(primary_key=True) employee_id = models.CharField(max_length=20, blank=True, null=True,db_index=True) email_address = models.CharField(max_length=255, blank=True, null=True) userid = models.CharField(max_length=45, blank=True, null=True,db_index=True) modified_on = models.DateTimeField(blank=True,null=True) modified_by_id = models.IntegerField() name = models.CharField(max_length=100, blank=True, null=True) I have created an API to fetch the response but the response format is not as expected. Code - Dehydrate method def dehydrate(self, bundle): if bundle.obj.contact_id: con = Contacts.objects.filter(contact_id=bundle.obj.contact_id).values('name','contact_type', 'last_name', 'email_address', 'userid')[0] if con['contact_type'] == 'group': bundle.data['contact'] = con['last_name'] else: bundle.data['contact'] = con['name'] bundle.data['email_address'] = con['email_address'] bundle.data['userid'] = con['userid'] return bundle Get response method def get_temp(self, request, **kwargs): try: #import pdb; pdb.set_trace() request_method = request.method.lower() result = {} if request_method in ['get']: res_json = CONTACTS_GET_RESPONSE return self.create_response(request, res_json) elif request_method in ['post']: input_data = json.loads(request.body.decode()) logger.info("Input Request: {0}".format(input_data)) return super(CustomContactsResourceBulk,self).get_list(request, **kwargs) else: return http.HttpNotImplemented() except Exception, e: logger.error('Error occurred Custom Application resource search: ' + str(e)) return self.create_response(request, {'error':'Error occurred during search '+str(e)}) Response - [ { "app_contact_id": 33, "contact": "XYZ", … -
Getting pk_set value in django signal runs into an atomic error
This is my signal def my_signal(instance, action, pk_set, **kwrags): instance.animal_count = instance.animals.all().count() instance.save() if action == 'post_add': print pk_set #works print pk_set[0] #no work The weird thing is, if I just print pk_set I get set([1]) but if I try and get the actual value using [0] I run into: TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. Is there any way to just get the pk_set number? I literally only need the id. Note: This happens during test cases. -
Change the order of fields in normal serializer response
Using django rest framework i want to change the serializer response fields order dynamically by a list of given field names output from DRF is the following, {"items": [{"name": "John", "age": 25, "id": 3}, {"name": "Sam", "age": 20, "id": 8}]} My filed order list is: order_list = ['id', 'age', 'name'] What I want is: {"items": [{"id": 3, "age": 25, "name": "John"}, {"id": 8, "age": 20, "name": "Sam"}]} -
View in django launched twice
all my views in Django are launched twice each time i'm calling them with a url. Here is one example: urls.py urlpatterns = [ url(r'^$', views.HomePageView.as_view(), name='home'), # Notice the URL has been named url(r'login/', views.login, name='test'), # Notice the URL has been named url(r'login_click/', 'polls.views.login_click', name='login_click'), url(r'^profiler1_click/', views.profiler1, name='profiler1'), ] views.py def login (request): print("testpagelogin") return render(request, "login.html", {}) The print("testloginpage") is printed twice and i don't understand why. Thanks very much in advance. -
Implement scroll down menu
I am really not an expert with html, css and javascript. I would like to create a scroll like scroll down menu. Instead of 'Pop' in the image, it could be just 'Total customers' or being blank. Could I do that with django-crispy-forms? What is the best way to implement such scroll? -
Django:Find no of days between 2 dates and compare with sysdate and return if it matches
I want to know who is on leave today based on end_date and start_date which are DatetimeField by comparing values between end_date and start_date with sysdate and returning if it matches with sysdate. models.py class leave(models.Model): employee = models.ForeignKey(employees, on_delete=models.CASCADE, default='1') start_date = models.DateField() end_date = models.DateField() -
How do I associate the post to a comic in custom form
My model looks like this: class ComicSeries(models.Model): """Model definition for ComicSeries.""" # TODO: Define fields here user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, verbose_name='Uploaded by: ' ) title = models.CharField(verbose_name='Series Title', max_length=500) cover = models.ImageField(verbose_name='Series cover', upload_to='comic_series', height_field=None, width_field=None, max_length=None ) description = models.TextField(verbose_name='Description') artist = models.CharField(verbose_name='Artist(s)', max_length=500) date_uploaded = models.DateTimeField(auto_now_add=True) slug = models.SlugField(default='') class ComicIssue(models.Model): """Model definition for ComicIssue.""" # TODO: Define fields here user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, verbose_name='Uploaded by: ' ) title = models.ForeignKey(ComicSeries, on_delete=models.CASCADE, verbose_name='Series Title') issue = models.CharField(verbose_name='Issue Number', max_length=500) issue_title = models.CharField(verbose_name='Issue Title', max_length=1000) issue_cover = models.ImageField(verbose_name='Issue cover', upload_to='comic_issues', height_field=None, width_field=None, max_length=None) issue_description = models.TextField(verbose_name='Description') issue_file = models.FileField(verbose_name='Issue file', upload_to='comic_issues_files', max_length=100, help_text='File in pdf or as single image' ) is_favorite = models.BooleanField(default=False) issue_slug = models.SlugField(default='') views.py : class ComicIssueCreate(LoginRequiredMixin, CreateView): model = ComicIssue fields = ['issue_title', 'issue_cover', 'issue_description', 'issue_cover', 'issue_file'] def form_valid(self, form): form.instance.user = self.request.user return super(ComicIssueCreate, self).form_valid(form) I am able to select to which ComicSeries a ComicIssue belongs to in Django admin. But I have a problem doing this in a custom form. Is there a way I can determine to which series an issue belongs to in a custom form using CreateView? -
Django postgres : Is their any way to reference jsonfield of one model into another?
I have a jsonfoeld in a model now I want to use that jsonfield into another model . Is their any way to referrence jsonfield of one model into another? -
Django on Digital Ocean
So I am beginner Django Developer and have been learning by developing local apps. I am looking to finally deploy something so people can use it. I have been looking around at various hosting providers and I am wondering what it's like using Digital Ocean for Django hosting. Specifically what exactly is involved/required with managing a Django app on Digital Ocean. Hostgator, which is another host I've been looking at, does not offer any "one-click" install for stuff like Nginx or anything else which I noticed Digital Ocean does have, so I would have to install that that as well as anything else I'd need myself. I guess my question is after that one click install what is involved with managing a Django app on Digital Ocean? Do I have to learn how to do a ton of other stuff regarding managing a server and dealing with Nginx (I would have to do that on HostGator) or does that One-click install for Django handle all that? Also other than Django, are there any skills that I have to learn in order to be able to do this? -
Is there a way to apply django filters only if the screen has a certain size?
I was wondering if there is a way to apply a filter of Django in a template only if the screen has a certain size. Just like a media query does with Css. -
Docker compose with multiple Dockfiles and images (Django+Angular)
I'm building an app that uses Django and Angular that is split up into two different repositories and docker images. My file structure is: . docker-compose.yml djangoapp/ DockerFile manage.py ... angularapp/ DockerFile ... I've been unable to get it to work properly, all documentation I found on this seem to expect you to have the docker-compose.yml file together with the DockerFile. I've tried multiple different variations but my current (not working) docker-compose.yml file looks like this: version : '3' services: web: build: djangoapp command: python manage.py runserver 0.0.0.0:8000 ports: - "8000:8000" This gives me error can't open file 'manage.py': [Errno 2] No such file or directory. If I go into the djangoapp/ directory and create a docker-compose.yml file there according to the offical Docker docs, it works fine. So it's nothing wrong with the actual build, the issue is accessing it from outside like I'm trying to do. -
Jinja2 Multi-level template inheritance issue
I have the following three files in a Django App, with the template engine being Jinja2 skeleton.html <head> {% block head_content %} <meta charset="utf-8"> <title> {% if page_title %} {{ page_title }} | {% endif %} Bhargavi Books & Stationery </title> <link rel="stylesheet" href="{{ static("css/semantic.min.css") }}"> <link rel="stylesheet" href="{{ static("Icons/font-awesome.min.css") }}"> {% endblock head_content %} </head> <body> <div id="navigation"> {% block navigation %} <div class="ui three item menu"> <a class="active item">Home</a> <a class="item">New Bill</a> <a class="item">View Bills</a> </div> {% endblock navigation %} </div> <div id="frame"> {% block frame_content %} <p> Body content goes here. Body for {{ content_name }}</p> {% endblock frame_content %} </div> <div id="app"> {% block app_content %} <p> APP content goes here. Body for {{ content_name }}</p> {% endblock app_content %} </div> {% block scripts %} <script src="{{ static("js/jquery.js") }}"></script> <script src=" {{ static("js/semantic.min.js") }} "></script> {% endblock scripts %} </body> base.html {% extends "skeleton.html" %} {% from "macros/globalmacros.html"import SUIIconList,SUISimpleList, SUIImageLabel,SUILabel, SUIActionInput,SUILabeledInput,SUIInput, SUIDimmableActionCard,SUICard, %} {% block frame_content %} Frame Content {% endblock frame_content %} {% block scripts %} {{ super() }} <script src=" {{ static("js/globalmacros.js") }} "></script> {% endblock scripts %} dashboard.html {% extends "base.html" %} <div> {% block body_content %} Body 3 {% endblock body_content %} … -
Django Admin - Custom Inline Form
I'm attempting to use a custom inline form within the django admin. admin.py -- class EmpInline(admin.StackedInline): model = Emp form = UpdateYearlyForm show_change_link = True class CompanyAdmin(admin.ModelAdmin): list_display = ('companyname','companyid','get_active', 'get_updated') inlines = [EmpInline] When the Company name is clicked on, the company details are shown along with a formset for all the related employees. This works in regards to displaying the form however one of the fields is a custom choice field which indirectly updated a model field. Which, in the normal user view (this form needs to be used both by an admin for all records and for users for the records pertaining to them) the custom field is handled as below. I've only shown a snippet of the view as it is quite long. views.py -- if formset.is_valid(): for form in formset.forms: if form.is_valid(): obj = form.save(commit=False) data = form.cleaned_data if data['updatefield'] == 'accident': obj.years += 1 else data['updatefield'] == 'free': obj.years += 1 obj.save() Is there a way of handling the form (and the custom field) in the same way when used as an inlineform in the admin? -
Pass None to DRF SerializerField's to_representation
I have the following SerializerField: class TimestampField(Field): def to_representation(self, value): if not value: return '' return value.timestamp() And I use it like this in my serializer: class ArticlePhotobookSerializer(ModelSerializer): delivery_date_from = TimestampField() delivery_date_to = TimestampField() Now the getter delivery_date_to can return None, which I want to transform into an empty string using the to_representation method. however, when I use the Serializer to parse this None value, it doesn't even enter the to_representation method and immediately returns None. What should I change to also use the method to_representation for None? -
Django: Data uownership for users
I am trying to create a simple app. It has the following model: Model: Product class Product(models.Model): product_owner = models.ForeignKey(User, verbose_name='User') product_title = models.CharField(max_length=100, null=False, verbose_name='Product title') product_description = models.TextField(max_length=250, verbose_name='Product description') product_qty = models.IntegerField(verbose_name='Quantity') product_mrp = models.DecimalField(max_digits=12, decimal_places=2, verbose_name='Maximum retail price') product_sku = models.CharField(max_length=100, null=False, unique=True, verbose_name='SKU',help_text='Enter Product Stock Keeping Unit') product_barcode = models.CharField(max_length=100, null=False, verbose_name='Barcode') I am using only the built in Admin App provided by django framework. And I was able to Make the Product data availaible for only the respective user by adding the following in the Admin classes. class ProductAdmin(ImportExportModelAdmin): exclude = ('product_owner',) list_display = ['product_title','product_description', 'product_qty', 'product_mrp','product_sku','product_barcode'] search_fields = ['product_title', 'product_description', 'product_sku', 'product_barcode'] ordering = ['id'] list_display_links = ['product_title'] def get_queryset(self, request): if request.user.is_superuser: return Product.objects.all() return Product.objects.filter(product_owner=request.user) def save_model(self, request, obj, form, change): if not change: obj.product_owner = request.user obj.save() As I just started experimenting, I added 2 users, User1 and User2. For User1 I added 10 products. Then I loggen in as User2 and User2 cannot see the products added by User1. Now when I am tying to add products for User2, and if there is a conflict in product_sku field which is a unique field, I cannot add the product at … -
How to raise 503 error in django?
I want to make site maintenance page and I create singleton model for site maintenance with checkbox field, So when I checked that checkbox from Django admin then the site should show maintenance page if we hit any URL of the website. I checked 503 status code is related to SERVICE UNAVAILABLE So How can I raise 503 error manually in my code and also want to render a custom template when 503 error raise. -
Django decimal precision loss
worth = Decimal(request.POST.get('worth')) print(request.user.profile.cash) # -> prints 10000.000000000000000 print(worth) # -> prints 10000 Profile.objects.filter(user=request.user).update(cash=F('cash')-worth) request.user.profile.refresh_from_db() if request.user.profile.cash < 0: ###!!!!#### print(request.user.profile.cash) # -> -1.819E-12 #model definition: class Profile(models.Model): cash = models.DecimalField(default=10000, max_digits=30, decimal_places=15) as can be seen, the player has 10k cash and I subtract 10k, which results in minus values, how can I solve this problem? I don't allow cash to be negative as you can expect. Am I doing something principally wrong? I want the player to be able to go all-in with his money. -
I have some CSV data and I want to import into django models using DB relationship
Thank you in advance. I have a Django database with some models: class District(models.Model): code = models.CharField("Code".encode('utf-8'),max_length=512, null=True) name = models.CharField("Name".encode('utf-8'),max_length=512) class Neighborhood(models.Model): code = models.CharField("Code".encode('utf-8'),max_length=512, null=True) name = models.CharField("Name".encode('utf-8'),max_length=512) district = models.ForeignKey(District, on_delete=models.CASCADE) dHab = models.DecimalField("Densiy of Habitants".encode('utf-8'),max_digits=15, decimal_places=5, default=0, validators = [MinValueValidator(0)]) And I need to import a csv file uploading both District and Neighborhood data. 01 District 1 02 District 2 03 District 3 011 Neigborhood a (Belongs to District 1) 012 Neigborhood b (Belongs to District 1) 021 Neigborhood c (Belongs to District 2) 031 Neigborhood d (Belongs to District 3) etc. If I upload a Neighborhood, how do I find the proper District before inserting into the database so they can be correctly related to each other? Because I far as I know, Django has an auto_increment field -
Inserting data into DataBase using Forms not working
So I'm building my 1st website and I'm having an issue. I don't really understand how views, modules and my website connects.. And maybe thats the reason I got this error... My folder of the html files is map/templates/serverlist.html I am trying to add my data into the DB and I have a problem because of the form action... I wrote 'map:serverlist' because I think it's the name of the project and the name of the template. isn't it? THE PROBLEM IS EITHER IN THE FORM LINE IN THE HTML OR THE url.py file. I don't know what to write in both of them.. :( Any idea what's missing? IndentationError at / unexpected indent (forms.py, line 6) Request Method: GET Request URL: http://172.16.10.60:8000/ Django Version: 1.3.1 Exception Type: IndentationError Exception Value: unexpected indent (forms.py, line 6) Exception Location: /media/sf_C_DRIVE/Users/eilon.ashkenazi/Desktop/EilonA/DevOpsMap/WebFiles/../WebFiles/map/views.py in <module>, line 4 Python Executable: /usr/bin/python Python Version: 2.7.5 Python Path: ['/media/sf_C_DRIVE/Users/eilon.ashkenazi/Desktop/EilonA/DevOpsMap/WebFiles', '/usr/lib64/python27.zip', '/usr/lib64/python2.7', '/usr/lib64/python2.7/plat-linux2', '/usr/lib64/python2.7/lib-tk', '/usr/lib64/python2.7/lib-old', '/usr/lib64/python2.7/lib-dynload', '/usr/lib64/python2.7/site-packages', '/usr/lib64/python2.7/site-packages/gtk-2.0', '/usr/lib/python2.7/site-packages'] Server time: Wed, 13 Sep 2017 07:39:50 -0500 view.py # Create your views here. from django.shortcuts import render_to_response from django.template import RequestContext from map.forms import PostForm from map.models import serverlist def home(request): entries = serverlist.objects.all() return render_to_response('serverlist.html', {'serverlist' : … -
Cannot assign "{'id': 31}": "Model.table_ABC" must be a "ABC" instance
I double checked if the id 31 exists, where some_id here is 31, where id is a pk. It does exist under ABC model and there is data. I don't see how this is incorrect? I've also tried ABC.objects.filter(id=some_id), also tried just setting abc=31, which doesn't make sense but wanted to try, also tried .get(pk=some_id) ABC is a foreign key to Model. a_id = ABC.objects.get(id=some_id) person_abc= Model(user=request.user, abc=a_id) form = ModelForm(request.POST, instance=person_abc) -
What are the best practices for installing Django with python3 & venv?
I have read other similar questions before posting but they still left me a bit unclear on some issues. I use both Linux Ubuntu and Windows 10 for development. On both platforms I have multiple versions of Python, in both python3 and python2 versions. 1) If I use Anaconda2 and Anaconda3, the version of Python that comes with Anaconda is the same binary as the default version of Python that I get on python.org? 2) With Anaconda and the conda command, virtual environments are put into a hidden directory, e.g. .myvenv. If I put my application, such as Django in a directory beneath that .myvenv then my IDE cannot find it. So in development, I can activate the appropriate venv ( with conda command or with virtualenv ) and put my application in a sibling or parent directory that is not hidden? Is that correct? 3) Why would I see python2 versions of modules/packages being installed with the pip command even when I have activated a python3 venv? For example, I saw a package with name that includes py2.python3. That may be a python3 version of Django but I think I have seen pip installing a clearly python2 package. In … -
Querying Record DRF (get_queryset defined)
I currently have a viewset with the following code class IndigentViewset(viewsets.ModelViewSet): serializer_class = IndigentSerializer def get_queryset(self): qry_status = self.request.GET.get('review_status') try: qry_limit = int(self.request.GET.get('qry_limit')) except Exception as e: pass try: qry_hldID = self.request.GET.get('hldID') except Exception as i: pass if qry_status == "un_reviewed" : retrieved_info = UrbanHousehold.objects.filter(form_reviewed=False)[:qry_limit] elif qry_status == "reviewed": retrieved_info = UrbanHousehold.objects.filter(form_reviewed=True)[:qry_limit] elif 'qry_hldID' in locals(): retrieved_info = UrbanHousehold.objects.filter(id=qry_hldID) else: retrieved_info = UrbanHousehold.objects.all() return retrieved_info I am more of a front-end developer so I am only learning Django and DRF on the fly as i go with my projects.My question is that when I try to retrieve a record using its ID from the Model associated with his viewset, all I keep getting is a 404 error stating the record was not found. Can any one assist with this problem or possibly point out what I might not be understanding.