Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How i can make a query using django orm group by date
How I can make a group by date using django Orm I have a query of sales I need return a query group by date sale by in django I don't have any idea how i can make a group by in a query -
adding custom ordering to django model
class MemberAdmin(CustomUserAdmin, admin.ModelAdmin): redirect_model_name = 'memberaccountproxy' change_form_template = 'loginas/change_form.html' list_display = ('username', 'email', 'first_name', 'last_name','country', 'gender', 'created_at', 'profile_pic') search_fields = ('username', 'first_name', 'last_name', 'email',) add_form = AccountProfileForm list_filter = ( 'gender', 'incomplete', 'email_verified', 'suspended', 'deleted', ) # profile1 = None def get_queryset(self, objects): return Account.objects.filter(usertype=1) def country(self, obj): profile1 = Profile.objects.get(account=obj) if profile1.country: return profile1.country return '' country.admin_order_field = 'country' What I am trying to achieve is to make my country column on Member list page sortable.(currently its not) Now the problem is that I get the 'obj' from method county(self, obj) as an Account object(as defined in the get_queryset()), and later I use that obj to get another object of type Profile (which has a member variable country). but when i try to register my country method to 'admin_order_field', it can only take member variables of obj (of type Account, which doesn't have country variable in it). So is there anyway I can sort the country column based on the field from Profile class instead of Account. -
Server Request every second
I have implemented a django web app which requires a get request from the server every second which I call through ajax without refreshing the page. At a time only 8 people can be accessing the server at a time so that is 8 requests per second which go to the database and return selected objects. It is to be deployed on a server with 128gb ram and 1.9 Tb hardisk. Will the server crash? -
Freelance Developer Needed For Wagtail Project
I plan to build a content-rich news magazine site. Wagtail seems to be a good base to build on, but I need a developer. Anyone looking for a freelance opportunity, or can advise on where to look? Appreciate any feedback at teymoor@eco-business.com Many thanks -
Android to Mysql database connection using django rest
What should i give in URL in android side .java file to connect with my django REST API and code for django to get data through POST? -
django queries data using wrong digits
I parsed a GET param named cb,66.45, and I converted it into float,got 66.45. cb = request.GET.get("cb", '') if re.match('^\d+(\.\d+)?$', cb): cb=float(cb) params['cb'] = cb And then I used it to query db data, got empty. products = Product.objects.filter(**params) In fact ,I found when debugging, the query sql used 66.4500000000000028421709430404007434844970703125 instead of 66.45, and that caused my empty query result. The cb is defined in Product model as below: cb = models.DecimalField(max_digits=6, decimal_places=2, default=0) Is there anything wrong? I am confused. -
Django model ensuring two properties should always be different - Is unique_together the answer?
How do I ensure that a unique combination of two properties should not be repeated For instance in the following model class modelBodyPart(models.Model): area = models.CharField(max_length=128) crush_name = models.CharField(max_length=128) In each instance of modelBodyPart area and crush_name should always be different for example some allowed and non-allowed results are: area = Area_A crush_name=Jenny //OK area = Area_A crush_name=Jordan //OK area = Area_B crush_name=Jenny //OK area = Area_A crush_name=Jenny //Not allowed How would I implement this in the model ? Will I use unique_together I could not totally understand the case requirement from the above link that is why I am asking here. -
Django too many open files
I'm getting "Too many open files" in my django application. I think it's related to the logging system, because with every request a new descriptor is created for file stage.log. The handler python_logging_rabbitmq.RabbitMQHandler belongs to this package python-logging-rabbitmq Any help? Thanks. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'request_id': { '()': 'log_request_id.filters.RequestIDFilter' }, 'ip': { '()': 'audit.ip_address.filters.IPAddressFilter' } }, 'formatters': { 'standard': { 'format': STANDARD_FORMAT }, 'compact': { 'format': COMPACT_FORMAT }, 'json': { '()': 'pythonjsonlogger.jsonlogger.JsonFormatter', 'fmt': JSON_FORMAT } }, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'filters': ['request_id', 'ip'], 'filename': BASE_DIR + '/logs/stage.log', 'formatter': 'standard', 'backupCount': LOG_FILE_BACKUP_COUNT, 'maxBytes': LOG_FILE_MAX_SIZE }, 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'filters': ['request_id', 'ip'], 'formatter': 'compact' }, 'rabbit': { 'level': 'DEBUG', 'class': 'python_logging_rabbitmq.RabbitMQHandler', 'formatter': 'json', 'host': RABBIT_HOST, 'username': RABBIT_USER, 'password': RABBIT_PWD, 'exchange': 'log', 'fields': { 'origin': 'main-api', 'env': 'stage' }, 'fields_under_root': True } }, 'loggers': { 'app': { 'handlers': ['console', 'file', 'rabbit'], 'level': 'DEBUG', 'propagate': False, }, 'django.request': { 'handlers': ['console', 'file'], 'level': 'DEBUG', 'propagate': False, }, 'requests.packages.urllib3': { 'handlers': ['console', 'file'], 'level': 'DEBUG', 'propagate': True, } } } -
how should i parse a word doc in django?
I'm trying to create a blog where I can upload a word or text doc and Django automatically parses the file, takes the article and pushes it onto the template. I'm fairly new at Django so I'm not sure how I should go about this -- 1) is FileField the best choice for models if only fellow admins will be posting files? 2) Should I save the parsed article to a new database straightaway, or should I have Django render the article via a views method? For the former, how would I go about designing a method to automatically parse the article each time an admin uploads a new file / makes a new entry? Thanks and sorry if this is a basic question. -
show django messages inside form_invalid of FormView
How can i show a message when using FormView class when form is invalid? I could show the message in form_valid function but no idea on form_invalid as i am using self.get_context_data. This is what i have done to show message when the form is valid def form_valid(self, form): messages.success(self.request, '{0} added successfully'.format(name)) return HttpResponseRedirect('/') How can i use message here? def form_invalid(self, form): return self.render_to_response(self.get_context_data(form=form)) -
Django saving an image that is a model field, works on /admin but not custom upload page
Rather than using Django admin, I wanted to make my own images upload on my site at 127.0.0.1/upload Now, when I upload an image through the admin, it works fine. But when I upload though my own image, it's not uploading (and not to the correct path). views.py def publish(request): image = request.POST.get('image_upload', '') photo = Photo(image=image) photo.save() return HttpResponseRedirect('/') models.py def generate_path(self, filename): url = "%s/%s" % (self.college.name, filename) return url class Photo(models.Model): image = models.ImageField(upload_to=generate_path, default="buildingimages/default.png") This is was I usually do for text based fields, but I'm assuming files work differently, and that's why this is not working? The object shows up in my admin after I try my upload, but the image itself doesn't seem to upload nor go to the right directory. So the generate_path works totally fine when I upload through the admin, but through my own publish view, it seems to upload to /media/ and then it says image does not exist? Any idea what I'm doing wrong -
Django migrate alternative for mysql db
I am trying to release a patch and trying to add a new model on the production machine. But when I try to run makemigrations or migrate after copying the migrate files from Dev. I am getting conflicting model type error. I tried removing the init.py from.project directory and also changing the import statement for models but it is still giving the error. So can I just directly create the model using mysql command line instead of makemigrations? What could be the issues due to it? Thanks in advance -
Django model return groups
Let's say there's a Django model User who is assigned a type. |id|name |type| |--|-----|----| |1 | John| A | |2 | Doe | B | |3 | Jane| A | I want to query the User model so that it returns groups of users. Something like Users.group('type') I should get [[@john,@jane],[@doe]]. So basically I want to do a group by but still get the whole models instead of some aggregate function result. -
Reverse for 'google-analytics-grant' with arguments '()' and keyword arguments '{'pk': 32}' not found. 0 pattern(s) tried: []
i'm new to django1.10.6/python3.6.0 and i tried to use an admin template django-jet1.0.5, all worked out until i needed google analytics which i'm new to the functionality too. i follow all the steps at th documentation and i get stuck here attach Google account and choose Google Analytics counter and when clicking on attach i get the error : NoReverseMatch at /jet/dashboard/module/32/ i have no clue to why this is happening so that i would look for the error TraceBack Environment: Request Method: GET Request URL: http://127.0.0.1:8000/jet/dashboard/module/32/ Django Version: 1.10.6 Python Version: 3.6.0 Installed Applications: ['primary_app.apps.PrimaryAppConfig', 'jet.dashboard', 'jet', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template C:\Users\Zakariae\AppData\Local\Programs\Python\Python36-32\lib\site-packages\jet\dashboard\templates\jet.dashboard\update_module.html, error at line 18 Reverse for 'google-analytics-grant' with arguments '()' and keyword arguments '{'pk': 32}' not found. 0 pattern(s) tried: [] 8 : {% if app %} 9 : &rsaquo; <a href="{{ app.app_url }}">{% if app.name != app.app_label|capfirst|escape %}{{ app.name }}{% else %}{% trans app.app_label as app_label %}{{ app_label|capfirst|escape }}{% endif %}</a> 10 : {% endif %} 11 : &rsaquo; {{ object.title|capfirst }} 12 : </div> 13 : {% endblock %} 14 : {% endif %} 15 : 16 : {% block … -
Django Help: How to take text data from textbox and pass through python script?
I'm making a Django web app where I want to take user input from an HTML textbox and run it through a python script. The script works when I input text from the command line, but I want to be able to make the web app print what happens to the text when it goes through the script. I have already made a Django web app, and when the server is run a basic HTML page with a simple text box and a submit button appears (it's a form). I have written a separate python script which will take user input (from the command line) and run the text entered through the script. How would I be able to replace the input() from the function with form data from the HTML page? An example of what I want to do: <form action=""> text: <input type="text" name="handle" value=""><br> <input type="submit" value="Submit"> </form> The above is a simple form with the submit button. When the 'submit' button is pressed, I want that data to go to a script: import statements def blah(): screenname = input('Enter your name here: ') output = screenname.functionA print(output) Except the input() is replaced with the form data … -
in django, hwo to search my database?
can you check my code. i was going to make serching from my DB {{ serch_form.as_p }} not working.. and, also let me know about whether my code is right or not.. this is my form class Searchform(forms.ModelForm): search = forms.CharField(max_length=100, required=False) class Meta: model = MyUser fields = ('Nationality', 'Mother_language','Wish_language' ) this is my model class MyUser(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) username = models.CharField(max_length = 30, unique = True, null = False) Nationality =models.CharField(max_length = 30,choices= Country_choice,null = False) Mother_language = models.CharField(max_length = 30,choices= Language_list,null = False) Wish_language =models.CharField(max_length = 30,choices= Language_list,null = False) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) picture = models.ImageField(upload_to='profile_images',blank=True) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username','Nationality','Mother_language','Wish_language','picture'] this is my view def search(request): if request.method == 'POST': results = MyUser.objects.all() serch_form =MyUserAdmin(data=request.POST) search = request.POST.get('search', None) if search: results = results.filter(Q(username=search)|Q(Nationality=search)|Q(Mother_language=search)|Q(Wish_language=search)) Nationality = request.POST.get('Nationality', None) if Nationality: results = results.filter(Nationality=Nationality) Mother_language = request.POST.get('Mother_language', None) if Mother_language: results = results.filter(Mother_language=Mother_language) Wish_language = request.POST.get('Wish_language', None) if Wish_language: results = results.filter(Wish_language=Wish_language) return render_to_response('index.html', {'form': Searchform(request.POST), 'MyUser': results}) return render_to_response('index.html', {'form': Searchform()}) this is my index.html (search html) <form id="MyUserAdmin" method="get" action="{% url 'index' %}"> {% csrf_token %} {{ serch_form.as_p }} <input type="submit" value="submit" … -
Is it possible to run south command without creating another app folder?
Need to modify old code where south is used, django 1.6. The problem is south is supposed to be applied to created app folder (the folder created after start app command), but in my case all logic is in original project folder(created after start project) So that I have no idea what shall be the command be applied to now? ./manage.py schemamigration ? --initial It doesn't work without the folder name marked by question sign, and I couldn't find answer in documentation so far. Is it possible to run this command without creating another app folder? -
how to access joining table/object of django many to many relationship
I have the following models: class InvestmentChoice(models.Model): title = models.CharField(max_length=64) class Offering(models.Model): entity = models.OneToOneField(Entity) investment = models.ManyToManyField(InvestmentChoice, blank=True) I want to get a list of the Entity objects that have a certain investment choice. I think this would mean I need access to the many-to-many joining table. If so, how can I do this? -
How do I access dynamically created fields to get their cleaned data in Django Forms?
I understand how to use form.cleaned_data['<field>'] to get a fields value, but how do I access my dynamically created fields? I have this code in my form: class DevicesForm(forms.Form): prefix = 'deviceform' device_type = forms.ModelMultipleChoiceField( queryset = Device.objects.all(), # not optional, use .all() if unsure widget = forms.CheckboxSelectMultiple, ) def __init__(self, *args, **kwargs): super(DevicesForm, self).__init__(*args, **kwargs) self.fields['device_type'].empty_label = None for i in Device.objects.all(): self.fields["%s build:" % i] = forms.CharField() How do I access the data the user enters into the Charfield() in self.fields["%s build:" % i] = forms.CharField() after POST? -
django serch from django's database?
i am using db.sqlite3 as DB. i want to search Email which user registered. class MyUser(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) date_of_birth = models.DateField() is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['date_of_birth'] how do i make serchform,views,html... plz, help me.! -
Django: filter queryset by field of not related model
I have models without relations: class A(models.Model): pass class B(models.Model): a_id = models.IntegerField() How to filter queryset of A objects if there is B object and A().id == B().a_id? It's easy to do with ForeignKey (A.objects.filter(b__isnull=False)), but how to do it without relation? -
Django: how to update model attribute through a view?
I have albums and songs. When at specific album page I want to add a song by clicking "Add Song" button and return to that album's page: Album's page The from opens fine and lets me input song title. But when I click "Submit" it breaks with this exception: Exception Here is a portion of template code where form is called: {% block body %} <div class="container-fluid" style="position:relative; padding-left: 100px; padding-top: 50px;"> <img src="{{ album.album_logo.url }}" class="img-responsive" height="200" width="200"> <h1>{{ album.album_title }}</h1> <h3>{{ album.artist }}</h3> {% for song in album.song_set.all %} {{ song.song_title }} {% if song.is_favorite %} <img src="http://vignette1.wikia.nocookie.net/defendersquest/images/1/17/Yellow_star_small.png/revision/latest?cb=20120430053933" height="10" width="10"/> {% endif %} <br> {% endfor %} <a href="{% url 'music:song-add' album.pk %}"> <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>&nbsp; Add Song </a> </div> {% endblock %} Here is urls.py: urlpatterns = [ # /music/ url(r'^$', views.IndexView.as_view(), name='index'), # "$" sign means nothing more was requested from user # /music/<album_id>/ - here album_id is an ID of specific Album for example url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'), # this will look for numbers 0-9 in user request #and map it to variable named 'album_id'. Plus sign emplies to look for one or more numbers #^-sign implies begingin of reg. expression and $-implies the end … -
Not able to configure haystack-elasticsearch for search in android
I started with this tutorial but i was not able to understand how to set up it for search in android app.Till now I have made model in using django rest framework, then used retrofit in android to make GET ,PUT ,POST request. Now i want to do search my products by name. From the above tutorial it was trying to make search html page and typing the query in that html page. But i want a endpoint where i can sent get request for searching. Please help now able to understand how to do it. -
How to customize user during RemoteUserBackend authentication
I copied the RemoteUserBackend class from Django and modified it to do check if the remote_user that is connecting is in a specific LDAP group before continuing with the authentication. If the user has never logged on before the user is populated in Django's database. I'm trying to figure out how to set the first_name, last_name, and email fields as well as make the user stuff and a superadmin. This is the code that I have. It's part of the RemoteUserBackend class. I'm doing something wrong. The LDAP lookup is fine but the user isn't changed. def configure_user(self, user): """ Configures a user after creation and returns the updated user. By default, returns the user unmodified. """ con = ldap.initialize(settings.AUTH_LDAP_SERVER_URI) bind_dn = settings.AUTH_LDAP_BIND_DN bind_pw = settings.AUTH_LDAP_BIND_PASSWORD con.simple_bind_s(bind_dn, bind_pw) base_dn = settings.AUTH_LDAP_USER_DN attrs = ['givenName', 'sn', 'mail'] filter = '(SAMAccountName={0})'.format(user.username) ldap_user = con.search_s(base_dn, ldap.SCOPE_SUBTREE, filter, attrs) givenName = ldap_user[0][1]['givenName'][0].decode('utf-8') sn = ldap_user[0][1]['sn'][0].decode('utf-8') mail = ldap_user[0][1]['mail'][0].decode('utf-8') user.is_staff = True user.is_superadmin = True user.first_name = givenName user.last_name = sn user.email = mail user.save() return user -
Django Memory Error while Loading XML
I'm having an issue with loading in xml to display it onto a page in django. The following is how I'm loading the xml file. def getinstance(self, instance_location): """ Loads xml file into dicts to use in html template """ self.logger.debug(instance_location) try: with open(instance_location + '.xml', 'r') as xml_read: self.data = xml_read.read() xml_data = ElementTree.fromstring(self.data) xml_data.findall('.') # pull info from xml file base_categories = xml_data.findall('./BaseCategory') main_categories = xml_data.findall('./BaseCategory/MainCategory') sub_categories = xml_data.findall('./BaseCategory/MainCategory/SubCategory') enums = xml_data.findall('./BaseCategory/MainCategory/SubCategory/Enumerations') enums_types = xml_data.findall('./BaseCategory/MainCategory/SubCategory/Enumerations/EnumerationTypes') enums_content = xml_data.findall('./BaseCategory/MainCategory/SubCategory/Enumerations/EnumerationTypes/EnumerationContent') base_dict = [] main_dict = [] sub_dict = [] enum_dict = [] enum_type_dict = [] enum_content_dict = [] for base_category in base_categories: base_dict.append({ 'name': base_category.find('Name').text, 'form_type_id': base_category.find('form_type').text, 'id': int(base_category.find('base_id').text), 'position': int(base_category.find('position').text), 'order_by_type': (True if base_category.find('order_by_type').text.lower() == 'true' else False), 'order_by_asc': (True if base_category.find('order_by_asc').text.lower() == 'true' else False), }) print('base_cats set') for main_category in main_categories: main_dict.append({ 'id': int(main_category.find('main_id').text), 'name': main_category.find('Name').text, 'base_category_id': int(main_category.find('base_category_id').text), 'is_visible': (True if main_category.find("is_visible").text.lower() == 'true' else False), 'is_seller_field': (True if main_category.find("is_seller_field").text.lower() == 'true' else False), 'help_text': main_category.find('help_text'), 'position': int(main_category.find('position').text), 'order_by_type': (True if main_category.find("order_by_type").text.lower() == 'true' else False), 'order_by_asc': (True if main_category.find("order_by_asc").text.lower() == 'true' else False), 'show_seller': (True if main_category.find("show_seller").text.lower() == 'true' else False), }) print('main_cats set') for sub_category in sub_categories: sub_dict.append({ 'id': int(sub_category.find('sub_id').text), 'name': sub_category.find('Name').text, 'library_id': sub_category.find('sub_library_id').text, 'field_display_type': …