Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework use source to access different model with reverse relation?
I have the following problem, I have the default User model and Profile model. I want to merge them into one serializer but without nesting - It's just ugly. Instead, I want to have all their fields on the first level. So I created the following (for simplicity profile contains just one Bool field and one relation field): class UserSerializer(serializers.ModelSerializer): achievements = serializers.PrimaryKeyRelated(many=True, queryset=Achievements.objects.all()) trusted = serializers.BooleanField() def create(self, validated_data): user=User.objects.create_user( password = validated_data['password'], username = validated_data['username'], email = validated_data['email'], ) Profile.objects.update_or_create(user, defaults={ 'trusted': validated_data['trusted'], 'achievements': validatd_data['achievements'], } ) return user class Meta: model = User fields = ("id", "username", "email", "password", "trusted", "achievements"), read_only = ("id",) extra_kwargs = { 'password': { 'write_only': True, }, } Profile is connected to a user via a user field containing models.OneToOneField instance. When I try to list all profiles I get Error that I need to specify source but I have no idea how and documentation mentions only something that dot notation should be used. Thanks. -
Typical "relation "auth_user" does not exist" with PSQL and Django 2
I know that it is a recurrent ask, which it's solutioned with migrations, but not my case (I think). I have a Django project (I've tried with Django 2.0, 2.1 and 2.1.1) that had a db.sqlite3 and worked fine. Now, I've tried to switch the database with PostgreSQL 10 with those configurations: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', #I've already tested with PostgreSQL_psycopg2 'NAME': 'mydbs', 'USER': 'niknitro', 'PASSWORD': 'password', 'HOST': '127.0.0.1', 'PORT': '5432', } } In pg_hba.conf, I added this line: host all all 0.0.0.0/32 trust And when I try to do a "python manage.py migrate", "python manage.py makemigrations" or "python manage.py runserver", the error it's the same: Starting myproject execution... /root/PycharmProjects/myproject/venv/lib/python3.6/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>. """) Starting myproject execution... /root/PycharmProjects/myproject/venv/lib/python3.6/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>. """) Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f4ce0070e18> Traceback (most recent call last): File "/root/PycharmProjects/myproject/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: … -
Django - global dictionary
I'm trying to make a teacher/student model where every student has one (or zero) teacher and teachers have multiple students. The teacher should be able to see a list of students and the students don't need to see anything other than their own teacher. The differences between the teacher and student are few for my uses. So, I made just one custom model User and when registering you can choose whether you are a student or administrator. If you are an administrator, you must enter a "class code" for which students can sign up under your name. class User(AbstractBaseUser, PermissionsMixin): "username, password, email, etc.. goes here" usertype = models.CharField(max_length=140, null=True) classcode = models.CharField(max_length=140, null = True, unique=True) teacher = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null = True ) objects = UserManager() USERNAME_FIELD = "username" REQUIRED_FIELDS = ['email', 'first_name', 'last_name'] def __str__(self): return self.username For teachers the teacher field would be null and for students, obviously, there would be a link to the teacher. I'm trying to manage the signup right now. def create_user(self, email, username, password, first_name, last_name): user = self.model( email = self.normalize_email(email), username = username, first_name = first_name, last_name = last_name) if user.usertype == "admin": # user is a teacher … -
SerializerMethodField for more than one fields
This question might have an easier answer. But I don't get what it is. Please consider this example class ModelA(models.Model): a1 = models.CharField(max_length=100, default="") a2 = models.CharField(max_length=100, default="") class ModelB(models.Model): b1 = models.ForeignKey(ModelA, on_delete=models.CASCADE) b2 = models.CharField(max_length=100, default="") With below ModelBSerializer I can get the values of the a1 or a2 of ModelA using the SerializerMethodField for b1 field. class ModelBSerializer(serializers.ModelSerializer): b1 = SerializerMethodField() class Meta: model = ModelB fields = ( 'b1', 'b2', ) def get_b1(self, obj): return obj.a1 # or obj.a2 But What if I want both a1 and a2? And I want them to be included in the ModelBserializer fields along with b1 and b2. -
Dropdown menu not appearing in the form rendered by django in a template
Here is the code for post model. class Post(models.Model): category_choices = ( ('technology', 'Technology'), ('personal', 'Personal'), ('poetry', 'Poetry'), ('rants', 'Rants'), ('random', 'Random'), ) author = models.ForeignKey('auth.User', on_delete=models.CASCADE) title = models.CharField(max_length=70) body = models.TextField() summary = models.CharField(max_length=100) created_date = models.DateTimeField(default=timezone.now()) published_date = models.DateTimeField(blank=True, null=True) slug = models.SlugField(max_length=40, unique=True) category = models.CharField(max_length=10, choices=category_choices, default='technology') Here is the code for form. class PostForm(forms.ModelForm): class Meta: model = Post fields = ('title', 'category', 'body') This is how I am rendering form in html page. <h1>New post</h1> <div class="row"> <form method="POST" action="{% url 'post_new' %}" class="col s12 m12 l12"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn">Save</button> </form> </div> This is how it looks in browser. -
Use Ajax in Django
I am beginner in Django .I am simply create a blog post web app. My problem is, I want to comment on post with Ajax But when I write ajax function in viewpost.html then it's not working. Means When I click on comment button then It's not goes to 'POST' method. If I do without Ajax then It's working. urls.py from django.conf.urls import url from .views import HomeView,viewpost from . import views urlpatterns = [ url(r'^$', views.HomeView, name='Myprofile'), url(r'^posts/(?P<id>[0-9]+)$', views.viewpost, name='viewpost'), ] view.py file def viewpost(request,id): posts = get_object_or_404(Post,pk=id) comments = Comments.objects.all().filter(post_id=id) print("caalingme") if request.method == 'GET': print("OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO") template_name = 'home/viewpost.html' postcommenting = PostsData() args = {'postcommenting': postcommenting,'posts':posts, 'comments':comments,'id':id} return render(request, 'home/viewpost.html', args) else: print("*********************************") template_name = 'home/viewpost.html' postcommenting = PostsData(request.POST) if postcommenting.is_valid(): print("********* comment **********") postcomment = postcommenting.save(commit=False) text = postcommenting.cleaned_data['comment'] postcomment.user = request.user posts = get_object_or_404(Post,pk=id) postcomment.post = posts postcomment.save() postcommenting = PostsData() return render(request, 'home/comment.html',{'text':text}) else: posts = get_object_or_404(Post,pk=id) findlike = Like.objects.all().filter(post_id=posts.id,user=request.user) if(len(findlike)==0): posts.likee+=1 tolike = Like() tolike.count_l = posts.likee tolike.user = request.user tolike.post = posts posts.save() tolike.save() print(posts.likee) args = {'postcommenting': postcommenting,'posts':posts, 'comments':comments,'id':id} return render(request, 'home/viewpost.html', args) My viewpost.html file {% extends 'base.html' %} {% block ajaxcall %} <script type="text/javascript"> $(document).ready(function(){ $("#post_form").submit(function(e){ e.preventDefault(); alert($(this).serialize()) $.ajax({ url: … -
Django and Pipelinedb: Programming Error: column <database_name>.location_id does not exist
I'm working on a project using Django and postgresdb with streaming data coming in using pipelinedb. A sync script is running this. Everything is Dockerized. The data is updated every 60 seconds on the test server. I added this field to the model: location = models.ForeignKey('Location', related_name='assigned_sensor', on_delete=models.CASCADE, null=True) And for reference, here are both the Weather and Location models: class WeatherStatsMrel(models.Model): id = models.BigIntegerField(db_column='$pk', primary_key=True) loc = models.CharField(max_length=3, null=True) dat = models.DateField(blank=True, null=True, editable=True) tim = models.TimeField(blank=True, null=True, editable=False) aws = models.FloatField(blank=True, null=True, editable=False) awd = models.TextField(blank=True, null=True, editable=False) mws = models.FloatField(blank=True, null=True,editable=False) mwd = models.TextField(blank=True, null=True,editable=False) tmp = models.FloatField(blank=True, null=True,editable=False) hum = models.FloatField(blank=True, null=True,editable=False) r10 = models.FloatField(blank=True, null=True,editable=False) r60 = models.FloatField(blank=True, null=True,editable=False) rda = models.FloatField(blank=True, null=True,editable=False) rcu = models.TextField(blank=True, null=True,editable=False) rad = models.TextField(blank=True, null=True,editable=False) sun = models.TextField(blank=True, null=True,editable=False) location = models.ForeignKey('Location', related_name='assigned_sensor', on_delete=models.CASCADE, null=True) class Meta: db_table = 'weather_stats_mrel' def __unicode__(self): return str({self.loc}, {self.dat}, {self.tim}, {self.aws}, {self.awd}, {self.mws}, {self.mwd}, {self.tmp}, {self.hum}, {self.r10}, {self.r60}, {self.rda}, {self.rcu}, {self.rad}, {self.sun}) class Location(models.Model): id = models.AutoField(primary_key=True) abbreviated_name = models.CharField(max_length=3) full_name = models.CharField(max_length=25) def __str__(self): return self.abbreviated_name When I start up the server, everything is fine. Through the admin page (Django's default admin page) I can navigate to the weather_stats_mrel page in an … -
'services' object is not iterable Django
I'm having a problem and here's my code please help. I did this because what I want is when an existing user login the details of the task done by the user automatically appears on the page because the database has multiple rows of every user I would like to display of particular user This my view def service(request,emp_id): u = User.objects.get(sys_id = emp_id) s = services.objects.get(email = emp_id) if request.method == 'POST': user_form = ServiceForm(data=request.POST) if user_form.is_valid(): user_form.save() else: print(user_form.errors) else: user_form = ServiceForm() return render(request, 'service.html', { 'user_form':user_form,'u':u,'s':s}) This is my model class User(AbstractBaseUser): sys_id = models.AutoField(primary_key=True, blank=True) email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) first_name = models.CharField(max_length=50,blank=True,null=True) last_name = models.CharField(max_length=50,blank=True,null=True) address = models.TextField(max_length=300,blank=True,null=True) DOB = models.DateField('Date of Birth', blank=True, null=True) DOJ = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) class services(models.Model): taskid = models.AutoField(primary_key=True, blank=True) client = models.CharField(max_length=50,blank=True,null=True) project = models.CharField(max_length=50,blank=True,null=True) taskTime = models.DateField('Task Date', blank=True, null=True) hours = models.TimeField(blank=True, null=True) minutes = models.TimeField(blank=True, null=True) Description = models.TextField(max_length=300,blank=True,null=True) email = models.ForeignKey(User, unique=False, on_delete=models.CASCADE) This is my html {% for service in s %} <tr> <td>{{ service.client }}</td> <td>{{ service.project }}</td> <td>{{ service.taskTime }}</td> <td>{{ service.address }}</td> <td>{{ service.hours }}</td> <td>{{ service.minutes }}</td> <td>{{ … -
Images aren't displayed in Djanog, but link works in searchbar
I have a little problem with Django and the way to display images with it. I have a folder, called media and a subfolder called media in media.. yea .. don't judge me. I've uploaded a image to a post module and tried to load image with <img height="400px" width="400" scr="{{ post.pageImage.url }}" alt="Image"> output: <img height="400px" width="400" scr="/media/media/1_g4XcQbA156OfOKVlMox2Tw.png" alt="Image"> The output is okay, if I enter the link in the searchbar, it can open the image and load it, but the image isn't displayed on the page. I've tried a lot of things, : - MEDIA_URL and ROOT MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media/') path('blog/',include('blog.urls')), path('project/',include('project.urls')), ] + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) I've tried to make absolute paths, but still, the image stays hidden. I thank you in advance and hope you can help me. Nick 'Iywern' Anthony -
Order post by date
I've created a list of post and now I want order this list by date of publishing. If I use order_by(-post_publishing_date) in the view the shell show me this error: NameError: name 'post_publishing_date' is not defined models.py class PostModel(models.Model): post_title = models.CharField(max_length=70) post_short_description = models.TextField(max_length=200) post_contents = models.TextField() post_publishing_date = models.DateTimeField(auto_now=False, auto_now_add=True) post_author = models.ForeignKey(AuthorModel, on_delete=models.CASCADE, related_name="connected_author") post_keyconcept = models.ManyToManyField(KeyConceptModel, related_name="connected_keyconcept") slug = models.SlugField(verbose_name="Slug", unique="True") post_highlighted = models.BooleanField(default=False) def __str__(self): return self.post_title def get_absolute_url(self): return reverse("singlepostManuscriptusView", kwargs={"slug": self.slug}) class Meta: verbose_name = "Articolo" verbose_name_plural = "Articoli" views.py class SinglePostGDV(DetailView): model = PostModel template_name = "manuscriptus_post_detail.html" class ListPostGDV(ListView): model = PostModel template_name = "manuscriptus_home.html" queryset = PostModel.objects.filter().order_by(-post_publishing_date) urls.py urlpatterns = [ path("it/blog/", ListPostGDV.as_view(), name="homeManuscriptusView"), path("it/blog/<slug:slug>/", SinglePostGDV.as_view(), name="singlepostManuscriptusView"), ] What I did wrong? -
Auto update of model instances for Django page
I will begin by describing my project first. I have a front-end app for users communicating with my Django server using Rest. The user is able to make a request through the app, and respectively my Django server will create a Request object using the Request model I have. So what I want is a live feed page displaying all the available Request objects, possibly through an url like http://myproject.com/pending/requests/. That means anytime an user make a new request, this page will be able to reload and display the new Request. Also next to each request is a check button which allows staff to check when a Request has been processed, and the Request will be cleared from the page after this. It works very similar to an ordering system. What would be the best tool for me to get a live feed of all the Request like what I just described? I'm thinking of using Ajax but I'm not sure if it would be best way to get me what I need. Any advice is appreciated. -
Building mobile apps using django
Please can django applications be turned to android applications with kivy using webview with the django server within the application and not with rest-api? Has anyone actually done it? -
Django - TypeError: object of type 'NoneType' has no len() occurred while doing Pagination
TypeError: object of type 'NoneType' has no len() occurres when I'm adding a pagination to a list view. Error: I want to allow users to search for books by entering a book title or an author name or a publisher name. I have three if statements below for fetching data in one of any these three situations. The last return statement is for returning an empty query set when a user enters an invalid key word for searching. book/views: class SearchResultView(generic.ListView): template_name = 'book/search.html' model = Book context_object_name = 'book_list' paginate_by = 2 def get_queryset(self): queryset = super().get_queryset() search = self.request.GET.get('search') if search: books_with_title = queryset.filter(title__icontains=search) if len(books_with_title) > 0: return books_with_title books_with_author = queryset.filter(authors__name=search) if len(books_with_author) > 0: return books_with_author books_with_publisher = queryset.filter(publisher__name=search) if len(books_with_publisher) > 0: return books_with_publisher return queryset.filter(title='no result found') # empty queryset for showing 'No result found.' on web pages I'm not sure whether I made the pagination correct or not (I can't test it due to the error) , I mean the href attribute. Cos I have no idea how to use the {% url 'some_view' %} for href in this case. If I did it wrong, please let me know or correct it. … -
Filtering and grouping in Python Model Objects after queryng the datbase
I have the following model: class Item(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, related_name='item',on_delete=models.SET_NULL) email = models.BooleanField(blank=True, null=True) ..... I need to send an email to user, where Item email attribute is False. I have the following query: items = Item.objects.filter(email=False) I want to filter/group item by User. I want to do it python because I want to send emails with delay and not to overwhelm the database at once with many queries. For each use I want to create a context dictionary that I can sent to the Django Email. -
Celery + Django on startup
I have written a code with django and celery, it is for a machine to run some tasks and to be accessible through net. So I need the django and celery to run automatically when the built-in PC starts. Can anyone please tell me the best and easiest way to do this? Can servers like Apache handle such thing? -
Python / Django pdfkit wkhtmltopdf UnknownContentError
I'm getting an UnknownContentError when generating a PDF document from a project URL (https://ourcodeworld.com/articles/read/241/how-to-create-a-pdf-from-html-in-django) - using pdfkit (wkhtmltopdf). pdf = pdfkit.from_url('http://127.0.0.1:8000/cb/open_detailed_research_outputs/', False, options) The URL is valid and displays the way it should in the browser. Could someone please advise where I'm going wrong. [Other URLs in my web app project seem to work except for this one.] Further error info: wkhtmltopdf reported an error: Loading pages (1/6) [> ] 0% [======> ] 10% [=======> ] 13% [==============================> ] 50% Error: Failed to load http://127.0.0.1:8000/cbib/open_detailed_research_outputs/, with network status code 299 and http status code 500 - Error downloading http://127.0.0.1:8000/cbib/open_detailed_research_outputs/ - server replied: Internal Server Error [============================================================] 100% Counting pages (2/6) [============================================================] Object 1 of 1 Resolving links (4/6) [============================================================] Object 1 of 1 Loading headers and footers (5/6) Printing pages (6/6) [> ] Preparing [============> ] Page 1 of 5 [========================> ] Page 2 of 5 [====================================> ] Page 3 of 5 [================================================> ] Page 4 of 5 [============================================================] Page 5 of 5 Done Exit with code 1 due to network error: UnknownContentError Request Method: POST Request URL: http://127.0.0.1:8000/cbib/open_detailed_research_outputs/download/ Django Version: 2.0.2 Exception Type: OSError Exception Value: wkhtmltopdf reported an error: Loading pages (1/6) [> ] 0% [======> ] 10% … -
user-defined function raised exception occurred
I have following error when I'm using below user defined function with raw query: Django Version: 2.1 Exception Type: OperationalError Exception Value: user-defined function raised exception from django.db.backends.signals import connection_created from django.dispatch import receiver @receiver(connection_created) def extend_sqlite(connection=None, **kwargs): if connection.vendor == "sqlite": # sqlite doesn't natively support math functions, so add them cf = connection.connection.create_function cf('acos', 1, math.acos) cf('cos', 1, math.cos) cf('radians', 1, math.radians) cf('sin', 1, math.sin) Here are is my raw query. query = """SELECT id, (6367*acos(cos(radians(%2f)) *cos(radians(lat))*cos(radians(long)-radians(%2f)) +sin(radians(%2f))*sin(radians(lat)))) AS distance FROM ksApp_outlet group by id having distance < %2f """ % ( float(lat), float(lng), float(lat), float(radius) ) outletdata = Outlet.objects.raw(query) Not sure what I'm doing wrong here. Can any one help me to figure out this error? -
Django form not getting submitted after first ajax call
On the page i have a drop down (when i change selected option, first ajax gets fired). First ajax is working fine and page is updating. After updating page, I have an add button on UI, upon clicking which second ajax is fired. It should submit the form. But Add button ajax (second ajax) is working only if i have not run the first ajax. Second ajax is not even getting called if I have run first ajax before it. I suspect there is some CSRF token issue here. Second ajax gets called if I don't run first ajax before. First ajax: var topicId = $(".topic_select option:selected").attr("data-topic"); $(".topic_select").change(function(){ var topicId = $(".topic_select option:selected").attr("data-topic"); if (topicId == undefined){ topicId = 999999; }; $.ajax({ type: "GET", url: "{% url 'recruiter:add_question_library' %}", data: { topicId: topicId, }, success: function(response){ // alert("Showing questions from topic " + topicId); $("#question_list").replaceWith($("#question_list",response)); } }); }); Second Ajax: $('.add-question-form').on('submit',function(e){ alert("hh"); e.preventDefault(); var $this = $(this); var qstn_id = $this.attr('id').split('_')[1]; $.ajax({ type: "POST", url: "{% url 'recruiter:add_question_to_interview' %}", data: { qstn_id: qstn_id, 'csrfmiddlewaretoken': '{{ csrf_token }}', }, success: function(response){ // $("#question-alert").animate({right: '20%'}, "slow"); // $('#question-alert').append('<div class="alert alert-success alert-dismissible fade show" role="alert"><strong>Question added to interview</strong><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button></div>'); … -
How to access Google Analytics in django admin panel?
I have a doubt how to google analytics dispaly in django admin panel.can give any suggestion or give proper documentation.I see many documentation cant understand .can give any example code.I tried but its not working can give proper documentation or any code.I tried api key also is not working . -
How can I add field to reqeust body in django middleware
I want to add new field in request body in middleware and use it in views. I googled it but the results was not worked. How can I do it ? Django v2 python 3.6 -
Django ORM multiple distinct and order by
I work on a simple chat app. I need to query db for an user to get last message of user conversation to other users. Same as main page of whatsapp and telegram. Model: class CHAT(models.Model): sender_uid = models.CharField(max_length=150, db_index=True) receiver_uid = models.CharField(max_length=150, db_index=True) message = models.TextField(verbose_name='Message Text') created = models.IntegerField(default=created_time_epoch) I tried this query: message_list = self.model.objects.filter(Q(sender_uid=user_uid)|Q(receiver_uid=user_uid)).order_by('receiver_uid', 'sender_uid', '-created').distinct('receiver_uid', 'sender_uid') Output: <QuerySet [<CHAT: ted@ted.com Message: hello 4 To: saeed@saeed.com>, <CHAT: marshal@marshal.com Message: hello6 To: saeed@saeed.com>, <CHAT: saeed@saeed.com Message: hello 5 To: ted@ted.com>]> My problem is I get two last message from each conversation (if both user send message to each other), In one of them user is sender and in other one user is receiver. For now I handle it with below code: message_send_list = list(self.model.objects.filter(sender_uid=user_uid).order_by('receiver_uid', '-created').distinct('receiver_uid')) message_receive_list = list(self.model.objects.filter(receiver_uid=user_uid).order_by('sender_uid', '-created').distinct('sender_uid')) temp_list = [] for s_message in message_send_list: r_message = next((item for item in message_receive_list if item.sender_uid == s_message.receiver_uid), None) if r_message is not None: message_receive_list.pop(message_receive_list.index(r_message)) if s_message.created > r_message.created: temp_list.append(s_message) else: temp_list.append(r_message) else: temp_list.append(s_message) temp_list.extend(message_receive_list) Output: [<CHAT: saeed@saeed.com Message: hello 5 To: ted@ted.com>, <CHAT: marshal@marshal.com Message: hello6 To: saeed@saeed.com>] My question is how can I get this result in one query? Problem is user can be sender and … -
Get the FK attributes of a model , if a model is passed
I have the following Model(s): class Comp(models.Model): .... is_active = models.BooleanField(default=False) class Item(models.Model): comp = models.ForeignKey(Comp, blank=True, null=True, related_name='items', on_delete=models.CASCADE) romp = models.ForeignKey(Romp, blank=True, null=True, related_name='items', on_delete=models.CASCADE) is_active = models.BooleanField(default=False) I want to write a generic Model clean method,to check for non Null Foreign Keys of a Model, if their is_active=True I want to inherit this method over multiple Models(using abstract Model) In the code below I check each model attribute over a general list of FKs def clean(self, *args, **kwargs): .... for attr in FK_LIST: if hasattr(self, attr): fk_obj = getattr(self, attr) if not fk_obj.active: raise ValidationError({'is_active': 'The {} {} needs to be active first' .format(type(fk_obj).__name__, fk_obj.name)}) There 2 issues with my code: I have two manually maintain a list of FKs name I need to loop thru all attributes instead of checking just FKs Instead of having an implicit FK_list to check in, I prfer to have an exclude list(easy to maintain): Check all FK on the model that are not NULL or in Exclude_list -
Multithreading using queues in django + uWSGI
I am struggling to make Python standard queues work in uWSGI master. Sample code: import queue, threading, time from django.apps import AppConfig my_queue = queue.Queue() class MyApp(AppConfig): def ready(self): thread1 = threading.Thread(target=process_queue, args=()) thread1.daemon = True thread1.start() thread2 = threading.Thread(target=poll, args=()) thread2.daemon = True thread2.start() def poll(): while True: time.sleep(1) logging.info("Polling works every time") def process_queue(): while True: logging.info("I get here") email = my_queue.get(block=True, timeout=None) logging.info("I NEVER GET here. **I would like to get here**") def put(): # I call this from the django views on requests my_queue.put("1") Both threads start. Thread 2 prints at regular intervals as expected. Thread 1 waits on the queue forever, even though I add to it from main thread (As part of Django requests, inside the views) My uWSGI config: [uwsgi] master = true module = backend.wsgi processes = 1 thunder-lock = true enable-threads = true socket = /tmp/django.sock chmod-socket = 666 vacuum = true Notice that if I run uWSGI with master = false, everything works as expected Additional information: I am running this as a vassal. The emperor is not running as master I do not really understand pre/post forking in django + uWSGI. This could be an issue This works if … -
Understanding Image Fields, MEDIA_ROOT & MEDIA URL
Building of neverwalkaloner's answer here, I tried migrating my image model attribute from a CharField to an ImageField and then setting MEDIA ROOT & MEDIA URL in settings.py. My understanding, reading the documentation: here (how Django handles files), here (what does MEDIA URL and MEDIA ROOT mean), and here (what ImageField is and its different arguments), Django will handle the absolute path to the file of the particular ImageField based of the upload_path & settings. So I tested it in the shell. So far, it isn't working. UPDATED ATTEMPT AT PRODUCT In settings.py: MEDIA_ROOT = BASE_DIR + '/project' + '/media/' MEDIA_URL = '/media/' In models.py: from django.db import models class Product(models.Model): sku = models.CharField(validators=[isalphanumeric], max_length=20, null=False, blank=False) image = models.CharField(upload_to="products/" max_length=20, blank=False, null=False) Testing it out in the Python Django shell: In [1]: from app.models import Product In [2]: test_product = Product(sku='alphanumeric23', image='test_product.png') In [3]: test_product.log.path Out [3]: 'C:\\Users\\user\\path\\to\\project\\project\\media\\test_product.png' But my expected output should have been: 'C:\\Users\\user\\path\\to\\project\\project\\media\\product\\test_product.png' Is it because there's an assumption that it hasnt technically been uploaded yet (triggered by the test_product.save() (I'm assuming)? Something feels off. -
Pagination Django Class Based View Not Working Properly
I'm trying to use Django (v2.0) pagination with CBV and got issues. The pagination is active because the tag {% if is_paginated %} returns "True" and shows the "PagNav" and the browser path changes too, like this (..?page=1, ...?page=2, etc...) but the displayed elements are all, not 3 just as I set in "paginate_by=3". For example, if the query has 15 elements must to show 3 elements per page and 1 to 5 in the pagination down bellow, but shows all elements. I attach an image and the code: models.py: from django.db import models from django.contrib.auth.models import User from ckeditor.fields import RichTextField # Create your models here. class Project(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE, default=1) name = models.CharField(verbose_name='Nombre del proyecto', max_length=200) client = models.CharField(verbose_name='Nombre del cliente', max_length=200) description = RichTextField(verbose_name='Descripción') start = models.DateField(verbose_name='Fecha de Inicio', null=True, blank=True) ending = models.DateField(verbose_name='Fecha de Finalización', null=True, blank=True) order = models.SmallIntegerField(verbose_name="Orden", default=0) created = models.DateTimeField(verbose_name='Fecha de creación', auto_now_add=True) updated = models.DateTimeField(verbose_name='Fecha de modificación', auto_now=True) class Meta: verbose_name = 'Proyecto' verbose_name_plural = 'Proyectos' ordering = ['-start', 'order'] def __str__(self): return self.name class Album(models.Model): project = models.ForeignKey(Project, verbose_name='Proyecto relacionado', on_delete = models.CASCADE) title = models.CharField(verbose_name='Título de la imagen', max_length=200) image = models.ImageField(verbose_name='Imagen', upload_to='portfolio') created = …