Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Display Topic by User Subscription to Topic Category
I'm new to Django Python framework. i have the Topic model, SubChannel model, SubChannelSubscription model. i want to display the Topics according to what the user subscribed to. For example, If a User subscribed to Physics category only, the User should only see Physics Topics Python 3 and Django 2 class SubChannelSubscription(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='subscriptions', verbose_name='Subscriber', default=True) category = models.ForeignKey(SubChannel, related_name='Topic+', on_delete=models.CASCADE, verbose_name='SubChannel', default=True) def __str__(self): return '%(user)s\'s subscription to "%(category)s"' % {'user': self.user, 'category': self.category} class Meta(object): verbose_name = 'Subscription to SubChannel' verbose_name_plural = 'Subscriptions to SubChannel' class Topic(models.Model): by = models.ForeignKey(User, on_delete=models.CASCADE, default=True) subject = models.CharField(max_length=150, unique=True, null=True) date_created = models.DateTimeField(auto_now_add=True) category = models.ForeignKey(SubChannel, on_delete=models.CASCADE, null=True, default=True, related_name='topics') file = RichTextUploadingField(blank=True, null=True) def __str__(self): return self.subject def get_absolute_url(self): return reverse('Topic_detail', kwargs={'pk': self.pk}) I have my Views.py code for User Subscription shown below class SubChannelSubscriptionView(ListView): template_name = 'subscription.html' model = Topic def get_queryset(self): self.user = get_object_or_404(User, pk=self.kwargs['pk']) return SubChannelSubscription.objects.filter(user=self.user) def get_context_data(self, **kwargs): context = super(SubChannelSubscriptionView, self).get_context_data(**kwargs) context['topics'] = self.user context['top'] = Topic.objects.filter(category=1) return context my urls.py path('subscription/<int:pk>', SubChannelSubscriptionView.as_view(), name='subscription'), -
Unable to Redirect to homepage after login in Django
hay i'm new to django framework, i got issue that i can not solved. It is when i tried to redirect the admin to admin custom homepage using LOGIN_REDIRECT_URL, i set it to /profile, but instead go to homepage it raised "Page not found (404)" here's my root url file urlpatterns = [ path('admin/', admin.site.urls), path('', include('front_page.urls')), path('accounts/login',views.LoginView.as_view(),name='login'), path('accounts/logout/', views.logout, name='logout', kwargs={'next_page': '/'}), path('profile/', include('admin_page.urls')), ] admin apps url app_name = "admin" urlpatterns = [ path('home/', views.index, name='admin_index'), path('berita/', views.BeritaList.as_view(), name='all_berita'), ] setting.py LOGIN_REDIRECT_URL = '/profile' homepage file <div class="jumbotron"> <div class="container"> <h1>Hello, admin</h1> <p>Selamat di halaman utama administrator,silahkan menekan tombol dibawah untuk menginput Peta atau berita</p> <p><a class="btn btn-primary btn-lg" href="{% url 'admin:all_berita' %}" role="button">Berita</a> <a class="btn btn-primary btn-lg" href="" role="button">Peta</a></p> </div> </div> i got confused because it happen only when i try to redirect admin after login, can someone help me solve it, thank you -
Django templates. I get in my mail parameters, how can I send them to another html with include?
This is my welcome container: <tr> <td align="center"> <!-- Start internal container --> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td height="30" style="line-height:30px; font-size:30px;">&nbsp;</td> </tr> <tr> <td align="left" style="font-family: 'Lato', sans-serif; font-size:20px; line-height:26px;"> <p style="font-family: 'Lato', sans-serif; margin: 0; padding: 15px 60px 15px 60px; font-weight: bold; color: #333333;"> {{ title }} </p> <p style="font-family: 'Lato', sans-serif; font-size:16px; margin: 0; padding: 0px 60px 0px 60px; color: #333333;"> {{ subtitle }} </p> </td> </tr> </table> <!-- End internal container --> </td> I tried this: {% "Hi {{first_name}}" as titleStr%} {% with title=titleStr subtitle="Please confirm your email address by clicking this button." %} {% include "emails/_parts/welcome_container.html" %} {% endwith %} But I get this issue: Invalid block tag on line 29: '"Hi', expected 'endblock'. Did you forget to register or load this tag? What am I doing wrong? Line 29 is the one with title=titleStr -
Dealing with Many models and relations in Django Rest Framework
I am working on building an API backend full of many models and relations among them. I am confused between three options: - Using Django Rest Framework: It will be useful as a specialized framework to build an API, but it becomes very complex while: dealing with many models and relations. customizing the queries itself (for example: if I want to use select_related attribute to query on a one to many field instead of leaving it to DRF). Serializing many models together and in different situations like ListView, DetailsView, ..etc. However, I see that this package could be useful: https://github.com/MattBroach/DjangoRestMultipleModels I think it will be overhead on the application itself and it will be slower (I am not sure). the hierarchy that it use, more and more complexity. So, finally I see that it is restricted when it comes to deep customization. However, it provides many features to be used directly instead of inventing the wheel. - Using pure Django: This will make it more flexible to build my application and I can use the django.core.serializers.serialize to serialize my data like: Django or Django Rest Framework, I can also use the pyjwt and others. I know that the disadvantage of … -
Django 2.0: Url path to homepage/index
I'm trying to set my django homepage, linked to the root of my website: i.e. http://127.0.0.1:8000/index/ but instead, I keep getting errors where Django is searching for myapp as the homepage: http://127.0.0.1:8000/myapp/. I would just like to land on a homepage with "index" in the url instead of "myapp/" The error is as follows: Using the URLconf defined in Main.urls, Django tried these URL patterns, in this order: admin/ [name='index'] [name='myapp_index'] publications/ [name='publications'] ^static\/(?P<path>.*)$ The current path, myapp/, didn't match any of these. Views.py def index(request): return render(request, 'index.html') Main/urls from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('myapp.urls')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) myapp/urls from django.urls import path from logbook import views urlpatterns = [ path('', views.index, name='index'), path('', views.myapp_index, name='myapp_index'), path('publications/', views.publications, name='publications'), ] Now, if I change the path in Main/urls.py to path('myapp/', include('myapp.urls')), I land on the appropriate homepage, except, I would prefer that there is "index/" listed in the URL instead of "myapp/". I may be missing something very simple here. This is what I think is my MWE, happy to add more. -
Strategy to measure memory usage for Django queryset
I want to measure how much memory Django queryset use. For example, I try the simple way. import psutil process = psutil.Process(os.getpid()) s = process.memory_info().rss # in bytes for i in queryset: pass e = process.memory_info().rss # in bytes print('queryset memory: %s' % (e-s)) Since iterating queryset, Django will hit a database and the result will be cached and by getting memory usage for the Python process, I try to measure queryset memory usage. I wonder if the access would be right or there is any way to measure my goal, you guys know. This measure is to predict if there would be any issue when trying to get a massive query result and if there is, from how many rows result in an issue. I know If I want to avoid caching queryset result, I can use iterator(). However, iterator() also should determine chunk_size parameter to reduce the number of hitting database and memory usage will be different depending on chunk_size. import psutil process = psutil.Process(os.getpid()) s = process.memory_info().rss # in bytes for i in queryset.iterator(chunk_size=10000): pass e = process.memory_info().rss # in bytes print('queryset memory: %s' % (e-s)) -
Django - unable to open database file
It gives 500 error (more precisely “unable to open database file”) when I go to the admin panel. + In the logs, nginx writes that it cannot find .css files, although they are in place. You can see the debugging at https://testeuppi98.ddns.net - root:root -
Pass Variable from View to Form Django
Basically i am sending email to user with password and username. I can get the username using self.cleaned_data.get('email'). But the problem is that i dont know how to get password from view which i am setting random password in views. So please help me to get that random password from views.py to forms.py in def send_email Forms.py class UserRegisterForm(forms.ModelForm): email = forms.EmailField() first_name = forms.CharField() last_name = forms.CharField() class Meta: model = User fields = ['first_name','last_name', 'email'] def send_email(self): name = self.cleaned_data.get('first_name') username = self.cleaned_data.get('email') to_email = self.cleaned_data.get('email') password1 = # Get Password from view Views.py def register(request): if request.method == 'POST': ur_form = UserRegisterForm(request.POST) pr_form = UserProfileForm(request.POST, request.FILES) user_role = 0 if ur_form.is_valid() and pr_form.is_valid(): new_user = ur_form.save(commit=False) new_user.username = new_user.email password = User.objects.make_random_password() # Pass This to Form send_email new_user.set_password(password) new_user.save() -
Django DateTimeField is not editable
I have a blog and I post many articles. Each article has a date of publication, and sometimes I have to edit this date. Everything running on the Django admin panel and I never encountered any 500 error since I decided to add the DateTimeField in my admin.py. The issue is, Django cannot edit the DateTimeField and it returns : Internal Server Error: /admin/wall/articles/62/change/ FieldError at /admin/wall/articles/62/change/ 'date' cannot be specified for Articles model form as it is a non-editable field. Check fields/fieldsets/exclude attributes of class ArticlesAdmin. I don't understand why it doesn't work. Models : class Articles(models.Model): title = models.CharField(max_length=100, null=False, verbose_name="Titre") description = models.TextField(max_length=500, null=False, verbose_name="Description pour les partages sur les réseaux sociaux") subtitle = models.TextField(max_length=300, null=True, verbose_name="Sous-titre") text = RichTextUploadingField() tag = models.ManyToManyField(Tag, verbose_name="Tag") subcategory = models.ForeignKey(SubCategory, verbose_name="Sous-catégorie", blank=True, null=True) image = models.FileField(upload_to='media/articles/', validators=[validate_file_extension], blank=True, null=True, verbose_name="Image de présentation") image_description = models.CharField(max_length=100, null=True, verbose_name="Description pour cette image") image_legende = models.CharField(max_length=100, null=True, verbose_name="Légende pour cette images") author = models.ForeignKey(User, verbose_name="Auteur") published = models.BooleanField(default=True, verbose_name="Publié") date = models.DateTimeField(auto_now_add=True, auto_now=False, verbose_name="Date de création") update = models.DateTimeField(auto_now=True, verbose_name="Dernière modification") def get_absolute_url(self): return reverse('read', kwargs={'post':self.id, 'slug':slugify(self.title)}) def __str__(self): return self.title admin.py class ArticlesAdmin(admin.ModelAdmin): list_display = ('date', 'title', 'author', 'published', 'update') fieldsets = … -
How to handle async task with Django atomic transactions creating db entries
My system receives payload from another source. This payload contains items information, including brand and such. I save this payload inside a buffer. Buffers are processed async with Celery tasks. Based on the payload we create the entries or update them if necessary. This is done by using an atomic transaction, in which we create the Item, the Brand and Category. The issue I am running into is that it can be possible that two buffers both have an Brand which is not yet created in the db. Using update_or_create inside the atomic block I check whether it already exists. Since both buffers are ran async at almost exactly the same time both think the Brand does not yet exists. This means both of them try to create the Brand yielding me the following database error: postgres_1 | ERROR: duplicate key value violates unique constraint "catalogue_brand_name_key" postgres_1 | DETAIL: Key (name)=(Bic) already exists. postgres_1 | STATEMENT: INSERT INTO "catalogue_brand" ("id", "created_date", "modified_date", "name") VALUES ('c8e9f328-cee7-4b9b-ba45-268180c723d8'::uuid, '2018-12-28T08:08:51.519672+00:00'::timestamptz, '2018-12-28T08:08:51.519691+00:00'::timestamptz, 'Bic') Since this is a db-level exception I am unable to catch it inside my code and the buffer will be marked as completed (since no exception inside the code was given). The … -
As you see, when I try to pull the api of a web page, I catch a bug
Because of some demand functions, I try to call the interface once a minute, but different devices will trigger the same bug at different times. I try to solve it, but I can't do anything about it.thanks! code: class ActorCloudAlertsNumberView(ListAPIView): """ get: """ def get(self, request, *args, **kwargs): try: last_time = request.GET['time'] except Exception: raise Error(errors.INVALID, 'xxxx', 'xxxx') page = '1' page_size = '100' ac_client = acc.ActorCloudClient.get_instance() # headers = {"Connection": "close", } # ac_result = ac_client.get(acc.AC_ALERTS_GET_URL.format(page=page, page_size=page_size), headers=headers) ac_result = ac_client.get(acc.AC_ALERTS_GET_URL.format(page=page, page_size=page_size)) if str(last_time) == 'null': full_number = ac_result.get('meta')['count'] return Response({'number': full_number}, status=status.HTTP_200_OK) try: last_time = datetime.strptime(last_time, '%Y-%m-%d|%H:%M:%S') except ValueError: raise Error(errors.PARSE_ERROR, 'xxxx', 'xxxx') ac_alerts_num = 0 for ac_alert in ac_result.get('items'): alert_time = ac_alert.get('startTime') alert_time = datetime.strptime(alert_time, '%Y-%m-%d %H:%M:%S') if last_time <= alert_time: ac_alerts_num += 1 else: break return Response({'number': ac_alerts_num}, status=status.HTTP_200_OK) error stack: ConnectionError at /api/v1/alerts/number HTTPConnectionPool(host='emqx.in.chinaopen.ai', port=80): Max retries exceeded with url: /api/v1/current_alerts?_page=1&_limit=100 (Caused by NewConnectionError(': Failed to establish a new connection: [Errno -3] Try again',)) Request Method: GET Request URL: http://xxxxx.ai/api/v1/alerts/number?time=null Django Version: 2.1.2 Python Executable: /usr/local/bin/python Python Version: 3.6.6 Python Path: ['/code/src/apps', '/code/src', '/usr/local/bin', '/usr/local/lib/python36.zip', '/usr/local/lib/python3.6', '/usr/local/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6/site-packages', '/code/src'] -
saving multiple images with different dimensions from a single ImageField in django models
How can I save multiple images with dimensions(eg: 10x10, 20x20, 30x30) into the "/media/" folder using a single models.ImageField() in django models? Thanks, Nitesh -
How to adapt java POJO generator for Django model with custom methods?
I am done with this tutorial which shows how to use textX to write a java POJO. I am thinking of adapting this to write Django model classes. The issue is when I have to add custom model methods to the Django model class. And then if I subsequently change the DSL, the generated model class will definitely remove the custom model methods. How to I cater for custom model methods if using textX to generate Django model classes? -
how to select html id which is assigned to Django variable in java script
I have an ID in html. This id is assigned to Django variable which contain ads ID. I want to add this ads ID to favorite list using local storage (cookies). Now, this ID is inside a loop and for every single ads will take different ID. The question is how to select the specific ID when the user click on that specific ID icons. Here is my code: {% for item in result %} <span id="favouriteBtn" style="color:#ccc" title="add this post to favorite list"> &#9734; </span> {% endfor %} THE ID SHOULD BE THIS WAY: id={{item.id}} Here is portion of javascript function: $('#favouriteBtn').click(function(){ currentAddFav(); I want to set the ID as : id={{item.id}} and be able to select specific id which has been clicked by the user. How can i do that? -
What is the best way to generate PDF from HTML (in bulk) and download all in zip file using Python(Django) or JavaScript?
For my site, I am looking for a solution that convert dynamic HTML pages to PDF. Actually, I've multiple reports to generate form HTML and I want it to be done on server-side and to be done in background(if possible), after that all the reports are downloaded in a single compressed file where all the reports are generated separately according to the template(HTML). -
Django Admin: How to Access to Logged-in User for Using It in Custom 'list_display' Field?
I want to create a hyperlink (custom field in display_list) and I have to use logged-in User's id as a part of query parameters in the link. Is there any solution for this? -
Android studio - Localhost connection File not found?
So I have been trying to make an authentication feature on my app where the users can login. I am trying to send JSON objects to my Django REST API so tha my users can get tokens. However, whenever after I press login with a valid user's credentials (me), my logcat throws a file not found exception to http://192.168.0.18:8000/token-auth/ even if I can access it in my browser. I am running my Django REST API through XAMPP in my macbook pro. My Android emulator is running in my Desktop. I was able to similar thing with my ReactJS app in my macbook pro where I can retrieve data from my Django REST API. I already placed <uses-permission android:name="android.permission.INTERNET" /> in my manifest.xml and it took care of my permission issue. Below are my codes: login.java public class Login extends AppCompatActivity { Button LoginButton; EditText uUserName, uPassWord; WSAdapter.SendAPIRequests AuthHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); //SetupHomeBtn = (ImageButton) findViewById(R.id.SetupHomeBtn); LoginButton = (Button) findViewById(R.id.LoginButton); uUserName = (EditText) findViewById(R.id.LoginUserBox); uPassWord = (EditText) findViewById(R.id.LoginPassBox); //AuthHelper = new WSAdapter().new SendDeviceDetails(); // Moves user to the main page after validation LoginButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // gets the username and … -
Social account adapter for allauth not working
I am trying to implement my own social adapter for AllAuth. However, it seems as if it doesn't recognize the adapter. I checked this by calling a print statement within the adapter class, but it does not execute. Here's what I have in my settings.py: SOCIALACCOUNT_ADAPTER = 'oauth.adapters.SocialAccountAdapter' Inside, oauth is a file named adapters and inside this file is a class called SocialAccountAdapter and looks like this: class SocialAccountAdapter(DefaultSocialAccountAdapter): def pre_social_login(self, request, sociallogin): if sociallogin.is_existing: return if 'email' not in sociallogin.account.extra_data: return try: email = sociallogin.account.extra_data['email'].lower() email_address = EmailAddress.objects.get(email__iexact=email) except EmailAddress.DoesNotExist: return account = User.objects.get(email=email).socialaccount_set.first() messages.error(request, "A " + account.provider.capitalize() + " account already exists associated to " + email_address.email + ". Log in with that instead, and connect your " + sociallogin.account.provider.capitalize() + " account through your profile page to link them together.") raise ImmediateHttpResponse(redirect('/accounts/login')) I have an email that I signed up with no social sign up, let's call it example@example.com Afterwards, I try to sign up with Facebook which also uses example@example.com as its email. I get an error that looks like this: DoesNotExist at /facebook/login/callback/ User matching query does not exist. Why doesn't my adapter work? -
Want to connect mongodb docker service with my django application
I want to create two docker services one is mongodb service another one is web service build using django. And i need that web-service (django app) which need to be connected to that mongodb docker service. but i dont know how to connect with mongodb docker service in my django application which is also a service running in a same docker swarm .`This is my docker-compose.yml: version: '3' services: mongo: image: mongo:latest command: mongod --storageEngine wiredTiger ports: - "27017:27017" restart: always environment: MONGO_INITDB_ROOT_USERNAME: root MONGO_INITDB_ROOT_PASSWORD: example web: build: . command: python3 manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" links: - mongo depends_on: - mongo Here i tried with mongoengine in settings.py of django application but failed MONGO_DATABASE_NAME = "reg_task21" MONGO_HOST = "mongo" mongoengine.connect(db=MONGO_DATABASE_NAME, host=MONGO_HOST,port=27017) -
Custom Attributes in Form Django
I want to add some custom attributes to field company_monthly_payment. My Generic View class CompanyCreateView(LoginRequiredMixin, generic.CreateView): model = Company fields = ['company_name', 'company_monthly_payment'] Custom Attribute before and after input field company_monthly_payment <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text">$</span> </div> <input type="text" class="form-control" aria-label="Amount (to the nearest dollar)"> <div class="input-group-append"> <span class="input-group-text">.00</span> </div> </div> Even i want to add aria-label to input field. Even i dont want to hardcore html code inside template -
Navbar Active won't change when clicking to another page
Navbar is being buggy. I wish to have the activate tab change as a user goes through the different pages. I am using a base template so I don't want to reproduce the navbar html/css for every single page so I believe javascript is the answer to my issue here. I've attempted to use some Jquery from another question, it unfortunately created a separate problem, I am not well versed with Jquery so I found it very difficult to fix the issue. This is the HTML <div class="container-fluid"> <a class="navbar-brand" href="#"><img src="{% static 'images/sidespacer.png' %}"></a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li class="nav-item active"><a class="nav-link" href="/Spaces">Home</a></li> <li class="nav-item"><a class="nav-link" href="/Spaces/space">Spaces</a></li> <li class="nav-item"><a class="nav-link" href="/Spaces/pricing">Prices</a></li> <li class="nav-item"><a class="nav-link" href="/Spaces/howitworks">How it Works</a></li> <li class="nav-item"><a class="nav-link" href="#">Contact</a></li> {% if user.is_authenticated %} <li class="nav-item"><a class="nav-link" href="{% url 'logout' %}">Log out {{user.username}}</a></li> {% else %} <li class="nav-item"><a class="nav-link" href="{% url 'signup' %}">Sign Up</a></li> <li class="nav-item"><a class="nav-link" href="{% url 'login' %}">Login</a></li> {% endif %} </ul> </div> </div> </nav> This is the current Jquery $(document).ready(function() { $( ".nav-item" ).bind( "click", function(event) { event.preventDefault(); var clickedItem = $( this ); $( ".nav-item" ).each( function() { $( this ).removeClass( "active" … -
user profile system data base design with multiple users and a admin dashboard
i'm new to database design.i want to design a data base for a notes taking app which has a user profile system with multiple users and a admin dashboard who keeps track of all users.help me creating a schema design for this data base for these and also for login ,sign up and i'm trying to design a notes taking app and consider there are future version requirements like sharing the notes and notifying a user if a notes is shared with him and the user should be able to manage his profile with in the system -
Django 2.1 unable to detect my new models during makemigrations
I've been searching on how to fix this. These are the things that i tried before posting this question. Unfortunately none of them worked. Added the app name (myapp) in setting's INSTALLED_APPS list, it Didn't work. Tried adding just the app name, but it didn't work as well. So now I'm using the full dotted path (myapp.settings.MyappConfig) just to be safe. Deleted __pycache__/*.pyc When I run $ python manage.py showmigrations, i can see that "myapp" is recognized but there's no migration. I've placed all my models in a folder to organize it. See my folder structure below. What am I missing here? This is so frustrating, please help me. Thanks in advance! mysite |__myapp | |__ models | | |__ project.py | | | |___apps.py | |__mysite |__ settings.py -
NameError at /Signup/ name 'all_users' is not defined
from django.http import HttpResponse from .models import signUp from django .template import loader def index(request): template = loader.get_template("Signup/signup.html") context = { 'all_users': all_users, } return HttpResponse(template.render(context, request)) -
Model-First approach options in Python ORMs(and Code-First)
I have a project that contains work with complex excel file(bank balance sheet), db and web interface. Naturally I would like to design diagram visually to autogenerate sql(Model-First approach in Entity framework), but I was rather surprised and frustrated not to find design surface options in python ORMs. Is it the case and I left with Code-First option only? That will take a lot of time and effort in my case. I will need to visualise my data structure anyway somehow(at least on paper). In my case it's all about fast development and proof of consept. If Django orm and SQLalchemy lack design surface(I hope I'm wrong), what do Python programmers do usually in my case? If they always start with classes that's ok(maybe), but please let me know, because I need to know for sure that Model-first is not used in Python, so my stupid anxiety will go away.