Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Hi there,i'm using Django1.8.6 with NGINX and GUNICORN. i want to receive data from TCP connection.can anyone help me?
i want to listen tcp data sent from external hardware.i am using tcp protocol. can i use python socket module on Django? -
Django migrations: create a partial index and set `db_index=True` without creating a full index?
I'm adding a NULL column to a large table, and I'd like to make sure that it has db_index=True set in the model definition: class MyLargeModel(Model): new_field = IntegerField(null=True, default=None, db_index=True) But for the actual index I'd like to use a partial index: migrations.RunSQL(""" CREATE INDEX my_index ON mylargemodel (new_field) WHERE new_field IS NOT NULL """) However, by default, this will mean Django's migrations will create an index (which will be very slow), then I'll need to manually drop that index and create my own. How can I create a migration which will tell Django Migrations that db_index=True is set without creating the index in the database? -
Django model CharField throws int() error when calling save()
Here's my model: class MarketData(models.Model): data_source = models.CharField(max_length=100) And here's the code that I keep testing python3 manage.py shell Then, I run this from q.models import MarketData data = MarketData("Broker") data.save() Which throws the error File "/home/soverton/.local/lib/python3.5/site-packages/django/db/models/fields/init.py", line 946, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: 'Broker' I've run the following and get status ok messages python3 ./manage.py makemigrations q Migrations for 'q': q/migrations/0006_auto_20170110_1911.py: - Alter field data_source on marketdata And finally, I push those with migrate. python3 manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, q, sessions Running migrations: Applying q.0006_auto_20170110_1911... OK So what am I getting an int() error when saving when it should be saving a char? I recently reformatted the project to switch from SQLite to PostgresSQL and deleted migration history. Is there something weird going on with the database? -
Django. ORM filter by function's keyword argument
I'm trying to extract some records (about magazines) from database to create table with stats. Extraction is made by time period and name of magazin. Here is the code that I currently have, but I suppose it is not DRY enough for two reasons: def get_statistic(date__gte=None, date__lte=None, name=None): magazines_qs = Magazines.objects.all() #1 move filters to "for" #2 get rid of "if" statement (may be by setting default values which # makes filter equal to .all() method) if date__gte: magazines_qs = magazines_qs.filter(date__gte=date__gte) if date__lte: magazines_qs = magazines_qs.filter(date__lte=date__lte) if offer: magazines_qs = magazines_qs.filter(name=name) I suppose it is possible to receive something like: def get_statistic(date__gte=None, date__lte=None, name=None): magazines_qs = Magazines.objects.all() for filter in arguments() magazines_qs = magazines_qs.filter(filter) But I don't know how. -
What is the best way to store translations of static pages in Django
I'm aware about two options. Enclose each sentence of content in blocktrans. Advantage: no need to repeat file formattting for every language. Disadvantages: meaning of text can be lost when splitted into sentences, very large po files. Create separate file for each language. Disadvantage: repeat file formattting for every language. Advantages: meaning of text is not lost, po files are not so large. What is the best technique? Possibly, other? Thank you. -
Django :The 'imgwh' attribute has no file associated with it
First: No, I'm not calling this attribute in my template. I was getting it on templates that don't call that attribute, and in fact, I removed the field entirely and I'm still getting this error from beyond the grave. Next: It all started when I realized I didn't quite understand MEDIA_ROOT and was doing something very stupid, had a model with: class Country(models.Model): imgwh = models.ImageField(upload_to=os.path.join(MEDIA_ROOT, 'country','imgwh'), null=True, blank=True) So I changed it to class Country(models.Model): imgwh = models.ImageField(upload_to=os.path.join('country','imgwh'), null=True, blank=True) (I know usually people just toss all Media into the same folder but to me that sounds like a hellpit and I separate them by field.) (My project is still in production, btw. Django project # 3 or 4 for me.) Then I tried to programmatically change the path, but I had not yet read the docs thoroughly, so I did obj.imgwh.name = NEW_NAME obj.save() and then that's when this started. I've tried checking with os.path.exists to see if they all exist, and at any rate all of the instances of the objects that had imgwh were connected to existing files. I've tried almost every piece of advice here: Programmatically saving image to Django ImageField and they did not … -
Templates in Django have been updated
In the old system, the templates used the follow syntax : Hello ear {# NOM_CLIENT #}, Now, with the 'Django's new template engine', the syntax becomes Hello dear {{ user.get_full_name }}, I have to verify in a program if the templates have been updated. Could anyone could give me a good website about that new structure? -
How do I send an array of objects from a django class based view to my index.html file?
The Goal: I want to use FullCalendar(https://fullcalendar.io/) to display event objects from my database. FullCalendar accepts an array of event objects as a property. The Problem I'm having: I can send context data back to the template with the event objects but as far as I know I can only interact with the data using Django's template tagging system. index.html: {% extends 'base.html' %} {% block content %} //ACCESSING THE CONTEXT DATA LIKE THIS WORKS BUT I CAN'T USE ptoHistory IN MY FULLCALLENDAR SCRIPT {% for history in ptoHistory %} <li>{{obj.leave_type}}</li> {% endfor %} <div class="container"> <div id="calendar"> <!-- Calendar is injected here --> </div> <!----------------------- SCRIPTS -----------------------------> <script> $(document).ready(function() { $('#calendar').fullCalendar({ defaultView:'month', editable: true, // MY ARRAY OF OBJECTS WILL REPLACE THIS HARDCODED ARRAY events: [ { title: 'All Day Event', start: '2017-01-12', }, { title: 'Meeting', start: '2017-01-13T10:30:26', end: '2014-06-13T12:30:00' }, ], }); }); </script> {% endblock content%} IndexView.py: class IndexView(FormView): template_name = 'accounts/index.html' form_class = PtoRequestForm success_url = 'login/' def form_valid(self, form): form.save() return super(IndexView, self).form_valid(form) def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) context['ptoHistory'] = PtoHistory.objects.all() print(context['ptoHistory']) return context Could someone point me in the right direction? -
Django 1.9 - create inline model during user save if it doesn't exist
Hello, I have this model: class ExtendedUser(models.Model): user = models.OneToOneField(User) GA_id = models.CharField(max_length=100,blank=False,default="anonymous") # Google Analytics ID #more stuff here It is inlined in the admin class, which is also customized some, like this: class ExtendedUserInline(admin.StackedInline): model = ExtendedUser can_delete = False verbose_name_plural = "extended user" class UserAdmin(BaseUserAdmin): inlines = (ExtendedUserInline,) def get_queryset(self, request): qs = super(UserAdmin, self).get_queryset(request) if not request.user.is_superuser: return qs.exclude(username__startswith='aprefix:') else: return qs admin.site.unregister(User) admin.site.register(User, UserAdmin) When creating a user, the ExtendedUser model cannot be edited, since it does not exist. Doing so will raise an error, so users must leave it at all default values. My current "solution" is to create the ExtendedUser instance during post-save, and then users can edit it after the user has been created: @receiver(post_save, sender=User) def user_postsave_handler(sender, instance, **kwargs): try: neu = ExtendedUser.objects.get(user=instance) except ExtendedUser.DoesNotExist: neu = ExtendedUser(user=instance) neu.save() # Do lots of stuff to it Obviously this is not ideal! Is there a proper way to make sure that an extended user is created & can be edited during the initial creation? Thank you! -
Django ORM select_related rendering template
I have this models in Django 1.10 version class Game(models.Model): game_code = models.CharField(max_length=10) home_team = models.ForeignKey(Team, related_name="home_set", default=2, blank=True, null=True) away_team = models.ForeignKey(Team, related_name="away_set", default=2, blank=True, null=True) class GameCoefficient(models.Model): game = models.ForeignKey(Game, default=3) win_type = models.CharField(choices=win_type, max_length=250, blank=True, null=True, default="") value = models.FloatField(max_length=250, blank=True, null=True, default="") after this ORM query class BaseView(View): data = dict() template = "index.html" def get(self, request): self.data['coefficents_and_game'] = GameCoefficient.objects.all().select_related('game') return render_to_response(self.template, self.data) I was able to get the coefficients and display their games. Now in template displays repeating "game_code". I find it difficult to display the game and its coefficients. -
Django: Check multiple choices with not fixed choices
I am new to Django, and I am trying to create a multiple selection with checkboxes. The problem is that all of the examples that I found have fixed choices that are specified in the form, and I don't need that. More concretely, let this be a model for a simple car dealership app: class CarBrand(models.Model): name = model.CharField() class CarModel(models.Model): name = model.CharField() brand = model.ForeignKey(CarBrand) My goal is when I enter the page for Audi, I get options A3, A4, A5, but when I enter the page for BMW, I get options M3, M4, M5. After clicking the submit it should send all the car models that were selected. -
Django select and order based on related value
I have 2 models: Subscriber and Notification. class Subscriber(models.Model): email = models.CharField() class Notification(models.Model): subscriber = models.ForeignKey(Subscriber, related_name='notifications') timestamp = models.DateTimeField(default=timezone.now) type = models.SmallIntegerField(choices=TYPES) What I want to retrieve is the subscribers who didn't receive a notification (based on type) within the last 5 minutes and order them by the time they last received ascending. I would probably solve this within sql with a subquery or something but I'm wondering if it's doable in Django. -
Filter objects that exist in the Foreign Key relationship
I have the following relationship in my data: Models: class Course(models.Model): name = models.CharField(max_length=200) concepts = models.ManyToManyField(Concept, related_name='course_concepts') class Concept(models.Model): name = models.CharField(max_length=120) But I would like to build a query set of Concepts that belong to a particular course (course_x). I have tried the following but continuously get reference errors: Concept.objects.filter(self__in=course_x) As such, what is the correct way to query only objects that match a foreign key relationship for a particular object? -
Is it possible to serialize geom field as topojson from Django?
I know how to render geom as json from Django Rest Framework, but I would like to serialize my model with topojson format to get best performance on my transactions. Is it possible to use the topojson.py https://github.com/calvinmetcalf/topojson.py on Django ? and how to do this for a basic use case ? -
Importerror: No module named memcache (Django project)
In a Django project of mine, I run this command to run the project on localhost: python manage.py runserver It results in the error: Importerror: No module named memcache However, I've already fulfilled the requirement via: sudo apt-get install python-memcache Peculiarly, if I go into the python shell outside my virtualevn and try import memcache, it works fine. However, inside my virtualenv, if I go into the python shell and try import memcache, I get the same import error listed above. What's going on? -
Custom save method for inherited Django model
I'm trying to use a custom save method that checks if an object exists already based on a query and then saving a new object if that query fails. So far this seems to be working within people/models.py, allowing me to prevent duplicate records from being created. However, I run into trouble when trying to extend this to another app's models.py which inherits from people. The problem is whenever I try to create a new member that is already within the person table, the member isn't created. However, when I create a member that isn't already in the person table, both a new person and a new member record are created. I'd like to be able to create a member record even if it already exists in the person table while maintaining checks for duplicates based on dob, first_name, and last_name. Any ideas on where I'm going wrong are extremely appreciated. A = Record Create A in Person --> Person Created Create A in Member --> Member Not Created **If person already exists no new member is created. But: Create A in Member --> New Member Created & New Person Created **If person or member doesn't exist new member and … -
Overloading Django ORM's "all" method
The question here, does Django provide any way to overload ORM all() method, ideally, in the model definition ? I have read in the doc that it's possible for save method, but nothing is mentioned about filtering operators, and specifically, all() To illustrate why and for what purpose I want to implement this, I provide an example below. Consider a model def my_model(models.Model) # main_fields is_deleted_flg = models.BooleanField() As you guessed, I don't physically delete any piece of data in my db, and I use is_deleted_flg field to mark rows that the user has deleted. Given this architecture, every time I want to get all instances of my_model, I do my_model.objects.filter(is_deleted_flg = False) Clearly, the problem here is violation of DRY, meaning I must remember which tables have is_deleted_flg and be cautious not to forget to write filter(is_deleted_flg = False) instead of .all(). One solution that I am familiar with is using custom querysets (let's call the filter is_deleted_filter. Using this approach, I would write my_model.objects.is_deleted_filter(), but I don't like this approach because 1) again, I have to remember, with which tables I should use .all(), and with which ones .filter_is_deleted() 2) and what is even worse for me, in … -
How to put just date from date time in unique constraint in Django
I have two columns in a Django model. name and start_date_time. I have the requirement of to make name and date unique in this model. I am able to make name and start_date_time unique but I have no idea at all how to make just date (not time) and name unique. So below example should not be a valid. It should throw error while saving second entry. name | start_date_time ------------------------ name1 | 2017-01-01 00:00:00 name1 | 2017-01-01 11:11:11 Please guide me in right direction how can I achieve this? -
How to Set the relative path; Static files are working perfectly on localhost but not getting loaded while deploying django application on AWS EB
this is the file structure the static files are present in firstproject/music/static/ folder on the local machine. on EB environment, the path to static files is: /home/ubuntu/firstproject/music/static/` In settings.py, I have written: STATIC_ROOT = '/home/ubuntu/moodyteens/music/static/' STATIC_URL = '/music/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # it is the original path where file is being saved. MEDIA_URL = '/media/' # it is the reference given to the path. In urls.py: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^music/', include('music.urls')), url(r'^', include('music.urls')), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and I am using the static files in base.html as: {% load staticfiles %} <link rel="shortcut icon" type="image/png" href="{% static 'favicon.ico' %}"/> <link rel="stylesheet" type="text/css" href="{% static 'music/style.css'%}" /> <script src="{% static 'music/js/main.js'%}"></script> How to set the relative path of the static files? Why static files are working perfectly on localhost but not on the AWS EB environment? I have also run the 'python manage.py collectstatic' on server side. -
Custom user model will no longer authenticate
Implemented a custom user model and everything was fine. Not sure what I changed over the last 24 hours but now when a user registers, they can no longer login. The user is always met with "Please enter a correct email address and password. Note that both fields may be case-sensitive" on the form error. After doing some investigating, it seems that when I create a super user through 'manage.py createsuperuser', that superuser has no problem authenticating and logging in. Been looking all night but can't find what I am doing wrong. Thanks in advance. views.py class Home(View): form_class = AuthenticationForm # Display Blank Sign In Form def get(self, request): form = self.form_class(None) return render(request, 'index.html', {'login_form': form}) # Process Form Data def post(self, request): form = self.form_class(data=request.POST) email = request.POST['username'] password = request.POST['password'] user = authenticate(username=email, password=password) if user is not None: login(request, user) return render(request, 'index.html', {}) else: return render(request, 'index.html', {'login_form': form}) class SignUp(View): form_class = MyRegistrationForm # Display blank user sign up form def get(self, request): form = self.form_class(None) return render(request, 'sign-up.html', {'form': form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(False) user.set_password(user.password) print(user.password) user.save() return redirect('/') else: return render(request, 'sign-up.html', {'form': form}) … -
How can I display updated image, when Iam using pagination?
As I am a begginer django student, I am tryng to make a blog. This blog must have a few pages (therefore I am using pagination) and in it django-admin I can update images also a single text post. The template show the text post and image(5 posts I set in pagination).I have sucess when I try to do one of this two things, so my blog show me well if I use pagination without images or I a update images without pagination. If I run server with this two, the brownser retorn me this follow message:"ValueError at / The 'arquivo' attribute has no file associated with it." - When I try to go to next page. Can somebody help me? My django version is 1.85, and python2.7 Follow my config: settings.py:(only the relevant part of the code, I think) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'media') project/urls.py: urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'', include('noob.urls')), ] if settings.DEBUG:#preciso estudar a saber o que foi feito aqui urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) app/urls.py: urlpatterns = [ url(r'^$', views.post_list), url(r'^post/(?P<pk>[0-9]+)/$', views.post_detail), ] as I am trying to do this using pagination, views.py: … -
Build a hierarchy of self referencing foreignkey rows
I have a these models def Group(Model): parent_group = ForeignKey("self") name = CharField(max=12) def Member(Model): group = ForeignKey(Group) name = CharField(max=12) score = BigIntegerField() Groups can be nested any number of times. How to write a function that returns data in the following format? {Group1: {Group2: {Group3: {Group4:{Member2: score}, Member1: score}, Member3:score}}} I have tried writing the following recursive function, but it doesn't work. rd = {} def find_parent(group): if group.parent_group is not None: return find_parent(group.parent_group) else: return group def populate_with_groups(parent_group=None, rd_part=None): if parent_group is None: groups = Group.objects.all() else: groups = Group.objects.filter(parent_group=parent_group) old_rd_part = None rd_part = rd if rd_part is None else rd_part for group in groups: if find_parent(group).name in rd: old_rd_part = rd_part rd_part = rd_part.setdefault(group.name, {}) members = Member.objects.filter(group=group) for member in members: rd_part[member.name] = member.score if len(Group.objects.filter(parent_group=group)) > 0: populate_with_groups(group, rd_part) rd_part = old_rd_part else: rd_part = old_rd_part else: ult_parent = find_parent(group) rd_part = rd.setdefault(ult_parent.name, {}) populate_with_groups(ult_parent, rd_part) populate_with_groups() Is there a simpler / correct way to do this? -
Django HTTP_HOST error from probing hackers, how to disable this 500 error?
I'm getting an error message sent to my settings.py: ADMIN = ['admin.error.email.here@domain.com'] email address. This error message occurs at a constant rate of around two per minute. I want to stop all error messages sent to my admin email that are HTTP_HOST errors, but at the same time still receive 500 error messages. I looked at the documentation and couldn't find any help. I searched on Stack Overflow and only found changing nginx 80 port server config file to contain a header error to a 444 error, so to bypass the 500 error report. However, this didn't work. Is there any setting.py variable for excluding certain errors? Time is of the essence - like I said, 2 damn emails per minute from some asshole that is desperate to scrape data. It's not a security risk but it is annoying and consuming my monthly email limit from my email host. Thanks for any help. -
How to simplify this Javascript substring slice search function
I have a URL like this in an HTML page on an HREF link: <a id="view_server_link" href="{% url 'view_server' serverid=1 %}"> Disregard the Django variable in the template. Effectively this produces a plain-text URL in the rendered HTML page like: http://site.domain.com/page/1/ And I'm trying to isolate this: http://site.domain.com/page/ in a JS variable so that later I can dynamically modify the HREF URL. All of that is working, but my URL reducing/isolating function seems bloated. I was hoping someone here could fine a way to simplify it. Again, this WORKS for me. var $view_server_href = $('#view_server_link').attr('href').substring(0, $('#view_server_link').attr('href').slice(0, -1).search(/\/\w*$/) + 1); -
Django int() argument must be a string, a bytes-like object or a number, not 'QueryDict'
I have a view which displays a form and saves the same form. There is no problem showing the view but when saving I get this following error: int() argument must be a string, a bytes-like object or a number, not 'QueryDict' Here is my code: MODEL: class Category(models.Model): name = models.CharField(max_length=100, db_index=True, unique=True) slug = models.SlugField(max_length=100, db_index=True, unique=True) user = models.ForeignKey(User, related_name='categories') class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.name) super(Category, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('wallet:category_details', args=[self.id]) VIEW: @login_required def category_create(request): user = request.user if request.method == 'POST': category_create_form = CategoryCreateForm(request.POST) if category_create_form.is_valid(): new_category = category_create_form.save(commit=False) new_category.user = request.user new_category.save() return render(request, 'category/done.html') else: category_create_form = CategoryCreateForm() return render(request, 'category/create.html', {'category_form': category_create_form}) FORMS: class TransactionCreateForm(forms.ModelForm): field_order = ['name', 'type', 'wallet', 'category', 'date', 'amount', 'notes', ] class Meta: model = Transaction fields = ('name', 'type', 'wallet', 'category', 'date', 'amount', 'notes',) def __init__(self, user, *args, **kwargs): super(TransactionCreateForm, self).__init__(*args, **kwargs) self.fields['wallet'] = forms.ChoiceField( choices=[(wallet, str(wallet)) for wallet in Wallet.objects.filter(user=user)]) How should I solve it?