Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to skip creation of one of the test databases in Django
We have two databases we work with in our Django application, a "transactional" one and an "analytical" one (serving as a data warehouse). The "transactional" one is created using django models and the "analytical" one is created using our custom scripts containing raw sql of multiple joins of the "transactional" ones tables. When we run tests for the django app, both of the databases get their test counterpart versions created, let's say, "test_transactional" and "test_analytical". The creation of the "test_transactional" is ok, but we would like for the creation of the "test_analytical" to be skipped since that one will be created and filled by our custom scripts. Snippet from jenkins logs: python manage.py test --keepdb cis.tests.test_views -- noinput --settings=strainprint.settings.local --verbosity=2 ... Using existing test database for alias 'analytics' ('test_strainprint_analytics')... ... Synchronizing apps without migrations: Creating tables... Creating table django_admin_log Creating table auth_permission ... Is there a way to achieve this in Django? We are using django 1.10. -
Creating a lookup table with multiple foreign keys
I'm trying to create a lookup table in Django and not quite sure how to implement. I have two tables, one with "money spent" and the second with "free gifts". You spend a certain amount, the more free gifts you get (one to many). For example in image below, if you spend $50, you get Ice Cream and Soda as free gifts. At a lower level you would only get one free gift. I created this model but running migrations doesn't like it. class GiftDefaults(models.Model): """ Default gifts associated with spending levels """ # Fields gift = models.ForeignKey(Gift, null=True, blank=True,on_delete=models.CASCADE), spending_level = models.ForeignKey(SpendingLevel, null=True, blank=True,on_delete=models.CASCADE) def __str__(self): return self.gift What is the proper way to create this lookup table in Django models? Not sure what's wrong with my Model. -
What is the best way to redirect to a model with its own unique template?
I have a league that will be made up of individual teams which are represented by a team model. What I want to do is list the teams on the league homepage(base.html) and have each team be a link to their respective page which is represented by a different template that extends base.html. What is the best strategy for achieving this? I can make it work if I write each team link one by one I guess, but I'm running into trouble if I try to use a for loop in the base.html template. Is it possible to have a template attribute in a model where I save the template and somehow redirect to that attribute? # Team class Team(models.Model): team_choices = TEAM_CHOICES name = models.CharField(max_length=50, null=True, blank=True, choices=team_choices) players = models.ManyToManyField('accounts.User', related_name='players', blank=True) season = models.ManyToManyField('Season', related_name='team_seasons', blank=True) city = models.ForeignKey(City, on_delete=models.CASCADE, blank=True) neighborhood = models.CharField(max_length=100, null=True, blank=True) sponsor = models.CharField(max_length=100, null=True, blank=True) about = models.TextField(null=True, blank=True) credits = models.TextField(null=True, blank=True) url = models.CharField(max_length=50, null=True, blank=True) photo = models.ImageField(null=True, blank=True, upload_to='images') video = models.FileField(null=True, blank=True, upload_to='videos') date_created = models.DateField(auto_now_add=True) class Meta: ordering = ['name', 'neighborhood', 'sponsor', 'about', 'credits'] def create(self): self.created_date = timezone.now() self.save() def __str__(self): return self.name def … -
Django ManyToManyField how to add created_at and updated_at
How can I add created_at and updated_at fields to my ManyToManyField? class Profile (models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Group(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) profiles = models.ManyToManyField(Profile, related_name='groups') -
Wagtail: Is it possible to don't prepend link's hrefs with a domain?
I want to make the urls which I put in the WYSIWYG editor just absolute like /something but not sitename.com/something. I know that I can use the "external link" option, but it is not very handy for my editors. -
Populate OneToOneField with objects from another model in Django Rest Framework
(Django 2.0, Python 3.6, Django Rest Framework 3.8) I'm trying to create a booking system between clients and gyms and have run into a bit of a problem. Let's say I have the following model for Gym Clients: class ClientProfile(models.Model): parent_TriUser_link = models.OneToOneField(TriUser, \ primary_key=True, db_column="id", parent_link=True, on_delete=models.CASCADE, \ related_name='ParentLinkRelatedName') selected_trainer = models.ForeignKey('TrainerProfile', related_name='TrainerProfileRelatedName2',\ blank=True, null=True, on_delete=models.CASCADE) def __str__(self): return str(self.profile) and the following model for Gym Trainers: class TrainerProfile(models.Model): """data required to pull up trainer profile""" profile = models.OneToOneField(TriUser, on_delete=models.CASCADE) availability = models.ManyToManyField('Availability', related_name='AvailabilityRelatedName', blank=True) def __str__(self): return str(self.profile) #return self.trainer_is_moderator Where profile is linked to a user model named TriUser (a standard User model with a couple added fields), and Availability is: class Availability(models.Model): SUNDAY = 'SUNDAY' MONDAY = 'MONDAY' TUESDAY = 'TUESDAY' WEDNESDAY = 'WEDNESDAY' THURSDAY = 'THURSDAY' FRIDAY = 'FRIDAY' SATURDAY = 'SATURDAY' AVAILABILITY_DATE_CHOICES = ( (SUNDAY, 'Sunday'), (MONDAY, 'Monday'), (TUESDAY, 'Tuesday'), (WEDNESDAY, 'Wednesday'), (THURSDAY, 'Thursday'), (FRIDAY, 'Friday'), (SATURDAY, 'Saturday'), ) availability_date = models.CharField( max_length = 9, choices=AVAILABILITY_DATE_CHOICES ) T1200_1230_AM = '12:00 am - 12:30 am' T1230_100_AM = '12:30 am - 1:00 am' T100_130_AM = '1:00 am - 1:30 am' T130_200_AM = '1:30 am - 2:00 am' T200_230_AM = '2:00 am - 2:30 am' T230_300_AM = … -
Custom User auth in DRF (Django Rest Framework)
I already have a working auth.token registration using the django default User class, but i was asked to add a new field to the User, i investigate things as AbtractUser, AbstractBaseUser, etc. And i think the best solution will be the OneToOneField "method". This is what i tried to do: models.py: class Usuario(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) es_tecnico = models.BooleanField(name = 'es_tecnico', default = False, blank = True) serializers.py class UsuarioSerializer(serializers.ModelSerializer): user = UserSerializer(required=True) class Meta: model = Usuario fields = ('user', 'es_tecnico') def create(self, validated_data): """ Overriding the default create method of the Model serializer. :param validated_data: data containing all the details of student :return: returns a successfully created student record """ user_data = validated_data.pop('user') user = UserSerializer.create(UserSerializer(), validated_data=user_data) usuario, created = Usuario.objects.update_or_create(user=user, es_tecnico=validated_data.pop('es_tecnico')) return usuario views.py: class UsuarioViewSet(viewsets.ModelViewSet): lookup_field = 'id' serializer_class = UsuarioSerializer queryset = Usuario.objects.all().filter(es_tecnico = False) class TecnicoViewSet(viewsets.ModelViewSet): lookup_field = 'id' serializer_class = UsuarioSerializer queryset = Usuario.objects.all().filter(es_tecnico = True) I want to make it work as simple as possible, this is what i get when i use the command "python3 manage.py makemigrations": Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/stalker/PycharmProjects/ingSoft/servidor/virenv/lib/python3.5/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/stalker/PycharmProjects/ingSoft/servidor/virenv/lib/python3.5/site-packages/django/core/management/__init__.py", … -
django rest_frameworks orderingfilter is wrong?
I'm new to python/django and I'm running into a weird sorting problem. I'm importing and using OrderingFilter in a base model class. Then I declare ordering_fields on the model class with the field to use for ordering. For instance, I'm using name so that when I make a URL request with a query param (https://something.com/api/v3/campaigns/?ordering=name), I expect that list of results to be sorted alphabetically by name. If my list of names is: Pitched Campaign Pitch Rejected Campaign Awesome Campaign I expect the filtered call to return: Awesome Campaign Pitch Rejected Campaign Pitched Campaign Instead, I get: Awesome Campaign Pitched Campaign Pitch Rejected Campaign It's as if the OrderingFilter ignores the whitespace in those strings and orders that way. It's the only thing I can think of to explain why: Pitched Campaign (pitchedcampaign) comes before Pitch Rejected Campaign (pitchrejectedcampaign) Is there something I'm missing? -
How to change view function to Django createView?
I would like to change my view function that checks POST method, and change this to CreateView built-in class.. I have a trouble with getting request parameter and checking ifPOST etc.. is there any way I change it into CreateView class? def addDatabase(request): FormSet = formset_factory(YamlForm) # get existing yaml form data. yaml_data = Form_info.objects.all() if request.method == 'POST': yamlFormSet = FormSet(request.POST) if yamlFormSet.is_valid() != False: # Now save the data for each form in the formset try: with transaction.atomic(): # replace the old with the new Form_info.objects.all().delete() for form in yamlFormSet: form.save() # form save and bulk_create are equal # And notify if that worked messages.success(request, 'It has been added') except IntegrityError: # if the transaction failed messages.error(request, "There was an error") return return render(request, 'niro/output.html', {'formset': yamlFormSet}) else: yamlFormSet = FormSet() context = {'yamlFormSet': yamlFormSet} return render(request, 'niro/addDatabase.html', context) -
Django fastest way to join two models and get a list of paired tuples
Here is how my models.py look like: class Foo(models.Model): name = models.CharField(max_length=30) class Bar(models.Model): name = models.CharField(max_length=30) class Hat(models.Model): foo = models.ForeignKey(Foo, on_delete=models.CASCADE) bar = models.ForeignKey(Bar, on_delete=models.CASCADE) num = models.PositiveIntegerField(default=0) class Meta: unique_together = ('foo', 'bar') Now in my views.py I want to have a function like: def index(request): foo = request.foo bars = Bar.objects.all() hats = Hat.objects.filter(foo=foo).all() #return ??? what I want as output of index function is a list of tuple like [(bar_1, hat_1),(bar_2, hat_2), ...] where for each hat_i we have hat_i.bar == bar_i and if there is no Hat object associated with a bar_i I want it to be paired with None. Please notice that as Hat has a unique constraint on (foo, bar), hence the number of retrieved hats filtered by foo cannot be more than the number of Bar objects. What's the fastest way that I can build such list in Django? -
Django reverse inline for admin
I have the User class which is referenced by foreign key by the Student class, Parent class, and Teacher class. class User(): pass class Parent(): user = models.ForeignKey(User) class Student(): user = models.ForeignKey(User) class Teacher(): user = models.ForeignKey(User) I would like to do a UserInline and have ParentAdmin TeacherAdmin, etc. Of course, DjangoAdmin requires that User be the one that has a ForeignKey to Parent, Teacher, Student, etc., however I was wondering if we could potentially somehow reverse it or structure it that I could just create a Student or Teacher while incorporating the UserInline -
DJANGO FUSIONCHARTS: Object of type 'int64' is not JSON serializable
The graph works if use data from the sqlite database but using a csv file gives me this error and I'm not sure what to do I have looked at similar problems online like "TypeError: (Integer) is not JSON serializable" when serializing JSON in Python? but I am able to figure out the solution...I am still a beginner in django and fusioncharts I have attached the fucntion below Thank you def chart2001(request): data = pd.read_csv('20_Victims_of_rape.csv') year = '2001' dataSource = {} dataSource['chart'] = { "caption": "Click on each State for a Subgroup Analysis", "xAxisName": "Name of the State", "yAxisName": "Number of Reported crimes against women", "theme": "ocean", "paletteColors" : "#0075c2", "bgColor" : "#ffffff", "borderAlpha": "20", "canvasBorderAlpha": "0", "usePlotGradientColor": "0", "plotBorderAlpha": "10", "showXAxisLine": "1", "xAxisLineColor" : "#999999", "showValues" : "0", "divlineColor" : "#999999", "divLineIsDashed" : "1", "showAlternateHGridColor" : "0" } dataSource['data'] = [] dataSource['linkeddata'] = [] d = data[(data['Year'] == 2001) & (data['Subgroup'] == 'Total Rape Victims')] d = d.reset_index(drop=True) # Iterate through the data in `Revenue` model and insert in to the `dataSource['data']` list. for key in range(0,len(d)): data = {} data['label'] = d['Area_Name'][key] data['value'] = d['Rape_Cases_Reported'][key] data['link'] = 'newchart-json-'+ d['Area_Name'][key] dataSource['data'].append(data) # Create the linkData for cities drilldown linkData … -
Graphene Mutation Tultorial not working
I´ve started learning GraphQL for a week, and my biggest challenge is dealing with Post Data. I´ve read that it´s all about mutations, however Im not doig it right. I´m just trying to post a Survivor(my model) Object to my database Here´s the code: This is the app´s schema import graphene from graphene import relay, ObjectType from graphene_django.types import DjangoObjectType from graphene_django.filter import DjangoFilterConnectionField from .models import Survivor class SurvivorNode(DjangoObjectType): class Meta: model = Survivor filter_fields = ['name'] interfaces = (relay.Node, ) class SurvivorInput(graphene.InputObjectType): name = graphene.String(required=True) age = graphene.Int(required=True) class AddSurvival(graphene.Mutation): class Arguments: survivor_data = SurvivorInput() survivor = graphene.Field(SurvivorNode) @staticmethod def mutate(root,info,survivor_data): survivor=Survivor( name = survivor_data.name, age = survivor_data.age ) return AddSurvival(survivor = survivor) class Query(object): all_survivors = DjangoFilterConnectionField(SurvivorNode) survivor = relay.Node.Field(SurvivorNode) Would you guys please tell me what´s wrong? and what should I do right? -
Django view returning stale data, fixed after server restart
I have a Django webserver with a postgresql database. I have a view (Django REST framework) that is giving exhibiting strange behavior. The view lists the date of the most recent record in a table. Records are consistently added multiple times per minute to this table. I do not have any caching implemented on this view. Today I have observed the following: view on production server was returning stale data (latest data 2 days ago) view on local development server (connects to same remote database) returned fresh data view within ./manage.py shell run on production server returned fresh data I had not restarted production server since 2 days ago After restarting production server today, data in view is fresh again 30 minutes later, the data is now 30 minutes stale What could be causing this? Why did I have to refresh the connection to the database to get fresh data? -
relation "django_session" does not exist
Now I am new in heroku and trying to deploy my django app on heroku. It was successful by just following instructions and I could test in heroku. But after I changed my local db from sqlite to postgres, I can not go further because of the error. It might be related to DB. My app is still working good in local base but not in heroku while I push all to heroku. base.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } db_from_env = dj_database_url.config() DATABASES['default'].update(db_from_env) error message on debug mode ProgrammingError at / relation "django_session" does not exist LINE 1: ...ession_data", "django_session"."expire_date" FROM "django_se... ^ Request Method: GET Request URL: https://happybom.herokuapp.com/ Django Version: 2.0.4 Exception Type: ProgrammingError Exception Value: relation "django_session" does not exist LINE 1: ...ession_data", "django_session"."expire_date" FROM "django_se... ^ Exception Location: /app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py in _execute, line 85 Python Executable: /app/.heroku/python/bin/python Python Version: 3.6.4 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python36.zip', '/app/.heroku/python/lib/python3.6', '/app/.heroku/python/lib/python3.6/lib-dynload', '/app/.heroku/python/lib/python3.6/site-packages'] heroku logs 2018-06-27T16:19:46.500148+00:00 app[api]: Starting process with command `bash` by user txxx@gmail.com 2018-06-27T16:19:54.976946+00:00 heroku[run.8196]: Awaiting client 2018-06-27T16:19:55.035413+00:00 heroku[run.8196]: Starting process with command `bash` 2018-06-27T16:19:55.078847+00:00 heroku[run.8196]: State changed from starting to up 2018-06-27T16:20:17.457935+00:00 heroku[run.8196]: Client connection closed. … -
Django/PostgreSQL manage.py flush error. look at output of 'django-admin sqlflush'
Build: Heroku Python server, Postgresql 10.4, Django 2, wagtail 2.1 I'm trying to essentially destroy and recreate my app DB on Heroku. Here are the steps I've followed: create db dump (success) rm all migrations and recreated the 'initial' migrations (success) run `heroku pg:reset DATABASE` (success) push new migrations and db dump (success) run `heroku run python manage.py migrate` (success) run `heroku run python manage.py flush` (**failed**) JVsquad$ heroku run python manage.py flush Running python manage.py flush on ⬢ my_app... up, run.2459 (Hobby) You have requested a flush of the database. This will IRREVERSIBLY DESTROY all data currently in the 'my_app_db' database, and return each table to an empty state. Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel: yes CommandError: Database my_app_db couldn't be flushed. Possible reasons: * The database isn't running or isn't configured correctly. * At least one of the expected database tables doesn't exist. * The SQL was invalid. Hint: Look at the output of 'django-admin sqlflush'. That's the SQL this command wasn't able to run. My 7th step was going to be heroku run python manage.py loaddata db_dump.json but it also failed, because the flush won't work. HELP … -
URL issue in Droplets and Django
I purchased a domain name from GoDaddy and I linked it to my Droplets server's A records. So far everything was working fine, it loaded the static files, it loaded the home view properly, everything was going great until I tried to go to a different part of my site (for example '...com/login/'). I ran into this weird issue where the site would only load the home page view, whatever URL I typed in it wouldn't serve anything else. Maybe the problem is that I developed the site using Django 2, and the Droplets Ubuntu server only uses Django 1.10, maybe. Anyway if anyone has any kind of solution to this it would be greatly appreciated, I've been trying to solve this problem for about 2 weeks now, thanks! (Also if anyone knows how to upgrade to Django 2 on droplets, post that too please, thanks!) -
Pass a datetime object to url in django
How can I pass a datetime e.g. datetime.date(2017, 12, 31) object to a url in django? My template: {% for key, value in my_dictionary.items %} {{ key.0 }} # it displays Dec. 31, 2017 ... {% endfor %} Passing it to the url as: href="{% url 'my_url:my_date' selected_day=key.0 %}"> My urls.py: url(r'^my-date/(?P<selected_day>\w+)/$', name='my_date') Error: Exception Type: NoReverseMatch Exception Value: Reverse for 'my_date' with keyword arguments '{'selected_day': datetime.date(2017, 12, 31),}'not found. 1 pattern(s) tried: ['my-url/my-date/(?P<selected_day>\\w+)/$'] -
Filtering django queryset by text applying the diacritics
I am trying to filter a queryset in python by a text the model is: models.Offer id = pk description = text I am trying to filter it like: someText = self.shave_marks(someText) offers = offers.filter(description__icontains=someText) Where the shave_marks is replacing the special characters like: ç will become c. The text in the database (in the description field) also has special characters, what I need is to "shave" the description text first then do the filtering. Any help, thank you very much!!! -
Django filtering with F and Q operations
I have a model class in my django project: *user_id *amount *net_balance I have a list of user_ids. I need to get the last row for each user_id and then do some operation and create a new row for each user id. How do this efficiently. I can certainly do 6 transactions. -
Django INSTALLED_APPS 'polls' vs 'polls.apps.PollsConfig'
In every youtube tutorial I'v seen people simply add to INSTALLED_APPS list. Yesterday I started Official Django Tutorial and they suggest .apps.Conf notations. Im guessing official way is a better way and it's not hard to memorize additional syntax, I just wanna be sure. Because stuff works ether way. Please give me a simple, easy to understand answer so even I could get it. Thanks! -
django's setting.py can't read utf-8 characters
I have tried to give a value to my MEDIA_ROOT that constain a word with an accent mark, but django doent accept it. I have tried to unicode(utf-8) and encoding it with no positive results The error that I get is: SyntaxError: Non-ASCII character '\xc3' in file What can I do in order to make settings accept acent marks(ó,á,é,í,ú) -
Django: Setting model's properties dynamically
Is it possible to define the property of a model dynamically since 'self' is not defined? I have two models, Slider and SliderImage. I would like to define the property in SliderImage according to the value of a property defined in the related model Slider. class Slider(models.Model): width = models.SmallIntegerField(blank=True,null=False) height = models.SmallIntegerField(blank=True,null=False) class SliderImagen(models.Model): imagen = ProcessedImageField(processors[ResizeToFill( **self.slider.width**,**self.slider.height**)]) slider = models.ForeignKey('Slider',on_delete=models.CASCADE,db_column='slider', related_name='imagenes') -
rss django renderer option python rest api
This isn't a question, more of a quick guide for someone looking to render the Django Rest in RSS format that is readable by browsers like internet explorer. I think I saw online some source code for an RSS library that Django offers, but that wasn't really for what I needed for my project. I copied the standard rest_framework_xml library and made my own edits to have an 'RSS' renderer option. Goal: Be able to get an RSS option for the &format=xxx parameter of the GET request. Approach: For the browser to understand the RSS feed apart from standard XML (meaning that you should be able to "subscribe" to the content), you must include the following core element attributes within the XML document: <rss version= "2.0"> <channel> ---content here--- </channel> </rss> where within ---content here--- you have the <item><title><description><link> attributes, etc. Once you get these attributes added into the XML, you can then use the API link to render the page in readable RSS format. My project pulls data from a database and then a user can go to the link http://URL.com/api/ and add optional filtering parameters. So, for example, let us assume the user just wanted to get content … -
Django ajax MultiValueDictKeyError when using POST
I have this data in my script // an array var foo = [ { 'name': 'Foo', 'age': 12 }, { 'name': 'Bar', 'age': 34 } ]; // in ajax data: { 'foobar': foo } The error occurs when I try to do request.POST['foobar'] When I tried to print request.POST, I saw that I can access the data by using request.POST['foobar[0][name]'] Is there a way I can do request.POST['foobar'] since I want to loop it?