Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Javascript POST data corrupted in DJango
I'm sending a request through AJAX but noticed the data being corrupted when I read in the server. Java script data:- gen_points == {"0":[{"x_axis":"0.65","y_axis":"07/09/2016 03:59","point":"239","callout":"","y_axis_position":"","x_axis_position":"","callout_box_color":"AB2567","draw_type":"Box","height":"","width":"","angle":""}]} Server data:- alldata = request.POST print 'Store Callouts == ', alldata Store Callouts == <QueryDict: {u'0[0][height]': [u''], u'0[0][angle]': [u''], u'0[0][y_axis_position]': [u''], u'0[0][x_axis_position]': [u''], u'0[0][point]': [u'239'], u'0[0][y_axis]': [u'07/09/2016 03:59'], u'0[0][width]': [u''], u'0[0][callout]': [u''], u'0[0][draw_type]': [u'Box'], u'0[0][callout_box_color]': [u'AB2567'], u'0[0][x_axis]': [u'0.65']}> Not sure why the data is totally different. -
How to upload a list of large files using django?
I know how to upload large files using the django-chunked-upload package. It's an elegant solution to upload one file using an <input type="file"/> tag. I haven't found anything allowing me to upload more than one file with this package. In my case I try to create a drag'n'drop zone in which the user could drop multiple files. With the JavaScript, I obtain a FileList object I can iterate to obtain File objects. I would like to send this files chunked to my django app. The problem is that package work using the <input type="file"/> with a CSRF protection and it seems to be forbidden to change the file present in it. Is anyone knowing a solution to interact with this type of input if files are already known in JavaScript or if other django solution exist? -
Django migration issue after deleting a table
So this is the steps I followed in order to delete a table that was being referenced in another model in my Django app. Delete field referencing some table in another app (let's call it table A) Create and run migrations Delete Table A Create and run migrations again Worked as expected. I'm trying to set up a new development environment so I run migrate to set up my blank db. However, Django complains that Table A is missing. It is as if Django doesn't run the migrations in the correct order. What are my options here? I tried forcing it to first run migration for a specific app without success. I also don't want to edit the migrations as I'm unsure what effect this might have on the production db. I've been stuck for hours and really have no idea to to proceed so any help will be appreciated. I've already pushed this code and migrations to a production environment so I can't delete and recreate all the migrations. So I deleted a model (db table) from my Django app -
form calculation without absurd amount of if statements?
So I am trying to create a page with a form to calculate what size a user should get per item based on their measurements so they do not have to look at a bunch of sizing charts. I am currently working with the following user supplied fields: chest waist hip So my question is, is there a way to say something like: if form.chest = <35.5 but >36.4 return size8 if form.chest = <36.4 but >37.4 return size10 etc etc without having to use an absurd amount of if statements to achieve the end goal in Django? -
Need to get id instead of selected value in modelchoicefield django
This is a very very basic question and i have already searched and tried lots of ways to do it but i want to know the good practice/best method to go about it. There is a table in which i am trying to store the user selected code from another table. What is want is A model form combo box which shows 'description' field value while saves its respective 'pos_code' in the table. This is my model and forms. pos_code = forms.ModelChoiceField(queryset=Positions.objects) Here i want to insert the 'pos_code' against the user selected 'description'. class TmpPlInvoice(models.Model): voucher_id = models.CharField(primary_key=True, max_length=10) pos_code = models.CharField(max_length=10, blank=True, null=True) class Meta: managed = False db_table = 'tmp_pl_invoice'` I am getting the choice field from this model. `class Positions(models.Model): pos_code = models.CharField(primary_key=True, max_length=10, blank=True, null=True) description = models.CharField(max_length=100, blank=True, null=True) class Meta: managed = False db_table = 'positions' def __unicode__(self): return self.description` but it gives me description instead of pos_code. I know that i am returning description but i need to show it to user and get code in the views. -
Using Django outside of view.py
I have a twisted based script running that is managing IO, monitoring serial inputs, writing logs etc. It uses Twisted to run events every minute and every hour as well as interrupt on serial traffic. Can Django be used to provide an interface for this, for example taking live values and display them using #python code generating value1 and value2 def displayValues(request): context = { 'value1':value1, 'value2':value2 } return render(request, 'interface.html', context) The obvious issue is that this python file doesn't live in the Django file setup and so the URL call wouldn't know where to look or how to call the displayValues function. An additional feature I might look to is to write the IO values in to a mysql database through Django as it is already setup. I understand Django from a simple databases application point of view but this is not something I've come across online and I might be moving outside of the scope of Django. I've seen this but it is more to do with using the Model outside of the standard setup. Using Django database layer outside of Django? Is this possible? Thanks! -
Django filter_horizontal filtering
I have 2 models related by M2M type of relationship. I use filter_horizontal in the admin for editing my entities. However, I would like to have a control on what is presented in the left side of the filter_horizontal widget. For example, I would like to filter and show only those entities that match some certain criteria. Any recommendation please? Thank you! -
How to sort django list filter by alphanumeric
I have used default django filter but it not show record by sorting i.e alphanumeric following is my code class VoteAdminModel(admin.ModelAdmin): list_filter = ('business__poll__town__parent') models class Business(models.Model): poll = models.ForeignKey('Poll') business_name = models.CharField(max_length=256, blank=True,null=True) class Poll(models.Model): town = models.ForeignKey('Town', verbose_name="Survey") category = models.ForeignKey(Category) class Vote(models.Model): business = models.ForeignKey(Business) vote_year = models.IntegerField(verbose_name="Year") gender = models.CharField(max_length=10) class Town(models.Model): town_name = models.CharField(max_length=256, verbose_name="Survey") parent = models.ForeignKey('self', db_column='parent', blank=True, null=True, verbose_name="Survey") -
django and heroku: serving static files locally bot not on heroku
This is my static files configuration: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] my DEBUG is True and my urls.py don't mention static at all: from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^', admin.site.urls), url(r'^chats/', include('chats.urls')), ] so locally I can get my static files served perfectly: curl http://127.0.0.1:8000/static/dummy.css .test_div { background-color: red; } curl http://127.0.0.1:8000/static/admin/css/base.css .... an admin CSS file gets served here .... however, when I deploy the same exact configuration on Heroku - I get 404 errors for admin files and for my custom static files: curl https://pleshka-timer.herokuapp.com/static/admin/css/base.css ... a 404 message.... The heroku collectstatic command that it runs with every code deployment finishes without errors. If I explore the dyno with heroku run bash I see that my staticfiles directory is sitting there, waiting to be served. What am I missing? By the way, I can always do this urlpatterns = [ url(r'^', admin.site.urls), url(r'^chats/', include('chats.urls')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) as per Django docs, and this would work; but why the hell should I do this if Heroku does the collectstatic routine for me? -
pass several parameters in Django rest Framework
I am new with Django and Django rest framework, I try to create several routes to get the data from the database. Right now in my urls.py file I have this router = routers.DefaultRouter() router.register(r'cpuProjects', cpuProjectsViewSet, base_name='cpuProjects'), this return this "cpuProjects": "http://127.0.0.1:8000/cpuProjects/" and I have the possibility to do this http://127.0.0.1:8000/cpuProjects/ => return all project http://127.0.0.1:8000/cpuProjects/ad => return a particular project. In my view.py I have this class cpuProjectsViewSet(viewsets.ViewSet): serializer_class = serializers.cpuProjectsSerializer # lookup_field = 'project_name' lookup_url_kwarg = 'project_name' def list(self, request): all_rows = connect_database() serializer = serializers.cpuProjectsSerializer(instance=all_rows, many=True) return Response(serializer.data) def retrieve(self, request, project_name=None): try: opc = {'name_proj' : project_name } all_rows = connect_database(opc) except KeyError: return Response(status=status.HTTP_404_NOT_FOUND) except ValueError: return Response(status=status.HTTP_400_BAD_REQUEST) serializer = serializers.cpuProjectsSerializer(instance=all_rows, many=True) return Response(serializer.data) Now I want that my Url accepted something like that http://127.0.0.1:8000/cpuProjects/ad/comments http://127.0.0.1:8000/cpuProjects/ad/ussing http://127.0.0.1:8000/cpuProjects/ad/process For this I add this new url router.register(r'cpuProjects/([a-zA-Z0-9]+)$', cpuProjectsViewSet, base_name='cpuProjects'), but now when I try this http://127.0.0.1:8000/cpuProjects/ad/ussing I obtain "page no found" I understood that this URL have to call to retrieve function to get the parameters, so, why this error? This URL don't do the same process like http://127.0.0.1:8000/cpuProjects/ad Thanks in advance! -
Django test discovery fails
I have a bunch of apps, all are inside a apps folder. I'm adding some tests to my project. It works well, the models / templates / static discovery works super well. Now I would like to add some tests to my projects, so I created a tests.py file inside my app. When I want to run the test (manage.py test) it does not work. I have to specify the name of the app to make it works. I tried with django-nose and I have to same output. I figure out it's because my apps are nested inside a folder but every other django discovery works. -
Create rewrite rule to any web server by node.js application
It's hard to explain, so I am sorry if something is unclear. I need to create web application on Node.js. Easy, but it's not all. ;) There is basic web application(it can be written by any language) based on web server. User can install my node.js application on the same server parallel to his own. After installation and running every couple of minutes my application generates random name. I need to create rewrite rule for web server, that will redirect to my application if path is the same as the name. For example: I generate string 'aaaaa'. If request goes somesite.com/aaaa it will be redirected to localhost:8080. If we are talking about Apache, my application can check if file .htaccess exists inside basic application and add rewrite rule RewriteRule ^aaaaa$ localhost:8080 [L] So my application should generate rewrite rules dynamically. But I need to create the same logic for all of these web servers: Nginx, Tomcat, Jboss, Apache, Glassfish, Jetty, Weblogic, IIS, Windows Server AppFabric, Django, Gunicorn. Can someone suggest some universal decision? I thought to run one more web server for example Apache, that will be filter traffic and redirect to existing web server. But it will slow any … -
How to add an initial/default value using Django Filters?
How can I add an initial/default value when using Django Filters? For example, something like this initial=False class UserFilter(django_filters.FilterSet): archive = django_filters.BooleanFilter(initial=False) class Meta: model = User fields = ['archive'] I've tired to override the __init__ but this does not appear to work. -
Django refresh session to obtain any new messages for user
I'm trying to do a simple push protocol for django messages. So in my REST call, I have the following snippet: storage = get_messages(self.request) res = dict(messages=[dict(level=item.level, message=item.message) for item in storage]) now = monotonic() while not res.messages and monotonic() - now < 15: sleep(.5) res.messages = [dict(level=item.level, message=item.message) for item in storage] Naturally, the while loop does nothing because the messages framework simply re-reads the session variable which only "updates" on new requests. I tried going into the underlying code to see if there was anything about updating the storage on the fly, but there seems to be no code that would do this, at least in the messaging framework. There was this promising undocumented storage.update() method, but it turned out to do something else. So, is there anything in Django framework that would allow me to poll for any messages changes and report that to the browser when it happens? Or a different method that would achieve the same thing more elegantly? -
how to set a cronjob to run a django managment commnad in AWS elastic beanstalk
I've a Django application running in Aws Elastic beanstalk.I need to run a cron which runs a django management command every 10 minutes (python manage.py test) For that i created a .ebextensions/cron.config file. .ebextensions/cron.config container_commands: 01_some_cron_job: command: "cat .ebextensions/cron_test.txt > /etc/cron.d/cron_test && chmod 644 /etc/cron.d/some_cron_job" .ebextensions/cron_test.txt */10 * * * * /opt/python/run/venv/bin/python34 /opt/python/current/app/manage.py test Is this the right way to run a django management command as cron job in AWS elastic beanstalk?? Do we need to activate the virtual environment before running the command?? -
Django Djoser resend activation email
Is it possible to add option to resend Djoser activation email? I do not see option to do it outside RegistrationView. -
Conditional Attributes for Django User based on Groups
A given user can be in zero or more of the following categories: floor staff managers owners If the user is floor staff they require extra attributes (e.g. seniority and staffType). My initial attempt looked something like this: Create a Group for each category (this seems to make sense since each type of user should have different permissions within the site) Create a FloorStaff model with the required extra attributes and a 1-to-1 relationship with User Handle User creation and FloorStaff creation separately (i.e. using separate forms, accessed separately). The form to create FloorStaff adds the User to the floor staff group automatically. While this works, it is not the most intuitive way to add a new floor staff employee to the site. From a manager's perspective, filling out 2 forms to add one employee makes little sense. That is, if I hire someone new, I should be able to fill out a "new employee" form that includes adding said employee to the correct categor(y/ies) at the same time as adding their basic info, and, if that employee is to be floor staff then the extra attributes should be added as well. I've been toying with creating a custom user … -
django foriegnKey refere to more than one table
I had two models. Parents and Children. Because Children and Parents have some different fields I had to separate them instead of having a single model person. And because a child should have a father and a mother I had two separate fathers and mothers in separate models. so far: class Father(models.Model): name = models.CharField(max_length=50) ... class Mother(models.Model): name = models.CharField(max_length=50) ... class Child(models.Model): name = models.CharField(max_length=50) ... father=models.ForeignKey(Father) mother... It should be better design there but I am not a pro. Now I need to have another model for health. Is it possible to have a model which fields belongs to a child or a father or a mother? Or I should make one health model for each like childhealth, fatherhealth etc? thnx in advance -
Django/Python: How to get the latest value from a model queryset?
I have created a model 'VehicleDetails' in which a user can fill the details of a vehicle and another model 'TripStatus' in which he can update the vehicle location. I wanted to get the latest location for which I did as in my below code. But when i running the server, it returns all the values not the latest value. I would appreciate helping me solve this or suggesting a new approach. models.py: class VehicleDetails(models.Model): Vehicle_No = models.CharField(max_length=20) class TripStatus(models.Model): vehicledetails = models.ForeignKey(VehicleDetails, related_name='tripstatuss') CHOICES = (('Yet to start', 'Yet to start'),('Trip starts', 'Trip starts'), ('Chennai','Chennai'), ('Vizag', 'Vizag'), ('Kolkata', 'Kolkata')) Vehicle_Status = models.CharField(choices=CHOICES, default="Yet to start", max_length=20) statustime = models.DateTimeField(auto_now=False, auto_now_add=True) views: def status(request): tripstatus = TripStatus.objects.all().latest('statustime') context = { "tripstatus": tripstatus, } return render(request, 'loggedin_load/active_deals.html', context) template: {% for status in vehicledetails.statuses.all %} {{status.Vehicle_Status}} {% endfor %} -
Running Nginx Webserver with Latest Changes
I have configured my nginx webserver according to this documentation http://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html So now, I pull the latest code from my github account and restarted my server and its not showing the latest changes. I want it to show the latest code changes. Important info: /usr/local/bin/uwsgi --emperor /etc/uwsgi/vassals I used this command to run my sever -
Django - order queryset alphabetically for cyrillic symbols
I have an issue with default ordering of cyrillic CharField's in Django. Is there a way to order cyrillic words alphabetically? Taxonomy.objects.filter(type=tax_type).order_by('name') This ordering returns me such data: For english words ordering works as expected: -
I can not log in with Django on the frontend - The shell works however
I developed a project on OS X and now I decided to use Debian for the development instead. I have the production setup with Debian as well so I thought that it might be a good idea to use it for the development. However I ran into strange errors that I'm not really sure how to debug. When I try logging in with Djangos auth system, it creates a session perfectly fine. But I'm not logged in to the system when using the forms. I tried logging in to the shell and that works fine. >>> from django.contrib.auth import authenticate >>> u = authenticate(username="a_superuser", password="password") >>> u.is_active >>> True >>> u.is_superuser >>> True I thought it could maybe be some database issue, so I ran all possible commands for PostgreSQL so that the user would have superuser privileges. I'm using: Mezzanine 4.2.0 Django 1.10.1 Python 3.4.2 PostgreSQL 9.4.9 Linux 3.16.0-4-amd64 -
Messenger account linking authentication flow in Django
How can I complete the authentication flow of the account linking in Django? I send the login template to user. When the user clicks on it, she is redirect to https://example.ngork.io/authenticate with the parameters account_linking_token and redirect_uri. Now, when I perform the redirection I have this error: Page not found (404) Request URL: http://example.ngrok.io/[redirect_uri] ^admin/ ^$ [name='index'] ^messengerhook [name='messengerhook'] ^authenticate [name='authenticate'] The current URL didn't march any of these. -
Django OneToOneField and signals
I have a model called DeviceStatus which has a OneToOne relationship with another model called Device. I want to get the id passed to the DeviceStatus object before saving, but all I get is a ForwardManyToOneDescriptor object. class DeviceStatus(TimeStampedModel): device = models.OneToOneField(Device) # other fields def __unicode__(self): return u'{}'.format(self.device) def copy_to_archive(**kwargs): print DeviceStatus.device pre_save.connect(copy_to_archive) Can somebody guide me through how to get the Device id being passed? TIA -
Filter with arbitrary number or Q objects combined by OR logical operator
Django 1.10.1 Search form. The user inserts words separated by spaces. Necessary to find objects with ANY of these words in the title field. I'm planning to use something like this: Article.objects.filter( Q(title__icontains="table") | Q(title__icontains="helm") ) I can make Q objects easily: q = Q(title__icontains="table"). But the obstacle is how to pass arguments to the filter method. https://docs.djangoproject.com/en/1.10/topics/db/queries/ The syntax is filter(**kwargs). With a loop I can prepare a dictionary like this : q_objects = {"1": Q(title__icontains="table"), "2": Q(title__icontains="glasses")} But the problem is with that "|". How to pass it to the filter method is a mystery to me. In other words I fail to build a filter with OR logical operator. Could you help me?