Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I configure my model such that my generated Django migration doesn't result in an error?
I'm using Django and Python 3.7. When I run my command to generate a migration ... (venv) localhost:web davea$ python manage.py makemigrations maps Migrations for 'maps': maps/migrations/0003_auto_20200416_1017.py - Alter field name on cooptype - Alter unique_together for cooptype (0 constraint(s)) The generated migration looks like ... # Generated by Django 2.0 on 2020-04-16 15:17 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('maps', '0002_auto_20200401_1440'), ] operations = [ migrations.AlterField( model_name='cooptype', name='name', field=models.CharField(max_length=200, unique=True), ), migrations.AlterUniqueTogether( name='cooptype', unique_together=set(), ), ] However, running the migration results in an error ... (venv) localhost:web davea$ python manage.py migrate maps System check identified some issues: WARNINGS: ?: (mysql.W002) MySQL Strict Mode is not set for database connection 'default' HINT: MySQL's Strict Mode fixes many data integrity problems in MySQL, such as data truncation upon insertion, by escalating warnings into errors. It is strongly recommended you activate it. See: https://docs.djangoproject.com/en/2.0/ref/databases/#mysql-sql-mode Operations to perform: Apply all migrations: maps Running migrations: Applying maps.0003_auto_20200416_1017...Traceback (most recent call last): File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 71, in execute return self.cursor.execute(query, args) File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/MySQLdb/cursors.py", line 209, in execute res = self._query(query) File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/MySQLdb/cursors.py", line 315, in _query db.query(q) File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/MySQLdb/connections.py", line 239, in … -
Is there any issue about installation of Django?
enter image description here Hello all ,I am creating my very first project in django using VS code editor its very basic but giving error unexpected indent pylint error -
Sidebar content list is coming below profile image in django webpage bootstrap 4
Everything was right until I used profile pic in webpage. The sidebar content which was on the right of webpage is now coming below profile pic. If I use float-right it comes to the right but still below profile pic. I'm using sublime 3 for this django project. My code for profile pic is- {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <div class="media"> <img class="rounded-circle" width="100px" src="{{ user.profile.image.url }}"> <div class="media-body"> <h2 class="account-heading">{{ user.username }}</h2> <p class="text-secondary">{{ user.email }}</p> </div> </div> <!-- FORM HERE --> </div {% endblock content %} And that for sidebar content is- <div class="col-md-4"> <div class="content-section"> <h3>Our Sidebar</h3> <p class='text-muted'>You can put any information here you'd like. <ul class="list-group"> <li class="list-group-item list-group-item-light">Latest Posts</li> <li class="list-group-item list-group-item-light">Announcements</li> <li class="list-group-item list-group-item-light">Calendars</li> <li class="list-group-item list-group-item-light">etc.</li> </ul> </p> </div> </div> And my webpage actually looks like this- "PROF username ILE email PIC" Sidebar content Sorry I couldn't upload image -
What is the purpose of app_name in urls.py in Django?
When include()ing urlconf from the Django app to the project's urls.py, some kind of app's name (or namespace) should be specified as: app_namespace in include((pattern_list, app_namespace), namespace=None) in main urls.py or app_name variable in app's urls.py. Since, I guess, Django 2, the second method is the preferred one Although I copy-pasted first function signature from Django 3 documentation. But that's not the main point. My current understanding of namespace parameter of include() is that it's what I use when using reverse(). What is the purpose of app_name in app's urls.py or app_namespace in main urls.py? Are these exactly the same thing? How is it used by Django? Existing questions (and answers) I've found here explain HOW I should specify it rather than WHY. -
Create auto increment number for every user when ordering
This is the most asked question, but I am failing to accomplish this task. I have a Book model with book_history field like class Book(Models): customer = models.ForeignKey(Customer) book_history_number = models.CharField(max_length=120) def _get_book_customer_id(self): b_id = self.customer num = 1 while Book.objects.filter(customer=b_id).exists(): num += 1 return cus_ord_id def save(self, *args, **kwargs): if not self.book_history_number: self.book_history_number = self._get_book_customer_id() my objective is to increment by when a user book something for example I have A and B users and A booked smth and book_history_number should be 1 next time it should 2 like this: A: 1, 2,... n because A booked two times B: 0 B did not booked but if B user did it would be 1. with above code I cannot able to solve this problem. Any help please -
How can I move my django project to another directory?
There have been questions asked about similar things, but over 4 years ago. I'm sure those things don't apply because I have tried them and they didn't work. I was working in a directory where I had my virtualvenv and django project but I wanted to create a new folder and move them to that new folder: old path: dev/python/django/ new path: dev/python/django/blog I then activated my virtualenv and moved into the directory where the manage.py file was and, as I always have, ran python manage.py runserver however it shot out an error: File "manage.py", line 16 ) from exc ^ SyntaxError: invalid syntax I haven't changed anything in my manage.py file, in fact, I didn't change anything since the last time I ran this project. Since I moved the project and the virtualenv attached to it, it no longer runs. I tried reinstalling django in my env, but it says it already exists. I tried running python3 manage.py runserver as some other posts suggest, but that doesn't work either. Same error... What am I missing? All of the paths in my files are from the BASE_DIR variable and no paths are absolute. What am I missing? How can I … -
Problems of object grabbing
I want to add course.tutor.add(self.request.user) to the function below but don't know how to do that, because i don't know how to do without slug and so on class FormWizardView(SessionWizardView): template_name = 'courses/create_course.html' file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT,'courses')) form_list = (CourseForm1,CourseForm2,CourseForm3,CourseForm4) def done(self, form_list, **kwargs): instance = Course() for form in form_list: for field, value in form.cleaned_data.items(): setattr(instance, field, value) instance.save() return redirect('courses:my_courses',username=self.request.user.username) -
How to add request.session/user data to Postman POST?
A web request POST has request.user and request.session as the follows that was logged on server. It's easy to add parameters and body etc. How to add the request.session/user data (or simulate ?) to Postman POST? request.user: { id: 1061, username: jhon, name: 'jhon, smith' } request.session: {'case_id': 777, 'profile_id': u'101'} -
Connecting Serializers in Django 'int' object has no attribute 'split'
This is the first time I started working with APIs in Django, and I'm building a web app that processes a lot of changes very quickly. After much research, I decided to use serpy instead of the DRF for the serializers, but I'm having trouble connecting multiple serializers. I don't think this is a serpy issue, but just a general lack of knowledge of working with serializers in general. I have a Membership model and a Project model, and when I request the Project model, I want to see the active Memberships associated with that project. Pretty simple stuff right. Here are my serializers: ###################################################### # Memberships ###################################################### class MembershipSerializer(LightWeightSerializer): id = Field() user = Field(attr="user_id") project = Field(attr="project_id") role = Field(attr="role_id") is_admin = Field() created_at = Field() user_order = Field() role_name = MethodField() full_name = MethodField() is_user_active = MethodField() color = MethodField() photo = MethodField() project_name = MethodField() project_slug = MethodField() is_owner = MethodField() def get_photo(self, obj): return get_photo_url(obj['photo']) def get_role_name(self, obj): return obj.role.name if obj.role else None def get_full_name(self, obj): return obj.user.get_full_name() if obj.user else None def get_is_user_active(self, obj): return obj.user.is_active if obj.user else False def get_color(self, obj): return obj.user.color if obj.user else None def get_project_name(self, obj): return … -
No reverse match error on redirect (django)
I encountered a NoReverseMatch at /login Reverse for '' not found. '' is not a valid view function or pattern name. template <form action="" method="post"> {% csrf_token %} <input type="text" name="username" placeholder="Username"><br> <input type="password" name="password" placeholder="Password"><br> <input type="submit"> </form> views.py def loginuser(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username = username,password=password) if user is not None: auth.login(request, user) return redirect(request,'home') else: messages.info(request,'Invalid username or password') return render(request,'login.html') urls.py from django.urls import path from accounts import views urlpatterns = [ path('', views.signup, name='signup'), path('login',views.loginuser,name='login'), path('logout',views.logout,name='logout'), path('home', views.home, name='home'), ] -
back-end architecture to integrate with Cube.js
I'm looking for advise choosing a back-end architecture for a web app. In the app, users upload tabular data from multiple files. Their data is then processed, aggregated and visualized. Data is private and each user has their own dashboard. I believe Cube.js is an excellent choice for the dashboard, but I am wondering what back-end web framework I should integrate it with. I have experience of Django, but would use Express if it had significant advantages. Thanks for any advice! -
I am getting the error below every time I run the code and I do not know what is wrong
I am getting the error below. Any help is appreciated. I am probably missing something very important from the documentation. Kindly point out my mistake if you see it and enlighten me about many to many relations from Django. From the error presented does it mean that the .add() function cannot be used on querysets? Traceback Internal Server Error: /7/ Traceback (most recent call last): File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\music\songs\views.py", line 141, in Playlist_Add playlist.song.add(song) File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\fields\related_descriptors.py", line 926, in add self._add_items(self.source_field_name, self.target_field_name, *objs) File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\fields\related_descriptors.py", line 1073, in _add_items '%s__in' % target_field_name: new_ids, File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py", line 844, in filter return self._filter_or_exclude(False, *args, **kwargs) File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py", line 862, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\query.py", line 1263, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\query.py", line 1287, in _add_q split_subq=split_subq, File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\query.py", line 1225, in build_filter condition = self.build_lookup(lookups, col, value) File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\query.py", line 1096, in build_lookup lookup = lookup_class(lhs, rhs) File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\lookups.py", line 20, in __init__ self.rhs = self.get_prep_lookup() File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\fields\related_lookups.py", line 59, in get_prep_lookup self.rhs = [target_field.get_prep_value(v) for v in self.rhs] … -
How to get primary key of recently created record in django not the latest one
id = request.session['user-id'] Forum.objects.create(user_id=id, forum_name=self.name,tags=self.tags, description=self.desc,reply=0,status=0) Tags.objects.create(forum_id='?', tag=self.tags) How to get forum_id from recently created Forum object not the latest one forum_id? -
django multi tenant app: login and urls mapping best pra
I am struggling with sign in my tenants into their schemas. the login system works well. my issue is in the URLs organization. I wish that user sign in in the public domain and then get redirect to their own domain but that if they directly try to access their domains, it raises an error saying that they are not logged in. Currently, what happens is that it runs into a circle and never change page. I am fairly new to this and I am was wondering if someone has an idea about best practices in urls mapping for multi tenant app. public urls: urlpatterns = [ path('register', registration), path('login', login_view) ] urls urlpatterns = [ path('upload', login_required(Getfiles.as_view())), path('upload/Home', HomeView.as_view()), path('upload/Home/items', ItemPage.as_view()), ] Thank you in advance -
has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request
Angular 8, Django 3. I am unsure why I am getting this error ONLY with a certain angular component. My entire web application works fine and I am accessing the backend and pulling data in all parts of the app with the exception of one component that keeps throwing this error. I have disabled CORS, i have the chrome plugin disabling CORS, i have the corsheaders package installed with CORS_ORIGIN_ALLOW_ALL = True. this is the component: DashboardComponent export class DashboardRestaurantComponent implements OnInit { constructor( private authenticationService: AuthenticationService, private restaurantservice : RestaurantService ) { this.authenticationService.currentUser.subscribe(x => this.user = x) } user; restaurants; ngOnInit() { this.get_owner_restaurants() } get_owner_restaurants(){ this.restaurantservice.getownerrestaurants().subscribe(x => this.restaurants = x) } } RestaurantService getownerrestaurants(): Observable<Restaurant[]>{ return this.http.get<Restaurant[]>(this.ownerrestaurantsUrl2) } DjangoView class RestaurantList(generics.ListAPIView): serializer_class = RestaurantSerializer queryset = Restaurant.objects.all() In other parts of the app I am accessing the same DjangoView with no problem, I dont get why all of the sudden I am having an issue.. -
how to import and display csv file in django project
I have two different project and one of them is a django project . I want to import the csv file and display it in html template . but since I'm a beginner I read a lot of articles and none of them helped me ? -
Deploy Django website to alias on ubuntu 18.04
I have a django application that I need to deploy. The hosting server runs on Ubuntu 18.04. My problem is that I don't have a dedicated domain, but I need to "append" the app to a domain already in use (i.e. I have www.mydomain.com that contains my not-django reseach group website, and I need my django app to be available at www.mydomain.com/new-content). Now my problem is how to write/modify the file on /etc/apache2/sites-available/. For a normal site I would do: Alias /face-perception /var/www/new-content/ <Directory /var/www/new-content> Order allow,deny Allow from all Options -Indexes </Directory> But online guides suggest me to have a structure like the following: <VirtualHost *:80> ServerAdmin webmaster@mydomain.com ServerName mydomain.com ServerAlias www.mydomain.com WSGIScriptAlias / var/www/mydomain.com/index.wsgi Alias /static/ /var/www/mydomain.com/static/ <Location "/static/"> Options -Indexes </Location > </VirtualHost > Is there any way I can achieve this? I tried combining the two in different ways but always ended up with being unable to restart apache or with a 404 error. Ps: for now I am not considering the option to use a dedicated domain as trough my institution it requires time and we need the app online as soon as possible to work remotely. -
Using Boot Strap To Insert New Rows In Comment Section (Python - Django)
I tried to use <div class="row">after looking at the Bootstrap material but the comments still appeared to be rendering in a series of columns and not rows. <article class="media content-section"> <!-- comments --> <h2>{{ comments.count }} Comments</h2> {% for comment in comments %} <div class="row"> <div class="media-body "> <a class="mr-2" href="#">{{ comment.name }}</a> <small class="text-muted">{{ comment.created_on|date:"F d, Y" }}</small> </div> <p class="article-content">{{ comment.body }}</p> </div> {% endfor %} -
How to make a video chat in DJango?
I want to make an app in django to make video calls with it. I have searched a lot, but I didn't find any good source or any example for it. Is there any api that we can use for making video calls? Or how we can do this simply? I read about webRTC and 0MQ but I didn't get the whole idea how I can do this? Thank you in advance. -
Django view isn't called while performing an AJAX call
I'm trying to setup an AJAX call in order to call a Django view, perform some calculations and then return the ouput into my html page. Unfortunately, the view doesn't seem to be reached. Not sure what is wrong but I have very limited AJAX experience. The idea is that when my slider sees a change in value, it triggers the AJAX call. The trigger seems to work as it displays my alert pop-up. But that's it, nothing else happens. Could you please help? Here is my html/AJAX code: <div class="slider-wrapper"> <span>Option 1 Imp. Vol.</span> <input class="toChange" id="rangeInput" name="rangeInput" type="range" value="{{Sigma}}" min="0" max="150" step="0.1" oninput="amount.value=rangeInput.value" /> <input class="toChange" id="amount" type="number" value="{{Sigma}}" min="0" max="150" step="0.1"oninput="rangeInput.value=amount.value" /> </div> <label>Ajax Test:</label> <span id="Atest"> <script type="text/javascript"> function inputChange () { var Sigma = document.getElementById("rangeInput").value; alert(); $.ajax({ url: '/finance/templates/optionstrategies/', type: 'POST', data: {'Sigma': Sigma, }, //dataType: "json", success: function(optionVal) { document.getElementById("Atest").innerHTML = optionVal; } }); } $(".toChange").change(inputChange); </script> And here is my view.py: def optionStrategies(request): errors='' if request.method == 'POST' and request.is_ajax(): print('ok') Type = request.POST.get('Type') V = request.POST.get('V') Q = request.POST.get('Q') S = request.POST.get('S') K = request.POST.get('K') r = request.POST.get('r') t = request.POST.get('t') Sigma = request.POST.get('rangeInput') BS = BlackScholes(Type = 'Vanilla', S = float(S), … -
Django redirect does nothing
I am currently try to redirect from one view to another view. However, nothing happens, the token gets printed and that's it. class SocialLoginInvUserAPIView(APIView): permission_classes = [AllowAny] @staticmethod def post(request): print(request.data["token"]) return redirect("login/") Here is the login url: url(r'login/$', LoginInvUserAPIView.as_view(), name='auth_user_login'), -
Django - Filtering Field In DeailView
Hi all, I've been building a Django app that allows users to stream and download music. However, there is one issue that I'm having with the artists profile pages; I'm trying to request the songs by the artist only in a DetailView as I'm treating it like a blog system. Is this possible in a DetailView? Or do I need to make a filter? I've been searching the web for days now and didn't really understand what I can do or how to get the specific data field from the model. Any help or guidance would be highly appreciated! class musicartist(DetailView): model = MusicArtist template_name = 'RS_MUSIC/artist.html' # override context data def get_context_data(self, *args, **kwargs): context = super(musicartist, self).get_context_data(*args, **kwargs) # add extra field current_band = MusicItems.objects.all().filter(artist=MusicArtist.title)[:1] context["songs"] = MusicItems.objects.filter(artist=MusicArtist.objects.all().filter(title=current_band)[:1]) return context -
Django form submission without reloading page
I have a django register form .On the event of an invalid form submission, page is reloading.I need to stay on that same page if the data entered is invalid. -
making dynamic template of the dictionary passed to the django
I'm working on coc api in which i want to display player information on the webpage and there are lot's of field in the response i want to display the result dynamically when any dictionary passed to the template it should arrange itself views.py: token = 'token' timeout = 1 api = CocApi(token, timeout) data = api.labels_clans() def index(request): data = api.players("#PJVVUCCJG") return render(request,"index.html", data) tried to print hierarchically: code: from cocapi import CocApi def getall(dictn, lvl=0): sep = " " for key, item in dictn.items(): if isinstance(item, list): print(lvl * sep + key + ":") for it in item: getall(it, lvl=lvl+1) print("") continue if isinstance(item, dict): print(lvl * sep + key + ":") getall(item, lvl=lvl + 1) continue print(lvl * sep + str(key) + ":" + str(item)) token = 'token' timeout = 1 api = CocApi(token, timeout) data = api.players("#PJVVUCCJG") getall(dict(data)) print(len(data)) print(data) Output: tag:#2U2RCLYLL name:killer townHallLevel:10 expLevel:115 trophies:1165 bestTrophies:2826 warStars:178 attackWins:72 defenseWins:10 builderHallLevel:7 versusTrophies:2422 bestVersusTrophies:2444 versusBattleWins:509 role:coLeader donations:70 donationsReceived:953 clan: tag:#LLQ0CULQ name:Thê BèäTlës clanLevel:11 badgeUrls: small:https://api-assets.clashofclans.com/badges/70/exHkY8LEWfWyugWdyfVDCvns2J7TgIoUgurt6DUFg4Q.png large:https://api-assets.clashofclans.com/badges/512/exHkY8LEWfWyugWdyfVDCvns2J7TgIoUgurt6DUFg4Q.png medium:https://api-assets.clashofclans.com/badges/200/exHkY8LEWfWyugWdyfVDCvns2J7TgIoUgurt6DUFg4Q.png league: id:29000006 name:Silver League I iconUrls: small:https://api-assets.clashofclans.com/leagues/72/nvrBLvCK10elRHmD1g9w5UU1flDRMhYAojMB2UbYfPs.png tiny:https://api-assets.clashofclans.com/leagues/36/nvrBLvCK10elRHmD1g9w5UU1flDRMhYAojMB2UbYfPs.png medium:https://api-assets.clashofclans.com/leagues/288/nvrBLvCK10elRHmD1g9w5UU1flDRMhYAojMB2UbYfPs.png achievements: name:Bigger Coffers stars:3 value:11 target:10 info:Upgrade a Gold Storage to level 10 completionInfo:Highest Gold Storage level: 11 village:home name:Get those … -
After comand ACTIVATE django activates but shows only half name of the folder
My Django project is in folder Django-projects. When I activate it the folder name becomes in round bracket, but only in one in the begining please look at printscrin. enter image description here