Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Custom functions in __init__.py cause Django Apps Aren't Installed Yet Error
I have a setup like the following Tasks |__ __init__.py |__ a.py |__ b.py |__ c.py ... Inside the __init__.py file, from .a import custom1, custom2 from .b import custom3, custom4 I wrote a function within Tasks which requires Tasks to be added as an INSTALLED_APP. The custom functions however raise django.core.exceptions.AppRegistryNotReady: "Apps aren't loaded yet.". Why does this happen, and is there a way to fix this error WITHOUT moving the custom functions out of the init.py file? -
Django dynamically display a list but ignore some items
I am trying to show a list of groups on the sidebar on my html using Django. The first item will always be "all". so when I tranverse through all the groups/subreddits, I would first display "all" and then display the rest. however, when I display the rest and when it hits "all" again, instead of doing nothing, it seems to be printing a empty line because later when I display it in forms, I notice that I have a blank cell. I wonder how do I make sure that it just ignores "all" and goes on to display the next group without the empty space. Here is the code: <div class="post" id="title"><h4>Groups </h4></div> {% for sub in subreddits %} {% if sub.name == 'all' %} <div class="post"> <a href="{% url 'sub_detail' pk=sub.pk %}">{{ sub.name }}</a></div> {% endif %} {% endfor %} {% for sub in subreddits %} <div class="post"> {% if sub.name != 'all' %} <a href="{% url 'sub_detail' pk=sub.pk %}">{{ sub.name }}</a> {% endif %} </div> {% endfor %} -
Django Rest Framework action when request comes in
I'm creating a Django project that uses Django REST Framework for the API. Other projects will be making POST, PUT, and DELETE requests to this project. When one of those requests comes in, I want to send a message to a websocket group using channels. For some reason I am struggling to do this. I am using ThreadViewSet, which extends ModelViewSet, for a model named Thread. class ThreadViewSet(ModelViewSet): queryset = Thread.objects.all() serializer_class = ThreadSerializer I have tried adding the channels call to this class but it doesn't seem to be run: class ThreadViewSet(ModelViewSet): queryset = Thread.objects.all() serializer_class = ThreadSerializer channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)("group", {'type': 'new_message', 'message': "New Thread"}) The next thing I tried was overriding create(), update(), and destroy() and this worked, but it seemed like so much work for one simple task. Am I missing something? There has to be an easier way to do this. -
Django how to load statics inside a python file
I'm trying to load a an image from static to a from element I tried to load it inside my forms.py as a style attribute widget=forms.Select(attrs={ 'style': 'background: url("{% static \'/img/Arrow_bottom.png\' %}") 2rem / 2rem no-repeat #eee;' }) but it's interpreted in the browser as a text "background: url("{% static '/img/Arrow_bottom.png' %}") I want "background: url("static_dir/img/Arrow_bottom.png") how can I load statics to my forms.py file or to the css file -
Using Vue with Django: How to separate publicPath from static file prefix
I'm trying to convert my existing and sprawling Django project, which currently uses Vue from a CDN in individual pages on the frontend, to an SPA via NPM with the backend and frontend now separate (except for Django handling some URL routes and loading the Vue initially). I'm running into a problem with static files and URL routing. In vue.config.js, I was originally advised to set values as follows: const pages = { index: "src/main.js" }; module.exports = { runtimeCompiler: true, publicPath: "/static/vue/", outputDir: "./dist/static/vue/", indexPath: "../../templates/vue_index.html", pages: pages }; so that when combined with the way Django looks for static files: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'frontend/dist/templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] STATICFILES_DIRS = [os.path.join(BASE_DIR, 'frontend/dist/static')] STATIC_URL = '/static/' the page will be able to load. Unfortunately, if I try to load the page, rather than loading at the website root /, it loads at /static/vue/ (i.e. localhost:8000/static/vue/). If I try to directly access localhost:8000, it immediately redirects to localhost:8000/static/vue/, which I suppose is vue-router's doing. Django is able to find the Vue entry point template just fine, but it seems to need publicPath: "/static/vue/" in order … -
Celery tasks running every 20 seconds is overlapping and starting before the last can finish
I have a celery task running every 20 seconds. The problem is handler is firing off twice sometimes the tasks overlap. Seems like the filtered items are not updating while the tasks overlap: @periodic_task(run_every=timedelta(seconds=20)) def process_webhook_transactions(): """Process webhook transactions""" transactions = WebhookTransaction.objects.filter(status=WebhookTransaction.UNPROCESSED) for transaction in transactions: data = transaction.body event = data.get('event_category') if event is None: transaction.status = WebhookTransaction.ERROR transaction.save() continue handler = WEBHOOK_HANDLERS.get(event, default_handler) success = handler(data) if success: transaction.status = WebhookTransaction.PROCESSED else: transaction.status = WebhookTransaction.ERROR transaction.save() What is the best way to avoid this? -
Many to Many Field en Django
soy nueva trabajando con Django. Tengo un campo ManytoMany y al hacer el post desde la App, en algunas ocasiones no va ese dato porque no tiene asociada esa clave foranea. Mi pregunta es ¿Hay forma de permitir que el Django reciba ese dato en None? He probado con blank=True y siempre sale el error que esa clave primaria no existe ¿Alguna sugerencia? -
Create django model with as many fields as an integer in other field
I have the following model in django class params(models.Model): name = models.CharField(max_length=30, default = 'no_name') cs_n = models.IntegerField(default=16) alt_n = models.IntegerField(default=2) opt_out = models.BooleanField(default=1) at_n = models.IntegerField(default=4) I want to create a new model with as many fields as at_n. For example, if the user enter "4" in at_n, I want this to create automatically: class params(models.Model): at_1 = models.IntegerField(default=2) at_2 = models.IntegerField(default=2) at_3 = models.IntegerField(default=2) at_4 = models.IntegerField(default=2) Thanks -
I can't get AWS S3 to serve media files on my Django/Heroku App
Been stuck on this for a while. In my django site's admin page, I can upload a photo along with my blog post. The photo will appear in my S3 bucket, but the photo won't render on the blog post. Just a little photo icon. Followed the simpleisbetterthancomplex tutorial, and have read through every relevant stackoverflow question I can find. Can anyone see what it is that I'm missing? Thanks. Here is my settings.py: AWS_ACCESS_KEY_ID = '**********' AWS_SECRET_ACCESS_KEY = '*********' AWS_STORAGE_BUCKET_NAME = 'matt-george-portfolio' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_LOCATION = 'static' STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATIC_URL = '/static/' MEDIA_URL = '/images/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) import django_heroku django_heroku.settings(locals()) I added this to my AWS S3 permissions: [ { "AllowedHeaders": [ "*" ], "AllowedMethods": [ "GET", "PUT", "POST", "HEAD", "DELETE" ], "AllowedOrigins": [ "*" ], "ExposeHeaders": [], "MaxAgeSeconds": 3000 } ] -
Im new in django I'm using gitpod workspace and trying to set up an authentication system with django-allauth
Im trying to set up an authentication system with django-allauth and to customize the allauth login templates I need to make copies of them in my own templates/allauth directory, I'm using gitpod. this is the command I'm using to copy cp -r ../.pip.modules/lib/python3.8/site-packages/allauth/templates/* ./templates/allauth/ but Im getting this error message cp: cannot stat '../.pip.modules/lib/python3.8/site-packages/allauth/templates/*': No such file or directory this are the installed apps in setting.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', ] -
I am facing issue while writing records to google cloud postgresql using apace beam and beam-nuggets
TypeError: expected bytes, str found [while running 'Writing to DB/ParDo(_WriteToRelationalDBFn)-ptransform-186378'] Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/apache_beam/runners/worker/sdk_worker.py", line 289, in _execute response = task() File "/usr/local/lib/python3.7/site-packages/apache_beam/runners/worker/sdk_worker.py", line 362, in lambda: self.create_worker().do_instruction(request), request) File "/usr/local/lib/python3.7/site-packages/apache_beam/runners/worker/sdk_worker.py", line 607, in do_instruction getattr(request, request_type), request.instruction_id) File "/usr/local/lib/python3.7/site-packages/apache_beam/runners/worker/sdk_worker.py", line 644, in process_bundle bundle_processor.process_bundle(instruction_id)) File "/usr/local/lib/python3.7/site-packages/apache_beam/runners/worker/bundle_processor.py", line 957, in process_bundle op.start() File "apache_beam/runners/worker/operations.py", line 710, in apache_beam.runners.worker.operations.DoOperation.start File "apache_beam/runners/worker/operations.py", line 712, in apache_beam.runners.worker.operations.DoOperation.start File "apache_beam/runners/worker/operations.py", line 714, in apache_beam.runners.worker.operations.DoOperation.start File "apache_beam/runners/common.py", line 1290, in apache_beam.runners.common.DoFnRunner.start File "apache_beam/runners/common.py", line 1275, in apache_beam.runners.common.DoFnRunner._invoke_bundle_method File "apache_beam/runners/common.py", line 1321, in apache_beam.runners.common.DoFnRunner._reraise_augmented File "/usr/local/lib/python3.7/site-packages/future/utils/init.py", line 446, in raise_with_traceback raise exc.with_traceback(traceback) File "apache_beam/runners/common.py", line 1273, in apache_beam.runners.common.DoFnRunner._invoke_bundle_method File "apache_beam/runners/common.py", line 518, in apache_beam.runners.common.DoFnInvoker.invoke_start_bundle File "apache_beam/runners/common.py", line 524, in apache_beam.runners.common.DoFnInvoker.invoke_start_bundle File "/usr/local/lib/python3.7/site-packages/beam_nuggets/io/relational_db.py", line 178, in start_bundle self._db.start_session() File "/usr/local/lib/python3.7/site-packages/beam_nuggets/io/relational_db_api.py", line 255, in start_session if create_if_missing and is_database_missing(): File "/usr/local/lib/python3.7/site-packages/beam_nuggets/io/relational_db_api.py", line 254, in is_database_missing = lambda: not database_exists(self._source.url) File "/usr/local/lib/python3.7/site-packages/sqlalchemy_utils/functions/database.py", line 481, in database_exists return bool(get_scalar_result(engine, text)) File "/usr/local/lib/python3.7/site-packages/sqlalchemy_utils/functions/database.py", line 455, in get_scalar_result result_proxy = engine.execute(sql) File "/usr/local/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 2234, in execute connection = self._contextual_connect(close_with_result=True) File "/usr/local/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 2302, in _contextual_connect self._wrap_pool_connect(self.pool.connect, None), File "/usr/local/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 2336, in _wrap_pool_connect return fn() File "/usr/local/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 364, in connect return _ConnectionFairy._checkout(self) File "/usr/local/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 778, in … -
i work django and me working on entering the display screen control admin but cannot access to get page admin
i work django and me working on entering the display screen control admin but cannot access to get page admin Blank information is displayed on the request path to: http://127.0.0.1:8000/admin/login/?next=codeviaew/admin/ This problem occurs when I am working on a fake environment Pipfile inside Pipfile: [[source]] url = "https://pypi.org/simple" verify_ssl = true name = "pypi" [packages] django = "*" django-crispy-forms = "*" pillow = "*" [dev-packages] [requires] python_version = "3.8" I deleted the database, recreated it and created a user, but the problem still exists -
i want to host django server by apache server but a saw the admin/index.html template doesn't exist?
enter image description here [1]enter image description here: https://i.stack.imgur.com/NfKkp.png -
Unexpected error: replace() takes 2 positional arguments but 3 were given
In settings.py I have: BASE_DIR = Path(__file__).resolve().parent.parent Then In some view: from django.http import HttpResponse from django.conf import settings def(request): return HttpResponse( settings.BASE_DIR.replace("src", "") ) This gives error: replace() takes 2 positional arguments but 3 were given Bit confused because if do: return HttpResponse( settings.BASE_DIR ) this returns full path, something like: /home/full/path/to/project/src also this works return HttpResponse( "/home/full/path/to/project/src".replace("src", "") ) Can you help me and tell what is wrong with this line: return HttpResponse( settings.BASE_DIR.replace("src", "") ) ? -
how can i share to facebook with real image post?
I have a period of time I want to share an article in my django blog app to facebook but every time I find a problem, when treid to share post it share with pic profile not with image post... please help me this is the link of my app, treid to share some post , you well seing what is exactly the problem Link: http://mazaridz.pythonanywhere.com article.html <div class="text-center center-block"> <p class="txt-railway" style="font-family: 'Cairo', sans-serif;"><a href="{{art.source}}">مصدر المقال</a> <p> <p class="txt-railway" style="font-family: 'Cairo', sans-serif;">مشاركة المقال</p> <hr> <br /> <a href="https://www.facebook.com/sharer/sharer.php?u=http://mazaridz.pythonanywhere.com/article/{{art.id}}/{{art.slug}}"><i id="social-fb" class="fa fa-facebook-square fa-3x social" target = ""></i></a> <a href="https://twitter.com/home?status={{request.build_absolute_url}}%20{{share_title}}"><i id="social-tw" class="fa fa-twitter-square fa-3x social"></i></a> <a href="https://plus.google.com/share?url=mazaridz.pythonanywhere.com/article/{{art.id}}"><i id="social-gp" class="fa fa-google-plus-square fa-3x social"></i></a> <a href="mailto:bootsnipp@gmail.com"><i id="social-em" class="fa fa-envelope-square fa-3x social"></i></a> </div> -
User report function
I want to implement a report feature with Django in my blog which users will be able click a link/button under a post and the admin will be notified and he will decide if the post shows up on the homepage or not . My Post model class Post(models.Model): title = models.CharField(max_length=225) post_image = models.ImageField(null=True, blank=True, upload_to="images/") author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() post_date = models.DateField(auto_now_add=True) likes = models.ManyToManyField(User, related_name='blog_posts') def total_likes(self): return self.likes.count() def __str__(self): return self.title + ' | ' + str(self.author) def get_absolute_url(self): return reverse('post-detail', args=(str(self.id)),) My views.py def LikeView(request, pk): post = get_object_or_404(Post, id=request.POST.get('post_id')) liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) liked = False else: post.likes.add(request.user) liked = True return HttpResponseRedirect(reverse('post-detail', args=[str(pk)])) class HomeView(ListView): model = Post template_name = 'home.html' ordering = ['-post_date'] class Suggest(ListView): queryset = Post.objects.annotate(like_count=Count('likes')).order_by('like_count') template_name = 'home.html' context_object_name = 'post_list' # Providing a useful context_object_name is always a good idea class PostDetail(DetailView): model = Post template_name = 'post_detail.html' def get_context_data(self, *args, **kwargs): context = super(PostDetail, self).get_context_data() current_post = get_object_or_404(Post, id=self.kwargs['pk']) total_likes = current_post.total_likes() liked = False if current_post.likes.filter(id=self.request.user.id).exists(): liked = True context['total_likes'] = total_likes context['liked'] = liked return context class AddPost(CreateView): model = Post form_class = PostForm template_name = 'add_post.html' # fields … -
How can I add column to the admin from other table, that isn't directly connected?
I have four tables connected together: -meeting (two foreign keys of person) -person (many to many field to 'issue dictionary' -issue (foreign key of person and issue dictionary) -issue dictionary my 'meeting' table has foreign key of 'person' and 'person' is connected many-to-many to 'issue dictionary', which goes through table 'issue' (because I had to add extra flags there). I want to add one column from 'issue dictionary' to meeting view, but I have no idea how can I do it. When running in python shell, I achieve what I need Meeting.objects.filter(id=1).values('person_in_need__person_c__condition__issue') But, as mentioned above, I have no idea how to add the option to choose what it returns on the meeting class. Here are the models (the important bits): class ConditionDictionary(models.Model): issue = models.CharField(max_length=50) description = models.TextField() class Condition(models.Model): person = models.ForeignKey(Person, related_name = 'person_c', on_delete=models.CASCADE) condition = models.ForeignKey(ConditionDictionary, related_name = 'condition_c', on_delete=models.CASCADE) class Person(models.Model): issue = models.ManyToManyField(ConditionDictionary, through='Condition') class Meeting(models.Model): person1 = models.ForeignKey(Person, related_name='in_need', on_delete=models.CASCADE) person2 = models.ForeignKey(Person, related_name='carer', on_delete=models.CASCADE) My idea is that with every meeting created, you could choose what issue is treated this time. -
Try to set Django time field to 00:00:00 but dont want it to say midnight when I display it
I have a model that has a Time Field called Duration. Format "hh:mm:ss" but its a running time, not a clock time. SO if there is no duration entered yet, I want the default value to be '00:00:00' but when displaying listing for the entry - it always get converted to midnight and displays 'midnight' for the duration field. Tried setting DATETIME_FORMAT and Time_Input_Formats in settings.py but that doesn't help.... Sometimes the entries could be created and have no duration yet.... -
Is it possible to implement OAuth while using Django Rest Knox?
I have been trying to figure out whether there is a way to use Django Rest Knox for user authentication in a Django application using the Rest Framework and also implement social logins such as Google or Facebook as alternatives. I have been looking for an answer to this question for a while and one package that always pops up is Django AllAuth. Is there a way of combining the two packages or are they mutually exclusive? If so, how would I go about this? -
Django rest auth store token securely
I'm trying to implement authentication with django-rest-auth library in the backend and I'm using react for the front-end. Django-rest-auth returns a token after authentication and I was guessing how to handle it. From a security perspective can that token be saved in an HTTPOnly cookie or it should be kept only in memory? Exists a tested approach to achieve local persistence with django-rest-auth and react without implementing vulnerabilities in the website? -
Table not displaying a data from model
this is my views.py def sms(request): obj = Sms.objects.all() return render(request, 'advisory.html', {'sms': obj}) and this is on my html. {% for i in sms %} <tr> <td>{{ i.description }}</td> <td>{{ i.timestamp }}</td> </tr> {% endfor %} this is the model class Sms(models.Model): description = models.CharField(max_length=100, blank=True) timestamp = models.DateTimeField(auto_now_add=True) And i don't really know why its not returning any data from my model. please help! thanks -
Get Data from all objects of a queryset in django
I have two models Order and OrderEntries class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) order_entries = models.ManyToManyField(OrderEntries, blank=True) ... class OrderEntries(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField() Now, I have to get history of purchased products. As I can get all previous orders placed by a user like this queryset = Order.objects.filter(user=self.request.user, client=self.request.client) But how I can get list of products from all those orders? -
Can't figure out how to craft my GraphQL query with graphene-django
I'm just starting out with graphene-django and GraphQL and can't figure out how to craft my mutation correctly. Here's my current mutation request: mutation createCustomer { createCustomer(input: { customerName: "John Smith", customerAddress: "1000 Airport Drive", customerCity: "1", customerState: "TX", customerZip: "75121", customerEmail: "me@me.com", customerCellPhone: "124567894", referredFrom: "g" }) { ok, customer{ id, customerName, customerZip, customerAddress } } } Here's my CustomerInput schema: input CustomerInput { id: ID customerName: String customerAddress: String customerCity: [LocationInput] customerState: String customerZip: String customerEmail: String customerCellPhone: String customerHomePhone: String referredFrom: String } LocationInput schema: input LocationInput { id: ID locationCity: String locationState: String locationSalesTaxRate: Float } And the error I'm receiving: { "errors": [ { "message": "Syntax Error GraphQL (6:28) Unexpected :\n\n5: customerAddress: \"1000 Airport Drive\",\n6: customerCity: [location:{id:1}],\n ^\n7: customerState: \"TX\",\n", "locations": [ { "line": 6, "column": 28 } ] } ] } And finally, here is my models: class Location(BaseModel, models.Model): location_city = models.CharField(max_length=100, blank=False, null=False, unique=True) location_state = models.CharField(max_length=2, blank=False, null=False, default="TX") location_sales_tax_rate = models.DecimalField(max_digits=4, decimal_places=2, verbose_name="Sales Tax Rate (%)", blank=True, null=True) class Customer(BaseModel, models.Model): """Customer model.""" REFERRAL_CHOICES = ( ('g', 'Google'), ('o', 'A friend'), ('f', 'Facebook'), ) # templates = "workorders/customers/customer.html" customer_name = models.CharField(max_length=100, blank=False, null=False, help_text="John Doe", verbose_name="Name") customer_address = models.CharField(max_length=100, blank=False, … -
Django: Is it appropriate to make queries from the template?
I have two models, Book and Chapter: class Book(models.Model): title = models.CharField(max_length = 200) class Chapter(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name="chapter_set") index = models.IntegerField() In my template, I present each book and subsequent chapter indexes: {% for book in books %} <h2>{{ book.title }}</h2> <br> {% for chapter in book.chapter_set.all %} <p>{{ chapter.index }}</p> {% endfor %} {% endfor %} This code works fine. However, I hear repeatedly that it's a bad idea to place logic in the template that could be placed in the view or model. I'm hesitant to implement so many queries from my template if I'm hindering performance. I'm considering refactoring this code so that the template doesn't process queries through related_name. Is a refactor unnecessary, or am I violating best practices by making queries in the template? -
How to use Sphix's sphinx.ext.coverage's coverage_show_missing_items?
Sorry, I am a newbie trying to add Sphinx to auto-generate documentation for a Django project and also ensure sufficient documentation coverage of the project. I want to configure Sphinx to tell me which Objects are missing documentation by using the coverage_show_missing_items flag, specified here: https://www.sphinx-doc.org/ar/master/usage/extensions/coverage.html#confval-coverage_show_missing_items Unfortunately, I have not been able to figure out where/how to set this configuration. My Google-fu didn't come up with any examples on how to configure these settings. I'm guessing it should go inside conf.py somewhere, but haven't come across any examples on how to do it. Thank you for your time :)