Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django model TextField not rendering
I've been trying to render the contents of a TextField onto my HTML page, but it's the only thing that just refuses to render. Here is my model: class Section(models.Model): order_id = models.IntegerField() SECTION_TYPE_CHOICES = (('reg', 'regular'), ('not', 'note'), ) section_type = models.CharField( max_length=5, choices=SECTION_TYPE_CHOICES, default='reg', ) class TextSection(Section): contents = models.TextField(blank=True, max_length=5000) class Post(models.Model): post_id = models.IntegerField(unique=True) author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) slug = models.CharField(unique=True, max_length=20) created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) belongs_to = models.ForeignKey('Story') order_id = models.IntegerField() contents = models.ManyToManyField(Section, blank=True) and the template {% extends 'stories/base.html' %} {% block title %} {{ post.belongs_to.title }} | {{ post.title }} {% endblock %} {% block content %} <!-- Story Information --> <div> <h1>{{ post.title }}</h1> <p>by {{ post.author }} on {{ post.published_date }}</p> </div> <!-- Post Contents --> <div> {% for section in post.contents.all %} <div> <p>{{ section.contents|safe }}</p> {{ section.order_id }} </div> {% endfor %} </div> {% endblock %} It always renders the section.order_id but never renders the section.contents Thanks in advance for any advice. -
Install Django + Postgresql with Gunicorn in Ubuntu Server
I need to mount a Django Server in a computer with Ubuntu Server. This computer gonna be in local network with other computers with Windows. I know that the best way is using Gunicorn and Nginx but I'm not sure about how to do this. Sorry if i am not very specific. Thanks! -
Passing data through views context to javascript in Django
I'm trying to pass some data from the views.py to a template and using it in a javascript and I can't make it work. Does anyone know how can I solve this? In the views.py listaUsuarios = User.objects.values_list('username', flat=True) context = {'listaUsuarios':listaUsuarios} return render(request, redirect, context) This actually works and if I do a print(listaUsuarios[2]) it shows just the username number 2 in the database. The javascript in the template function checkForm(form) { for (i = 0; i < listaUsuarioss.length; i++) { if(form.username.value==listaUsuarioss[i]){ alert("Error: El nombre de usuario ya está en uso"); form.username.focus(); return false; } } } The invocation to the script <form method="post" action="{% url 'register' %}" onsubmit="return checkForm(this,{{listaUsuarios}});"> I know I should have used Django forms for the registration but I didn't and I'm trying to make this work for checking before the registration of a new user if that username is already in use. Thank you to everyone! -
Changing '?' to '&' in adress bar
For example, in my web-app I have a link with url www.example.com/profile?name=name. When I click to that link, I'm getting a page, where I can change profile's information, BUT after clicking to that link, url in adress bar turns into www.example.com/profile&name=name. More interesting: when I make some changes and click SAVE - url reverts to www.example.com/profile?name=name. If i don't click SAVE, just refresh page, i'm getting error 404. How can it be possible? P.S My view function @check_document_access_permission() def notebook(request, is_embeddable=False): if not SHOW_NOTEBOOKS.get(): return serve_403_error(request) notebook_id = request.GET.get('notebook', request.GET.get('editor')) is_yarn_mode = False try: from spark.conf import LIVY_SERVER_SESSION_KIND is_yarn_mode = LIVY_SERVER_SESSION_KIND.get() except: LOG.exception('Spark is not enabled') return render('notebook.mako', request, { 'editor_id': notebook_id or None, 'notebooks_json': '{}', 'is_embeddable': request.GET.get('is_embeddable', False), 'options_json': json.dumps({ 'languages': get_ordered_interpreters(request.user), 'session_properties': SparkApi.get_properties(), 'is_optimizer_enabled': has_optimizer(), 'is_navigator_enabled': has_navigator(request.user), 'editor_type': 'notebook' }), 'is_yarn_mode': is_yarn_mode, }) -
Django RangeField - lookups doesn't work as expected
Can't figure out how to do lookups on DateRangeField properly. I will show my cases on numbers: Let's say my object (trip) has range <5,10> I need to be able to filter other trips which: Overlaps this object on the beginning - (-inf,4> to <5,10> (eg. <3,5>,<4,8> etc.) Overlaps this object from the end - <5,10> to <11,inf> Daterange is contained by given objects daterange - <5,10> to <5,10> Daterange contains given objects daterange - (-inf,4> to <11,inf) For now, I'm using two dates in my model. date_from and date_to so lookups are like this: Trip.objects.filter(user=trip.user, date_from__lt=trip.date_from, date_to__gte=trip.date_from,date_to__lte=trip.date_to) Trip.objects.filter(user=trip.user, date_from__gte=trip.date_from, date_from__lte=trip.date_to, date_to__gt=trip.date_to) Trip.objects.filter(user=trip.user, date_from__gte=trip.date_from, date_to__lte=trip.date_to) Trip.objects.filter(user=trip.user, date_from__lt=trip.date_from, date_to__gt=trip.date_to) To simplify lookups and forms I'm trying to change date_from and date_to to daterange. But lookups doesn't work as I expected: class OverlappingTripsTestCase(TestCase): def setUp(self): self.city = City.objects.create(place_id='xxx',name_en='xxx') self.user = User.objects.create(username='testuser') self.base_trip = Trip.objects.create(user=self.user, city=self.city,daterange=(date(2010, 1, 2), date(2010, 10, 1))) self.trip_contains = Trip.objects.create(user=self.user, city=self.city,daterange=(date(2010, 1, 1), date(2010, 12, 1))) self.trip_contained_by = Trip.objects.create(user=self.user, city=self.city,daterange=(date(2010, 2, 1), date(2010, 9, 1))) self.trip_overlap_start = Trip.objects.create(user=self.user, city=self.city,daterange=(date(2009, 1, 1), date(2010, 2, 1))) self.trip_overlap_end = Trip.objects.create(user=self.user, city=self.city,daterange=(date(2010, 1, 1), date(2010, 10, 1))) def test_overlaps(self): self.assertEqual(Trip.objects.filter(daterange__contains=self.base_trip.daterange).first().pk,self.base_trip.pk) self.assertEqual(Trip.objects.filter( daterange__contained_by=self.base_trip.daterange).first().pk,self.trip_contained_by.pk) Even the first assertion doesn't work because it returns 0 results. … -
Which IDEs are most suited for Django to build a web application?
I am a beginner. I choose Python as my first programming language because I love computer science. I learn to code by myself. I am using Eclipse to build my first Django website. I really want to know the best IDEs to work with Django. P/s: Excuse me about my writing English. Here is the first time I ask a question on Stack Overflow. I really appreciate any help you can provide. -
Django - Reducing duplicate context code in the view
Say I have a view function like so: def check_view(request): if user.is_authenticated: ... return render(request, 'user-template.html', {'variablea':a, 'variableb':b, 'variablec':c} else: ... return render(request, 'user-template.html', {'variablea':a, 'variableb':b, 'variabled':d} Is there any way to only write the context variables just one time (given that there some similar variables for both conditions), but the variables that are different can be written under their own parent conditions? So variable C will belong to the if statement and D to the else, whereas both variables A and B can be written once but apply to both the if and else statement.... Note how the last variable for each condition is different (c and d) Thanks -
How can I get the OneToOne relationship easily?
I have two model, names User and Account, the Account to User is one to one relationship: class User(AbstractUser): real_name = models.CharField(max_length=12, null=True,blank=True) phone = models.CharField( max_length=11) email_is_validated = models.BooleanField(default=False) qq = models.CharField(max_length=10, null=True, blank=True) class Account(models.Model): user = models.OneToOneField(to=User) balance = models.DecimalField(max_digits=16, decimal_places=2, default=0.00) total_charge = models.DecimalField(max_digits=16, decimal_places=2, default=0.00) total_consume = models.DecimalField(max_digits=16, decimal_places=2, default=0.00) So, in this case, in my serializer: class OrderCreateSerializer(ModelSerializer): def create(self, validated_data): request = self.context.get("request") if request and hasattr(request, "user"): user = request.user I get the user, can I use user.account to get the account? and or whether I need to do something in User model, such as user @property. (those are my whimsical idea) Or is there a convenient way to get the user's account instance? -
Django Users not showing the date_of_birth in the admin site
I am registering users by sending token activation email using built-in register and activate functions. The register form subclass the UserCreationForm to add extra fields for email and date_of_birth validations. My code is the following: forms.py: class UserRegisterForm(UserCreationForm): date_of_birth = forms.DateField(widget=forms.SelectDateWidget(years=range(2017, 1900, -1))) email = forms.EmailField(required=True) def clean_username(self): username = self.cleaned_data.get('username') if User.objects.filter(username__iexact=username).exists(): raise forms.ValidationError('Username already exists') return username def clean_date_of_birth(self): ''' Only accept users aged 13 and above ''' userAge = 13 dob = self.cleaned_data.get('date_of_birth') today = date.today() if (dob.year + userAge, dob.month, dob.day) > (today.year, today.month, today.day): raise forms.ValidationError('Users must be aged {} years old or above.'.format(userAge)) return dob def clean_email(self): email = self.cleaned_data.get('email') if User.objects.filter(email__iexact=email).exists(): raise forms.ValidationError('A user has already registered using this email') return email def clean_password2(self): ''' we must ensure that both passwords are identical ''' password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 and password2 and password1 != password2: raise forms.ValidationError('Passwords must match') return password2 class Meta: model = User fields = ['username', 'email', 'date_of_birth', 'password1', 'password2'] views.py: def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): email = form.cleaned_data.get('email') date_of_birth = form.cleaned_data.get('date_of_birth') new_user = form.save(commit=False) new_user.is_active = False new_user.save() current_site = get_current_site(request) message = render_to_string('email_activation_link.html', { 'new_user':new_user, 'domain':current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(new_user.pk)), 'token': … -
django can't visit "models class object" object
My English is poor,maybe my descriptions were have many grammar wrong. My Pycharm told me a error.Pycharm can not let me visit models class object object. But,The code can run.I very confuse.Thanks everybody This is view.py This is models.py The code can run,and I use Python3.6 and Django 1.11.7.Pycharm version is 2017.4 pro -
How to show two onetoone related tables in django admin?
My two models are: class User(AbstractUser): ##all user related infos class Payment(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, related_name='payment') Now my admin.py is like class PaymentAdmin(admin.ModelAdmin): list_display = ('id', 'chargebee_customerid') search_fields = ('id',) ordering = ('id',) def get_search_results(self, request, queryset, search_term): if search_term: queryset = self.model.objects.filter( Q(id__contains=search_term) ) return queryset, False return queryset, False I want to show both tables side by side like first the payment table then after that user table. How can I do that. -
Sending email with render template but doesn't work
I use this function to send email, but it works only when i use the message with text. With template html, the function cause a problem ( the emails aren't sent but without display of any error). I try to resolve this problem but i couldn't find the error The template: <!DOCTYPE html> <html> <head> <title>Backtest ready</title> </head> <body> <p> Dear {{ user.username }}, <br> <br> Your backtest {{ backtest.title }} is now ready! <br> <br> In order to see the details of your strategy, visit the following link : <br> <br> http://104.131.14.247{{ result_url }} <br> <br> If you would like to check all the backtests you performed so far, go to <a href="{% url 'backtest_result_list' %}"> my backtests</a>. def send_email_with_backtest_result(request, backtest): user= request.user subject = 'Your backtest results' result_url = reverse('backtest_result_detail', kwargs={'backtest_id': backtest.id}) if backtest.user.is_active: template = get_template('interface/emailbacktest.html') context = Context{'user': user, 'backtest': backtest, 'result_url': result_url} msg = template.render(context) # msg = 'http://104.131.14.247{}'.format(result_url) else: # this will act as a result page and user activation token = backtest.user.create_activation_token() msg = 'http://104.131.14.247{}?token={}'.format(result_url, token) send_mail(subject, msg, settings.DEFAULT_FROM_EMAIL, [backtest.user.email]) def store_backtest_result(path, backtest_id): backtest = BackTest.objects.get(uid=backtest_id) file_path = extract_result(path, backtest_id, settings.BACKTEST_RESULTS_FOLDER) backtest_result = BackTestResult(backtest=backtest, path=file_path) backtest_result.save() backtest.results_status = 'cl' backtest.save() send_email_with_backtest_result(request, backtest) backtest.user.notify_backtest_result(backtest) … -
Django rest framework - Model serialization raise not JSON serializable
Hello I'm facing a problem with serializing a list of models. So I have a FileInfo model and I also have a UserFileInfo model which contains a ForeignKey to FileInfo. When I try to serialize a QuerySet of UserFileInfo I can do it and it also serialize the nested FileInfo. But when I try to serialize a FileInfo QuerySet it failes with the following error: File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 184, in default raise TypeError(repr(o) + " is not JSON serializable") TypeError: FileListSerializer(, ]>): file_name = CharField(max_length=100) file_path = CharField(allow_blank=True, allow_null=True, max_length=150, required=False) file_token = CharField(allow_blank=True, max_length=100, required=False, validators=[]) created = DateTimeField(read_only=True) is_available = BooleanField(required=False) is not JSON serializable I tried to remove fields to eliminate a problem with one of the fields but with only fields = ('id') it also fails. Tried to serialize a single FileInfo, fails. Tried creating a ListSerializer, fails. Would appreciate any help, below are code samples: The model: class FileInfo(models.Model): file_name = models.CharField(max_length=100, blank=False) file_token = models.CharField(max_length=100, blank=True, unique=True, default=uuid.uuid4) file_path = models.CharField(max_length=150, blank=True, null=True, default="") created = models.DateTimeField(auto_now=False, auto_now_add=True) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) is_available = models.BooleanField(default=True) groups = models.ManyToManyField(Group, related_name='groups', null=True, blank=True) def __unicode__(self): return self.file_name The file serializer: class FileSerializer(serializers.ModelSerializer): created_by = UserSimpleSerializer() class … -
form not saving form.is_valid() returning false
below is all my models basically this is an auction website class Item(models.Model): name = models.CharField(max_length = 30) description = models.TextField() image = models.ImageField(upload_to='media/') category = models.CharField(max_length=100) ask = models.DecimalField(default=0, max_digits=6, decimal_places=2) created_at = models.DateTimeField(default=datetime.now, blank=True) closes = models.DateTimeField() class Bid(models.Model): item = models.ForeignKey(Item) user = models.ForeignKey(User) price = models.DecimalField(default=0, max_digits=6, decimal_places=2) created_at = models.DateTimeField(default=datetime.now, blank=True) this is the form class itemform(ModelForm): class Meta: model = Item fields =['name','description','image','category','ask','closes'] view for saving the form def createitem(request): if request.method == "POST": form= itemform(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('/items') else: form = itemform() return render(request, 'app/create.html', {'form':form}) create.html {% extends 'app/layout.html' %} {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p}} <button type ="submit">Save</button> </form> {% endblock %} it would also be helpful if someone could help me making a view of details of the of the items as i have to show this by end of the weekend -
using django on heroku, connect to AWS S3
Hi I'm trying to use S3 on heroku(making Django App) as a storage to save PDF files to view on the page. I saw instructions on heroku to connect S3 to heroku and finished setting with $ heroku config:set AWS_ACCESS_KEY_ID =xxx AWS_SECRET_ACCESS_KEY =yyy Adding config vars and restarting app... done, v21 AWS_ACCESS_KEY_ID => xxx AWS_SECRET_ACCESS_KEY => yyy $ heroku config:set S3_BUCKET = zzz Adding config vars and restarting app... done, v21 S3_BUCKET => zzz Do i need to write AWS ACCESS ID and SECRET KEY to settings.py? -
django - Is it possible to access multiple databases without declaring in settings.py file?
Every time a Company is created I want to create an individual database to store corresponding values. models.py(company App) class Company(models.Model): name = models.CharField(max_length=30) user = models.ForeignKey(User) views.py (company App) class AddCompany(LoginRequiredMixin, CreateView): mode = Company form_class = AddCompanyForm template_name = "add_company.html" settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } models.py(Inventory App) class Inventory(models.Model): item = models.CharField(max_length=30) quantity = models.IntegerField(null=False) company = models.ForeignKey('company.Company') views.py(Inventory App) class AddToInventory(LoginRequiredMixin, CreateView): model =Inventory form_class = AddToInventoryForm template_name = "add_inventory.html" Is it possible to access a database without declaring the database in settings.py file and without using any routes. I want the items belonging to each company to be stored in a separate database if the database of company does not exist then a new database has to be created and I have to be able to read and write data from the databases without using any routes. Is it possible to do something like with django by using some SQLAlchemy? Is this even possible with django? -
Django query table to find Item that only exist in Parent field
I been struggling with doing a query to get the rows where a Item only exsist in Parnet field and not Child field. This is the models. class Item(models.Model): text = models.CharField() class ItemRelations(models.Model): child = models.ForeignKey('Item', related_name='itemchild') parent = models.ForeignKey('Item', related_name='itemparent') So I only want to filter out the Items that are not a child, but is a Parent. I call it the firstParent. I tried so many different ways. I want to accomplish something like this. firstParent = Item.objects.filter(ItemRelations_parent__is=self).exclude(ItemRelations_child__is=self) Is it possible. Or does one have to make several queries and loops to manage this? -
Optimizng pattern of loading Django template filters in a for loop
In a Django template of mine, I use a for loop to display content. The content itself is of 3 types, each requiring its own set of conditions, HTML and CSS. I felt including all that processing in 1 template would make it tough to maintain the file, so instead I'm using template tags: {% load get_display_type_1 %} {% load get_display_type_2 %} {% load get_display_type_3 %} {% for item in content %} {% if item == '1' %} {% display_type_1 payload='foo' %} {% elif item == '2' %} {% display_type_2 payload='bar' %} {% elif item == '3' %} {% display_type_3 payload='foo bar' %} {% endif %} {% endfor %} And where, for example, the template tag called display_type_1 has the following code: from django import template register = template.Library() @register.inclusion_tag(file_name='display_type_1.html') def display_type_1(payload): return {'payload':payload} Standard stuff so far. But now take a look at the HTML template connected to the template tag: {% load myfilter %} <div class="type1">{{ payload|myfilter }}</div> I.e. notice I'm loading a custom filter called myfilter here. So here's the problem: in essence, I've called {% load myfilter %} within a for loop. How? Because the template tag itself resides in the parent template's for loop. This … -
ERROR: ' No module named 'django.core.urlresolvers'
I am trying to create web services using the Django Rest framework.While running the server, when I try to access the admin page, I get the following error: Invalid template library specified. ImportError raised when trying to load 'rest_framework.templatetags.rest_framework': No module named 'django.core.urlresolvers' Note: I have added the rest_framework on the settings. -
KeyError in ORM code when annotating using a Case and aggregating the annotation in a group by
We encountered this issue in a pretty complex project, but I've managed to reproduce it in a dummy project: This is django 1.11.7 on python3.6 and postgres10: models.py: from django.db import models class Thing(models.Model): multiplierA = models.IntegerField() multiplierB = models.IntegerField() class Data(models.Model): thing = models.ForeignKey('Thing') multiplier_choice = models.CharField(max_length=1, choices=(('A', 'use multiplier A'), ('B', 'use multiplier B'))) option = models.IntegerField(choices=((1, 'option 1'), (2, 'option 2'))) percentage = models.FloatField() tests.py: from django.db.models import Case, F, FloatField, IntegerField, Sum, When from django.test import TestCase from .models import Data, Thing class AnnotateTests(TestCase): def test_simple(self): thing = Thing.objects.create(multiplierA=2, multiplierB=3) Data.objects.create(thing=thing, multiplier_choice='A', option=1, percentage=0.2) Data.objects.create(thing=thing, multiplier_choice='A', option=2, percentage=0.3) Data.objects.create(thing=thing, multiplier_choice='A', option=3, percentage=0.1) Data.objects.create(thing=thing, multiplier_choice='B', option=1, percentage=0.1) Data.objects.create(thing=thing, multiplier_choice='B', option=2, percentage=0.4) Data.objects.create(thing=thing, multiplier_choice='B', option=3, percentage=0.5) whens = [ When(multiplier_choice='A', then=F('thing__multiplierA')), When(multiplier_choice='B', then=F('thing__multiplierB')) ] multiplier_case = Case(*whens, output_field=IntegerField(), default=0) qs = (Data.objects # select only certain options to sum up for each thing: .filter(thing=thing, option__in=[1, 2]) # select the correct multiplier .annotate(multiplier=multiplier_case) # group by thing => sum of percentage * multiplier .values('thing') .annotate(amount_sum=Sum(F('percentage') * F('multiplier'))) .values('amount_sum')) print(qs.values('thing__id', 'amount_sum')) Running this test will result in the following traceback: ====================================================================== ERROR: test_simple (annotate.tests.AnnotateTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/robin/src/ormweirdness/annotate/tests.py", line 34, in test_simple .annotate(amount_sum=Sum(F('percentage') * F('multiplier'))) File … -
How can I get the user data in serializer `create()` method?
How can I get the user data in serializer create() method? I tried to get the user data use self.request, but failed: class OrderCreateSerializer(ModelSerializer): class Meta: model = Order fields = ( "product_describe", "billing_type", "buytime", "count", "paytype", ) def create(self, validated_data): print(self.request.user.username) validated_data["order_num"] = generateOrderNum() return Order.objects.save() 'OrderCreateSerializer' object has no attribute 'request' -
Showing Many-To-Many in different model's form in Django?
Say I have three models, a Professor model, a Course model, and a Review model. The user is allowed to make a Review, which reviews a Professor that teaches a certain Course. I'm thinking of how to model the many to many relationship of Professor and Course, and how to reference that relationship in Review. My idea so far is to use models.ManyToMany to link Professor and Course. Models.py (Prof) class Prof(models.Model): first_name = models.CharField(max_length = 20, unique = False) last_name = models.CharField(max_length = 20, unique = False) def __str__ (self): return self.first_name + " " + self.last_name class Course(models.Model): name = models.CharField(max_length = 20, unique = True) prof = models.ManyToManyField(Prof) def __str__ (self): return self.name Models.py (Review) class Review(models.Model): message = models.TextField(max_length = 4000) created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(null = True) rating = models.IntegerField( default = 5, validators = [MaxValueValidator(5), MinValueValidator(0)] ) prof = models.ForeignKey(Prof, related_name = 'reviews') course = models.ForeignKey(Course, related_name = 'reviews') user = models.ForeignKey(User, related_name = 'reviews') def __str__ (self): return self.message forms.py class ReviewForm(ModelForm): rating = CharField(widget=TextInput(attrs={'type': 'number','value': 5, 'min': 0, 'max': 5})) class Meta: model = Review fields = ['message', 'rating', 'prof', 'course', 'user'] This is my code so far for … -
Perform lookup and update within a single Django query
I have two models: MetaModel and RelatedModel. I want to include the result of a RelatedModel lookup within a MetaModel query, and I'd like to do this within a single DB call. I've tried to define a 'subquery' QuerySet for use in the main query, but that hasn't worked - it's still making two queries to complete the operation. Note: I can't use a traditional ForeignKey relationship because the profile_id field is not unique. Uniqueness is a combination of profile_id and channel. This is an aggregation table and profile_id is not guaranteed to be unique across multiple third-party channels. Any suggestions? Models: class Channel(models.Model): id = models.AutoField(primary_key=True) name = models.CharField( max_length=25, ) class MetaModel(models.Model): profile_id = fields.IntegerField() channel = fields.ForeignKey(Channel)) metadata = fields.TextField() class RelatedModel(models.Model): related_id = fields.IntegerField() profile_id = fields.IntegerField() channel = fields.ForeignKey(Channel)) Dummy data channel = Channel("Web site A") channel.save() sample_meta = MetaModel(profile_id=1234, channel=channel) sample_related = RelatedModel(profile_id=1234, related_id=5678, channel=channel) Query: # Create a queryset to filter down to the single record we need the `profile_id` for # I've limited to the only field we need via a `values` operation related_qs = RelatedAccount.objects.filter( related_id=5678, channel=channel ).values_list("profile_id", flat=True) # I'm doing an update_or_create as there is other data to store, … -
How to add model through UI?
I need to create an app that generates an admin panel. One of the concepts is for it to have an option to add models (which will be migrated to the database) and have a list of all models. The question is: is it even possible to add Models through UI? After a few days search, I'm starting to think that the only way is by going into the code. I can create forms for adding objects, but not models. Any ideas? -
Difference between two lists of django models objects
I have two data sources. One is a psql table (managed using Django models) and another is a CSV. I have to keep the table in sync with the csv. So, my current procedure is: Reading all the rows from the table and creating a set of tuples, calling it old_data Reading all the rows from the csv and creating another set of tuples, calling it new data. So, old_data - new_data gives me all the objects that have been deleted and updated. Similarly, new_data - old_data gives me all the objects that have been inserted and also updated. So, objects with primary key in both the differences are the ones which will be used for updated. Rest are deleted and inserted accordingly. Now, this is not a Django way of doing it. (I'm comparing the two sets of tuples, not the model objects itself) Can this be done by comparing the models somehow.