Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I'm using python-social-auth but my app isn't logging out when the user logs out of Google
I have python-social-auth working to authorize my app and everything works great. I can log into my app via OAuth2 and log out via typical Django logout. My problem: if a user logs out of Google (from GMail, for example), it does not log me out of my Django app. I am still authorized as the Google user even though Google is logged out. I have tried refreshing tokens via the load strategy below to "force" a check to make sure Google is still logged in and that isn't working. social = request.user.social_auth.get(provider='google-oauth2') access_token = social.get_access_token(load_strategy()) social.refresh_token(load_strategy()) I feel like I'm going down the wrong road. All I want to do is validate that Google is logged into still so I can consider my OAuth2 session valid. Is there a way to do this integrity check? What am I doing wrong or do I need to do? My research so far suggests what I want is not even possible - I don't like that answer so hoping for a different one here. -
How can i create this type of Django Admin (as shown in the pic)
Chick Here for the Pic..... This is the Admin template, here the Model options are on left side and the content stored in the model is on right side. -
Trouble rendering a variable in Django
I'm trying to "create" a variable and render it in my template but for some reason I can't manage to do it. Here's my view.py: def test(request): person = {'firstname': 'Craig', 'lastname': 'Daniels'} weather = "sunny" context = { 'person': person, 'weather': weather, } return render(request, 'home/dashboard.html', context) and in my template dashboard.html : <h1>Hi {{ person.firstname }} {{ person.lastname }}</h1> Any idea on what I'm doing wrong? -
I can't delete users from my app in Django
I am developing a webpage for elderly people in Django for my internship. I received some code already done from another coworker but for some reason when I try to delete users from the /admin site it gives me and error. In addition, I only have one form to register and login in the webpage but it gives another error. login view: def login_view(request): if request.user.is_authenticated: return redirect(reverse('portada')) mensaje = 'El usuario no estaba registrado' if request.method == 'POST': username = request.POST.get('username') dia = request.POST.get('dia') mes = request.POST.get('mes') year = request.POST.get('year') password = dia + mes + year + 'year' user = authenticate( username=username, password=password) if user is not None: if user.is_active: login(request, user) return redirect(reverse('portada')) else: return render(request, 'accounts/login.html', {'error_message': 'Your account has been disabled'}) else: mensaje = 'Se va a registrar un usuario' form = RegistroUserForm(request.POST, request.FILES) if form.is_valid(): cleaned_data = form.cleaned_data dia = form.cleaned_data['dia'] mes = form.cleaned_data['mes'] year = form.cleaned_data['year'] password = dia + mes + year + 'year' user_model = User.objects.create_user(username=username, password=password) user_model.save() user_profile = UserProfile() user_profile.user = user_model user_profile.save() username = request.POST.get('username') dia = request.POST.get('dia') mes = request.POST.get('mes') year = request.POST.get('year') password = dia + mes + year + 'year' user = authenticate(username=username, password=password) if … -
Django Foreign Key to Filtered Object got errors: django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet
I have problem that i never face before. I have custom user model on models.py class User(AbstractUser): username = models.CharField( max_length=50, unique=True) email = models.EmailField(_('email address'), unique=True) phone = models.IntegerField(_('phone number'), unique=True, blank=True, null=True) these users associated with Groups : maker, checker, signer >>> print(Group.objects.all()) <QuerySet [<Group: maker>, <Group: checker>, <Group: signer>]> in other app called cleaning, I want have an object that associated with these users filtered by each group. So in my cleaning app models.py User = get_user_model() user_maker = User.objects.filter(groups__name='maker') user_checker = User.objects.filter(groups__name='checker') user_signer = User.objects.filter(groups__name='signer') class cln_daily(models.Model): . . . user_maker = models.ForeignKey(user_maker,on_delete=models.CASCADE, blank=True, null=True) user_checker = models.ForeignKey(user_checker,on_delete=models.CASCADE, blank=True, null=True) user_signer = models.ForeignKey(user_signer,on_delete=models.CASCADE, blank=True, null=True) but then I got an error that said django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. . . . File "D:\gtipwa\lib\site-packages\django\apps\registry.py", line 141, in check_models_ready raise AppRegistryNotReady("Models aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. any idea how to use filtered object in foreign key?? I'm not sure but i think the problem is caused by double underscore in object filter. I have no idea how to fix them. -
Wagtail internal link urls arent working properly
in my rich body text fields, when an internal page is used for a link, the url that gets attached to the a tag is "https//example.com/example", ie it's missing the colon and the link doesnt work. I get the error "https's server ip address could not be found". any idea why it is doing this? thanks -
Django: Inject code post pk/id generation and before save in DB
TL;DR: Is there a way to inject code post pk / id generation but before the object is saved in the db? Hello, So I am currently working on duplicating django objects. I have a duplicate function which enforces new object generation upon saving by setting pk and uid to None on a deep clone of my object: def gen_uuid() -> str: """Return a str representation of a uuid4""" return str(uuid4()) class Entry(PolymorphicModel): """Base class providing a custom lock permission, a name and a uid to replace Django's default id DB column.""" uid = models.CharField( unique=True, primary_key=True, db_index=True, default=gen_uuid, max_length=36, help_text="Object's primary key, it cannot be enforced and will be generated randomly. " "Example: c8daa3ac-3dd0-44e9-ba2a-b0cbd1c8d8ae.", ) name = models.CharField(max_length=128, help_text="Name of the object.") folder = models.ForeignKey( Folder, on_delete=models.CASCADE, default=None, null=True, blank=True, related_name="files", help_text="Primary key to the folder containing the object.", ) content = JSONField( default=dict, blank=True, help_text="JSON representation of the graph." ) def save(self, *args, **kwargs): """Handles entry saving and duplicate management This function is overridden so the models can be created with the name. This function does not fill missing duplicate numbers. It will create duplicates in such pattern: entry_name entry_name (2) entry_name (3) """ # Does some stuff... … -
No Response after calling the API
I am working on a project, where I am making a call to the API https://apis.justwatch.com/content/titles/en_IN/popular?body=%7B%22page_size%22:5,%22page%22:1,%22query%22:%22The%20Irishman%22,%22content_types%22:[%22movie%22]%7D I am making the call to the API, using the code import requests data = requests.get('https://apis.justwatch.com/content/titles/en_IN/popular?body=%7B%22page_size%22:5,%22page%22:1,%22query%22:%22The Irishman%22,%22content_types%22:[%22movie%22]%7D') print(data.json()) But, today when I made the call to the same API, it gave me None Response, and when I tried making the same API call on my browser, it worked fine. I made a minor change, that while making a call to the API, I added a header specifying the browser details, like header = { "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:72.0) Gecko/20100101 Firefox/72.0" } and now the code is working fine. Can anybody tell me why it is so, that the request was working fine earlier but why I had to specify the header now ? -
SAVE CHECKED STATE OF CHECKBOX AFTER CLOSING THE WEBSITE
I'm working on a django project in which i have a list of checkboxes. I'd like to know how do i save the fact that the checkbox has been checked after i close the website? the checkbox's label are the values of a Model that i created. As database i'm using the default one given by django, sqlite3. here's a little snippet of my code: <ul class="list-group list-group-flush"> <div class="form-check"> <input class="form-check-input" type="checkbox" value="" id="flexCheckDefault"> <label class="form-check-label" for="flexCheckDefault"> {{project.description}} </label> .... </ul> -
Make, migrate model programmatically, and reload / repopulate django application's new settings / configurations
I am making a model programmatically using the following code: modelObj = type(m.get("name"), (models.Model,), m.get("attrs")) After that I am trying to run the makemigrations, migrate, and autoreload command using the following code. def migrate_and_reload(): management.call_command("makemigrations") lm = MigrationRecorder.Migration.objects.filter(app=modelObject._meta.app_label).last() management.call_command("migrate", modelObject._meta.app_label, lm.__dict__.get("name"), "--database==test") from django.utils import autoreload autoreload.restart_with_reloader() But: And, get the Message from autoreloader that the server port is already use If I comment the autoreloader then Migration is not run into the database. However, Makemigration works and a migration file is created in the app's migration folder) My basic goal is to register the dynamic model programmatically, make respective migrations (handle any errors if there), migrate it to Db, and reload the server I will prefer not to reload the server, but seems like I have no other options to reload all the settings or populate the configurations in Django 3.0.3. Any help is welcome -
Django use rowspan in DataTables
I have a problem with DataTables in Django. I want to use DataTables to show some information, and use rowspan to group information by position. Look at the code below. <table id="example" class="display" style="width:100%"> <thead> <tr> <th colspan="2">HR Information</th> <th colspan="3">Contact</th> </tr> <tr> <th>Position</th> <th>Salary</th> <th>Office</th> <th>Extn.</th> <th>E-mail</th> </tr> </thead> <tbody> {% for x in pos %} {% for y in emp %} <tr> {% if forloop.first %} <td rowspan={{emp|length}}>{{ y.position }}</td> {% endif %} <td>{{ y.salary}}</td> <td>{{ y.office}}</td> <td>{{ y.extn}}</td> <td>{{ y.mail}}</td> </tr> { % endfor %} { % endfor %} </tbody> <tfoot> <tr> <th>Position</th> <th>Salary</th> <th>Office</th> <th>Extn.</th> <th>E-mail</th> </tr> </tfoot> </table> But I got "Uncaught TypeError: Cannot set property '_DT_CellIndex' of undefined" Could you explain to me, how can I resolve this issue? Have you any idea? -
Why is the data in the serializer not shown in django?
I'm going to make four serializers and put three serializers in one serializer. However, only one of the three serializers operates normally and the other two do not. I made the structure of the three serializer almost identical, but I don't understand if only one works. Please help me solve the problem. JSON { "pk": 1, "author": { "username": "username", "email": "email", "profile": "image_link" }, # AuthorSerializer is worked "title": "title1", "text": "text1", "view": 0, # ImageSerializer is not worked "like_count": 0, # LikerSerializer is not worked "comment_count": 0, "tag": "hash tag", "created_at": "time" } serializers.py class AuthorSerializer (serializers.ModelSerializer) : profile = serializers.ImageField(use_url=True) class Meta : model = User fields = ('username', 'email', 'profile') class ImageSerializer (serializers.ModelSerializer) : image = serializers.ImageField(use_url=True) class Meta : model = Image fields = ('image', ) class LikerSerializer (serializers.ModelSerializer) : id = serializers.IntegerField(source='liker.pk') class Meta : model = Like fields = ('id', ) class PostSerializer (serializers.ModelSerializer) : author = AuthorSerializer(read_only=True) image = ImageSerializer(read_only=True, many=True) like_count = serializers.ReadOnlyField() liker = LikerSerializer(read_only=True, many=True) comment_count = serializers.ReadOnlyField() class Meta : model = Post fields = ('pk', 'author', 'title', 'text', 'image', 'view', 'like_count', 'liker', 'comment_count', 'tag', 'created_at') def create (self, validated_data) : images_data = self.context['request'].FILES post = Post.objects.create(**validated_data) for … -
Issue with forms.ModelForm and ForeignKey
I am writting ToDo application with user login possibility. I want to do that, each user can see his own individual task-list. Problem - I can see the particular tasks for each user after login, but I can not add task via form in my app after adding ForeignKey to my TaskModel. I can only add task in admin panel Should I add ForeignKey - query to my form somehow? Model: from django.db import models from django.contrib.auth.models import User class Task(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=500) created_time = models.DateTimeField(auto_now_add=True) status = models.BooleanField(default=False) def __str__(self): return self.title Form: from django.contrib.auth.models import User class TaskForm(forms.ModelForm): class Meta: model = Task fields = '__all__' class CreateAccount(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] View: def tasks_list(request): tasks = Task.objects.filter(owner=request.user) form = TaskForm() if request.method =='POST': form = TaskForm(request.POST) if form.is_valid(): form.save() return redirect('/') context = { 'tasks': tasks, 'form': form, } return render(request, 'todo/base.html', context) -
MultiValueDictKeyError, when submitting the form
I am new to django and faced an unpleasant problem that I cannot solve for a couple of days, please help.Everything works for me for two forms, but when I add a third, the third form does not work, and the form with a page change is very important to me. How can I fix the error: ""? Exception Type: MultiValueDictKeyError Exception Value: 'ProfileUpdateForm-valuta' Exception Location: C:\Users\Maxim\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\utils\datastructures.py, line 78, in __getitem__ file views.py: #from django.contrib.auth.views import PasswordChangeView from django.contrib.auth.forms import PasswordChangeForm class ProfilePage(UpdateView): model=Profile template_name="market/profile.html" form_class=UserUpdateForm second_form_class= ProfileUpdateForm third_form_class=PasswordChangeForm def get_success_url(self): obj=Profile.objects.get(user__username=self.object) return reverse_lazy('profile',kwargs={'slug': obj.slug},) def get(self, request, *args, **kwargs): self.object = get_object_or_404(Profile,slug=self.kwargs['slug']) ctx = self.get_context_data(**kwargs) return self.render_to_response(ctx) def get_context_data(self, **kwargs): ctx = super(ProfilePage,self).get_context_data(**kwargs) ctx['UserUpdateForm'] = self.form_class( prefix='UserUpdateForm', data = self.request.POST if bool(set(['UserUpdateForm-submit']).intersection(self.request.POST)) else None, instance=self.request.user, ) ctx['ProfileUpdateForm'] = self.second_form_class( prefix='ProfileUpdateForm', data = self.request.POST if 'ProfileUpdateForm-submit' in self.request.POST else None, files = self.request.FILES if 'ProfileUpdateForm-submit' in self.request.POST else None, instance=self.request.user.profile, ) ctx['PasswordChangeForm'] = self.third_form_class( prefix='PasswordChangeForm', data = self.request.POST if 'PasswordChangeForm-submit' in self.request.POST else None, user=self.request.user, ) return ctx def post(self, request, *args, **kwargs): self.object = Profile.objects.get(user__username=self.request.user) ctx = self.get_context_data(**kwargs) recalculation_of_сost(self,ctx['ProfileUpdateForm']) if ctx['UserUpdateForm'].is_valid(): return self.form_valid(ctx['UserUpdateForm']) elif ctx['ProfileUpdateForm'].is_valid(): return self.form_valid(ctx['ProfileUpdateForm']) elif ctx['PasswordChangeForm'].is_valid(): return self.form_valid(ctx['PasswordChangeForm']) return self.render_to_response(ctx) -
Adding Inline HTML Code to Wagtail Rich Text Editor
I am using Wagtail CMS to build a website. I now want to embed a link with image into a paragraph. As I use the wagtail rich text editor I am wondering if there is any way to use inline html inside the rich text editor. Greetings -
IndexError at /user_upload/ (list index out of range for user model)
Even though the following code works, it throws the mentioned error. This is for importing data to user model. def user_upload(request): template = "client_admin/user_upload.html" data = User.objects.all() if request.method == "GET": return render(request, template, prompt) csv_file = request.FILES['file'] if not csv_file.name.endswith('.csv'): messages.error(request, 'THIS IS NOT A CSV FILE') data_set = csv_file.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) for column in csv.reader(io_string, delimiter=',', quotechar="|"): _, created = User.objects.update_or_create( username=column[0], first_name=column[1], last_name=column[2], email=column[3], ) context = {} return render(request, template, context) and user model is class User(AbstractUser): is_approved = models.CharField(max_length=80, choices=APPROVAL_CHOICES, default='t-2') is_member = models.BooleanField(default=False) is_premium_member = models.BooleanField(default=False) -
How to use DRF OrderingFilter inside @action view?
I can't find information on how to use OrderingFilter from django rest framework inside ModelViewSet @action, does anyone know how would i implement that? I have categories and those categories have products that i get with that action, i want to order those products with a query string. Basically i would need to know how to use it on a queryset, but i cant find any info about that. Example url: http://example.com/categories/2/get_products/?ordering=price And here is the code, thanks for any help. class CategoryViewSet(viewsets.ModelViewSet): queryset = Category.objects.all() serializer_class = CategorySerializer @action(detail=True) def get_products(self, request, pk=None): categories = Category.objects.get(id=pk).get_descendants( include_self=True).values_list('product_type__id', flat=True) products = Product.objects.filter( product_type__id__in=list(categories) ) paginator = ProductPagination() paginated_products = paginator.paginate_queryset(products, request) serializer = ProductSerializer( paginated_products, many=True, context={'request': request}) return paginator.get_paginated_response(serializer.data) -
Problem while changing input value through jquery and django?
Here I have the many values but in the input values only one value(last) will be placed. I want to display all the values in the input. How can I do this ? Example. I have values like this [10,12,13,14] but in the input only one value changes. I want to place all these values in my html input value. I think I need some changes in my script. I want to do something like this. $("#input").val(data.name); views.py def attribute_values(request): attribute = Attribute.objects.get(pk=request.GET.get('pk')) values = list(attribute.attributevalues_set.all()) serializer_values = serializers.serialize('json', values) data = { 'values': serializer_values } return JsonResponse(data, safe=False) script $("#select").change(function () { var attribute_pk = $(this).val(); console.log(attribute_pk) $.ajax({ url: ' {% url 'attribute_values' %}', data: { 'pk': attribute_pk }, dataType: 'json', success: function(data) { var values = data.values; data = $.parseJSON(values); console.log(data) $.each(data, function (index, el) { var name = el.fields.name; $("#input").val(name); }) } }); }); -
adding multiple image in django model
I am trying to add multiple images to a django model, it works in admin but i am completely blank on how to show it on my template. here is what i tried, it doesn't give any error but the image doesn't show. models.py class Export_Trade_Data(models.Model): country = models.ForeignKey( BannerandInformation, on_delete=models.CASCADE, null=True) # country_name = models.CharField('Country Name', max_length=100, default='') trade_text = models.TextField('Text for Trade Data', null=True) # date added date_added = models.DateTimeField('Date Updated', auto_now=True) def __str__(self): return "Export Trade Data" class ExportImage(models.Model): country = models.ForeignKey( BannerandInformation, on_delete=models.CASCADE, null=True) export_trade_data = models.ForeignKey(Export_Trade_Data, on_delete=models.CASCADE) export_sample_image = models.ImageField( 'Export Sample Image', upload_to='country', null=True) def __str__(self): return "Export Trade Data" views.py def country(request, country): exch_val = '' banners = BannerandInformation.objects.filter(country=country) for b in banners: country_name = b exch_r = b.exch_rate exch_cur = exch_r.split("/")[0] ######Export_Trade_Data Model####### etrds = Export_Trade_Data.objects.filter(country_id=ct_id) ######ExportImage Model####### expics = ExportImage.objects.filter(country_id=ct_id) for s in expics: etd_pic = s.export_sample_image content = { "etrds": etrds, "etd_pic": etd_pic, } return render(request, 'country/country-page.html', content) country-page.html <tbody> {% for expics in etrds %} <tr> <img src="/country/{{expics.export_sample_image}}" height="604px" width="527px" alt=""> </tr> {% endfor %} </tbody> -
Django manage.py dumpdata returns an error
Hello there! I have a Windows Home 10 (rus), Python 3.7, Django 3.1, Postgresql 12. When executing the command manage.py dumpdata returns an error. python manage.py dumpdata --traceback > db.json Traceback (most recent call last): File "manage.py", line 24, in execute_from_command_line(sys.argv) File "C:\Users\User\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\core\management_init_.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\User\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\core\management_init_.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\User\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\User\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Users\User\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\core\management\commands\dumpdata.py", line 195, in handle object_count=object_count, File "C:\Users\User\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\core\serializers_init_.py", line 128, in serialize s.serialize(queryset, **options) File "C:\Users\User\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\core\serializers\base.py", line 115, in serialize self.end_object(obj) File "C:\Users\User\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\core\serializers\json.py", line 54, in end_object json.dump(self.get_dump_object(obj), self.stream, **self.json_kwargs) File C:\Users\User\AppData\Local\Programs\Python\Python37\Lib\json_init_.py", line 180, in dump fp.write(chunk) File "C:\Users\User\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\core\management\base.py", line 147, in write self._out.write(style_func(msg)) File "C:\Users\User\AppData\Local\Programs\Python\Python37\Lib\encodings\cp1252.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_table)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\xe9' in position 6: character maps to undefined The code '\se9' is Latin accented e - é (my database stores strings containing English, French and Russian words.) -
DJANGO datetime wrong on template even after timezone setup
I have a DJANGO application, and I am completely lost about times. I am located in Budapest, Hungary, my current time for these test is: 09:26 I have my timezone correctly set in settings.py ... TIME_ZONE = 'Europe/Budapest' USE_I18N = True USE_L10N = True USE_TZ = True ... Lets say I store a datetime object in my SQLite database, the admin page will show the correct time: If I query that data in a view the date is suddenly wrong. 2020-10-06 07:26:41.040463+00:00 I have read solutions that I need to activate timezone in my view, but it does not work: tzname = pytz.timezone("Europe/Budapest") timezone.activate(tzname) for i in MyObject.objects.all(): print(i.date) returns 2020-10-06 07:26:41.040463+00:00 I usually fill my templates with Ajax JS calls, so I was not able to try template filters like this: {{ value|timezone:"Europe/Budapest" }} How can I change the time so that my JsonResponse sends the correct time to my templates? -
Using firebase with django
I want to use firebase with my django project. Well I didn't find any proper documentation to connect with the firebase. Except for connecting firebase with django with pyrebase. Proper documentation I mean without using the REST API can I use firebase for my project to save the model and to make migrations. -
Django IntegrityError 'author_id' violates not-null constraint
I don't know why Django raise IntegrityError when I try to post a comment form. It forces me to defin author and halp to null=True and blank=True but I don't want to. In my project, when someone post a comment, the author and the post (halp) attached must not be null. 1st: 'author_id' violates not-null constraint 2nd: 'halp_id' violates not-null constraint models.py: class Comment(models.Model): STATE_CHOICES = [ ('open', _('Ouvert')), ('deleted', _('Supprimé')) ] halp = models.ForeignKey("Halp", on_delete=models.CASCADE) text = models.TextField() comment = models.ForeignKey("self", on_delete=models.CASCADE, related_name="comment_child", null=True, blank=True) date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(User, on_delete=models.CASCADE) state = models.CharField(max_length=20, choices=STATE_CHOICES, default='open') is_solution = models.BooleanField(default=False) class Meta: ordering = ['halp', '-id'] def __str__(self): return self.halp.title def get_text(self): return self.text[:20] forms.py: class CommentForm(forms.ModelForm): text = forms.CharField( label='', widget=forms.Textarea(attrs={ 'class': 'form-control form-custom', 'placeholder': _('Redigez une réponse ou un commentaire...') }) ) class Meta: model = Comment fields = ['text'] views.py: class CommentCreate(LoginRequiredMixin, CreateView): model = Comment form_class = forms.CommentForm def form_valid(self, form): text = form.cleaned_data['text'] self.halp = Halp.objects.get(slug=self.kwargs['slug']) self.comment = Comment.objects.create( text=text, author=self.request.user, halp=self.halp, ) return super(CommentCreate, self).form_valid(form) def get_success_url(self, **kwargs): return reverse_lazy('forum:halp-detail', kwargs={'slug': self.halp.slug}) If anyone can help me, I think I have missed something. Thank you in advance. Best regards. -
Django: Changing directory structure and adding an apps and scripts folder
I want to optimize my django directory structure. Therefore I had a look at this structure: Best practice for Django project working directory structure This is my current structure: django_project | |--project_name # Directory created by django |-manage.py |--project-name |--__init__.py |--asgi.py |--settings.py |--urls.py |--wsgi.py |--app_1 |--__init__.py |--app_2 |--__init__.py | |--docs | |--static |--admin |--css |--fonts |--js |--images |--vendor | |--templates |--errors |--includes | |--venv # virtual enviroment | |--README.text |--requirements.txt The new structure I want to archieve is listed below. I tried to create some new folders manually, for instance creating the scripts folder with and move manage.py into it which caused an error. I would be happy about a detailed explanation because I am working with django just for a few weeks and I am not familiar with the whole functionality / python. I am still learning yet. I would like to change the following things: Scripts folder Adding a scripts folder which contains manage.py. I had a look at Using setup.py in Your (Django) Project but it wasn't quiet helpful. Apps New created apps should be inside an apps directory. Can I do this manually after I create a new app via startapp command? For instance, creating the … -
How to perform the join on multiple fields in django queryset?
Here is my models : class Picture(models.Model): picture_id = models.IntegerField(db_column='PictureID', primary_key=True) gold_item =models.ForeignKey(GoldItem,db_column="GoldItemID",related_name="pictures",on_delete=models.CASCADE) gold_item_branch = models.ForeignKey(GoldItemBranch, db_column="GoldItemBranchID", related_name="pictures", on_delete=models.CASCADE) code = models.CharField(db_column='Code', max_length=5, blank=True, null=True) class GoldItemBranch(models.Model): gold_item_branch_id = models.IntegerField(db_column='GoldItemBranchID', primary_key=True) gold_item_id = models.IntegerField(db_column='GoldItemID') gold_item_branch_name = models.CharField(db_column='GoldItemBranchName', max_length=30, blank=True, null=True) I need to perform the join operation on multiple columns in above models. The columns are gold_item_id and gold_item_branch_id I wrote the SQL Query : select * from Pictures join GoldItemBranches on Pictures.GoldItemID = GoldItemBranches.GoldItemID and Pictures.GoldItemBranchID = GoldItemBranches.GoldItemBranchID How I can do the same query in Django queryset ?